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