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