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