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