1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the AsmPrinter class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/AsmPrinter.h" 14 #include "CodeViewDebug.h" 15 #include "DwarfDebug.h" 16 #include "DwarfException.h" 17 #include "WasmException.h" 18 #include "WinCFGuard.h" 19 #include "WinException.h" 20 #include "llvm/ADT/APFloat.h" 21 #include "llvm/ADT/APInt.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 34 #include "llvm/BinaryFormat/COFF.h" 35 #include "llvm/BinaryFormat/Dwarf.h" 36 #include "llvm/BinaryFormat/ELF.h" 37 #include "llvm/CodeGen/GCMetadata.h" 38 #include "llvm/CodeGen/GCMetadataPrinter.h" 39 #include "llvm/CodeGen/GCStrategy.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineConstantPool.h" 42 #include "llvm/CodeGen/MachineDominators.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineFunctionPass.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBundle.h" 48 #include "llvm/CodeGen/MachineJumpTableInfo.h" 49 #include "llvm/CodeGen/MachineLoopInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 55 #include "llvm/CodeGen/StackMaps.h" 56 #include "llvm/CodeGen/TargetFrameLowering.h" 57 #include "llvm/CodeGen/TargetInstrInfo.h" 58 #include "llvm/CodeGen/TargetLowering.h" 59 #include "llvm/CodeGen/TargetOpcodes.h" 60 #include "llvm/CodeGen/TargetRegisterInfo.h" 61 #include "llvm/IR/BasicBlock.h" 62 #include "llvm/IR/Comdat.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalIFunc.h" 71 #include "llvm/IR/GlobalIndirectSymbol.h" 72 #include "llvm/IR/GlobalObject.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/Instruction.h" 76 #include "llvm/IR/Mangler.h" 77 #include "llvm/IR/Metadata.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Operator.h" 80 #include "llvm/IR/Type.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCAsmInfo.h" 83 #include "llvm/MC/MCContext.h" 84 #include "llvm/MC/MCDirectives.h" 85 #include "llvm/MC/MCDwarf.h" 86 #include "llvm/MC/MCExpr.h" 87 #include "llvm/MC/MCInst.h" 88 #include "llvm/MC/MCSection.h" 89 #include "llvm/MC/MCSectionCOFF.h" 90 #include "llvm/MC/MCSectionELF.h" 91 #include "llvm/MC/MCSectionMachO.h" 92 #include "llvm/MC/MCSectionXCOFF.h" 93 #include "llvm/MC/MCStreamer.h" 94 #include "llvm/MC/MCSubtargetInfo.h" 95 #include "llvm/MC/MCSymbol.h" 96 #include "llvm/MC/MCSymbolELF.h" 97 #include "llvm/MC/MCSymbolXCOFF.h" 98 #include "llvm/MC/MCTargetOptions.h" 99 #include "llvm/MC/MCValue.h" 100 #include "llvm/MC/SectionKind.h" 101 #include "llvm/Pass.h" 102 #include "llvm/Remarks/Remark.h" 103 #include "llvm/Remarks/RemarkFormat.h" 104 #include "llvm/Remarks/RemarkStreamer.h" 105 #include "llvm/Remarks/RemarkStringTable.h" 106 #include "llvm/Support/Casting.h" 107 #include "llvm/Support/CommandLine.h" 108 #include "llvm/Support/Compiler.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/Format.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/Path.h" 113 #include "llvm/Support/TargetRegistry.h" 114 #include "llvm/Support/Timer.h" 115 #include "llvm/Support/raw_ostream.h" 116 #include "llvm/Target/TargetLoweringObjectFile.h" 117 #include "llvm/Target/TargetMachine.h" 118 #include "llvm/Target/TargetOptions.h" 119 #include <algorithm> 120 #include <cassert> 121 #include <cinttypes> 122 #include <cstdint> 123 #include <iterator> 124 #include <limits> 125 #include <memory> 126 #include <string> 127 #include <utility> 128 #include <vector> 129 130 using namespace llvm; 131 132 #define DEBUG_TYPE "asm-printer" 133 134 static const char *const DWARFGroupName = "dwarf"; 135 static const char *const DWARFGroupDescription = "DWARF Emission"; 136 static const char *const DbgTimerName = "emit"; 137 static const char *const DbgTimerDescription = "Debug Info Emission"; 138 static const char *const EHTimerName = "write_exception"; 139 static const char *const EHTimerDescription = "DWARF Exception Writer"; 140 static const char *const CFGuardName = "Control Flow Guard"; 141 static const char *const CFGuardDescription = "Control Flow Guard"; 142 static const char *const CodeViewLineTablesGroupName = "linetables"; 143 static const char *const CodeViewLineTablesGroupDescription = 144 "CodeView Line Tables"; 145 146 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 147 148 char AsmPrinter::ID = 0; 149 150 using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>; 151 152 static gcp_map_type &getGCMap(void *&P) { 153 if (!P) 154 P = new gcp_map_type(); 155 return *(gcp_map_type*)P; 156 } 157 158 /// getGVAlignment - Return the alignment to use for the specified global 159 /// value. This rounds up to the preferred alignment if possible and legal. 160 Align AsmPrinter::getGVAlignment(const GlobalValue *GV, const DataLayout &DL, 161 Align InAlign) { 162 Align Alignment; 163 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 164 Alignment = Align(DL.getPreferredAlignment(GVar)); 165 166 // If InAlign is specified, round it to it. 167 if (InAlign > Alignment) 168 Alignment = InAlign; 169 170 // If the GV has a specified alignment, take it into account. 171 const MaybeAlign GVAlign(GV->getAlignment()); 172 if (!GVAlign) 173 return Alignment; 174 175 assert(GVAlign && "GVAlign must be set"); 176 177 // If the GVAlign is larger than NumBits, or if we are required to obey 178 // NumBits because the GV has an assigned section, obey it. 179 if (*GVAlign > Alignment || GV->hasSection()) 180 Alignment = *GVAlign; 181 return Alignment; 182 } 183 184 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 185 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 186 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) { 187 VerboseAsm = OutStreamer->isVerboseAsm(); 188 } 189 190 AsmPrinter::~AsmPrinter() { 191 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 192 193 if (GCMetadataPrinters) { 194 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 195 196 delete &GCMap; 197 GCMetadataPrinters = nullptr; 198 } 199 } 200 201 bool AsmPrinter::isPositionIndependent() const { 202 return TM.isPositionIndependent(); 203 } 204 205 /// getFunctionNumber - Return a unique ID for the current function. 206 unsigned AsmPrinter::getFunctionNumber() const { 207 return MF->getFunctionNumber(); 208 } 209 210 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 211 return *TM.getObjFileLowering(); 212 } 213 214 const DataLayout &AsmPrinter::getDataLayout() const { 215 return MMI->getModule()->getDataLayout(); 216 } 217 218 // Do not use the cached DataLayout because some client use it without a Module 219 // (dsymutil, llvm-dwarfdump). 220 unsigned AsmPrinter::getPointerSize() const { 221 return TM.getPointerSize(0); // FIXME: Default address space 222 } 223 224 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 225 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 226 return MF->getSubtarget<MCSubtargetInfo>(); 227 } 228 229 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 230 S.emitInstruction(Inst, getSubtargetInfo()); 231 } 232 233 void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) { 234 assert(DD && "Dwarf debug file is not defined."); 235 assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode."); 236 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0); 237 } 238 239 /// getCurrentSection() - Return the current section we are emitting to. 240 const MCSection *AsmPrinter::getCurrentSection() const { 241 return OutStreamer->getCurrentSectionOnly(); 242 } 243 244 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 245 AU.setPreservesAll(); 246 MachineFunctionPass::getAnalysisUsage(AU); 247 AU.addRequired<MachineModuleInfoWrapperPass>(); 248 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 249 AU.addRequired<GCModuleInfo>(); 250 } 251 252 bool AsmPrinter::doInitialization(Module &M) { 253 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>(); 254 MMI = MMIWP ? &MMIWP->getMMI() : nullptr; 255 256 // Initialize TargetLoweringObjectFile. 257 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 258 .Initialize(OutContext, TM); 259 260 const_cast<TargetLoweringObjectFile &>(getObjFileLowering()) 261 .getModuleMetadata(M); 262 263 OutStreamer->InitSections(false); 264 265 // Emit the version-min deployment target directive if needed. 266 // 267 // FIXME: If we end up with a collection of these sorts of Darwin-specific 268 // or ELF-specific things, it may make sense to have a platform helper class 269 // that will work with the target helper class. For now keep it here, as the 270 // alternative is duplicated code in each of the target asm printers that 271 // use the directive, where it would need the same conditionalization 272 // anyway. 273 const Triple &Target = TM.getTargetTriple(); 274 OutStreamer->emitVersionForTarget(Target, M.getSDKVersion()); 275 276 // Allow the target to emit any magic that it wants at the start of the file. 277 emitStartOfAsmFile(M); 278 279 // Very minimal debug info. It is ignored if we emit actual debug info. If we 280 // don't, this at least helps the user find where a global came from. 281 if (MAI->hasSingleParameterDotFile()) { 282 // .file "foo.c" 283 OutStreamer->emitFileDirective( 284 llvm::sys::path::filename(M.getSourceFileName())); 285 } 286 287 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 288 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 289 for (auto &I : *MI) 290 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 291 MP->beginAssembly(M, *MI, *this); 292 293 // Emit module-level inline asm if it exists. 294 if (!M.getModuleInlineAsm().empty()) { 295 // We're at the module level. Construct MCSubtarget from the default CPU 296 // and target triple. 297 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 298 TM.getTargetTriple().str(), TM.getTargetCPU(), 299 TM.getTargetFeatureString())); 300 OutStreamer->AddComment("Start of file scope inline assembly"); 301 OutStreamer->AddBlankLine(); 302 emitInlineAsm(M.getModuleInlineAsm() + "\n", 303 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 304 OutStreamer->AddComment("End of file scope inline assembly"); 305 OutStreamer->AddBlankLine(); 306 } 307 308 if (MAI->doesSupportDebugInformation()) { 309 bool EmitCodeView = MMI->getModule()->getCodeViewFlag(); 310 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) { 311 Handlers.emplace_back(std::make_unique<CodeViewDebug>(this), 312 DbgTimerName, DbgTimerDescription, 313 CodeViewLineTablesGroupName, 314 CodeViewLineTablesGroupDescription); 315 } 316 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) { 317 DD = new DwarfDebug(this, &M); 318 DD->beginModule(); 319 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName, 320 DbgTimerDescription, DWARFGroupName, 321 DWARFGroupDescription); 322 } 323 } 324 325 switch (MAI->getExceptionHandlingType()) { 326 case ExceptionHandling::SjLj: 327 case ExceptionHandling::DwarfCFI: 328 case ExceptionHandling::ARM: 329 isCFIMoveForDebugging = true; 330 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 331 break; 332 for (auto &F: M.getFunctionList()) { 333 // If the module contains any function with unwind data, 334 // .eh_frame has to be emitted. 335 // Ignore functions that won't get emitted. 336 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) { 337 isCFIMoveForDebugging = false; 338 break; 339 } 340 } 341 break; 342 default: 343 isCFIMoveForDebugging = false; 344 break; 345 } 346 347 EHStreamer *ES = nullptr; 348 switch (MAI->getExceptionHandlingType()) { 349 case ExceptionHandling::None: 350 break; 351 case ExceptionHandling::SjLj: 352 case ExceptionHandling::DwarfCFI: 353 ES = new DwarfCFIException(this); 354 break; 355 case ExceptionHandling::ARM: 356 ES = new ARMException(this); 357 break; 358 case ExceptionHandling::WinEH: 359 switch (MAI->getWinEHEncodingType()) { 360 default: llvm_unreachable("unsupported unwinding information encoding"); 361 case WinEH::EncodingType::Invalid: 362 break; 363 case WinEH::EncodingType::X86: 364 case WinEH::EncodingType::Itanium: 365 ES = new WinException(this); 366 break; 367 } 368 break; 369 case ExceptionHandling::Wasm: 370 ES = new WasmException(this); 371 break; 372 } 373 if (ES) 374 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName, 375 EHTimerDescription, DWARFGroupName, 376 DWARFGroupDescription); 377 378 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2). 379 if (mdconst::extract_or_null<ConstantInt>( 380 MMI->getModule()->getModuleFlag("cfguard"))) 381 Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName, 382 CFGuardDescription, DWARFGroupName, 383 DWARFGroupDescription); 384 return false; 385 } 386 387 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 388 if (!MAI.hasWeakDefCanBeHiddenDirective()) 389 return false; 390 391 return GV->canBeOmittedFromSymbolTable(); 392 } 393 394 void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 395 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 396 switch (Linkage) { 397 case GlobalValue::CommonLinkage: 398 assert(!TM.getTargetTriple().isOSBinFormatXCOFF() && 399 "CommonLinkage of XCOFF should not come to this path."); 400 LLVM_FALLTHROUGH; 401 case GlobalValue::LinkOnceAnyLinkage: 402 case GlobalValue::LinkOnceODRLinkage: 403 case GlobalValue::WeakAnyLinkage: 404 case GlobalValue::WeakODRLinkage: 405 if (MAI->hasWeakDefDirective()) { 406 // .globl _foo 407 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 408 409 if (!canBeHidden(GV, *MAI)) 410 // .weak_definition _foo 411 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition); 412 else 413 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 414 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) { 415 // .globl _foo 416 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 417 //NOTE: linkonce is handled by the section the symbol was assigned to. 418 } else { 419 // .weak _foo 420 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak); 421 } 422 return; 423 case GlobalValue::ExternalLinkage: 424 if (MAI->hasDotExternDirective() && GV->isDeclaration()) 425 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Extern); 426 else 427 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 428 return; 429 case GlobalValue::PrivateLinkage: 430 return; 431 case GlobalValue::InternalLinkage: 432 if (MAI->hasDotLGloblDirective()) 433 OutStreamer->emitSymbolAttribute(GVSym, MCSA_LGlobal); 434 return; 435 case GlobalValue::ExternalWeakLinkage: 436 if (TM.getTargetTriple().isOSBinFormatXCOFF()) { 437 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak); 438 return; 439 } 440 LLVM_FALLTHROUGH; 441 case GlobalValue::AppendingLinkage: 442 case GlobalValue::AvailableExternallyLinkage: 443 llvm_unreachable("Should never emit this"); 444 } 445 llvm_unreachable("Unknown linkage type!"); 446 } 447 448 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 449 const GlobalValue *GV) const { 450 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler()); 451 } 452 453 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 454 return TM.getSymbol(GV); 455 } 456 457 MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const { 458 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an 459 // exact definion (intersection of GlobalValue::hasExactDefinition() and 460 // !isInterposable()). These linkages include: external, appending, internal, 461 // private. It may be profitable to use a local alias for external. The 462 // assembler would otherwise be conservative and assume a global default 463 // visibility symbol can be interposable, even if the code generator already 464 // assumed it. 465 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) { 466 const Module &M = *GV.getParent(); 467 if (TM.getRelocationModel() != Reloc::Static && 468 M.getPIELevel() == PIELevel::Default) 469 if (GV.isDSOLocal() || (TM.getTargetTriple().isX86() && 470 GV.getParent()->noSemanticInterposition())) 471 return getSymbolWithGlobalValueBase(&GV, "$local"); 472 } 473 return TM.getSymbol(&GV); 474 } 475 476 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 477 void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 478 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal(); 479 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 480 "No emulated TLS variables in the common section"); 481 482 // Never emit TLS variable xyz in emulated TLS model. 483 // The initialization value is in __emutls_t.xyz instead of xyz. 484 if (IsEmuTLSVar) 485 return; 486 487 if (GV->hasInitializer()) { 488 // Check to see if this is a special global used by LLVM, if so, emit it. 489 if (emitSpecialLLVMGlobal(GV)) 490 return; 491 492 // Skip the emission of global equivalents. The symbol can be emitted later 493 // on by emitGlobalGOTEquivs in case it turns out to be needed. 494 if (GlobalGOTEquivs.count(getSymbol(GV))) 495 return; 496 497 if (isVerbose()) { 498 // When printing the control variable __emutls_v.*, 499 // we don't need to print the original TLS variable name. 500 GV->printAsOperand(OutStreamer->GetCommentOS(), 501 /*PrintType=*/false, GV->getParent()); 502 OutStreamer->GetCommentOS() << '\n'; 503 } 504 } 505 506 MCSymbol *GVSym = getSymbol(GV); 507 MCSymbol *EmittedSym = GVSym; 508 509 // getOrCreateEmuTLSControlSym only creates the symbol with name and default 510 // attributes. 511 // GV's or GVSym's attributes will be used for the EmittedSym. 512 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 513 514 if (!GV->hasInitializer()) // External globals require no extra code. 515 return; 516 517 GVSym->redefineIfPossible(); 518 if (GVSym->isDefined() || GVSym->isVariable()) 519 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 520 "' is already defined"); 521 522 if (MAI->hasDotTypeDotSizeDirective()) 523 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 524 525 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 526 527 const DataLayout &DL = GV->getParent()->getDataLayout(); 528 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 529 530 // If the alignment is specified, we *must* obey it. Overaligning a global 531 // with a specified alignment is a prompt way to break globals emitted to 532 // sections and expected to be contiguous (e.g. ObjC metadata). 533 const Align Alignment = getGVAlignment(GV, DL); 534 535 for (const HandlerInfo &HI : Handlers) { 536 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 537 HI.TimerGroupName, HI.TimerGroupDescription, 538 TimePassesIsEnabled); 539 HI.Handler->setSymbolSize(GVSym, Size); 540 } 541 542 // Handle common symbols 543 if (GVKind.isCommon()) { 544 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 545 // .comm _foo, 42, 4 546 const bool SupportsAlignment = 547 getObjFileLowering().getCommDirectiveSupportsAlignment(); 548 OutStreamer->emitCommonSymbol(GVSym, Size, 549 SupportsAlignment ? Alignment.value() : 0); 550 return; 551 } 552 553 // Determine to which section this global should be emitted. 554 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM); 555 556 // If we have a bss global going to a section that supports the 557 // zerofill directive, do so here. 558 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 559 TheSection->isVirtualSection()) { 560 if (Size == 0) 561 Size = 1; // zerofill of 0 bytes is undefined. 562 emitLinkage(GV, GVSym); 563 // .zerofill __DATA, __bss, _foo, 400, 5 564 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value()); 565 return; 566 } 567 568 // If this is a BSS local symbol and we are emitting in the BSS 569 // section use .lcomm/.comm directive. 570 if (GVKind.isBSSLocal() && 571 getObjFileLowering().getBSSSection() == TheSection) { 572 if (Size == 0) 573 Size = 1; // .comm Foo, 0 is undefined, avoid it. 574 575 // Use .lcomm only if it supports user-specified alignment. 576 // Otherwise, while it would still be correct to use .lcomm in some 577 // cases (e.g. when Align == 1), the external assembler might enfore 578 // some -unknown- default alignment behavior, which could cause 579 // spurious differences between external and integrated assembler. 580 // Prefer to simply fall back to .local / .comm in this case. 581 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 582 // .lcomm _foo, 42 583 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value()); 584 return; 585 } 586 587 // .local _foo 588 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local); 589 // .comm _foo, 42, 4 590 const bool SupportsAlignment = 591 getObjFileLowering().getCommDirectiveSupportsAlignment(); 592 OutStreamer->emitCommonSymbol(GVSym, Size, 593 SupportsAlignment ? Alignment.value() : 0); 594 return; 595 } 596 597 // Handle thread local data for mach-o which requires us to output an 598 // additional structure of data and mangle the original symbol so that we 599 // can reference it later. 600 // 601 // TODO: This should become an "emit thread local global" method on TLOF. 602 // All of this macho specific stuff should be sunk down into TLOFMachO and 603 // stuff like "TLSExtraDataSection" should no longer be part of the parent 604 // TLOF class. This will also make it more obvious that stuff like 605 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 606 // specific code. 607 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 608 // Emit the .tbss symbol 609 MCSymbol *MangSym = 610 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 611 612 if (GVKind.isThreadBSS()) { 613 TheSection = getObjFileLowering().getTLSBSSSection(); 614 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value()); 615 } else if (GVKind.isThreadData()) { 616 OutStreamer->SwitchSection(TheSection); 617 618 emitAlignment(Alignment, GV); 619 OutStreamer->emitLabel(MangSym); 620 621 emitGlobalConstant(GV->getParent()->getDataLayout(), 622 GV->getInitializer()); 623 } 624 625 OutStreamer->AddBlankLine(); 626 627 // Emit the variable struct for the runtime. 628 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 629 630 OutStreamer->SwitchSection(TLVSect); 631 // Emit the linkage here. 632 emitLinkage(GV, GVSym); 633 OutStreamer->emitLabel(GVSym); 634 635 // Three pointers in size: 636 // - __tlv_bootstrap - used to make sure support exists 637 // - spare pointer, used when mapped by the runtime 638 // - pointer to mangled symbol above with initializer 639 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 640 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 641 PtrSize); 642 OutStreamer->emitIntValue(0, PtrSize); 643 OutStreamer->emitSymbolValue(MangSym, PtrSize); 644 645 OutStreamer->AddBlankLine(); 646 return; 647 } 648 649 MCSymbol *EmittedInitSym = GVSym; 650 651 OutStreamer->SwitchSection(TheSection); 652 653 emitLinkage(GV, EmittedInitSym); 654 emitAlignment(Alignment, GV); 655 656 OutStreamer->emitLabel(EmittedInitSym); 657 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV); 658 if (LocalAlias != EmittedInitSym) 659 OutStreamer->emitLabel(LocalAlias); 660 661 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 662 663 if (MAI->hasDotTypeDotSizeDirective()) 664 // .size foo, 42 665 OutStreamer->emitELFSize(EmittedInitSym, 666 MCConstantExpr::create(Size, OutContext)); 667 668 OutStreamer->AddBlankLine(); 669 } 670 671 /// Emit the directive and value for debug thread local expression 672 /// 673 /// \p Value - The value to emit. 674 /// \p Size - The size of the integer (in bytes) to emit. 675 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const { 676 OutStreamer->emitValue(Value, Size); 677 } 678 679 void AsmPrinter::emitFunctionHeaderComment() {} 680 681 /// EmitFunctionHeader - This method emits the header for the current 682 /// function. 683 void AsmPrinter::emitFunctionHeader() { 684 const Function &F = MF->getFunction(); 685 686 if (isVerbose()) 687 OutStreamer->GetCommentOS() 688 << "-- Begin function " 689 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n'; 690 691 // Print out constants referenced by the function 692 emitConstantPool(); 693 694 // Print the 'header' of function. 695 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM)); 696 OutStreamer->SwitchSection(MF->getSection()); 697 698 emitVisibility(CurrentFnSym, F.getVisibility()); 699 700 if (MAI->needsFunctionDescriptors() && 701 F.getLinkage() != GlobalValue::InternalLinkage) 702 emitLinkage(&F, CurrentFnDescSym); 703 704 emitLinkage(&F, CurrentFnSym); 705 if (MAI->hasFunctionAlignment()) 706 emitAlignment(MF->getAlignment(), &F); 707 708 if (MAI->hasDotTypeDotSizeDirective()) 709 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 710 711 if (F.hasFnAttribute(Attribute::Cold)) 712 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold); 713 714 if (isVerbose()) { 715 F.printAsOperand(OutStreamer->GetCommentOS(), 716 /*PrintType=*/false, F.getParent()); 717 emitFunctionHeaderComment(); 718 OutStreamer->GetCommentOS() << '\n'; 719 } 720 721 // Emit the prefix data. 722 if (F.hasPrefixData()) { 723 if (MAI->hasSubsectionsViaSymbols()) { 724 // Preserving prefix data on platforms which use subsections-via-symbols 725 // is a bit tricky. Here we introduce a symbol for the prefix data 726 // and use the .alt_entry attribute to mark the function's real entry point 727 // as an alternative entry point to the prefix-data symbol. 728 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol(); 729 OutStreamer->emitLabel(PrefixSym); 730 731 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 732 733 // Emit an .alt_entry directive for the actual function symbol. 734 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry); 735 } else { 736 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 737 } 738 } 739 740 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily 741 // place prefix data before NOPs. 742 unsigned PatchableFunctionPrefix = 0; 743 unsigned PatchableFunctionEntry = 0; 744 (void)F.getFnAttribute("patchable-function-prefix") 745 .getValueAsString() 746 .getAsInteger(10, PatchableFunctionPrefix); 747 (void)F.getFnAttribute("patchable-function-entry") 748 .getValueAsString() 749 .getAsInteger(10, PatchableFunctionEntry); 750 if (PatchableFunctionPrefix) { 751 CurrentPatchableFunctionEntrySym = 752 OutContext.createLinkerPrivateTempSymbol(); 753 OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym); 754 emitNops(PatchableFunctionPrefix); 755 } else if (PatchableFunctionEntry) { 756 // May be reassigned when emitting the body, to reference the label after 757 // the initial BTI (AArch64) or endbr32/endbr64 (x86). 758 CurrentPatchableFunctionEntrySym = CurrentFnBegin; 759 } 760 761 // Emit the function descriptor. This is a virtual function to allow targets 762 // to emit their specific function descriptor. Right now it is only used by 763 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function 764 // descriptors and should be converted to use this hook as well. 765 if (MAI->needsFunctionDescriptors()) 766 emitFunctionDescriptor(); 767 768 // Emit the CurrentFnSym. This is a virtual function to allow targets to do 769 // their wild and crazy things as required. 770 emitFunctionEntryLabel(); 771 772 if (CurrentFnBegin) { 773 if (MAI->useAssignmentForEHBegin()) { 774 MCSymbol *CurPos = OutContext.createTempSymbol(); 775 OutStreamer->emitLabel(CurPos); 776 OutStreamer->emitAssignment(CurrentFnBegin, 777 MCSymbolRefExpr::create(CurPos, OutContext)); 778 } else { 779 OutStreamer->emitLabel(CurrentFnBegin); 780 } 781 } 782 783 // Emit pre-function debug and/or EH information. 784 for (const HandlerInfo &HI : Handlers) { 785 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 786 HI.TimerGroupDescription, TimePassesIsEnabled); 787 HI.Handler->beginFunction(MF); 788 } 789 790 // Emit the prologue data. 791 if (F.hasPrologueData()) 792 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData()); 793 } 794 795 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 796 /// function. This can be overridden by targets as required to do custom stuff. 797 void AsmPrinter::emitFunctionEntryLabel() { 798 CurrentFnSym->redefineIfPossible(); 799 800 // The function label could have already been emitted if two symbols end up 801 // conflicting due to asm renaming. Detect this and emit an error. 802 if (CurrentFnSym->isVariable()) 803 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 804 "' is a protected alias"); 805 if (CurrentFnSym->isDefined()) 806 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 807 "' label emitted multiple times to assembly file"); 808 809 OutStreamer->emitLabel(CurrentFnSym); 810 811 if (TM.getTargetTriple().isOSBinFormatELF()) { 812 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction()); 813 if (Sym != CurrentFnSym) 814 OutStreamer->emitLabel(Sym); 815 } 816 } 817 818 /// emitComments - Pretty-print comments for instructions. 819 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 820 const MachineFunction *MF = MI.getMF(); 821 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 822 823 // Check for spills and reloads 824 825 // We assume a single instruction only has a spill or reload, not 826 // both. 827 Optional<unsigned> Size; 828 if ((Size = MI.getRestoreSize(TII))) { 829 CommentOS << *Size << "-byte Reload\n"; 830 } else if ((Size = MI.getFoldedRestoreSize(TII))) { 831 if (*Size) 832 CommentOS << *Size << "-byte Folded Reload\n"; 833 } else if ((Size = MI.getSpillSize(TII))) { 834 CommentOS << *Size << "-byte Spill\n"; 835 } else if ((Size = MI.getFoldedSpillSize(TII))) { 836 if (*Size) 837 CommentOS << *Size << "-byte Folded Spill\n"; 838 } 839 840 // Check for spill-induced copies 841 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 842 CommentOS << " Reload Reuse\n"; 843 } 844 845 /// emitImplicitDef - This method emits the specified machine instruction 846 /// that is an implicit def. 847 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 848 Register RegNo = MI->getOperand(0).getReg(); 849 850 SmallString<128> Str; 851 raw_svector_ostream OS(Str); 852 OS << "implicit-def: " 853 << printReg(RegNo, MF->getSubtarget().getRegisterInfo()); 854 855 OutStreamer->AddComment(OS.str()); 856 OutStreamer->AddBlankLine(); 857 } 858 859 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 860 std::string Str; 861 raw_string_ostream OS(Str); 862 OS << "kill:"; 863 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 864 const MachineOperand &Op = MI->getOperand(i); 865 assert(Op.isReg() && "KILL instruction must have only register operands"); 866 OS << ' ' << (Op.isDef() ? "def " : "killed ") 867 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo()); 868 } 869 AP.OutStreamer->AddComment(OS.str()); 870 AP.OutStreamer->AddBlankLine(); 871 } 872 873 /// emitDebugValueComment - This method handles the target-independent form 874 /// of DBG_VALUE, returning true if it was able to do so. A false return 875 /// means the target will need to handle MI in EmitInstruction. 876 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 877 // This code handles only the 4-operand target-independent form. 878 if (MI->getNumOperands() != 4) 879 return false; 880 881 SmallString<128> Str; 882 raw_svector_ostream OS(Str); 883 OS << "DEBUG_VALUE: "; 884 885 const DILocalVariable *V = MI->getDebugVariable(); 886 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 887 StringRef Name = SP->getName(); 888 if (!Name.empty()) 889 OS << Name << ":"; 890 } 891 OS << V->getName(); 892 OS << " <- "; 893 894 // The second operand is only an offset if it's an immediate. 895 bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 896 int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0; 897 const DIExpression *Expr = MI->getDebugExpression(); 898 if (Expr->getNumElements()) { 899 OS << '['; 900 bool NeedSep = false; 901 for (auto Op : Expr->expr_ops()) { 902 if (NeedSep) 903 OS << ", "; 904 else 905 NeedSep = true; 906 OS << dwarf::OperationEncodingString(Op.getOp()); 907 for (unsigned I = 0; I < Op.getNumArgs(); ++I) 908 OS << ' ' << Op.getArg(I); 909 } 910 OS << "] "; 911 } 912 913 // Register or immediate value. Register 0 means undef. 914 if (MI->getOperand(0).isFPImm()) { 915 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 916 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 917 OS << (double)APF.convertToFloat(); 918 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 919 OS << APF.convertToDouble(); 920 } else { 921 // There is no good way to print long double. Convert a copy to 922 // double. Ah well, it's only a comment. 923 bool ignored; 924 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 925 &ignored); 926 OS << "(long double) " << APF.convertToDouble(); 927 } 928 } else if (MI->getOperand(0).isImm()) { 929 OS << MI->getOperand(0).getImm(); 930 } else if (MI->getOperand(0).isCImm()) { 931 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 932 } else if (MI->getOperand(0).isTargetIndex()) { 933 auto Op = MI->getOperand(0); 934 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")"; 935 return true; 936 } else { 937 Register Reg; 938 if (MI->getOperand(0).isReg()) { 939 Reg = MI->getOperand(0).getReg(); 940 } else { 941 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 942 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 943 Offset += TFI->getFrameIndexReference(*AP.MF, 944 MI->getOperand(0).getIndex(), Reg); 945 MemLoc = true; 946 } 947 if (Reg == 0) { 948 // Suppress offset, it is not meaningful here. 949 OS << "undef"; 950 // NOTE: Want this comment at start of line, don't emit with AddComment. 951 AP.OutStreamer->emitRawComment(OS.str()); 952 return true; 953 } 954 if (MemLoc) 955 OS << '['; 956 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 957 } 958 959 if (MemLoc) 960 OS << '+' << Offset << ']'; 961 962 // NOTE: Want this comment at start of line, don't emit with AddComment. 963 AP.OutStreamer->emitRawComment(OS.str()); 964 return true; 965 } 966 967 /// This method handles the target-independent form of DBG_LABEL, returning 968 /// true if it was able to do so. A false return means the target will need 969 /// to handle MI in EmitInstruction. 970 static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) { 971 if (MI->getNumOperands() != 1) 972 return false; 973 974 SmallString<128> Str; 975 raw_svector_ostream OS(Str); 976 OS << "DEBUG_LABEL: "; 977 978 const DILabel *V = MI->getDebugLabel(); 979 if (auto *SP = dyn_cast<DISubprogram>( 980 V->getScope()->getNonLexicalBlockFileScope())) { 981 StringRef Name = SP->getName(); 982 if (!Name.empty()) 983 OS << Name << ":"; 984 } 985 OS << V->getName(); 986 987 // NOTE: Want this comment at start of line, don't emit with AddComment. 988 AP.OutStreamer->emitRawComment(OS.str()); 989 return true; 990 } 991 992 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const { 993 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 994 MF->getFunction().needsUnwindTableEntry()) 995 return CFI_M_EH; 996 997 if (MMI->hasDebugInfo() || MF->getTarget().Options.ForceDwarfFrameSection) 998 return CFI_M_Debug; 999 1000 return CFI_M_None; 1001 } 1002 1003 bool AsmPrinter::needsSEHMoves() { 1004 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry(); 1005 } 1006 1007 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 1008 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 1009 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 1010 ExceptionHandlingType != ExceptionHandling::ARM) 1011 return; 1012 1013 if (needsCFIMoves() == CFI_M_None) 1014 return; 1015 1016 // If there is no "real" instruction following this CFI instruction, skip 1017 // emitting it; it would be beyond the end of the function's FDE range. 1018 auto *MBB = MI.getParent(); 1019 auto I = std::next(MI.getIterator()); 1020 while (I != MBB->end() && I->isTransient()) 1021 ++I; 1022 if (I == MBB->instr_end() && 1023 MBB->getReverseIterator() == MBB->getParent()->rbegin()) 1024 return; 1025 1026 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions(); 1027 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 1028 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 1029 emitCFIInstruction(CFI); 1030 } 1031 1032 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 1033 // The operands are the MCSymbol and the frame offset of the allocation. 1034 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 1035 int FrameOffset = MI.getOperand(1).getImm(); 1036 1037 // Emit a symbol assignment. 1038 OutStreamer->emitAssignment(FrameAllocSym, 1039 MCConstantExpr::create(FrameOffset, OutContext)); 1040 } 1041 1042 void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) { 1043 if (!MF.getTarget().Options.EmitStackSizeSection) 1044 return; 1045 1046 MCSection *StackSizeSection = 1047 getObjFileLowering().getStackSizesSection(*getCurrentSection()); 1048 if (!StackSizeSection) 1049 return; 1050 1051 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 1052 // Don't emit functions with dynamic stack allocations. 1053 if (FrameInfo.hasVarSizedObjects()) 1054 return; 1055 1056 OutStreamer->PushSection(); 1057 OutStreamer->SwitchSection(StackSizeSection); 1058 1059 const MCSymbol *FunctionSymbol = getFunctionBegin(); 1060 uint64_t StackSize = FrameInfo.getStackSize(); 1061 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize()); 1062 OutStreamer->emitULEB128IntValue(StackSize); 1063 1064 OutStreamer->PopSection(); 1065 } 1066 1067 static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF, 1068 MachineModuleInfo *MMI) { 1069 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo()) 1070 return true; 1071 1072 // We might emit an EH table that uses function begin and end labels even if 1073 // we don't have any landingpads. 1074 if (!MF.getFunction().hasPersonalityFn()) 1075 return false; 1076 return !isNoOpWithoutInvoke( 1077 classifyEHPersonality(MF.getFunction().getPersonalityFn())); 1078 } 1079 1080 /// EmitFunctionBody - This method emits the body and trailer for a 1081 /// function. 1082 void AsmPrinter::emitFunctionBody() { 1083 emitFunctionHeader(); 1084 1085 // Emit target-specific gunk before the function body. 1086 emitFunctionBodyStart(); 1087 1088 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 1089 1090 if (isVerbose()) { 1091 // Get MachineDominatorTree or compute it on the fly if it's unavailable 1092 MDT = getAnalysisIfAvailable<MachineDominatorTree>(); 1093 if (!MDT) { 1094 OwnedMDT = std::make_unique<MachineDominatorTree>(); 1095 OwnedMDT->getBase().recalculate(*MF); 1096 MDT = OwnedMDT.get(); 1097 } 1098 1099 // Get MachineLoopInfo or compute it on the fly if it's unavailable 1100 MLI = getAnalysisIfAvailable<MachineLoopInfo>(); 1101 if (!MLI) { 1102 OwnedMLI = std::make_unique<MachineLoopInfo>(); 1103 OwnedMLI->getBase().analyze(MDT->getBase()); 1104 MLI = OwnedMLI.get(); 1105 } 1106 } 1107 1108 // Print out code for the function. 1109 bool HasAnyRealCode = false; 1110 int NumInstsInFunction = 0; 1111 1112 for (auto &MBB : *MF) { 1113 // Print a label for the basic block. 1114 emitBasicBlockStart(MBB); 1115 for (auto &MI : MBB) { 1116 // Print the assembly for the instruction. 1117 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 1118 !MI.isDebugInstr()) { 1119 HasAnyRealCode = true; 1120 ++NumInstsInFunction; 1121 } 1122 1123 // If there is a pre-instruction symbol, emit a label for it here. 1124 if (MCSymbol *S = MI.getPreInstrSymbol()) 1125 OutStreamer->emitLabel(S); 1126 1127 if (ShouldPrintDebugScopes) { 1128 for (const HandlerInfo &HI : Handlers) { 1129 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1130 HI.TimerGroupName, HI.TimerGroupDescription, 1131 TimePassesIsEnabled); 1132 HI.Handler->beginInstruction(&MI); 1133 } 1134 } 1135 1136 if (isVerbose()) 1137 emitComments(MI, OutStreamer->GetCommentOS()); 1138 1139 switch (MI.getOpcode()) { 1140 case TargetOpcode::CFI_INSTRUCTION: 1141 emitCFIInstruction(MI); 1142 break; 1143 case TargetOpcode::LOCAL_ESCAPE: 1144 emitFrameAlloc(MI); 1145 break; 1146 case TargetOpcode::ANNOTATION_LABEL: 1147 case TargetOpcode::EH_LABEL: 1148 case TargetOpcode::GC_LABEL: 1149 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol()); 1150 break; 1151 case TargetOpcode::INLINEASM: 1152 case TargetOpcode::INLINEASM_BR: 1153 emitInlineAsm(&MI); 1154 break; 1155 case TargetOpcode::DBG_VALUE: 1156 if (isVerbose()) { 1157 if (!emitDebugValueComment(&MI, *this)) 1158 emitInstruction(&MI); 1159 } 1160 break; 1161 case TargetOpcode::DBG_LABEL: 1162 if (isVerbose()) { 1163 if (!emitDebugLabelComment(&MI, *this)) 1164 emitInstruction(&MI); 1165 } 1166 break; 1167 case TargetOpcode::IMPLICIT_DEF: 1168 if (isVerbose()) emitImplicitDef(&MI); 1169 break; 1170 case TargetOpcode::KILL: 1171 if (isVerbose()) emitKill(&MI, *this); 1172 break; 1173 default: 1174 emitInstruction(&MI); 1175 break; 1176 } 1177 1178 // If there is a post-instruction symbol, emit a label for it here. 1179 if (MCSymbol *S = MI.getPostInstrSymbol()) 1180 OutStreamer->emitLabel(S); 1181 1182 if (ShouldPrintDebugScopes) { 1183 for (const HandlerInfo &HI : Handlers) { 1184 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1185 HI.TimerGroupName, HI.TimerGroupDescription, 1186 TimePassesIsEnabled); 1187 HI.Handler->endInstruction(); 1188 } 1189 } 1190 } 1191 1192 // We need a temporary symbol for the end of this basic block, if either we 1193 // have BBLabels enabled and we want to emit size directive for the BBs, or 1194 // if this basic blocks marks the end of a section (except the section 1195 // containing the entry basic block as the end symbol for that section is 1196 // CurrentFnEnd). 1197 MCSymbol *CurrentBBEnd = nullptr; 1198 if ((MAI->hasDotTypeDotSizeDirective() && MF->hasBBLabels()) || 1199 (MBB.isEndSection() && !MBB.sameSection(&MF->front()))) { 1200 CurrentBBEnd = OutContext.createTempSymbol(); 1201 OutStreamer->emitLabel(CurrentBBEnd); 1202 } 1203 1204 // Helper for emitting the size directive associated with a basic block 1205 // symbol. 1206 auto emitELFSizeDirective = [&](MCSymbol *SymForSize) { 1207 assert(CurrentBBEnd && "Basicblock end symbol not set!"); 1208 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1209 MCSymbolRefExpr::create(CurrentBBEnd, OutContext), 1210 MCSymbolRefExpr::create(SymForSize, OutContext), OutContext); 1211 OutStreamer->emitELFSize(SymForSize, SizeExp); 1212 }; 1213 1214 // Emit size directive for the size of each basic block, if BBLabels is 1215 // enabled. 1216 if (MAI->hasDotTypeDotSizeDirective() && MF->hasBBLabels()) 1217 emitELFSizeDirective(MBB.getSymbol()); 1218 1219 // Emit size directive for the size of each basic block section once we 1220 // get to the end of that section. 1221 if (MBB.isEndSection()) { 1222 if (!MBB.sameSection(&MF->front())) { 1223 if (MAI->hasDotTypeDotSizeDirective()) 1224 emitELFSizeDirective(CurrentSectionBeginSym); 1225 } 1226 } 1227 emitBasicBlockEnd(MBB); 1228 } 1229 1230 EmittedInsts += NumInstsInFunction; 1231 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount", 1232 MF->getFunction().getSubprogram(), 1233 &MF->front()); 1234 R << ore::NV("NumInstructions", NumInstsInFunction) 1235 << " instructions in function"; 1236 ORE->emit(R); 1237 1238 // If the function is empty and the object file uses .subsections_via_symbols, 1239 // then we need to emit *something* to the function body to prevent the 1240 // labels from collapsing together. Just emit a noop. 1241 // Similarly, don't emit empty functions on Windows either. It can lead to 1242 // duplicate entries (two functions with the same RVA) in the Guard CF Table 1243 // after linking, causing the kernel not to load the binary: 1244 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html 1245 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer. 1246 const Triple &TT = TM.getTargetTriple(); 1247 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() || 1248 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) { 1249 MCInst Noop; 1250 MF->getSubtarget().getInstrInfo()->getNoop(Noop); 1251 1252 // Targets can opt-out of emitting the noop here by leaving the opcode 1253 // unspecified. 1254 if (Noop.getOpcode()) { 1255 OutStreamer->AddComment("avoids zero-length function"); 1256 emitNops(1); 1257 } 1258 } 1259 1260 // Switch to the original section in case basic block sections was used. 1261 OutStreamer->SwitchSection(MF->getSection()); 1262 1263 const Function &F = MF->getFunction(); 1264 for (const auto &BB : F) { 1265 if (!BB.hasAddressTaken()) 1266 continue; 1267 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 1268 if (Sym->isDefined()) 1269 continue; 1270 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 1271 OutStreamer->emitLabel(Sym); 1272 } 1273 1274 // Emit target-specific gunk after the function body. 1275 emitFunctionBodyEnd(); 1276 1277 if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) || 1278 MAI->hasDotTypeDotSizeDirective()) { 1279 // Create a symbol for the end of function. 1280 CurrentFnEnd = createTempSymbol("func_end"); 1281 OutStreamer->emitLabel(CurrentFnEnd); 1282 } 1283 1284 // If the target wants a .size directive for the size of the function, emit 1285 // it. 1286 if (MAI->hasDotTypeDotSizeDirective()) { 1287 // We can get the size as difference between the function label and the 1288 // temp label. 1289 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1290 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 1291 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 1292 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 1293 } 1294 1295 for (const HandlerInfo &HI : Handlers) { 1296 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1297 HI.TimerGroupDescription, TimePassesIsEnabled); 1298 HI.Handler->markFunctionEnd(); 1299 } 1300 1301 1302 // Print out jump tables referenced by the function. 1303 emitJumpTableInfo(); 1304 1305 // Emit post-function debug and/or EH information. 1306 for (const HandlerInfo &HI : Handlers) { 1307 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1308 HI.TimerGroupDescription, TimePassesIsEnabled); 1309 HI.Handler->endFunction(MF); 1310 } 1311 1312 // Emit section containing stack size metadata. 1313 emitStackSizeSection(*MF); 1314 1315 emitPatchableFunctionEntries(); 1316 1317 if (isVerbose()) 1318 OutStreamer->GetCommentOS() << "-- End function\n"; 1319 1320 OutStreamer->AddBlankLine(); 1321 } 1322 1323 /// Compute the number of Global Variables that uses a Constant. 1324 static unsigned getNumGlobalVariableUses(const Constant *C) { 1325 if (!C) 1326 return 0; 1327 1328 if (isa<GlobalVariable>(C)) 1329 return 1; 1330 1331 unsigned NumUses = 0; 1332 for (auto *CU : C->users()) 1333 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1334 1335 return NumUses; 1336 } 1337 1338 /// Only consider global GOT equivalents if at least one user is a 1339 /// cstexpr inside an initializer of another global variables. Also, don't 1340 /// handle cstexpr inside instructions. During global variable emission, 1341 /// candidates are skipped and are emitted later in case at least one cstexpr 1342 /// isn't replaced by a PC relative GOT entry access. 1343 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1344 unsigned &NumGOTEquivUsers) { 1345 // Global GOT equivalents are unnamed private globals with a constant 1346 // pointer initializer to another global symbol. They must point to a 1347 // GlobalVariable or Function, i.e., as GlobalValue. 1348 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1349 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1350 !isa<GlobalValue>(GV->getOperand(0))) 1351 return false; 1352 1353 // To be a got equivalent, at least one of its users need to be a constant 1354 // expression used by another global variable. 1355 for (auto *U : GV->users()) 1356 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1357 1358 return NumGOTEquivUsers > 0; 1359 } 1360 1361 /// Unnamed constant global variables solely contaning a pointer to 1362 /// another globals variable is equivalent to a GOT table entry; it contains the 1363 /// the address of another symbol. Optimize it and replace accesses to these 1364 /// "GOT equivalents" by using the GOT entry for the final global instead. 1365 /// Compute GOT equivalent candidates among all global variables to avoid 1366 /// emitting them if possible later on, after it use is replaced by a GOT entry 1367 /// access. 1368 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1369 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1370 return; 1371 1372 for (const auto &G : M.globals()) { 1373 unsigned NumGOTEquivUsers = 0; 1374 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1375 continue; 1376 1377 const MCSymbol *GOTEquivSym = getSymbol(&G); 1378 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1379 } 1380 } 1381 1382 /// Constant expressions using GOT equivalent globals may not be eligible 1383 /// for PC relative GOT entry conversion, in such cases we need to emit such 1384 /// globals we previously omitted in EmitGlobalVariable. 1385 void AsmPrinter::emitGlobalGOTEquivs() { 1386 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1387 return; 1388 1389 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1390 for (auto &I : GlobalGOTEquivs) { 1391 const GlobalVariable *GV = I.second.first; 1392 unsigned Cnt = I.second.second; 1393 if (Cnt) 1394 FailedCandidates.push_back(GV); 1395 } 1396 GlobalGOTEquivs.clear(); 1397 1398 for (auto *GV : FailedCandidates) 1399 emitGlobalVariable(GV); 1400 } 1401 1402 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1403 const GlobalIndirectSymbol& GIS) { 1404 MCSymbol *Name = getSymbol(&GIS); 1405 1406 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1407 OutStreamer->emitSymbolAttribute(Name, MCSA_Global); 1408 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1409 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference); 1410 else 1411 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1412 1413 bool IsFunction = GIS.getValueType()->isFunctionTy(); 1414 1415 // Treat bitcasts of functions as functions also. This is important at least 1416 // on WebAssembly where object and function addresses can't alias each other. 1417 if (!IsFunction) 1418 if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol())) 1419 if (CE->getOpcode() == Instruction::BitCast) 1420 IsFunction = 1421 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy(); 1422 1423 // Set the symbol type to function if the alias has a function type. 1424 // This affects codegen when the aliasee is not a function. 1425 if (IsFunction) 1426 OutStreamer->emitSymbolAttribute(Name, isa<GlobalIFunc>(GIS) 1427 ? MCSA_ELF_TypeIndFunction 1428 : MCSA_ELF_TypeFunction); 1429 1430 emitVisibility(Name, GIS.getVisibility()); 1431 1432 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1433 1434 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1435 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry); 1436 1437 // Emit the directives as assignments aka .set: 1438 OutStreamer->emitAssignment(Name, Expr); 1439 MCSymbol *LocalAlias = getSymbolPreferLocal(GIS); 1440 if (LocalAlias != Name) 1441 OutStreamer->emitAssignment(LocalAlias, Expr); 1442 1443 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1444 // If the aliasee does not correspond to a symbol in the output, i.e. the 1445 // alias is not of an object or the aliased object is private, then set the 1446 // size of the alias symbol from the type of the alias. We don't do this in 1447 // other situations as the alias and aliasee having differing types but same 1448 // size may be intentional. 1449 const GlobalObject *BaseObject = GA->getBaseObject(); 1450 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1451 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1452 const DataLayout &DL = M.getDataLayout(); 1453 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1454 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1455 } 1456 } 1457 } 1458 1459 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) { 1460 if (!RS.needsSection()) 1461 return; 1462 1463 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer(); 1464 1465 Optional<SmallString<128>> Filename; 1466 if (Optional<StringRef> FilenameRef = RS.getFilename()) { 1467 Filename = *FilenameRef; 1468 sys::fs::make_absolute(*Filename); 1469 assert(!Filename->empty() && "The filename can't be empty."); 1470 } 1471 1472 std::string Buf; 1473 raw_string_ostream OS(Buf); 1474 std::unique_ptr<remarks::MetaSerializer> MetaSerializer = 1475 Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename)) 1476 : RemarkSerializer.metaSerializer(OS); 1477 MetaSerializer->emit(); 1478 1479 // Switch to the remarks section. 1480 MCSection *RemarksSection = 1481 OutContext.getObjectFileInfo()->getRemarksSection(); 1482 OutStreamer->SwitchSection(RemarksSection); 1483 1484 OutStreamer->emitBinaryData(OS.str()); 1485 } 1486 1487 bool AsmPrinter::doFinalization(Module &M) { 1488 // Set the MachineFunction to nullptr so that we can catch attempted 1489 // accesses to MF specific features at the module level and so that 1490 // we can conditionalize accesses based on whether or not it is nullptr. 1491 MF = nullptr; 1492 1493 // Gather all GOT equivalent globals in the module. We really need two 1494 // passes over the globals: one to compute and another to avoid its emission 1495 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1496 // where the got equivalent shows up before its use. 1497 computeGlobalGOTEquivs(M); 1498 1499 // Emit global variables. 1500 for (const auto &G : M.globals()) 1501 emitGlobalVariable(&G); 1502 1503 // Emit remaining GOT equivalent globals. 1504 emitGlobalGOTEquivs(); 1505 1506 // Emit linkage(XCOFF) and visibility info for declarations 1507 for (const Function &F : M) { 1508 if (!F.isDeclarationForLinker()) 1509 continue; 1510 1511 MCSymbol *Name = getSymbol(&F); 1512 // Function getSymbol gives us the function descriptor symbol for XCOFF. 1513 if (TM.getTargetTriple().isOSBinFormatXCOFF() && !F.isIntrinsic()) { 1514 1515 // Get the function entry point symbol. 1516 MCSymbol *FnEntryPointSym = OutContext.getOrCreateSymbol( 1517 "." + cast<MCSymbolXCOFF>(Name)->getUnqualifiedName()); 1518 if (cast<MCSymbolXCOFF>(FnEntryPointSym)->hasRepresentedCsectSet()) 1519 // Emit linkage for the function entry point. 1520 emitLinkage(&F, FnEntryPointSym); 1521 1522 // Emit linkage for the function descriptor. 1523 emitLinkage(&F, Name); 1524 } 1525 1526 GlobalValue::VisibilityTypes V = F.getVisibility(); 1527 if (V == GlobalValue::DefaultVisibility) 1528 continue; 1529 1530 emitVisibility(Name, V, false); 1531 } 1532 1533 // Emit the remarks section contents. 1534 // FIXME: Figure out when is the safest time to emit this section. It should 1535 // not come after debug info. 1536 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer()) 1537 emitRemarksSection(*RS); 1538 1539 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1540 1541 TLOF.emitModuleMetadata(*OutStreamer, M); 1542 1543 if (TM.getTargetTriple().isOSBinFormatELF()) { 1544 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1545 1546 // Output stubs for external and common global variables. 1547 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1548 if (!Stubs.empty()) { 1549 OutStreamer->SwitchSection(TLOF.getDataSection()); 1550 const DataLayout &DL = M.getDataLayout(); 1551 1552 emitAlignment(Align(DL.getPointerSize())); 1553 for (const auto &Stub : Stubs) { 1554 OutStreamer->emitLabel(Stub.first); 1555 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 1556 DL.getPointerSize()); 1557 } 1558 } 1559 } 1560 1561 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1562 MachineModuleInfoCOFF &MMICOFF = 1563 MMI->getObjFileInfo<MachineModuleInfoCOFF>(); 1564 1565 // Output stubs for external and common global variables. 1566 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList(); 1567 if (!Stubs.empty()) { 1568 const DataLayout &DL = M.getDataLayout(); 1569 1570 for (const auto &Stub : Stubs) { 1571 SmallString<256> SectionName = StringRef(".rdata$"); 1572 SectionName += Stub.first->getName(); 1573 OutStreamer->SwitchSection(OutContext.getCOFFSection( 1574 SectionName, 1575 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | 1576 COFF::IMAGE_SCN_LNK_COMDAT, 1577 SectionKind::getReadOnly(), Stub.first->getName(), 1578 COFF::IMAGE_COMDAT_SELECT_ANY)); 1579 emitAlignment(Align(DL.getPointerSize())); 1580 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global); 1581 OutStreamer->emitLabel(Stub.first); 1582 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 1583 DL.getPointerSize()); 1584 } 1585 } 1586 } 1587 1588 // Finalize debug and EH information. 1589 for (const HandlerInfo &HI : Handlers) { 1590 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1591 HI.TimerGroupDescription, TimePassesIsEnabled); 1592 HI.Handler->endModule(); 1593 } 1594 Handlers.clear(); 1595 DD = nullptr; 1596 1597 // If the target wants to know about weak references, print them all. 1598 if (MAI->getWeakRefDirective()) { 1599 // FIXME: This is not lazy, it would be nice to only print weak references 1600 // to stuff that is actually used. Note that doing so would require targets 1601 // to notice uses in operands (due to constant exprs etc). This should 1602 // happen with the MC stuff eventually. 1603 1604 // Print out module-level global objects here. 1605 for (const auto &GO : M.global_objects()) { 1606 if (!GO.hasExternalWeakLinkage()) 1607 continue; 1608 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1609 } 1610 } 1611 1612 // Print aliases in topological order, that is, for each alias a = b, 1613 // b must be printed before a. 1614 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1615 // such an order to generate correct TOC information. 1616 SmallVector<const GlobalAlias *, 16> AliasStack; 1617 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1618 for (const auto &Alias : M.aliases()) { 1619 for (const GlobalAlias *Cur = &Alias; Cur; 1620 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1621 if (!AliasVisited.insert(Cur).second) 1622 break; 1623 AliasStack.push_back(Cur); 1624 } 1625 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack)) 1626 emitGlobalIndirectSymbol(M, *AncestorAlias); 1627 AliasStack.clear(); 1628 } 1629 for (const auto &IFunc : M.ifuncs()) 1630 emitGlobalIndirectSymbol(M, IFunc); 1631 1632 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1633 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1634 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1635 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1636 MP->finishAssembly(M, *MI, *this); 1637 1638 // Emit llvm.ident metadata in an '.ident' directive. 1639 emitModuleIdents(M); 1640 1641 // Emit bytes for llvm.commandline metadata. 1642 emitModuleCommandLines(M); 1643 1644 // Emit __morestack address if needed for indirect calls. 1645 if (MMI->usesMorestackAddr()) { 1646 Align Alignment(1); 1647 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1648 getDataLayout(), SectionKind::getReadOnly(), 1649 /*C=*/nullptr, Alignment); 1650 OutStreamer->SwitchSection(ReadOnlySection); 1651 1652 MCSymbol *AddrSymbol = 1653 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1654 OutStreamer->emitLabel(AddrSymbol); 1655 1656 unsigned PtrSize = MAI->getCodePointerSize(); 1657 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1658 PtrSize); 1659 } 1660 1661 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if 1662 // split-stack is used. 1663 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) { 1664 OutStreamer->SwitchSection( 1665 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0)); 1666 if (MMI->hasNosplitStack()) 1667 OutStreamer->SwitchSection( 1668 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0)); 1669 } 1670 1671 // If we don't have any trampolines, then we don't require stack memory 1672 // to be executable. Some targets have a directive to declare this. 1673 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1674 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1675 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1676 OutStreamer->SwitchSection(S); 1677 1678 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1679 // Emit /EXPORT: flags for each exported global as necessary. 1680 const auto &TLOF = getObjFileLowering(); 1681 std::string Flags; 1682 1683 for (const GlobalValue &GV : M.global_values()) { 1684 raw_string_ostream OS(Flags); 1685 TLOF.emitLinkerFlagsForGlobal(OS, &GV); 1686 OS.flush(); 1687 if (!Flags.empty()) { 1688 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1689 OutStreamer->emitBytes(Flags); 1690 } 1691 Flags.clear(); 1692 } 1693 1694 // Emit /INCLUDE: flags for each used global as necessary. 1695 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1696 assert(LU->hasInitializer() && 1697 "expected llvm.used to have an initializer"); 1698 assert(isa<ArrayType>(LU->getValueType()) && 1699 "expected llvm.used to be an array type"); 1700 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1701 for (const Value *Op : A->operands()) { 1702 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1703 // Global symbols with internal or private linkage are not visible to 1704 // the linker, and thus would cause an error when the linker tried to 1705 // preserve the symbol due to the `/include:` directive. 1706 if (GV->hasLocalLinkage()) 1707 continue; 1708 1709 raw_string_ostream OS(Flags); 1710 TLOF.emitLinkerFlagsForUsed(OS, GV); 1711 OS.flush(); 1712 1713 if (!Flags.empty()) { 1714 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1715 OutStreamer->emitBytes(Flags); 1716 } 1717 Flags.clear(); 1718 } 1719 } 1720 } 1721 } 1722 1723 if (TM.Options.EmitAddrsig) { 1724 // Emit address-significance attributes for all globals. 1725 OutStreamer->emitAddrsig(); 1726 for (const GlobalValue &GV : M.global_values()) 1727 if (!GV.use_empty() && !GV.isThreadLocal() && 1728 !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") && 1729 !GV.hasAtLeastLocalUnnamedAddr()) 1730 OutStreamer->emitAddrsigSym(getSymbol(&GV)); 1731 } 1732 1733 // Emit symbol partition specifications (ELF only). 1734 if (TM.getTargetTriple().isOSBinFormatELF()) { 1735 unsigned UniqueID = 0; 1736 for (const GlobalValue &GV : M.global_values()) { 1737 if (!GV.hasPartition() || GV.isDeclarationForLinker() || 1738 GV.getVisibility() != GlobalValue::DefaultVisibility) 1739 continue; 1740 1741 OutStreamer->SwitchSection( 1742 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, 1743 "", ++UniqueID, nullptr)); 1744 OutStreamer->emitBytes(GV.getPartition()); 1745 OutStreamer->emitZeros(1); 1746 OutStreamer->emitValue( 1747 MCSymbolRefExpr::create(getSymbol(&GV), OutContext), 1748 MAI->getCodePointerSize()); 1749 } 1750 } 1751 1752 // Allow the target to emit any magic that it wants at the end of the file, 1753 // after everything else has gone out. 1754 emitEndOfAsmFile(M); 1755 1756 MMI = nullptr; 1757 1758 OutStreamer->Finish(); 1759 OutStreamer->reset(); 1760 OwnedMLI.reset(); 1761 OwnedMDT.reset(); 1762 1763 return false; 1764 } 1765 1766 MCSymbol *AsmPrinter::getCurExceptionSym() { 1767 if (!CurExceptionSym) 1768 CurExceptionSym = createTempSymbol("exception"); 1769 return CurExceptionSym; 1770 } 1771 1772 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1773 this->MF = &MF; 1774 const Function &F = MF.getFunction(); 1775 1776 // Get the function symbol. 1777 if (!MAI->needsFunctionDescriptors()) { 1778 CurrentFnSym = getSymbol(&MF.getFunction()); 1779 } else { 1780 assert(TM.getTargetTriple().isOSAIX() && 1781 "Only AIX uses the function descriptor hooks."); 1782 // AIX is unique here in that the name of the symbol emitted for the 1783 // function body does not have the same name as the source function's 1784 // C-linkage name. 1785 assert(CurrentFnDescSym && "The function descriptor symbol needs to be" 1786 " initalized first."); 1787 1788 // Get the function entry point symbol. 1789 CurrentFnSym = OutContext.getOrCreateSymbol( 1790 "." + cast<MCSymbolXCOFF>(CurrentFnDescSym)->getUnqualifiedName()); 1791 } 1792 1793 CurrentFnSymForSize = CurrentFnSym; 1794 CurrentFnBegin = nullptr; 1795 CurrentSectionBeginSym = nullptr; 1796 CurExceptionSym = nullptr; 1797 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1798 if (F.hasFnAttribute("patchable-function-entry") || 1799 F.hasFnAttribute("function-instrument") || 1800 F.hasFnAttribute("xray-instruction-threshold") || 1801 needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize || 1802 MF.getTarget().Options.EmitStackSizeSection) { 1803 CurrentFnBegin = createTempSymbol("func_begin"); 1804 if (NeedsLocalForSize) 1805 CurrentFnSymForSize = CurrentFnBegin; 1806 } 1807 1808 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 1809 } 1810 1811 namespace { 1812 1813 // Keep track the alignment, constpool entries per Section. 1814 struct SectionCPs { 1815 MCSection *S; 1816 Align Alignment; 1817 SmallVector<unsigned, 4> CPEs; 1818 1819 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {} 1820 }; 1821 1822 } // end anonymous namespace 1823 1824 /// EmitConstantPool - Print to the current output stream assembly 1825 /// representations of the constants in the constant pool MCP. This is 1826 /// used to print out constants which have been "spilled to memory" by 1827 /// the code generator. 1828 void AsmPrinter::emitConstantPool() { 1829 const MachineConstantPool *MCP = MF->getConstantPool(); 1830 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1831 if (CP.empty()) return; 1832 1833 // Calculate sections for constant pool entries. We collect entries to go into 1834 // the same section together to reduce amount of section switch statements. 1835 SmallVector<SectionCPs, 4> CPSections; 1836 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1837 const MachineConstantPoolEntry &CPE = CP[i]; 1838 Align Alignment = CPE.getAlign(); 1839 1840 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1841 1842 const Constant *C = nullptr; 1843 if (!CPE.isMachineConstantPoolEntry()) 1844 C = CPE.Val.ConstVal; 1845 1846 MCSection *S = getObjFileLowering().getSectionForConstant( 1847 getDataLayout(), Kind, C, Alignment); 1848 1849 // The number of sections are small, just do a linear search from the 1850 // last section to the first. 1851 bool Found = false; 1852 unsigned SecIdx = CPSections.size(); 1853 while (SecIdx != 0) { 1854 if (CPSections[--SecIdx].S == S) { 1855 Found = true; 1856 break; 1857 } 1858 } 1859 if (!Found) { 1860 SecIdx = CPSections.size(); 1861 CPSections.push_back(SectionCPs(S, Alignment)); 1862 } 1863 1864 if (Alignment > CPSections[SecIdx].Alignment) 1865 CPSections[SecIdx].Alignment = Alignment; 1866 CPSections[SecIdx].CPEs.push_back(i); 1867 } 1868 1869 // Now print stuff into the calculated sections. 1870 const MCSection *CurSection = nullptr; 1871 unsigned Offset = 0; 1872 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1873 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1874 unsigned CPI = CPSections[i].CPEs[j]; 1875 MCSymbol *Sym = GetCPISymbol(CPI); 1876 if (!Sym->isUndefined()) 1877 continue; 1878 1879 if (CurSection != CPSections[i].S) { 1880 OutStreamer->SwitchSection(CPSections[i].S); 1881 emitAlignment(Align(CPSections[i].Alignment)); 1882 CurSection = CPSections[i].S; 1883 Offset = 0; 1884 } 1885 1886 MachineConstantPoolEntry CPE = CP[CPI]; 1887 1888 // Emit inter-object padding for alignment. 1889 unsigned NewOffset = alignTo(Offset, CPE.getAlign()); 1890 OutStreamer->emitZeros(NewOffset - Offset); 1891 1892 Type *Ty = CPE.getType(); 1893 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1894 1895 OutStreamer->emitLabel(Sym); 1896 if (CPE.isMachineConstantPoolEntry()) 1897 emitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1898 else 1899 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1900 } 1901 } 1902 } 1903 1904 // Print assembly representations of the jump tables used by the current 1905 // function. 1906 void AsmPrinter::emitJumpTableInfo() { 1907 const DataLayout &DL = MF->getDataLayout(); 1908 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1909 if (!MJTI) return; 1910 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1911 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1912 if (JT.empty()) return; 1913 1914 // Pick the directive to use to print the jump table entries, and switch to 1915 // the appropriate section. 1916 const Function &F = MF->getFunction(); 1917 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1918 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1919 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1920 F); 1921 if (JTInDiffSection) { 1922 // Drop it in the readonly section. 1923 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM); 1924 OutStreamer->SwitchSection(ReadOnlySection); 1925 } 1926 1927 emitAlignment(Align(MJTI->getEntryAlignment(DL))); 1928 1929 // Jump tables in code sections are marked with a data_region directive 1930 // where that's supported. 1931 if (!JTInDiffSection) 1932 OutStreamer->emitDataRegion(MCDR_DataRegionJT32); 1933 1934 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1935 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1936 1937 // If this jump table was deleted, ignore it. 1938 if (JTBBs.empty()) continue; 1939 1940 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1941 /// emit a .set directive for each unique entry. 1942 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1943 MAI->doesSetDirectiveSuppressReloc()) { 1944 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1945 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1946 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1947 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1948 const MachineBasicBlock *MBB = JTBBs[ii]; 1949 if (!EmittedSets.insert(MBB).second) 1950 continue; 1951 1952 // .set LJTSet, LBB32-base 1953 const MCExpr *LHS = 1954 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1955 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1956 MCBinaryExpr::createSub(LHS, Base, 1957 OutContext)); 1958 } 1959 } 1960 1961 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1962 // before each jump table. The first label is never referenced, but tells 1963 // the assembler and linker the extents of the jump table object. The 1964 // second label is actually referenced by the code. 1965 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1966 // FIXME: This doesn't have to have any specific name, just any randomly 1967 // named and numbered local label started with 'l' would work. Simplify 1968 // GetJTISymbol. 1969 OutStreamer->emitLabel(GetJTISymbol(JTI, true)); 1970 1971 MCSymbol* JTISymbol = GetJTISymbol(JTI); 1972 OutStreamer->emitLabel(JTISymbol); 1973 1974 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1975 emitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1976 } 1977 if (!JTInDiffSection) 1978 OutStreamer->emitDataRegion(MCDR_DataRegionEnd); 1979 } 1980 1981 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1982 /// current stream. 1983 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1984 const MachineBasicBlock *MBB, 1985 unsigned UID) const { 1986 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1987 const MCExpr *Value = nullptr; 1988 switch (MJTI->getEntryKind()) { 1989 case MachineJumpTableInfo::EK_Inline: 1990 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1991 case MachineJumpTableInfo::EK_Custom32: 1992 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1993 MJTI, MBB, UID, OutContext); 1994 break; 1995 case MachineJumpTableInfo::EK_BlockAddress: 1996 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1997 // .word LBB123 1998 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1999 break; 2000 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 2001 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 2002 // with a relocation as gp-relative, e.g.: 2003 // .gprel32 LBB123 2004 MCSymbol *MBBSym = MBB->getSymbol(); 2005 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2006 return; 2007 } 2008 2009 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 2010 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 2011 // with a relocation as gp-relative, e.g.: 2012 // .gpdword LBB123 2013 MCSymbol *MBBSym = MBB->getSymbol(); 2014 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2015 return; 2016 } 2017 2018 case MachineJumpTableInfo::EK_LabelDifference32: { 2019 // Each entry is the address of the block minus the address of the jump 2020 // table. This is used for PIC jump tables where gprel32 is not supported. 2021 // e.g.: 2022 // .word LBB123 - LJTI1_2 2023 // If the .set directive avoids relocations, this is emitted as: 2024 // .set L4_5_set_123, LBB123 - LJTI1_2 2025 // .word L4_5_set_123 2026 if (MAI->doesSetDirectiveSuppressReloc()) { 2027 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 2028 OutContext); 2029 break; 2030 } 2031 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2032 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2033 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 2034 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 2035 break; 2036 } 2037 } 2038 2039 assert(Value && "Unknown entry kind!"); 2040 2041 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 2042 OutStreamer->emitValue(Value, EntrySize); 2043 } 2044 2045 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 2046 /// special global used by LLVM. If so, emit it and return true, otherwise 2047 /// do nothing and return false. 2048 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) { 2049 if (GV->getName() == "llvm.used") { 2050 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 2051 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 2052 return true; 2053 } 2054 2055 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 2056 if (GV->getSection() == "llvm.metadata" || 2057 GV->hasAvailableExternallyLinkage()) 2058 return true; 2059 2060 if (!GV->hasAppendingLinkage()) return false; 2061 2062 assert(GV->hasInitializer() && "Not a special LLVM global!"); 2063 2064 if (GV->getName() == "llvm.global_ctors") { 2065 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2066 /* isCtor */ true); 2067 2068 return true; 2069 } 2070 2071 if (GV->getName() == "llvm.global_dtors") { 2072 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2073 /* isCtor */ false); 2074 2075 return true; 2076 } 2077 2078 report_fatal_error("unknown special variable"); 2079 } 2080 2081 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 2082 /// global in the specified llvm.used list. 2083 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) { 2084 // Should be an array of 'i8*'. 2085 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 2086 const GlobalValue *GV = 2087 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 2088 if (GV) 2089 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 2090 } 2091 } 2092 2093 namespace { 2094 2095 struct Structor { 2096 int Priority = 0; 2097 Constant *Func = nullptr; 2098 GlobalValue *ComdatKey = nullptr; 2099 2100 Structor() = default; 2101 }; 2102 2103 } // end anonymous namespace 2104 2105 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 2106 /// priority. 2107 void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List, 2108 bool isCtor) { 2109 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the 2110 // init priority. 2111 if (!isa<ConstantArray>(List)) return; 2112 2113 // Gather the structors in a form that's convenient for sorting by priority. 2114 SmallVector<Structor, 8> Structors; 2115 for (Value *O : cast<ConstantArray>(List)->operands()) { 2116 auto *CS = cast<ConstantStruct>(O); 2117 if (CS->getOperand(1)->isNullValue()) 2118 break; // Found a null terminator, skip the rest. 2119 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 2120 if (!Priority) continue; // Malformed. 2121 Structors.push_back(Structor()); 2122 Structor &S = Structors.back(); 2123 S.Priority = Priority->getLimitedValue(65535); 2124 S.Func = CS->getOperand(1); 2125 if (!CS->getOperand(2)->isNullValue()) 2126 S.ComdatKey = 2127 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 2128 } 2129 2130 // Emit the function pointers in the target-specific order 2131 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) { 2132 return L.Priority < R.Priority; 2133 }); 2134 const Align Align = DL.getPointerPrefAlignment(); 2135 for (Structor &S : Structors) { 2136 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 2137 const MCSymbol *KeySym = nullptr; 2138 if (GlobalValue *GV = S.ComdatKey) { 2139 if (GV->isDeclarationForLinker()) 2140 // If the associated variable is not defined in this module 2141 // (it might be available_externally, or have been an 2142 // available_externally definition that was dropped by the 2143 // EliminateAvailableExternally pass), some other TU 2144 // will provide its dynamic initializer. 2145 continue; 2146 2147 KeySym = getSymbol(GV); 2148 } 2149 MCSection *OutputSection = 2150 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 2151 : Obj.getStaticDtorSection(S.Priority, KeySym)); 2152 OutStreamer->SwitchSection(OutputSection); 2153 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 2154 emitAlignment(Align); 2155 emitXXStructor(DL, S.Func); 2156 } 2157 } 2158 2159 void AsmPrinter::emitModuleIdents(Module &M) { 2160 if (!MAI->hasIdentDirective()) 2161 return; 2162 2163 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 2164 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2165 const MDNode *N = NMD->getOperand(i); 2166 assert(N->getNumOperands() == 1 && 2167 "llvm.ident metadata entry can have only one operand"); 2168 const MDString *S = cast<MDString>(N->getOperand(0)); 2169 OutStreamer->emitIdent(S->getString()); 2170 } 2171 } 2172 } 2173 2174 void AsmPrinter::emitModuleCommandLines(Module &M) { 2175 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines(); 2176 if (!CommandLine) 2177 return; 2178 2179 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline"); 2180 if (!NMD || !NMD->getNumOperands()) 2181 return; 2182 2183 OutStreamer->PushSection(); 2184 OutStreamer->SwitchSection(CommandLine); 2185 OutStreamer->emitZeros(1); 2186 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2187 const MDNode *N = NMD->getOperand(i); 2188 assert(N->getNumOperands() == 1 && 2189 "llvm.commandline metadata entry can have only one operand"); 2190 const MDString *S = cast<MDString>(N->getOperand(0)); 2191 OutStreamer->emitBytes(S->getString()); 2192 OutStreamer->emitZeros(1); 2193 } 2194 OutStreamer->PopSection(); 2195 } 2196 2197 //===--------------------------------------------------------------------===// 2198 // Emission and print routines 2199 // 2200 2201 /// Emit a byte directive and value. 2202 /// 2203 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); } 2204 2205 /// Emit a short directive and value. 2206 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); } 2207 2208 /// Emit a long directive and value. 2209 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); } 2210 2211 /// Emit a long long directive and value. 2212 void AsmPrinter::emitInt64(uint64_t Value) const { 2213 OutStreamer->emitInt64(Value); 2214 } 2215 2216 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 2217 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 2218 /// .set if it avoids relocations. 2219 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 2220 unsigned Size) const { 2221 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 2222 } 2223 2224 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 2225 /// where the size in bytes of the directive is specified by Size and Label 2226 /// specifies the label. This implicitly uses .set if it is available. 2227 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 2228 unsigned Size, 2229 bool IsSectionRelative) const { 2230 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 2231 OutStreamer->EmitCOFFSecRel32(Label, Offset); 2232 if (Size > 4) 2233 OutStreamer->emitZeros(Size - 4); 2234 return; 2235 } 2236 2237 // Emit Label+Offset (or just Label if Offset is zero) 2238 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 2239 if (Offset) 2240 Expr = MCBinaryExpr::createAdd( 2241 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 2242 2243 OutStreamer->emitValue(Expr, Size); 2244 } 2245 2246 //===----------------------------------------------------------------------===// 2247 2248 // EmitAlignment - Emit an alignment directive to the specified power of 2249 // two boundary. If a global value is specified, and if that global has 2250 // an explicit alignment requested, it will override the alignment request 2251 // if required for correctness. 2252 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const { 2253 if (GV) 2254 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment); 2255 2256 if (Alignment == Align(1)) 2257 return; // 1-byte aligned: no need to emit alignment. 2258 2259 if (getCurrentSection()->getKind().isText()) 2260 OutStreamer->emitCodeAlignment(Alignment.value()); 2261 else 2262 OutStreamer->emitValueToAlignment(Alignment.value()); 2263 } 2264 2265 //===----------------------------------------------------------------------===// 2266 // Constant emission. 2267 //===----------------------------------------------------------------------===// 2268 2269 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 2270 MCContext &Ctx = OutContext; 2271 2272 if (CV->isNullValue() || isa<UndefValue>(CV)) 2273 return MCConstantExpr::create(0, Ctx); 2274 2275 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 2276 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 2277 2278 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 2279 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 2280 2281 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 2282 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 2283 2284 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 2285 if (!CE) { 2286 llvm_unreachable("Unknown constant value to lower!"); 2287 } 2288 2289 switch (CE->getOpcode()) { 2290 default: { 2291 // If the code isn't optimized, there may be outstanding folding 2292 // opportunities. Attempt to fold the expression using DataLayout as a 2293 // last resort before giving up. 2294 Constant *C = ConstantFoldConstant(CE, getDataLayout()); 2295 if (C != CE) 2296 return lowerConstant(C); 2297 2298 // Otherwise report the problem to the user. 2299 std::string S; 2300 raw_string_ostream OS(S); 2301 OS << "Unsupported expression in static initializer: "; 2302 CE->printAsOperand(OS, /*PrintType=*/false, 2303 !MF ? nullptr : MF->getFunction().getParent()); 2304 report_fatal_error(OS.str()); 2305 } 2306 case Instruction::GetElementPtr: { 2307 // Generate a symbolic expression for the byte address 2308 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 2309 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 2310 2311 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 2312 if (!OffsetAI) 2313 return Base; 2314 2315 int64_t Offset = OffsetAI.getSExtValue(); 2316 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 2317 Ctx); 2318 } 2319 2320 case Instruction::Trunc: 2321 // We emit the value and depend on the assembler to truncate the generated 2322 // expression properly. This is important for differences between 2323 // blockaddress labels. Since the two labels are in the same function, it 2324 // is reasonable to treat their delta as a 32-bit value. 2325 LLVM_FALLTHROUGH; 2326 case Instruction::BitCast: 2327 return lowerConstant(CE->getOperand(0)); 2328 2329 case Instruction::IntToPtr: { 2330 const DataLayout &DL = getDataLayout(); 2331 2332 // Handle casts to pointers by changing them into casts to the appropriate 2333 // integer type. This promotes constant folding and simplifies this code. 2334 Constant *Op = CE->getOperand(0); 2335 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 2336 false/*ZExt*/); 2337 return lowerConstant(Op); 2338 } 2339 2340 case Instruction::PtrToInt: { 2341 const DataLayout &DL = getDataLayout(); 2342 2343 // Support only foldable casts to/from pointers that can be eliminated by 2344 // changing the pointer to the appropriately sized integer type. 2345 Constant *Op = CE->getOperand(0); 2346 Type *Ty = CE->getType(); 2347 2348 const MCExpr *OpExpr = lowerConstant(Op); 2349 2350 // We can emit the pointer value into this slot if the slot is an 2351 // integer slot equal to the size of the pointer. 2352 // 2353 // If the pointer is larger than the resultant integer, then 2354 // as with Trunc just depend on the assembler to truncate it. 2355 if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType())) 2356 return OpExpr; 2357 2358 // Otherwise the pointer is smaller than the resultant integer, mask off 2359 // the high bits so we are sure to get a proper truncation if the input is 2360 // a constant expr. 2361 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 2362 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 2363 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 2364 } 2365 2366 case Instruction::Sub: { 2367 GlobalValue *LHSGV; 2368 APInt LHSOffset; 2369 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 2370 getDataLayout())) { 2371 GlobalValue *RHSGV; 2372 APInt RHSOffset; 2373 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 2374 getDataLayout())) { 2375 const MCExpr *RelocExpr = 2376 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 2377 if (!RelocExpr) 2378 RelocExpr = MCBinaryExpr::createSub( 2379 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 2380 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 2381 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 2382 if (Addend != 0) 2383 RelocExpr = MCBinaryExpr::createAdd( 2384 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 2385 return RelocExpr; 2386 } 2387 } 2388 } 2389 // else fallthrough 2390 LLVM_FALLTHROUGH; 2391 2392 // The MC library also has a right-shift operator, but it isn't consistently 2393 // signed or unsigned between different targets. 2394 case Instruction::Add: 2395 case Instruction::Mul: 2396 case Instruction::SDiv: 2397 case Instruction::SRem: 2398 case Instruction::Shl: 2399 case Instruction::And: 2400 case Instruction::Or: 2401 case Instruction::Xor: { 2402 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2403 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2404 switch (CE->getOpcode()) { 2405 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2406 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2407 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2408 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2409 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2410 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2411 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2412 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2413 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2414 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2415 } 2416 } 2417 } 2418 } 2419 2420 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2421 AsmPrinter &AP, 2422 const Constant *BaseCV = nullptr, 2423 uint64_t Offset = 0); 2424 2425 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2426 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP); 2427 2428 /// isRepeatedByteSequence - Determine whether the given value is 2429 /// composed of a repeated sequence of identical bytes and return the 2430 /// byte value. If it is not a repeated sequence, return -1. 2431 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2432 StringRef Data = V->getRawDataValues(); 2433 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2434 char C = Data[0]; 2435 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2436 if (Data[i] != C) return -1; 2437 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2438 } 2439 2440 /// isRepeatedByteSequence - Determine whether the given value is 2441 /// composed of a repeated sequence of identical bytes and return the 2442 /// byte value. If it is not a repeated sequence, return -1. 2443 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2444 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2445 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2446 assert(Size % 8 == 0); 2447 2448 // Extend the element to take zero padding into account. 2449 APInt Value = CI->getValue().zextOrSelf(Size); 2450 if (!Value.isSplat(8)) 2451 return -1; 2452 2453 return Value.zextOrTrunc(8).getZExtValue(); 2454 } 2455 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2456 // Make sure all array elements are sequences of the same repeated 2457 // byte. 2458 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2459 Constant *Op0 = CA->getOperand(0); 2460 int Byte = isRepeatedByteSequence(Op0, DL); 2461 if (Byte == -1) 2462 return -1; 2463 2464 // All array elements must be equal. 2465 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2466 if (CA->getOperand(i) != Op0) 2467 return -1; 2468 return Byte; 2469 } 2470 2471 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2472 return isRepeatedByteSequence(CDS); 2473 2474 return -1; 2475 } 2476 2477 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2478 const ConstantDataSequential *CDS, 2479 AsmPrinter &AP) { 2480 // See if we can aggregate this into a .fill, if so, emit it as such. 2481 int Value = isRepeatedByteSequence(CDS, DL); 2482 if (Value != -1) { 2483 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2484 // Don't emit a 1-byte object as a .fill. 2485 if (Bytes > 1) 2486 return AP.OutStreamer->emitFill(Bytes, Value); 2487 } 2488 2489 // If this can be emitted with .ascii/.asciz, emit it as such. 2490 if (CDS->isString()) 2491 return AP.OutStreamer->emitBytes(CDS->getAsString()); 2492 2493 // Otherwise, emit the values in successive locations. 2494 unsigned ElementByteSize = CDS->getElementByteSize(); 2495 if (isa<IntegerType>(CDS->getElementType())) { 2496 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2497 if (AP.isVerbose()) 2498 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2499 CDS->getElementAsInteger(i)); 2500 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i), 2501 ElementByteSize); 2502 } 2503 } else { 2504 Type *ET = CDS->getElementType(); 2505 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2506 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP); 2507 } 2508 2509 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2510 unsigned EmittedSize = 2511 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements(); 2512 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!"); 2513 if (unsigned Padding = Size - EmittedSize) 2514 AP.OutStreamer->emitZeros(Padding); 2515 } 2516 2517 static void emitGlobalConstantArray(const DataLayout &DL, 2518 const ConstantArray *CA, AsmPrinter &AP, 2519 const Constant *BaseCV, uint64_t Offset) { 2520 // See if we can aggregate some values. Make sure it can be 2521 // represented as a series of bytes of the constant value. 2522 int Value = isRepeatedByteSequence(CA, DL); 2523 2524 if (Value != -1) { 2525 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2526 AP.OutStreamer->emitFill(Bytes, Value); 2527 } 2528 else { 2529 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2530 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2531 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2532 } 2533 } 2534 } 2535 2536 static void emitGlobalConstantVector(const DataLayout &DL, 2537 const ConstantVector *CV, AsmPrinter &AP) { 2538 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2539 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2540 2541 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2542 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2543 CV->getType()->getNumElements(); 2544 if (unsigned Padding = Size - EmittedSize) 2545 AP.OutStreamer->emitZeros(Padding); 2546 } 2547 2548 static void emitGlobalConstantStruct(const DataLayout &DL, 2549 const ConstantStruct *CS, AsmPrinter &AP, 2550 const Constant *BaseCV, uint64_t Offset) { 2551 // Print the fields in successive locations. Pad to align if needed! 2552 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2553 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2554 uint64_t SizeSoFar = 0; 2555 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2556 const Constant *Field = CS->getOperand(i); 2557 2558 // Print the actual field value. 2559 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2560 2561 // Check if padding is needed and insert one or more 0s. 2562 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2563 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2564 - Layout->getElementOffset(i)) - FieldSize; 2565 SizeSoFar += FieldSize + PadSize; 2566 2567 // Insert padding - this may include padding to increase the size of the 2568 // current field up to the ABI size (if the struct is not packed) as well 2569 // as padding to ensure that the next field starts at the right offset. 2570 AP.OutStreamer->emitZeros(PadSize); 2571 } 2572 assert(SizeSoFar == Layout->getSizeInBytes() && 2573 "Layout of constant struct may be incorrect!"); 2574 } 2575 2576 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) { 2577 assert(ET && "Unknown float type"); 2578 APInt API = APF.bitcastToAPInt(); 2579 2580 // First print a comment with what we think the original floating-point value 2581 // should have been. 2582 if (AP.isVerbose()) { 2583 SmallString<8> StrVal; 2584 APF.toString(StrVal); 2585 ET->print(AP.OutStreamer->GetCommentOS()); 2586 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2587 } 2588 2589 // Now iterate through the APInt chunks, emitting them in endian-correct 2590 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2591 // floats). 2592 unsigned NumBytes = API.getBitWidth() / 8; 2593 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2594 const uint64_t *p = API.getRawData(); 2595 2596 // PPC's long double has odd notions of endianness compared to how LLVM 2597 // handles it: p[0] goes first for *big* endian on PPC. 2598 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) { 2599 int Chunk = API.getNumWords() - 1; 2600 2601 if (TrailingBytes) 2602 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes); 2603 2604 for (; Chunk >= 0; --Chunk) 2605 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2606 } else { 2607 unsigned Chunk; 2608 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2609 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2610 2611 if (TrailingBytes) 2612 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes); 2613 } 2614 2615 // Emit the tail padding for the long double. 2616 const DataLayout &DL = AP.getDataLayout(); 2617 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET)); 2618 } 2619 2620 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2621 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP); 2622 } 2623 2624 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2625 const DataLayout &DL = AP.getDataLayout(); 2626 unsigned BitWidth = CI->getBitWidth(); 2627 2628 // Copy the value as we may massage the layout for constants whose bit width 2629 // is not a multiple of 64-bits. 2630 APInt Realigned(CI->getValue()); 2631 uint64_t ExtraBits = 0; 2632 unsigned ExtraBitsSize = BitWidth & 63; 2633 2634 if (ExtraBitsSize) { 2635 // The bit width of the data is not a multiple of 64-bits. 2636 // The extra bits are expected to be at the end of the chunk of the memory. 2637 // Little endian: 2638 // * Nothing to be done, just record the extra bits to emit. 2639 // Big endian: 2640 // * Record the extra bits to emit. 2641 // * Realign the raw data to emit the chunks of 64-bits. 2642 if (DL.isBigEndian()) { 2643 // Basically the structure of the raw data is a chunk of 64-bits cells: 2644 // 0 1 BitWidth / 64 2645 // [chunk1][chunk2] ... [chunkN]. 2646 // The most significant chunk is chunkN and it should be emitted first. 2647 // However, due to the alignment issue chunkN contains useless bits. 2648 // Realign the chunks so that they contain only useful information: 2649 // ExtraBits 0 1 (BitWidth / 64) - 1 2650 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2651 ExtraBitsSize = alignTo(ExtraBitsSize, 8); 2652 ExtraBits = Realigned.getRawData()[0] & 2653 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2654 Realigned.lshrInPlace(ExtraBitsSize); 2655 } else 2656 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2657 } 2658 2659 // We don't expect assemblers to support integer data directives 2660 // for more than 64 bits, so we emit the data in at most 64-bit 2661 // quantities at a time. 2662 const uint64_t *RawData = Realigned.getRawData(); 2663 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2664 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2665 AP.OutStreamer->emitIntValue(Val, 8); 2666 } 2667 2668 if (ExtraBitsSize) { 2669 // Emit the extra bits after the 64-bits chunks. 2670 2671 // Emit a directive that fills the expected size. 2672 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType()); 2673 Size -= (BitWidth / 64) * 8; 2674 assert(Size && Size * 8 >= ExtraBitsSize && 2675 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2676 == ExtraBits && "Directive too small for extra bits."); 2677 AP.OutStreamer->emitIntValue(ExtraBits, Size); 2678 } 2679 } 2680 2681 /// Transform a not absolute MCExpr containing a reference to a GOT 2682 /// equivalent global, by a target specific GOT pc relative access to the 2683 /// final symbol. 2684 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2685 const Constant *BaseCst, 2686 uint64_t Offset) { 2687 // The global @foo below illustrates a global that uses a got equivalent. 2688 // 2689 // @bar = global i32 42 2690 // @gotequiv = private unnamed_addr constant i32* @bar 2691 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2692 // i64 ptrtoint (i32* @foo to i64)) 2693 // to i32) 2694 // 2695 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2696 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2697 // form: 2698 // 2699 // foo = cstexpr, where 2700 // cstexpr := <gotequiv> - "." + <cst> 2701 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2702 // 2703 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2704 // 2705 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2706 // gotpcrelcst := <offset from @foo base> + <cst> 2707 MCValue MV; 2708 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2709 return; 2710 const MCSymbolRefExpr *SymA = MV.getSymA(); 2711 if (!SymA) 2712 return; 2713 2714 // Check that GOT equivalent symbol is cached. 2715 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2716 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2717 return; 2718 2719 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2720 if (!BaseGV) 2721 return; 2722 2723 // Check for a valid base symbol 2724 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2725 const MCSymbolRefExpr *SymB = MV.getSymB(); 2726 2727 if (!SymB || BaseSym != &SymB->getSymbol()) 2728 return; 2729 2730 // Make sure to match: 2731 // 2732 // gotpcrelcst := <offset from @foo base> + <cst> 2733 // 2734 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2735 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2736 // if the target knows how to encode it. 2737 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2738 if (GOTPCRelCst < 0) 2739 return; 2740 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2741 return; 2742 2743 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2744 // 2745 // bar: 2746 // .long 42 2747 // gotequiv: 2748 // .quad bar 2749 // foo: 2750 // .long gotequiv - "." + <cst> 2751 // 2752 // is replaced by the target specific equivalent to: 2753 // 2754 // bar: 2755 // .long 42 2756 // foo: 2757 // .long bar@GOTPCREL+<gotpcrelcst> 2758 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2759 const GlobalVariable *GV = Result.first; 2760 int NumUses = (int)Result.second; 2761 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2762 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2763 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2764 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2765 2766 // Update GOT equivalent usage information 2767 --NumUses; 2768 if (NumUses >= 0) 2769 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2770 } 2771 2772 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2773 AsmPrinter &AP, const Constant *BaseCV, 2774 uint64_t Offset) { 2775 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2776 2777 // Globals with sub-elements such as combinations of arrays and structs 2778 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2779 // constant symbol base and the current position with BaseCV and Offset. 2780 if (!BaseCV && CV->hasOneUse()) 2781 BaseCV = dyn_cast<Constant>(CV->user_back()); 2782 2783 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2784 return AP.OutStreamer->emitZeros(Size); 2785 2786 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2787 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType()); 2788 2789 if (StoreSize < 8) { 2790 if (AP.isVerbose()) 2791 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2792 CI->getZExtValue()); 2793 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize); 2794 } else { 2795 emitGlobalConstantLargeInt(CI, AP); 2796 } 2797 2798 // Emit tail padding if needed 2799 if (Size != StoreSize) 2800 AP.OutStreamer->emitZeros(Size - StoreSize); 2801 2802 return; 2803 } 2804 2805 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2806 return emitGlobalConstantFP(CFP, AP); 2807 2808 if (isa<ConstantPointerNull>(CV)) { 2809 AP.OutStreamer->emitIntValue(0, Size); 2810 return; 2811 } 2812 2813 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2814 return emitGlobalConstantDataSequential(DL, CDS, AP); 2815 2816 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2817 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2818 2819 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2820 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2821 2822 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2823 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2824 // vectors). 2825 if (CE->getOpcode() == Instruction::BitCast) 2826 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2827 2828 if (Size > 8) { 2829 // If the constant expression's size is greater than 64-bits, then we have 2830 // to emit the value in chunks. Try to constant fold the value and emit it 2831 // that way. 2832 Constant *New = ConstantFoldConstant(CE, DL); 2833 if (New != CE) 2834 return emitGlobalConstantImpl(DL, New, AP); 2835 } 2836 } 2837 2838 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2839 return emitGlobalConstantVector(DL, V, AP); 2840 2841 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2842 // thread the streamer with EmitValue. 2843 const MCExpr *ME = AP.lowerConstant(CV); 2844 2845 // Since lowerConstant already folded and got rid of all IR pointer and 2846 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2847 // directly. 2848 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2849 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2850 2851 AP.OutStreamer->emitValue(ME, Size); 2852 } 2853 2854 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2855 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2856 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2857 if (Size) 2858 emitGlobalConstantImpl(DL, CV, *this); 2859 else if (MAI->hasSubsectionsViaSymbols()) { 2860 // If the global has zero size, emit a single byte so that two labels don't 2861 // look like they are at the same location. 2862 OutStreamer->emitIntValue(0, 1); 2863 } 2864 } 2865 2866 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2867 // Target doesn't support this yet! 2868 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2869 } 2870 2871 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2872 if (Offset > 0) 2873 OS << '+' << Offset; 2874 else if (Offset < 0) 2875 OS << Offset; 2876 } 2877 2878 void AsmPrinter::emitNops(unsigned N) { 2879 MCInst Nop; 2880 MF->getSubtarget().getInstrInfo()->getNoop(Nop); 2881 for (; N; --N) 2882 EmitToStreamer(*OutStreamer, Nop); 2883 } 2884 2885 //===----------------------------------------------------------------------===// 2886 // Symbol Lowering Routines. 2887 //===----------------------------------------------------------------------===// 2888 2889 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2890 return OutContext.createTempSymbol(Name, true); 2891 } 2892 2893 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2894 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2895 } 2896 2897 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2898 return MMI->getAddrLabelSymbol(BB); 2899 } 2900 2901 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2902 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2903 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) { 2904 const MachineConstantPoolEntry &CPE = 2905 MF->getConstantPool()->getConstants()[CPID]; 2906 if (!CPE.isMachineConstantPoolEntry()) { 2907 const DataLayout &DL = MF->getDataLayout(); 2908 SectionKind Kind = CPE.getSectionKind(&DL); 2909 const Constant *C = CPE.Val.ConstVal; 2910 Align Alignment = CPE.Alignment; 2911 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>( 2912 getObjFileLowering().getSectionForConstant(DL, Kind, C, 2913 Alignment))) { 2914 if (MCSymbol *Sym = S->getCOMDATSymbol()) { 2915 if (Sym->isUndefined()) 2916 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global); 2917 return Sym; 2918 } 2919 } 2920 } 2921 } 2922 2923 const DataLayout &DL = getDataLayout(); 2924 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2925 "CPI" + Twine(getFunctionNumber()) + "_" + 2926 Twine(CPID)); 2927 } 2928 2929 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2930 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2931 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2932 } 2933 2934 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2935 /// FIXME: privatize to AsmPrinter. 2936 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2937 const DataLayout &DL = getDataLayout(); 2938 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2939 Twine(getFunctionNumber()) + "_" + 2940 Twine(UID) + "_set_" + Twine(MBBID)); 2941 } 2942 2943 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2944 StringRef Suffix) const { 2945 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 2946 } 2947 2948 /// Return the MCSymbol for the specified ExternalSymbol. 2949 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2950 SmallString<60> NameStr; 2951 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2952 return OutContext.getOrCreateSymbol(NameStr); 2953 } 2954 2955 /// PrintParentLoopComment - Print comments about parent loops of this one. 2956 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2957 unsigned FunctionNumber) { 2958 if (!Loop) return; 2959 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2960 OS.indent(Loop->getLoopDepth()*2) 2961 << "Parent Loop BB" << FunctionNumber << "_" 2962 << Loop->getHeader()->getNumber() 2963 << " Depth=" << Loop->getLoopDepth() << '\n'; 2964 } 2965 2966 /// PrintChildLoopComment - Print comments about child loops within 2967 /// the loop for this basic block, with nesting. 2968 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2969 unsigned FunctionNumber) { 2970 // Add child loop information 2971 for (const MachineLoop *CL : *Loop) { 2972 OS.indent(CL->getLoopDepth()*2) 2973 << "Child Loop BB" << FunctionNumber << "_" 2974 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2975 << '\n'; 2976 PrintChildLoopComment(OS, CL, FunctionNumber); 2977 } 2978 } 2979 2980 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2981 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2982 const MachineLoopInfo *LI, 2983 const AsmPrinter &AP) { 2984 // Add loop depth information 2985 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2986 if (!Loop) return; 2987 2988 MachineBasicBlock *Header = Loop->getHeader(); 2989 assert(Header && "No header for loop"); 2990 2991 // If this block is not a loop header, just print out what is the loop header 2992 // and return. 2993 if (Header != &MBB) { 2994 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2995 Twine(AP.getFunctionNumber())+"_" + 2996 Twine(Loop->getHeader()->getNumber())+ 2997 " Depth="+Twine(Loop->getLoopDepth())); 2998 return; 2999 } 3000 3001 // Otherwise, it is a loop header. Print out information about child and 3002 // parent loops. 3003 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 3004 3005 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 3006 3007 OS << "=>"; 3008 OS.indent(Loop->getLoopDepth()*2-2); 3009 3010 OS << "This "; 3011 if (Loop->empty()) 3012 OS << "Inner "; 3013 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 3014 3015 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 3016 } 3017 3018 /// emitBasicBlockStart - This method prints the label for the specified 3019 /// MachineBasicBlock, an alignment (if present) and a comment describing 3020 /// it if appropriate. 3021 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 3022 // End the previous funclet and start a new one. 3023 if (MBB.isEHFuncletEntry()) { 3024 for (const HandlerInfo &HI : Handlers) { 3025 HI.Handler->endFunclet(); 3026 HI.Handler->beginFunclet(MBB); 3027 } 3028 } 3029 3030 // Emit an alignment directive for this block, if needed. 3031 const Align Alignment = MBB.getAlignment(); 3032 if (Alignment != Align(1)) 3033 emitAlignment(Alignment); 3034 3035 // If the block has its address taken, emit any labels that were used to 3036 // reference the block. It is possible that there is more than one label 3037 // here, because multiple LLVM BB's may have been RAUW'd to this block after 3038 // the references were generated. 3039 if (MBB.hasAddressTaken()) { 3040 const BasicBlock *BB = MBB.getBasicBlock(); 3041 if (isVerbose()) 3042 OutStreamer->AddComment("Block address taken"); 3043 3044 // MBBs can have their address taken as part of CodeGen without having 3045 // their corresponding BB's address taken in IR 3046 if (BB->hasAddressTaken()) 3047 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 3048 OutStreamer->emitLabel(Sym); 3049 } 3050 3051 // Print some verbose block comments. 3052 if (isVerbose()) { 3053 if (const BasicBlock *BB = MBB.getBasicBlock()) { 3054 if (BB->hasName()) { 3055 BB->printAsOperand(OutStreamer->GetCommentOS(), 3056 /*PrintType=*/false, BB->getModule()); 3057 OutStreamer->GetCommentOS() << '\n'; 3058 } 3059 } 3060 3061 assert(MLI != nullptr && "MachineLoopInfo should has been computed"); 3062 emitBasicBlockLoopComments(MBB, MLI, *this); 3063 } 3064 3065 if (MBB.pred_empty() || 3066 (!MF->hasBBLabels() && isBlockOnlyReachableByFallthrough(&MBB) && 3067 !MBB.isEHFuncletEntry() && !MBB.hasLabelMustBeEmitted())) { 3068 if (isVerbose()) { 3069 // NOTE: Want this comment at start of line, don't emit with AddComment. 3070 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":", 3071 false); 3072 } 3073 } else { 3074 if (isVerbose() && MBB.hasLabelMustBeEmitted()) { 3075 OutStreamer->AddComment("Label of block must be emitted"); 3076 } 3077 // Switch to a new section if this basic block must begin a section. 3078 if (MBB.isBeginSection()) { 3079 OutStreamer->SwitchSection( 3080 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(), 3081 MBB, TM)); 3082 CurrentSectionBeginSym = MBB.getSymbol(); 3083 } 3084 OutStreamer->emitLabel(MBB.getSymbol()); 3085 } 3086 } 3087 3088 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {} 3089 3090 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility, 3091 bool IsDefinition) const { 3092 MCSymbolAttr Attr = MCSA_Invalid; 3093 3094 switch (Visibility) { 3095 default: break; 3096 case GlobalValue::HiddenVisibility: 3097 if (IsDefinition) 3098 Attr = MAI->getHiddenVisibilityAttr(); 3099 else 3100 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 3101 break; 3102 case GlobalValue::ProtectedVisibility: 3103 Attr = MAI->getProtectedVisibilityAttr(); 3104 break; 3105 } 3106 3107 if (Attr != MCSA_Invalid) 3108 OutStreamer->emitSymbolAttribute(Sym, Attr); 3109 } 3110 3111 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 3112 /// exactly one predecessor and the control transfer mechanism between 3113 /// the predecessor and this block is a fall-through. 3114 bool AsmPrinter:: 3115 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 3116 // With BasicBlock Sections, beginning of the section is not a fallthrough. 3117 if (MBB->isBeginSection()) 3118 return false; 3119 3120 // If this is a landing pad, it isn't a fall through. If it has no preds, 3121 // then nothing falls through to it. 3122 if (MBB->isEHPad() || MBB->pred_empty()) 3123 return false; 3124 3125 // If there isn't exactly one predecessor, it can't be a fall through. 3126 if (MBB->pred_size() > 1) 3127 return false; 3128 3129 // The predecessor has to be immediately before this block. 3130 MachineBasicBlock *Pred = *MBB->pred_begin(); 3131 if (!Pred->isLayoutSuccessor(MBB)) 3132 return false; 3133 3134 // If the block is completely empty, then it definitely does fall through. 3135 if (Pred->empty()) 3136 return true; 3137 3138 // Check the terminators in the previous blocks 3139 for (const auto &MI : Pred->terminators()) { 3140 // If it is not a simple branch, we are in a table somewhere. 3141 if (!MI.isBranch() || MI.isIndirectBranch()) 3142 return false; 3143 3144 // If we are the operands of one of the branches, this is not a fall 3145 // through. Note that targets with delay slots will usually bundle 3146 // terminators with the delay slot instruction. 3147 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 3148 if (OP->isJTI()) 3149 return false; 3150 if (OP->isMBB() && OP->getMBB() == MBB) 3151 return false; 3152 } 3153 } 3154 3155 return true; 3156 } 3157 3158 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 3159 if (!S.usesMetadata()) 3160 return nullptr; 3161 3162 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 3163 gcp_map_type::iterator GCPI = GCMap.find(&S); 3164 if (GCPI != GCMap.end()) 3165 return GCPI->second.get(); 3166 3167 auto Name = S.getName(); 3168 3169 for (GCMetadataPrinterRegistry::iterator 3170 I = GCMetadataPrinterRegistry::begin(), 3171 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 3172 if (Name == I->getName()) { 3173 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 3174 GMP->S = &S; 3175 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 3176 return IterBool.first->second.get(); 3177 } 3178 3179 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 3180 } 3181 3182 void AsmPrinter::emitStackMaps(StackMaps &SM) { 3183 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 3184 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 3185 bool NeedsDefault = false; 3186 if (MI->begin() == MI->end()) 3187 // No GC strategy, use the default format. 3188 NeedsDefault = true; 3189 else 3190 for (auto &I : *MI) { 3191 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 3192 if (MP->emitStackMaps(SM, *this)) 3193 continue; 3194 // The strategy doesn't have printer or doesn't emit custom stack maps. 3195 // Use the default format. 3196 NeedsDefault = true; 3197 } 3198 3199 if (NeedsDefault) 3200 SM.serializeToStackMapSection(); 3201 } 3202 3203 /// Pin vtable to this file. 3204 AsmPrinterHandler::~AsmPrinterHandler() = default; 3205 3206 void AsmPrinterHandler::markFunctionEnd() {} 3207 3208 // In the binary's "xray_instr_map" section, an array of these function entries 3209 // describes each instrumentation point. When XRay patches your code, the index 3210 // into this table will be given to your handler as a patch point identifier. 3211 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const { 3212 auto Kind8 = static_cast<uint8_t>(Kind); 3213 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 3214 Out->emitBinaryData( 3215 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 3216 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1)); 3217 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3); 3218 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size"); 3219 Out->emitZeros(Padding); 3220 } 3221 3222 void AsmPrinter::emitXRayTable() { 3223 if (Sleds.empty()) 3224 return; 3225 3226 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 3227 const Function &F = MF->getFunction(); 3228 MCSection *InstMap = nullptr; 3229 MCSection *FnSledIndex = nullptr; 3230 const Triple &TT = TM.getTargetTriple(); 3231 // Use PC-relative addresses on all targets except MIPS (MIPS64 cannot use 3232 // PC-relative addresses because R_MIPS_PC64 does not exist). 3233 bool PCRel = !TT.isMIPS(); 3234 if (TT.isOSBinFormatELF()) { 3235 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3236 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER; 3237 if (!PCRel) 3238 Flags |= ELF::SHF_WRITE; 3239 StringRef GroupName; 3240 if (F.hasComdat()) { 3241 Flags |= ELF::SHF_GROUP; 3242 GroupName = F.getComdat()->getName(); 3243 } 3244 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 3245 Flags, 0, GroupName, 3246 MCSection::NonUniqueID, LinkedToSym); 3247 FnSledIndex = OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, 3248 Flags | ELF::SHF_WRITE, 0, GroupName, 3249 MCSection::NonUniqueID, LinkedToSym); 3250 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 3251 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 3252 SectionKind::getReadOnlyWithRel()); 3253 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0, 3254 SectionKind::getReadOnlyWithRel()); 3255 } else { 3256 llvm_unreachable("Unsupported target"); 3257 } 3258 3259 auto WordSizeBytes = MAI->getCodePointerSize(); 3260 3261 // Now we switch to the instrumentation map section. Because this is done 3262 // per-function, we are able to create an index entry that will represent the 3263 // range of sleds associated with a function. 3264 auto &Ctx = OutContext; 3265 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true); 3266 OutStreamer->SwitchSection(InstMap); 3267 OutStreamer->emitLabel(SledsStart); 3268 for (const auto &Sled : Sleds) { 3269 if (PCRel) { 3270 MCSymbol *Dot = Ctx.createTempSymbol(); 3271 OutStreamer->emitLabel(Dot); 3272 OutStreamer->emitValueImpl( 3273 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx), 3274 MCSymbolRefExpr::create(Dot, Ctx), Ctx), 3275 WordSizeBytes); 3276 OutStreamer->emitValueImpl( 3277 MCBinaryExpr::createSub( 3278 MCSymbolRefExpr::create(CurrentFnBegin, Ctx), 3279 MCBinaryExpr::createAdd( 3280 MCSymbolRefExpr::create(Dot, Ctx), 3281 MCConstantExpr::create(WordSizeBytes, Ctx), Ctx), 3282 Ctx), 3283 WordSizeBytes); 3284 } else { 3285 OutStreamer->emitSymbolValue(Sled.Sled, WordSizeBytes); 3286 OutStreamer->emitSymbolValue(CurrentFnSym, WordSizeBytes); 3287 } 3288 Sled.emit(WordSizeBytes, OutStreamer.get()); 3289 } 3290 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true); 3291 OutStreamer->emitLabel(SledsEnd); 3292 3293 // We then emit a single entry in the index per function. We use the symbols 3294 // that bound the instrumentation map as the range for a specific function. 3295 // Each entry here will be 2 * word size aligned, as we're writing down two 3296 // pointers. This should work for both 32-bit and 64-bit platforms. 3297 OutStreamer->SwitchSection(FnSledIndex); 3298 OutStreamer->emitCodeAlignment(2 * WordSizeBytes); 3299 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false); 3300 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false); 3301 OutStreamer->SwitchSection(PrevSection); 3302 Sleds.clear(); 3303 } 3304 3305 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 3306 SledKind Kind, uint8_t Version) { 3307 const Function &F = MI.getMF()->getFunction(); 3308 auto Attr = F.getFnAttribute("function-instrument"); 3309 bool LogArgs = F.hasFnAttribute("xray-log-args"); 3310 bool AlwaysInstrument = 3311 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 3312 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 3313 Kind = SledKind::LOG_ARGS_ENTER; 3314 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind, 3315 AlwaysInstrument, &F, Version}); 3316 } 3317 3318 void AsmPrinter::emitPatchableFunctionEntries() { 3319 const Function &F = MF->getFunction(); 3320 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0; 3321 (void)F.getFnAttribute("patchable-function-prefix") 3322 .getValueAsString() 3323 .getAsInteger(10, PatchableFunctionPrefix); 3324 (void)F.getFnAttribute("patchable-function-entry") 3325 .getValueAsString() 3326 .getAsInteger(10, PatchableFunctionEntry); 3327 if (!PatchableFunctionPrefix && !PatchableFunctionEntry) 3328 return; 3329 const unsigned PointerSize = getPointerSize(); 3330 if (TM.getTargetTriple().isOSBinFormatELF()) { 3331 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC; 3332 const MCSymbolELF *LinkedToSym = nullptr; 3333 StringRef GroupName; 3334 3335 // GNU as < 2.35 did not support section flag 'o'. Use SHF_LINK_ORDER only 3336 // if we are using the integrated assembler. 3337 if (MAI->useIntegratedAssembler()) { 3338 Flags |= ELF::SHF_LINK_ORDER; 3339 if (F.hasComdat()) { 3340 Flags |= ELF::SHF_GROUP; 3341 GroupName = F.getComdat()->getName(); 3342 } 3343 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3344 } 3345 OutStreamer->SwitchSection(OutContext.getELFSection( 3346 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName, 3347 MCSection::NonUniqueID, LinkedToSym)); 3348 emitAlignment(Align(PointerSize)); 3349 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize); 3350 } 3351 } 3352 3353 uint16_t AsmPrinter::getDwarfVersion() const { 3354 return OutStreamer->getContext().getDwarfVersion(); 3355 } 3356 3357 void AsmPrinter::setDwarfVersion(uint16_t Version) { 3358 OutStreamer->getContext().setDwarfVersion(Version); 3359 } 3360