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 = FrameInfo.getStackSize(); 1358 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize()); 1359 OutStreamer->emitULEB128IntValue(StackSize); 1360 1361 OutStreamer->PopSection(); 1362 } 1363 1364 void AsmPrinter::emitStackUsage(const MachineFunction &MF) { 1365 const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput; 1366 1367 // OutputFilename empty implies -fstack-usage is not passed. 1368 if (OutputFilename.empty()) 1369 return; 1370 1371 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 1372 uint64_t StackSize = FrameInfo.getStackSize(); 1373 1374 if (StackUsageStream == nullptr) { 1375 std::error_code EC; 1376 StackUsageStream = 1377 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text); 1378 if (EC) { 1379 errs() << "Could not open file: " << EC.message(); 1380 return; 1381 } 1382 } 1383 1384 *StackUsageStream << MF.getFunction().getParent()->getName(); 1385 if (const DISubprogram *DSP = MF.getFunction().getSubprogram()) 1386 *StackUsageStream << ':' << DSP->getLine(); 1387 1388 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t'; 1389 if (FrameInfo.hasVarSizedObjects()) 1390 *StackUsageStream << "dynamic\n"; 1391 else 1392 *StackUsageStream << "static\n"; 1393 } 1394 1395 static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF) { 1396 MachineModuleInfo &MMI = MF.getMMI(); 1397 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo()) 1398 return true; 1399 1400 // We might emit an EH table that uses function begin and end labels even if 1401 // we don't have any landingpads. 1402 if (!MF.getFunction().hasPersonalityFn()) 1403 return false; 1404 return !isNoOpWithoutInvoke( 1405 classifyEHPersonality(MF.getFunction().getPersonalityFn())); 1406 } 1407 1408 /// EmitFunctionBody - This method emits the body and trailer for a 1409 /// function. 1410 void AsmPrinter::emitFunctionBody() { 1411 emitFunctionHeader(); 1412 1413 // Emit target-specific gunk before the function body. 1414 emitFunctionBodyStart(); 1415 1416 if (isVerbose()) { 1417 // Get MachineDominatorTree or compute it on the fly if it's unavailable 1418 MDT = getAnalysisIfAvailable<MachineDominatorTree>(); 1419 if (!MDT) { 1420 OwnedMDT = std::make_unique<MachineDominatorTree>(); 1421 OwnedMDT->getBase().recalculate(*MF); 1422 MDT = OwnedMDT.get(); 1423 } 1424 1425 // Get MachineLoopInfo or compute it on the fly if it's unavailable 1426 MLI = getAnalysisIfAvailable<MachineLoopInfo>(); 1427 if (!MLI) { 1428 OwnedMLI = std::make_unique<MachineLoopInfo>(); 1429 OwnedMLI->getBase().analyze(MDT->getBase()); 1430 MLI = OwnedMLI.get(); 1431 } 1432 } 1433 1434 // Print out code for the function. 1435 bool HasAnyRealCode = false; 1436 int NumInstsInFunction = 0; 1437 1438 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1439 for (auto &MBB : *MF) { 1440 // Print a label for the basic block. 1441 emitBasicBlockStart(MBB); 1442 DenseMap<StringRef, unsigned> MnemonicCounts; 1443 for (auto &MI : MBB) { 1444 // Print the assembly for the instruction. 1445 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 1446 !MI.isDebugInstr()) { 1447 HasAnyRealCode = true; 1448 ++NumInstsInFunction; 1449 } 1450 1451 // If there is a pre-instruction symbol, emit a label for it here. 1452 if (MCSymbol *S = MI.getPreInstrSymbol()) 1453 OutStreamer->emitLabel(S); 1454 1455 for (const HandlerInfo &HI : Handlers) { 1456 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1457 HI.TimerGroupDescription, TimePassesIsEnabled); 1458 HI.Handler->beginInstruction(&MI); 1459 } 1460 1461 if (isVerbose()) 1462 emitComments(MI, OutStreamer->GetCommentOS()); 1463 1464 switch (MI.getOpcode()) { 1465 case TargetOpcode::CFI_INSTRUCTION: 1466 emitCFIInstruction(MI); 1467 break; 1468 case TargetOpcode::LOCAL_ESCAPE: 1469 emitFrameAlloc(MI); 1470 break; 1471 case TargetOpcode::ANNOTATION_LABEL: 1472 case TargetOpcode::EH_LABEL: 1473 case TargetOpcode::GC_LABEL: 1474 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol()); 1475 break; 1476 case TargetOpcode::INLINEASM: 1477 case TargetOpcode::INLINEASM_BR: 1478 emitInlineAsm(&MI); 1479 break; 1480 case TargetOpcode::DBG_VALUE: 1481 case TargetOpcode::DBG_VALUE_LIST: 1482 if (isVerbose()) { 1483 if (!emitDebugValueComment(&MI, *this)) 1484 emitInstruction(&MI); 1485 } 1486 break; 1487 case TargetOpcode::DBG_INSTR_REF: 1488 // This instruction reference will have been resolved to a machine 1489 // location, and a nearby DBG_VALUE created. We can safely ignore 1490 // the instruction reference. 1491 break; 1492 case TargetOpcode::DBG_PHI: 1493 // This instruction is only used to label a program point, it's purely 1494 // meta information. 1495 break; 1496 case TargetOpcode::DBG_LABEL: 1497 if (isVerbose()) { 1498 if (!emitDebugLabelComment(&MI, *this)) 1499 emitInstruction(&MI); 1500 } 1501 break; 1502 case TargetOpcode::IMPLICIT_DEF: 1503 if (isVerbose()) emitImplicitDef(&MI); 1504 break; 1505 case TargetOpcode::KILL: 1506 if (isVerbose()) emitKill(&MI, *this); 1507 break; 1508 case TargetOpcode::PSEUDO_PROBE: 1509 emitPseudoProbe(MI); 1510 break; 1511 case TargetOpcode::ARITH_FENCE: 1512 if (isVerbose()) 1513 OutStreamer->emitRawComment("ARITH_FENCE"); 1514 break; 1515 default: 1516 emitInstruction(&MI); 1517 if (CanDoExtraAnalysis) { 1518 MCInst MCI; 1519 MCI.setOpcode(MI.getOpcode()); 1520 auto Name = OutStreamer->getMnemonic(MCI); 1521 auto I = MnemonicCounts.insert({Name, 0u}); 1522 I.first->second++; 1523 } 1524 break; 1525 } 1526 1527 // If there is a post-instruction symbol, emit a label for it here. 1528 if (MCSymbol *S = MI.getPostInstrSymbol()) 1529 OutStreamer->emitLabel(S); 1530 1531 for (const HandlerInfo &HI : Handlers) { 1532 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1533 HI.TimerGroupDescription, TimePassesIsEnabled); 1534 HI.Handler->endInstruction(); 1535 } 1536 } 1537 1538 // We must emit temporary symbol for the end of this basic block, if either 1539 // we have BBLabels enabled or if this basic blocks marks the end of a 1540 // section. 1541 if (MF->hasBBLabels() || 1542 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection())) 1543 OutStreamer->emitLabel(MBB.getEndSymbol()); 1544 1545 if (MBB.isEndSection()) { 1546 // The size directive for the section containing the entry block is 1547 // handled separately by the function section. 1548 if (!MBB.sameSection(&MF->front())) { 1549 if (MAI->hasDotTypeDotSizeDirective()) { 1550 // Emit the size directive for the basic block section. 1551 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1552 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext), 1553 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext), 1554 OutContext); 1555 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp); 1556 } 1557 MBBSectionRanges[MBB.getSectionIDNum()] = 1558 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()}; 1559 } 1560 } 1561 emitBasicBlockEnd(MBB); 1562 1563 if (CanDoExtraAnalysis) { 1564 // Skip empty blocks. 1565 if (MBB.empty()) 1566 continue; 1567 1568 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix", 1569 MBB.begin()->getDebugLoc(), &MBB); 1570 1571 // Generate instruction mix remark. First, sort counts in descending order 1572 // by count and name. 1573 SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec; 1574 for (auto &KV : MnemonicCounts) 1575 MnemonicVec.emplace_back(KV.first, KV.second); 1576 1577 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A, 1578 const std::pair<StringRef, unsigned> &B) { 1579 if (A.second > B.second) 1580 return true; 1581 if (A.second == B.second) 1582 return StringRef(A.first) < StringRef(B.first); 1583 return false; 1584 }); 1585 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n"; 1586 for (auto &KV : MnemonicVec) { 1587 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str(); 1588 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n"; 1589 } 1590 ORE->emit(R); 1591 } 1592 } 1593 1594 EmittedInsts += NumInstsInFunction; 1595 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount", 1596 MF->getFunction().getSubprogram(), 1597 &MF->front()); 1598 R << ore::NV("NumInstructions", NumInstsInFunction) 1599 << " instructions in function"; 1600 ORE->emit(R); 1601 1602 // If the function is empty and the object file uses .subsections_via_symbols, 1603 // then we need to emit *something* to the function body to prevent the 1604 // labels from collapsing together. Just emit a noop. 1605 // Similarly, don't emit empty functions on Windows either. It can lead to 1606 // duplicate entries (two functions with the same RVA) in the Guard CF Table 1607 // after linking, causing the kernel not to load the binary: 1608 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html 1609 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer. 1610 const Triple &TT = TM.getTargetTriple(); 1611 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() || 1612 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) { 1613 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop(); 1614 1615 // Targets can opt-out of emitting the noop here by leaving the opcode 1616 // unspecified. 1617 if (Noop.getOpcode()) { 1618 OutStreamer->AddComment("avoids zero-length function"); 1619 emitNops(1); 1620 } 1621 } 1622 1623 // Switch to the original section in case basic block sections was used. 1624 OutStreamer->SwitchSection(MF->getSection()); 1625 1626 const Function &F = MF->getFunction(); 1627 for (const auto &BB : F) { 1628 if (!BB.hasAddressTaken()) 1629 continue; 1630 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 1631 if (Sym->isDefined()) 1632 continue; 1633 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 1634 OutStreamer->emitLabel(Sym); 1635 } 1636 1637 // Emit target-specific gunk after the function body. 1638 emitFunctionBodyEnd(); 1639 1640 if (needFuncLabelsForEHOrDebugInfo(*MF) || 1641 MAI->hasDotTypeDotSizeDirective()) { 1642 // Create a symbol for the end of function. 1643 CurrentFnEnd = createTempSymbol("func_end"); 1644 OutStreamer->emitLabel(CurrentFnEnd); 1645 } 1646 1647 // If the target wants a .size directive for the size of the function, emit 1648 // it. 1649 if (MAI->hasDotTypeDotSizeDirective()) { 1650 // We can get the size as difference between the function label and the 1651 // temp label. 1652 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1653 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 1654 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 1655 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 1656 } 1657 1658 for (const HandlerInfo &HI : Handlers) { 1659 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1660 HI.TimerGroupDescription, TimePassesIsEnabled); 1661 HI.Handler->markFunctionEnd(); 1662 } 1663 1664 MBBSectionRanges[MF->front().getSectionIDNum()] = 1665 MBBSectionRange{CurrentFnBegin, CurrentFnEnd}; 1666 1667 // Print out jump tables referenced by the function. 1668 emitJumpTableInfo(); 1669 1670 // Emit post-function debug and/or EH information. 1671 for (const HandlerInfo &HI : Handlers) { 1672 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1673 HI.TimerGroupDescription, TimePassesIsEnabled); 1674 HI.Handler->endFunction(MF); 1675 } 1676 1677 // Emit section containing BB address offsets and their metadata, when 1678 // BB labels are requested for this function. Skip empty functions. 1679 if (MF->hasBBLabels() && HasAnyRealCode) 1680 emitBBAddrMapSection(*MF); 1681 1682 // Emit section containing stack size metadata. 1683 emitStackSizeSection(*MF); 1684 1685 // Emit .su file containing function stack size information. 1686 emitStackUsage(*MF); 1687 1688 emitPatchableFunctionEntries(); 1689 1690 if (isVerbose()) 1691 OutStreamer->GetCommentOS() << "-- End function\n"; 1692 1693 OutStreamer->AddBlankLine(); 1694 } 1695 1696 /// Compute the number of Global Variables that uses a Constant. 1697 static unsigned getNumGlobalVariableUses(const Constant *C) { 1698 if (!C) 1699 return 0; 1700 1701 if (isa<GlobalVariable>(C)) 1702 return 1; 1703 1704 unsigned NumUses = 0; 1705 for (auto *CU : C->users()) 1706 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1707 1708 return NumUses; 1709 } 1710 1711 /// Only consider global GOT equivalents if at least one user is a 1712 /// cstexpr inside an initializer of another global variables. Also, don't 1713 /// handle cstexpr inside instructions. During global variable emission, 1714 /// candidates are skipped and are emitted later in case at least one cstexpr 1715 /// isn't replaced by a PC relative GOT entry access. 1716 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1717 unsigned &NumGOTEquivUsers) { 1718 // Global GOT equivalents are unnamed private globals with a constant 1719 // pointer initializer to another global symbol. They must point to a 1720 // GlobalVariable or Function, i.e., as GlobalValue. 1721 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1722 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1723 !isa<GlobalValue>(GV->getOperand(0))) 1724 return false; 1725 1726 // To be a got equivalent, at least one of its users need to be a constant 1727 // expression used by another global variable. 1728 for (auto *U : GV->users()) 1729 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1730 1731 return NumGOTEquivUsers > 0; 1732 } 1733 1734 /// Unnamed constant global variables solely contaning a pointer to 1735 /// another globals variable is equivalent to a GOT table entry; it contains the 1736 /// the address of another symbol. Optimize it and replace accesses to these 1737 /// "GOT equivalents" by using the GOT entry for the final global instead. 1738 /// Compute GOT equivalent candidates among all global variables to avoid 1739 /// emitting them if possible later on, after it use is replaced by a GOT entry 1740 /// access. 1741 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1742 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1743 return; 1744 1745 for (const auto &G : M.globals()) { 1746 unsigned NumGOTEquivUsers = 0; 1747 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1748 continue; 1749 1750 const MCSymbol *GOTEquivSym = getSymbol(&G); 1751 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1752 } 1753 } 1754 1755 /// Constant expressions using GOT equivalent globals may not be eligible 1756 /// for PC relative GOT entry conversion, in such cases we need to emit such 1757 /// globals we previously omitted in EmitGlobalVariable. 1758 void AsmPrinter::emitGlobalGOTEquivs() { 1759 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1760 return; 1761 1762 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1763 for (auto &I : GlobalGOTEquivs) { 1764 const GlobalVariable *GV = I.second.first; 1765 unsigned Cnt = I.second.second; 1766 if (Cnt) 1767 FailedCandidates.push_back(GV); 1768 } 1769 GlobalGOTEquivs.clear(); 1770 1771 for (auto *GV : FailedCandidates) 1772 emitGlobalVariable(GV); 1773 } 1774 1775 void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) { 1776 MCSymbol *Name = getSymbol(&GA); 1777 bool IsFunction = GA.getValueType()->isFunctionTy(); 1778 // Treat bitcasts of functions as functions also. This is important at least 1779 // on WebAssembly where object and function addresses can't alias each other. 1780 if (!IsFunction) 1781 IsFunction = isa<Function>(GA.getAliasee()->stripPointerCasts()); 1782 1783 // AIX's assembly directive `.set` is not usable for aliasing purpose, 1784 // so AIX has to use the extra-label-at-definition strategy. At this 1785 // point, all the extra label is emitted, we just have to emit linkage for 1786 // those labels. 1787 if (TM.getTargetTriple().isOSBinFormatXCOFF()) { 1788 assert(MAI->hasVisibilityOnlyWithLinkage() && 1789 "Visibility should be handled with emitLinkage() on AIX."); 1790 emitLinkage(&GA, Name); 1791 // If it's a function, also emit linkage for aliases of function entry 1792 // point. 1793 if (IsFunction) 1794 emitLinkage(&GA, 1795 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM)); 1796 return; 1797 } 1798 1799 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1800 OutStreamer->emitSymbolAttribute(Name, MCSA_Global); 1801 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage()) 1802 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference); 1803 else 1804 assert(GA.hasLocalLinkage() && "Invalid alias linkage"); 1805 1806 // Set the symbol type to function if the alias has a function type. 1807 // This affects codegen when the aliasee is not a function. 1808 if (IsFunction) { 1809 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction); 1810 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1811 OutStreamer->BeginCOFFSymbolDef(Name); 1812 OutStreamer->EmitCOFFSymbolStorageClass( 1813 GA.hasLocalLinkage() ? COFF::IMAGE_SYM_CLASS_STATIC 1814 : COFF::IMAGE_SYM_CLASS_EXTERNAL); 1815 OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION 1816 << COFF::SCT_COMPLEX_TYPE_SHIFT); 1817 OutStreamer->EndCOFFSymbolDef(); 1818 } 1819 } 1820 1821 emitVisibility(Name, GA.getVisibility()); 1822 1823 const MCExpr *Expr = lowerConstant(GA.getAliasee()); 1824 1825 if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1826 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry); 1827 1828 // Emit the directives as assignments aka .set: 1829 OutStreamer->emitAssignment(Name, Expr); 1830 MCSymbol *LocalAlias = getSymbolPreferLocal(GA); 1831 if (LocalAlias != Name) 1832 OutStreamer->emitAssignment(LocalAlias, Expr); 1833 1834 // If the aliasee does not correspond to a symbol in the output, i.e. the 1835 // alias is not of an object or the aliased object is private, then set the 1836 // size of the alias symbol from the type of the alias. We don't do this in 1837 // other situations as the alias and aliasee having differing types but same 1838 // size may be intentional. 1839 const GlobalObject *BaseObject = GA.getAliaseeObject(); 1840 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() && 1841 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1842 const DataLayout &DL = M.getDataLayout(); 1843 uint64_t Size = DL.getTypeAllocSize(GA.getValueType()); 1844 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1845 } 1846 } 1847 1848 void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) { 1849 assert(!TM.getTargetTriple().isOSBinFormatXCOFF() && 1850 "IFunc is not supported on AIX."); 1851 1852 MCSymbol *Name = getSymbol(&GI); 1853 1854 if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1855 OutStreamer->emitSymbolAttribute(Name, MCSA_Global); 1856 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage()) 1857 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference); 1858 else 1859 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage"); 1860 1861 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction); 1862 emitVisibility(Name, GI.getVisibility()); 1863 1864 // Emit the directives as assignments aka .set: 1865 const MCExpr *Expr = lowerConstant(GI.getResolver()); 1866 OutStreamer->emitAssignment(Name, Expr); 1867 MCSymbol *LocalAlias = getSymbolPreferLocal(GI); 1868 if (LocalAlias != Name) 1869 OutStreamer->emitAssignment(LocalAlias, Expr); 1870 } 1871 1872 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) { 1873 if (!RS.needsSection()) 1874 return; 1875 1876 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer(); 1877 1878 Optional<SmallString<128>> Filename; 1879 if (Optional<StringRef> FilenameRef = RS.getFilename()) { 1880 Filename = *FilenameRef; 1881 sys::fs::make_absolute(*Filename); 1882 assert(!Filename->empty() && "The filename can't be empty."); 1883 } 1884 1885 std::string Buf; 1886 raw_string_ostream OS(Buf); 1887 std::unique_ptr<remarks::MetaSerializer> MetaSerializer = 1888 Filename ? RemarkSerializer.metaSerializer(OS, Filename->str()) 1889 : RemarkSerializer.metaSerializer(OS); 1890 MetaSerializer->emit(); 1891 1892 // Switch to the remarks section. 1893 MCSection *RemarksSection = 1894 OutContext.getObjectFileInfo()->getRemarksSection(); 1895 OutStreamer->SwitchSection(RemarksSection); 1896 1897 OutStreamer->emitBinaryData(OS.str()); 1898 } 1899 1900 bool AsmPrinter::doFinalization(Module &M) { 1901 // Set the MachineFunction to nullptr so that we can catch attempted 1902 // accesses to MF specific features at the module level and so that 1903 // we can conditionalize accesses based on whether or not it is nullptr. 1904 MF = nullptr; 1905 1906 // Gather all GOT equivalent globals in the module. We really need two 1907 // passes over the globals: one to compute and another to avoid its emission 1908 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1909 // where the got equivalent shows up before its use. 1910 computeGlobalGOTEquivs(M); 1911 1912 // Emit global variables. 1913 for (const auto &G : M.globals()) 1914 emitGlobalVariable(&G); 1915 1916 // Emit remaining GOT equivalent globals. 1917 emitGlobalGOTEquivs(); 1918 1919 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1920 1921 // Emit linkage(XCOFF) and visibility info for declarations 1922 for (const Function &F : M) { 1923 if (!F.isDeclarationForLinker()) 1924 continue; 1925 1926 MCSymbol *Name = getSymbol(&F); 1927 // Function getSymbol gives us the function descriptor symbol for XCOFF. 1928 1929 if (!TM.getTargetTriple().isOSBinFormatXCOFF()) { 1930 GlobalValue::VisibilityTypes V = F.getVisibility(); 1931 if (V == GlobalValue::DefaultVisibility) 1932 continue; 1933 1934 emitVisibility(Name, V, false); 1935 continue; 1936 } 1937 1938 if (F.isIntrinsic()) 1939 continue; 1940 1941 // Handle the XCOFF case. 1942 // Variable `Name` is the function descriptor symbol (see above). Get the 1943 // function entry point symbol. 1944 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM); 1945 // Emit linkage for the function entry point. 1946 emitLinkage(&F, FnEntryPointSym); 1947 1948 // Emit linkage for the function descriptor. 1949 emitLinkage(&F, Name); 1950 } 1951 1952 // Emit the remarks section contents. 1953 // FIXME: Figure out when is the safest time to emit this section. It should 1954 // not come after debug info. 1955 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer()) 1956 emitRemarksSection(*RS); 1957 1958 TLOF.emitModuleMetadata(*OutStreamer, M); 1959 1960 if (TM.getTargetTriple().isOSBinFormatELF()) { 1961 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1962 1963 // Output stubs for external and common global variables. 1964 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1965 if (!Stubs.empty()) { 1966 OutStreamer->SwitchSection(TLOF.getDataSection()); 1967 const DataLayout &DL = M.getDataLayout(); 1968 1969 emitAlignment(Align(DL.getPointerSize())); 1970 for (const auto &Stub : Stubs) { 1971 OutStreamer->emitLabel(Stub.first); 1972 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 1973 DL.getPointerSize()); 1974 } 1975 } 1976 } 1977 1978 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1979 MachineModuleInfoCOFF &MMICOFF = 1980 MMI->getObjFileInfo<MachineModuleInfoCOFF>(); 1981 1982 // Output stubs for external and common global variables. 1983 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList(); 1984 if (!Stubs.empty()) { 1985 const DataLayout &DL = M.getDataLayout(); 1986 1987 for (const auto &Stub : Stubs) { 1988 SmallString<256> SectionName = StringRef(".rdata$"); 1989 SectionName += Stub.first->getName(); 1990 OutStreamer->SwitchSection(OutContext.getCOFFSection( 1991 SectionName, 1992 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | 1993 COFF::IMAGE_SCN_LNK_COMDAT, 1994 SectionKind::getReadOnly(), Stub.first->getName(), 1995 COFF::IMAGE_COMDAT_SELECT_ANY)); 1996 emitAlignment(Align(DL.getPointerSize())); 1997 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global); 1998 OutStreamer->emitLabel(Stub.first); 1999 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 2000 DL.getPointerSize()); 2001 } 2002 } 2003 } 2004 2005 // This needs to happen before emitting debug information since that can end 2006 // arbitrary sections. 2007 if (auto *TS = OutStreamer->getTargetStreamer()) 2008 TS->emitConstantPools(); 2009 2010 // Finalize debug and EH information. 2011 for (const HandlerInfo &HI : Handlers) { 2012 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 2013 HI.TimerGroupDescription, TimePassesIsEnabled); 2014 HI.Handler->endModule(); 2015 } 2016 2017 // This deletes all the ephemeral handlers that AsmPrinter added, while 2018 // keeping all the user-added handlers alive until the AsmPrinter is 2019 // destroyed. 2020 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end()); 2021 DD = nullptr; 2022 2023 // If the target wants to know about weak references, print them all. 2024 if (MAI->getWeakRefDirective()) { 2025 // FIXME: This is not lazy, it would be nice to only print weak references 2026 // to stuff that is actually used. Note that doing so would require targets 2027 // to notice uses in operands (due to constant exprs etc). This should 2028 // happen with the MC stuff eventually. 2029 2030 // Print out module-level global objects here. 2031 for (const auto &GO : M.global_objects()) { 2032 if (!GO.hasExternalWeakLinkage()) 2033 continue; 2034 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 2035 } 2036 if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) { 2037 auto SymbolName = "swift_async_extendedFramePointerFlags"; 2038 auto Global = M.getGlobalVariable(SymbolName); 2039 if (!Global) { 2040 auto Int8PtrTy = Type::getInt8PtrTy(M.getContext()); 2041 Global = new GlobalVariable(M, Int8PtrTy, false, 2042 GlobalValue::ExternalWeakLinkage, nullptr, 2043 SymbolName); 2044 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference); 2045 } 2046 } 2047 } 2048 2049 // Print aliases in topological order, that is, for each alias a = b, 2050 // b must be printed before a. 2051 // This is because on some targets (e.g. PowerPC) linker expects aliases in 2052 // such an order to generate correct TOC information. 2053 SmallVector<const GlobalAlias *, 16> AliasStack; 2054 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 2055 for (const auto &Alias : M.aliases()) { 2056 for (const GlobalAlias *Cur = &Alias; Cur; 2057 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 2058 if (!AliasVisited.insert(Cur).second) 2059 break; 2060 AliasStack.push_back(Cur); 2061 } 2062 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack)) 2063 emitGlobalAlias(M, *AncestorAlias); 2064 AliasStack.clear(); 2065 } 2066 for (const auto &IFunc : M.ifuncs()) 2067 emitGlobalIFunc(M, IFunc); 2068 2069 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 2070 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 2071 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 2072 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 2073 MP->finishAssembly(M, *MI, *this); 2074 2075 // Emit llvm.ident metadata in an '.ident' directive. 2076 emitModuleIdents(M); 2077 2078 // Emit bytes for llvm.commandline metadata. 2079 emitModuleCommandLines(M); 2080 2081 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if 2082 // split-stack is used. 2083 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) { 2084 OutStreamer->SwitchSection( 2085 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0)); 2086 if (HasNoSplitStack) 2087 OutStreamer->SwitchSection( 2088 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0)); 2089 } 2090 2091 // If we don't have any trampolines, then we don't require stack memory 2092 // to be executable. Some targets have a directive to declare this. 2093 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 2094 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 2095 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 2096 OutStreamer->SwitchSection(S); 2097 2098 if (TM.Options.EmitAddrsig) { 2099 // Emit address-significance attributes for all globals. 2100 OutStreamer->emitAddrsig(); 2101 for (const GlobalValue &GV : M.global_values()) { 2102 if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() && 2103 !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() && 2104 !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr()) 2105 OutStreamer->emitAddrsigSym(getSymbol(&GV)); 2106 } 2107 } 2108 2109 // Emit symbol partition specifications (ELF only). 2110 if (TM.getTargetTriple().isOSBinFormatELF()) { 2111 unsigned UniqueID = 0; 2112 for (const GlobalValue &GV : M.global_values()) { 2113 if (!GV.hasPartition() || GV.isDeclarationForLinker() || 2114 GV.getVisibility() != GlobalValue::DefaultVisibility) 2115 continue; 2116 2117 OutStreamer->SwitchSection( 2118 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, 2119 "", false, ++UniqueID, nullptr)); 2120 OutStreamer->emitBytes(GV.getPartition()); 2121 OutStreamer->emitZeros(1); 2122 OutStreamer->emitValue( 2123 MCSymbolRefExpr::create(getSymbol(&GV), OutContext), 2124 MAI->getCodePointerSize()); 2125 } 2126 } 2127 2128 // Allow the target to emit any magic that it wants at the end of the file, 2129 // after everything else has gone out. 2130 emitEndOfAsmFile(M); 2131 2132 MMI = nullptr; 2133 AddrLabelSymbols = nullptr; 2134 2135 OutStreamer->Finish(); 2136 OutStreamer->reset(); 2137 OwnedMLI.reset(); 2138 OwnedMDT.reset(); 2139 2140 return false; 2141 } 2142 2143 MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) { 2144 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum()); 2145 if (Res.second) 2146 Res.first->second = createTempSymbol("exception"); 2147 return Res.first->second; 2148 } 2149 2150 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 2151 this->MF = &MF; 2152 const Function &F = MF.getFunction(); 2153 2154 // Record that there are split-stack functions, so we will emit a special 2155 // section to tell the linker. 2156 if (MF.shouldSplitStack()) { 2157 HasSplitStack = true; 2158 2159 if (!MF.getFrameInfo().needsSplitStackProlog()) 2160 HasNoSplitStack = true; 2161 } else 2162 HasNoSplitStack = true; 2163 2164 // Get the function symbol. 2165 if (!MAI->needsFunctionDescriptors()) { 2166 CurrentFnSym = getSymbol(&MF.getFunction()); 2167 } else { 2168 assert(TM.getTargetTriple().isOSAIX() && 2169 "Only AIX uses the function descriptor hooks."); 2170 // AIX is unique here in that the name of the symbol emitted for the 2171 // function body does not have the same name as the source function's 2172 // C-linkage name. 2173 assert(CurrentFnDescSym && "The function descriptor symbol needs to be" 2174 " initalized first."); 2175 2176 // Get the function entry point symbol. 2177 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM); 2178 } 2179 2180 CurrentFnSymForSize = CurrentFnSym; 2181 CurrentFnBegin = nullptr; 2182 CurrentSectionBeginSym = nullptr; 2183 MBBSectionRanges.clear(); 2184 MBBSectionExceptionSyms.clear(); 2185 bool NeedsLocalForSize = MAI->needsLocalForSize(); 2186 if (F.hasFnAttribute("patchable-function-entry") || 2187 F.hasFnAttribute("function-instrument") || 2188 F.hasFnAttribute("xray-instruction-threshold") || 2189 needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize || 2190 MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) { 2191 CurrentFnBegin = createTempSymbol("func_begin"); 2192 if (NeedsLocalForSize) 2193 CurrentFnSymForSize = CurrentFnBegin; 2194 } 2195 2196 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 2197 } 2198 2199 namespace { 2200 2201 // Keep track the alignment, constpool entries per Section. 2202 struct SectionCPs { 2203 MCSection *S; 2204 Align Alignment; 2205 SmallVector<unsigned, 4> CPEs; 2206 2207 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {} 2208 }; 2209 2210 } // end anonymous namespace 2211 2212 /// EmitConstantPool - Print to the current output stream assembly 2213 /// representations of the constants in the constant pool MCP. This is 2214 /// used to print out constants which have been "spilled to memory" by 2215 /// the code generator. 2216 void AsmPrinter::emitConstantPool() { 2217 const MachineConstantPool *MCP = MF->getConstantPool(); 2218 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 2219 if (CP.empty()) return; 2220 2221 // Calculate sections for constant pool entries. We collect entries to go into 2222 // the same section together to reduce amount of section switch statements. 2223 SmallVector<SectionCPs, 4> CPSections; 2224 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 2225 const MachineConstantPoolEntry &CPE = CP[i]; 2226 Align Alignment = CPE.getAlign(); 2227 2228 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 2229 2230 const Constant *C = nullptr; 2231 if (!CPE.isMachineConstantPoolEntry()) 2232 C = CPE.Val.ConstVal; 2233 2234 MCSection *S = getObjFileLowering().getSectionForConstant( 2235 getDataLayout(), Kind, C, Alignment); 2236 2237 // The number of sections are small, just do a linear search from the 2238 // last section to the first. 2239 bool Found = false; 2240 unsigned SecIdx = CPSections.size(); 2241 while (SecIdx != 0) { 2242 if (CPSections[--SecIdx].S == S) { 2243 Found = true; 2244 break; 2245 } 2246 } 2247 if (!Found) { 2248 SecIdx = CPSections.size(); 2249 CPSections.push_back(SectionCPs(S, Alignment)); 2250 } 2251 2252 if (Alignment > CPSections[SecIdx].Alignment) 2253 CPSections[SecIdx].Alignment = Alignment; 2254 CPSections[SecIdx].CPEs.push_back(i); 2255 } 2256 2257 // Now print stuff into the calculated sections. 2258 const MCSection *CurSection = nullptr; 2259 unsigned Offset = 0; 2260 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 2261 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 2262 unsigned CPI = CPSections[i].CPEs[j]; 2263 MCSymbol *Sym = GetCPISymbol(CPI); 2264 if (!Sym->isUndefined()) 2265 continue; 2266 2267 if (CurSection != CPSections[i].S) { 2268 OutStreamer->SwitchSection(CPSections[i].S); 2269 emitAlignment(Align(CPSections[i].Alignment)); 2270 CurSection = CPSections[i].S; 2271 Offset = 0; 2272 } 2273 2274 MachineConstantPoolEntry CPE = CP[CPI]; 2275 2276 // Emit inter-object padding for alignment. 2277 unsigned NewOffset = alignTo(Offset, CPE.getAlign()); 2278 OutStreamer->emitZeros(NewOffset - Offset); 2279 2280 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout()); 2281 2282 OutStreamer->emitLabel(Sym); 2283 if (CPE.isMachineConstantPoolEntry()) 2284 emitMachineConstantPoolValue(CPE.Val.MachineCPVal); 2285 else 2286 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 2287 } 2288 } 2289 } 2290 2291 // Print assembly representations of the jump tables used by the current 2292 // function. 2293 void AsmPrinter::emitJumpTableInfo() { 2294 const DataLayout &DL = MF->getDataLayout(); 2295 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 2296 if (!MJTI) return; 2297 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 2298 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 2299 if (JT.empty()) return; 2300 2301 // Pick the directive to use to print the jump table entries, and switch to 2302 // the appropriate section. 2303 const Function &F = MF->getFunction(); 2304 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 2305 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 2306 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 2307 F); 2308 if (JTInDiffSection) { 2309 // Drop it in the readonly section. 2310 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM); 2311 OutStreamer->SwitchSection(ReadOnlySection); 2312 } 2313 2314 emitAlignment(Align(MJTI->getEntryAlignment(DL))); 2315 2316 // Jump tables in code sections are marked with a data_region directive 2317 // where that's supported. 2318 if (!JTInDiffSection) 2319 OutStreamer->emitDataRegion(MCDR_DataRegionJT32); 2320 2321 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 2322 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 2323 2324 // If this jump table was deleted, ignore it. 2325 if (JTBBs.empty()) continue; 2326 2327 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 2328 /// emit a .set directive for each unique entry. 2329 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 2330 MAI->doesSetDirectiveSuppressReloc()) { 2331 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 2332 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2333 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 2334 for (const MachineBasicBlock *MBB : JTBBs) { 2335 if (!EmittedSets.insert(MBB).second) 2336 continue; 2337 2338 // .set LJTSet, LBB32-base 2339 const MCExpr *LHS = 2340 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2341 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 2342 MCBinaryExpr::createSub(LHS, Base, 2343 OutContext)); 2344 } 2345 } 2346 2347 // On some targets (e.g. Darwin) we want to emit two consecutive labels 2348 // before each jump table. The first label is never referenced, but tells 2349 // the assembler and linker the extents of the jump table object. The 2350 // second label is actually referenced by the code. 2351 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 2352 // FIXME: This doesn't have to have any specific name, just any randomly 2353 // named and numbered local label started with 'l' would work. Simplify 2354 // GetJTISymbol. 2355 OutStreamer->emitLabel(GetJTISymbol(JTI, true)); 2356 2357 MCSymbol* JTISymbol = GetJTISymbol(JTI); 2358 OutStreamer->emitLabel(JTISymbol); 2359 2360 for (const MachineBasicBlock *MBB : JTBBs) 2361 emitJumpTableEntry(MJTI, MBB, JTI); 2362 } 2363 if (!JTInDiffSection) 2364 OutStreamer->emitDataRegion(MCDR_DataRegionEnd); 2365 } 2366 2367 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 2368 /// current stream. 2369 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI, 2370 const MachineBasicBlock *MBB, 2371 unsigned UID) const { 2372 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 2373 const MCExpr *Value = nullptr; 2374 switch (MJTI->getEntryKind()) { 2375 case MachineJumpTableInfo::EK_Inline: 2376 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 2377 case MachineJumpTableInfo::EK_Custom32: 2378 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 2379 MJTI, MBB, UID, OutContext); 2380 break; 2381 case MachineJumpTableInfo::EK_BlockAddress: 2382 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 2383 // .word LBB123 2384 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2385 break; 2386 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 2387 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 2388 // with a relocation as gp-relative, e.g.: 2389 // .gprel32 LBB123 2390 MCSymbol *MBBSym = MBB->getSymbol(); 2391 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2392 return; 2393 } 2394 2395 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 2396 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 2397 // with a relocation as gp-relative, e.g.: 2398 // .gpdword LBB123 2399 MCSymbol *MBBSym = MBB->getSymbol(); 2400 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2401 return; 2402 } 2403 2404 case MachineJumpTableInfo::EK_LabelDifference32: { 2405 // Each entry is the address of the block minus the address of the jump 2406 // table. This is used for PIC jump tables where gprel32 is not supported. 2407 // e.g.: 2408 // .word LBB123 - LJTI1_2 2409 // If the .set directive avoids relocations, this is emitted as: 2410 // .set L4_5_set_123, LBB123 - LJTI1_2 2411 // .word L4_5_set_123 2412 if (MAI->doesSetDirectiveSuppressReloc()) { 2413 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 2414 OutContext); 2415 break; 2416 } 2417 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2418 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2419 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 2420 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 2421 break; 2422 } 2423 } 2424 2425 assert(Value && "Unknown entry kind!"); 2426 2427 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 2428 OutStreamer->emitValue(Value, EntrySize); 2429 } 2430 2431 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 2432 /// special global used by LLVM. If so, emit it and return true, otherwise 2433 /// do nothing and return false. 2434 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) { 2435 if (GV->getName() == "llvm.used") { 2436 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 2437 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 2438 return true; 2439 } 2440 2441 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 2442 if (GV->getSection() == "llvm.metadata" || 2443 GV->hasAvailableExternallyLinkage()) 2444 return true; 2445 2446 if (!GV->hasAppendingLinkage()) return false; 2447 2448 assert(GV->hasInitializer() && "Not a special LLVM global!"); 2449 2450 if (GV->getName() == "llvm.global_ctors") { 2451 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2452 /* isCtor */ true); 2453 2454 return true; 2455 } 2456 2457 if (GV->getName() == "llvm.global_dtors") { 2458 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2459 /* isCtor */ false); 2460 2461 return true; 2462 } 2463 2464 report_fatal_error("unknown special variable"); 2465 } 2466 2467 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 2468 /// global in the specified llvm.used list. 2469 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) { 2470 // Should be an array of 'i8*'. 2471 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 2472 const GlobalValue *GV = 2473 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 2474 if (GV) 2475 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 2476 } 2477 } 2478 2479 void AsmPrinter::preprocessXXStructorList(const DataLayout &DL, 2480 const Constant *List, 2481 SmallVector<Structor, 8> &Structors) { 2482 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is 2483 // the init priority. 2484 if (!isa<ConstantArray>(List)) 2485 return; 2486 2487 // Gather the structors in a form that's convenient for sorting by priority. 2488 for (Value *O : cast<ConstantArray>(List)->operands()) { 2489 auto *CS = cast<ConstantStruct>(O); 2490 if (CS->getOperand(1)->isNullValue()) 2491 break; // Found a null terminator, skip the rest. 2492 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 2493 if (!Priority) 2494 continue; // Malformed. 2495 Structors.push_back(Structor()); 2496 Structor &S = Structors.back(); 2497 S.Priority = Priority->getLimitedValue(65535); 2498 S.Func = CS->getOperand(1); 2499 if (!CS->getOperand(2)->isNullValue()) { 2500 if (TM.getTargetTriple().isOSAIX()) 2501 llvm::report_fatal_error( 2502 "associated data of XXStructor list is not yet supported on AIX"); 2503 S.ComdatKey = 2504 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 2505 } 2506 } 2507 2508 // Emit the function pointers in the target-specific order 2509 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) { 2510 return L.Priority < R.Priority; 2511 }); 2512 } 2513 2514 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 2515 /// priority. 2516 void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List, 2517 bool IsCtor) { 2518 SmallVector<Structor, 8> Structors; 2519 preprocessXXStructorList(DL, List, Structors); 2520 if (Structors.empty()) 2521 return; 2522 2523 // Emit the structors in reverse order if we are using the .ctor/.dtor 2524 // initialization scheme. 2525 if (!TM.Options.UseInitArray) 2526 std::reverse(Structors.begin(), Structors.end()); 2527 2528 const Align Align = DL.getPointerPrefAlignment(); 2529 for (Structor &S : Structors) { 2530 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 2531 const MCSymbol *KeySym = nullptr; 2532 if (GlobalValue *GV = S.ComdatKey) { 2533 if (GV->isDeclarationForLinker()) 2534 // If the associated variable is not defined in this module 2535 // (it might be available_externally, or have been an 2536 // available_externally definition that was dropped by the 2537 // EliminateAvailableExternally pass), some other TU 2538 // will provide its dynamic initializer. 2539 continue; 2540 2541 KeySym = getSymbol(GV); 2542 } 2543 2544 MCSection *OutputSection = 2545 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 2546 : Obj.getStaticDtorSection(S.Priority, KeySym)); 2547 OutStreamer->SwitchSection(OutputSection); 2548 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 2549 emitAlignment(Align); 2550 emitXXStructor(DL, S.Func); 2551 } 2552 } 2553 2554 void AsmPrinter::emitModuleIdents(Module &M) { 2555 if (!MAI->hasIdentDirective()) 2556 return; 2557 2558 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 2559 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2560 const MDNode *N = NMD->getOperand(i); 2561 assert(N->getNumOperands() == 1 && 2562 "llvm.ident metadata entry can have only one operand"); 2563 const MDString *S = cast<MDString>(N->getOperand(0)); 2564 OutStreamer->emitIdent(S->getString()); 2565 } 2566 } 2567 } 2568 2569 void AsmPrinter::emitModuleCommandLines(Module &M) { 2570 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines(); 2571 if (!CommandLine) 2572 return; 2573 2574 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline"); 2575 if (!NMD || !NMD->getNumOperands()) 2576 return; 2577 2578 OutStreamer->PushSection(); 2579 OutStreamer->SwitchSection(CommandLine); 2580 OutStreamer->emitZeros(1); 2581 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2582 const MDNode *N = NMD->getOperand(i); 2583 assert(N->getNumOperands() == 1 && 2584 "llvm.commandline metadata entry can have only one operand"); 2585 const MDString *S = cast<MDString>(N->getOperand(0)); 2586 OutStreamer->emitBytes(S->getString()); 2587 OutStreamer->emitZeros(1); 2588 } 2589 OutStreamer->PopSection(); 2590 } 2591 2592 //===--------------------------------------------------------------------===// 2593 // Emission and print routines 2594 // 2595 2596 /// Emit a byte directive and value. 2597 /// 2598 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); } 2599 2600 /// Emit a short directive and value. 2601 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); } 2602 2603 /// Emit a long directive and value. 2604 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); } 2605 2606 /// Emit a long long directive and value. 2607 void AsmPrinter::emitInt64(uint64_t Value) const { 2608 OutStreamer->emitInt64(Value); 2609 } 2610 2611 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 2612 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 2613 /// .set if it avoids relocations. 2614 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 2615 unsigned Size) const { 2616 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 2617 } 2618 2619 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 2620 /// where the size in bytes of the directive is specified by Size and Label 2621 /// specifies the label. This implicitly uses .set if it is available. 2622 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 2623 unsigned Size, 2624 bool IsSectionRelative) const { 2625 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 2626 OutStreamer->EmitCOFFSecRel32(Label, Offset); 2627 if (Size > 4) 2628 OutStreamer->emitZeros(Size - 4); 2629 return; 2630 } 2631 2632 // Emit Label+Offset (or just Label if Offset is zero) 2633 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 2634 if (Offset) 2635 Expr = MCBinaryExpr::createAdd( 2636 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 2637 2638 OutStreamer->emitValue(Expr, Size); 2639 } 2640 2641 //===----------------------------------------------------------------------===// 2642 2643 // EmitAlignment - Emit an alignment directive to the specified power of 2644 // two boundary. If a global value is specified, and if that global has 2645 // an explicit alignment requested, it will override the alignment request 2646 // if required for correctness. 2647 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV, 2648 unsigned MaxBytesToEmit) const { 2649 if (GV) 2650 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment); 2651 2652 if (Alignment == Align(1)) 2653 return; // 1-byte aligned: no need to emit alignment. 2654 2655 if (getCurrentSection()->getKind().isText()) { 2656 const MCSubtargetInfo *STI = nullptr; 2657 if (this->MF) 2658 STI = &getSubtargetInfo(); 2659 else 2660 STI = TM.getMCSubtargetInfo(); 2661 OutStreamer->emitCodeAlignment(Alignment.value(), STI, MaxBytesToEmit); 2662 } else 2663 OutStreamer->emitValueToAlignment(Alignment.value(), 0, 1, MaxBytesToEmit); 2664 } 2665 2666 //===----------------------------------------------------------------------===// 2667 // Constant emission. 2668 //===----------------------------------------------------------------------===// 2669 2670 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 2671 MCContext &Ctx = OutContext; 2672 2673 if (CV->isNullValue() || isa<UndefValue>(CV)) 2674 return MCConstantExpr::create(0, Ctx); 2675 2676 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 2677 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 2678 2679 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 2680 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 2681 2682 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 2683 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 2684 2685 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) 2686 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM); 2687 2688 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV)) 2689 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx); 2690 2691 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 2692 if (!CE) { 2693 llvm_unreachable("Unknown constant value to lower!"); 2694 } 2695 2696 switch (CE->getOpcode()) { 2697 case Instruction::AddrSpaceCast: { 2698 const Constant *Op = CE->getOperand(0); 2699 unsigned DstAS = CE->getType()->getPointerAddressSpace(); 2700 unsigned SrcAS = Op->getType()->getPointerAddressSpace(); 2701 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS)) 2702 return lowerConstant(Op); 2703 2704 // Fallthrough to error. 2705 LLVM_FALLTHROUGH; 2706 } 2707 default: { 2708 // If the code isn't optimized, there may be outstanding folding 2709 // opportunities. Attempt to fold the expression using DataLayout as a 2710 // last resort before giving up. 2711 Constant *C = ConstantFoldConstant(CE, getDataLayout()); 2712 if (C != CE) 2713 return lowerConstant(C); 2714 2715 // Otherwise report the problem to the user. 2716 std::string S; 2717 raw_string_ostream OS(S); 2718 OS << "Unsupported expression in static initializer: "; 2719 CE->printAsOperand(OS, /*PrintType=*/false, 2720 !MF ? nullptr : MF->getFunction().getParent()); 2721 report_fatal_error(Twine(OS.str())); 2722 } 2723 case Instruction::GetElementPtr: { 2724 // Generate a symbolic expression for the byte address 2725 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 2726 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 2727 2728 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 2729 if (!OffsetAI) 2730 return Base; 2731 2732 int64_t Offset = OffsetAI.getSExtValue(); 2733 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 2734 Ctx); 2735 } 2736 2737 case Instruction::Trunc: 2738 // We emit the value and depend on the assembler to truncate the generated 2739 // expression properly. This is important for differences between 2740 // blockaddress labels. Since the two labels are in the same function, it 2741 // is reasonable to treat their delta as a 32-bit value. 2742 LLVM_FALLTHROUGH; 2743 case Instruction::BitCast: 2744 return lowerConstant(CE->getOperand(0)); 2745 2746 case Instruction::IntToPtr: { 2747 const DataLayout &DL = getDataLayout(); 2748 2749 // Handle casts to pointers by changing them into casts to the appropriate 2750 // integer type. This promotes constant folding and simplifies this code. 2751 Constant *Op = CE->getOperand(0); 2752 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 2753 false/*ZExt*/); 2754 return lowerConstant(Op); 2755 } 2756 2757 case Instruction::PtrToInt: { 2758 const DataLayout &DL = getDataLayout(); 2759 2760 // Support only foldable casts to/from pointers that can be eliminated by 2761 // changing the pointer to the appropriately sized integer type. 2762 Constant *Op = CE->getOperand(0); 2763 Type *Ty = CE->getType(); 2764 2765 const MCExpr *OpExpr = lowerConstant(Op); 2766 2767 // We can emit the pointer value into this slot if the slot is an 2768 // integer slot equal to the size of the pointer. 2769 // 2770 // If the pointer is larger than the resultant integer, then 2771 // as with Trunc just depend on the assembler to truncate it. 2772 if (DL.getTypeAllocSize(Ty).getFixedSize() <= 2773 DL.getTypeAllocSize(Op->getType()).getFixedSize()) 2774 return OpExpr; 2775 2776 // Otherwise the pointer is smaller than the resultant integer, mask off 2777 // the high bits so we are sure to get a proper truncation if the input is 2778 // a constant expr. 2779 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 2780 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 2781 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 2782 } 2783 2784 case Instruction::Sub: { 2785 GlobalValue *LHSGV; 2786 APInt LHSOffset; 2787 DSOLocalEquivalent *DSOEquiv; 2788 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 2789 getDataLayout(), &DSOEquiv)) { 2790 GlobalValue *RHSGV; 2791 APInt RHSOffset; 2792 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 2793 getDataLayout())) { 2794 const MCExpr *RelocExpr = 2795 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 2796 if (!RelocExpr) { 2797 const MCExpr *LHSExpr = 2798 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx); 2799 if (DSOEquiv && 2800 getObjFileLowering().supportDSOLocalEquivalentLowering()) 2801 LHSExpr = 2802 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM); 2803 RelocExpr = MCBinaryExpr::createSub( 2804 LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 2805 } 2806 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 2807 if (Addend != 0) 2808 RelocExpr = MCBinaryExpr::createAdd( 2809 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 2810 return RelocExpr; 2811 } 2812 } 2813 } 2814 // else fallthrough 2815 LLVM_FALLTHROUGH; 2816 2817 // The MC library also has a right-shift operator, but it isn't consistently 2818 // signed or unsigned between different targets. 2819 case Instruction::Add: 2820 case Instruction::Mul: 2821 case Instruction::SDiv: 2822 case Instruction::SRem: 2823 case Instruction::Shl: 2824 case Instruction::And: 2825 case Instruction::Or: 2826 case Instruction::Xor: { 2827 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2828 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2829 switch (CE->getOpcode()) { 2830 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2831 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2832 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2833 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2834 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2835 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2836 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2837 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2838 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2839 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2840 } 2841 } 2842 } 2843 } 2844 2845 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2846 AsmPrinter &AP, 2847 const Constant *BaseCV = nullptr, 2848 uint64_t Offset = 0); 2849 2850 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2851 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP); 2852 2853 /// isRepeatedByteSequence - Determine whether the given value is 2854 /// composed of a repeated sequence of identical bytes and return the 2855 /// byte value. If it is not a repeated sequence, return -1. 2856 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2857 StringRef Data = V->getRawDataValues(); 2858 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2859 char C = Data[0]; 2860 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2861 if (Data[i] != C) return -1; 2862 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2863 } 2864 2865 /// isRepeatedByteSequence - Determine whether the given value is 2866 /// composed of a repeated sequence of identical bytes and return the 2867 /// byte value. If it is not a repeated sequence, return -1. 2868 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2869 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2870 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2871 assert(Size % 8 == 0); 2872 2873 // Extend the element to take zero padding into account. 2874 APInt Value = CI->getValue().zextOrSelf(Size); 2875 if (!Value.isSplat(8)) 2876 return -1; 2877 2878 return Value.zextOrTrunc(8).getZExtValue(); 2879 } 2880 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2881 // Make sure all array elements are sequences of the same repeated 2882 // byte. 2883 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2884 Constant *Op0 = CA->getOperand(0); 2885 int Byte = isRepeatedByteSequence(Op0, DL); 2886 if (Byte == -1) 2887 return -1; 2888 2889 // All array elements must be equal. 2890 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2891 if (CA->getOperand(i) != Op0) 2892 return -1; 2893 return Byte; 2894 } 2895 2896 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2897 return isRepeatedByteSequence(CDS); 2898 2899 return -1; 2900 } 2901 2902 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2903 const ConstantDataSequential *CDS, 2904 AsmPrinter &AP) { 2905 // See if we can aggregate this into a .fill, if so, emit it as such. 2906 int Value = isRepeatedByteSequence(CDS, DL); 2907 if (Value != -1) { 2908 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2909 // Don't emit a 1-byte object as a .fill. 2910 if (Bytes > 1) 2911 return AP.OutStreamer->emitFill(Bytes, Value); 2912 } 2913 2914 // If this can be emitted with .ascii/.asciz, emit it as such. 2915 if (CDS->isString()) 2916 return AP.OutStreamer->emitBytes(CDS->getAsString()); 2917 2918 // Otherwise, emit the values in successive locations. 2919 unsigned ElementByteSize = CDS->getElementByteSize(); 2920 if (isa<IntegerType>(CDS->getElementType())) { 2921 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2922 if (AP.isVerbose()) 2923 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2924 CDS->getElementAsInteger(i)); 2925 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i), 2926 ElementByteSize); 2927 } 2928 } else { 2929 Type *ET = CDS->getElementType(); 2930 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2931 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP); 2932 } 2933 2934 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2935 unsigned EmittedSize = 2936 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements(); 2937 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!"); 2938 if (unsigned Padding = Size - EmittedSize) 2939 AP.OutStreamer->emitZeros(Padding); 2940 } 2941 2942 static void emitGlobalConstantArray(const DataLayout &DL, 2943 const ConstantArray *CA, AsmPrinter &AP, 2944 const Constant *BaseCV, uint64_t Offset) { 2945 // See if we can aggregate some values. Make sure it can be 2946 // represented as a series of bytes of the constant value. 2947 int Value = isRepeatedByteSequence(CA, DL); 2948 2949 if (Value != -1) { 2950 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2951 AP.OutStreamer->emitFill(Bytes, Value); 2952 } 2953 else { 2954 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2955 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2956 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2957 } 2958 } 2959 } 2960 2961 static void emitGlobalConstantVector(const DataLayout &DL, 2962 const ConstantVector *CV, AsmPrinter &AP) { 2963 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2964 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2965 2966 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2967 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2968 CV->getType()->getNumElements(); 2969 if (unsigned Padding = Size - EmittedSize) 2970 AP.OutStreamer->emitZeros(Padding); 2971 } 2972 2973 static void emitGlobalConstantStruct(const DataLayout &DL, 2974 const ConstantStruct *CS, AsmPrinter &AP, 2975 const Constant *BaseCV, uint64_t Offset) { 2976 // Print the fields in successive locations. Pad to align if needed! 2977 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2978 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2979 uint64_t SizeSoFar = 0; 2980 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2981 const Constant *Field = CS->getOperand(i); 2982 2983 // Print the actual field value. 2984 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2985 2986 // Check if padding is needed and insert one or more 0s. 2987 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2988 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2989 - Layout->getElementOffset(i)) - FieldSize; 2990 SizeSoFar += FieldSize + PadSize; 2991 2992 // Insert padding - this may include padding to increase the size of the 2993 // current field up to the ABI size (if the struct is not packed) as well 2994 // as padding to ensure that the next field starts at the right offset. 2995 AP.OutStreamer->emitZeros(PadSize); 2996 } 2997 assert(SizeSoFar == Layout->getSizeInBytes() && 2998 "Layout of constant struct may be incorrect!"); 2999 } 3000 3001 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) { 3002 assert(ET && "Unknown float type"); 3003 APInt API = APF.bitcastToAPInt(); 3004 3005 // First print a comment with what we think the original floating-point value 3006 // should have been. 3007 if (AP.isVerbose()) { 3008 SmallString<8> StrVal; 3009 APF.toString(StrVal); 3010 ET->print(AP.OutStreamer->GetCommentOS()); 3011 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 3012 } 3013 3014 // Now iterate through the APInt chunks, emitting them in endian-correct 3015 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 3016 // floats). 3017 unsigned NumBytes = API.getBitWidth() / 8; 3018 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 3019 const uint64_t *p = API.getRawData(); 3020 3021 // PPC's long double has odd notions of endianness compared to how LLVM 3022 // handles it: p[0] goes first for *big* endian on PPC. 3023 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) { 3024 int Chunk = API.getNumWords() - 1; 3025 3026 if (TrailingBytes) 3027 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes); 3028 3029 for (; Chunk >= 0; --Chunk) 3030 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 3031 } else { 3032 unsigned Chunk; 3033 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 3034 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 3035 3036 if (TrailingBytes) 3037 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes); 3038 } 3039 3040 // Emit the tail padding for the long double. 3041 const DataLayout &DL = AP.getDataLayout(); 3042 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET)); 3043 } 3044 3045 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 3046 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP); 3047 } 3048 3049 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 3050 const DataLayout &DL = AP.getDataLayout(); 3051 unsigned BitWidth = CI->getBitWidth(); 3052 3053 // Copy the value as we may massage the layout for constants whose bit width 3054 // is not a multiple of 64-bits. 3055 APInt Realigned(CI->getValue()); 3056 uint64_t ExtraBits = 0; 3057 unsigned ExtraBitsSize = BitWidth & 63; 3058 3059 if (ExtraBitsSize) { 3060 // The bit width of the data is not a multiple of 64-bits. 3061 // The extra bits are expected to be at the end of the chunk of the memory. 3062 // Little endian: 3063 // * Nothing to be done, just record the extra bits to emit. 3064 // Big endian: 3065 // * Record the extra bits to emit. 3066 // * Realign the raw data to emit the chunks of 64-bits. 3067 if (DL.isBigEndian()) { 3068 // Basically the structure of the raw data is a chunk of 64-bits cells: 3069 // 0 1 BitWidth / 64 3070 // [chunk1][chunk2] ... [chunkN]. 3071 // The most significant chunk is chunkN and it should be emitted first. 3072 // However, due to the alignment issue chunkN contains useless bits. 3073 // Realign the chunks so that they contain only useful information: 3074 // ExtraBits 0 1 (BitWidth / 64) - 1 3075 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 3076 ExtraBitsSize = alignTo(ExtraBitsSize, 8); 3077 ExtraBits = Realigned.getRawData()[0] & 3078 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 3079 Realigned.lshrInPlace(ExtraBitsSize); 3080 } else 3081 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 3082 } 3083 3084 // We don't expect assemblers to support integer data directives 3085 // for more than 64 bits, so we emit the data in at most 64-bit 3086 // quantities at a time. 3087 const uint64_t *RawData = Realigned.getRawData(); 3088 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 3089 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 3090 AP.OutStreamer->emitIntValue(Val, 8); 3091 } 3092 3093 if (ExtraBitsSize) { 3094 // Emit the extra bits after the 64-bits chunks. 3095 3096 // Emit a directive that fills the expected size. 3097 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType()); 3098 Size -= (BitWidth / 64) * 8; 3099 assert(Size && Size * 8 >= ExtraBitsSize && 3100 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 3101 == ExtraBits && "Directive too small for extra bits."); 3102 AP.OutStreamer->emitIntValue(ExtraBits, Size); 3103 } 3104 } 3105 3106 /// Transform a not absolute MCExpr containing a reference to a GOT 3107 /// equivalent global, by a target specific GOT pc relative access to the 3108 /// final symbol. 3109 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 3110 const Constant *BaseCst, 3111 uint64_t Offset) { 3112 // The global @foo below illustrates a global that uses a got equivalent. 3113 // 3114 // @bar = global i32 42 3115 // @gotequiv = private unnamed_addr constant i32* @bar 3116 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 3117 // i64 ptrtoint (i32* @foo to i64)) 3118 // to i32) 3119 // 3120 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 3121 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 3122 // form: 3123 // 3124 // foo = cstexpr, where 3125 // cstexpr := <gotequiv> - "." + <cst> 3126 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 3127 // 3128 // After canonicalization by evaluateAsRelocatable `ME` turns into: 3129 // 3130 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 3131 // gotpcrelcst := <offset from @foo base> + <cst> 3132 MCValue MV; 3133 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 3134 return; 3135 const MCSymbolRefExpr *SymA = MV.getSymA(); 3136 if (!SymA) 3137 return; 3138 3139 // Check that GOT equivalent symbol is cached. 3140 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 3141 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 3142 return; 3143 3144 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 3145 if (!BaseGV) 3146 return; 3147 3148 // Check for a valid base symbol 3149 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 3150 const MCSymbolRefExpr *SymB = MV.getSymB(); 3151 3152 if (!SymB || BaseSym != &SymB->getSymbol()) 3153 return; 3154 3155 // Make sure to match: 3156 // 3157 // gotpcrelcst := <offset from @foo base> + <cst> 3158 // 3159 // If gotpcrelcst is positive it means that we can safely fold the pc rel 3160 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 3161 // if the target knows how to encode it. 3162 int64_t GOTPCRelCst = Offset + MV.getConstant(); 3163 if (GOTPCRelCst < 0) 3164 return; 3165 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 3166 return; 3167 3168 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 3169 // 3170 // bar: 3171 // .long 42 3172 // gotequiv: 3173 // .quad bar 3174 // foo: 3175 // .long gotequiv - "." + <cst> 3176 // 3177 // is replaced by the target specific equivalent to: 3178 // 3179 // bar: 3180 // .long 42 3181 // foo: 3182 // .long bar@GOTPCREL+<gotpcrelcst> 3183 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 3184 const GlobalVariable *GV = Result.first; 3185 int NumUses = (int)Result.second; 3186 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 3187 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 3188 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 3189 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 3190 3191 // Update GOT equivalent usage information 3192 --NumUses; 3193 if (NumUses >= 0) 3194 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 3195 } 3196 3197 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 3198 AsmPrinter &AP, const Constant *BaseCV, 3199 uint64_t Offset) { 3200 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 3201 3202 // Globals with sub-elements such as combinations of arrays and structs 3203 // are handled recursively by emitGlobalConstantImpl. Keep track of the 3204 // constant symbol base and the current position with BaseCV and Offset. 3205 if (!BaseCV && CV->hasOneUse()) 3206 BaseCV = dyn_cast<Constant>(CV->user_back()); 3207 3208 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 3209 return AP.OutStreamer->emitZeros(Size); 3210 3211 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 3212 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType()); 3213 3214 if (StoreSize <= 8) { 3215 if (AP.isVerbose()) 3216 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 3217 CI->getZExtValue()); 3218 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize); 3219 } else { 3220 emitGlobalConstantLargeInt(CI, AP); 3221 } 3222 3223 // Emit tail padding if needed 3224 if (Size != StoreSize) 3225 AP.OutStreamer->emitZeros(Size - StoreSize); 3226 3227 return; 3228 } 3229 3230 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 3231 return emitGlobalConstantFP(CFP, AP); 3232 3233 if (isa<ConstantPointerNull>(CV)) { 3234 AP.OutStreamer->emitIntValue(0, Size); 3235 return; 3236 } 3237 3238 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 3239 return emitGlobalConstantDataSequential(DL, CDS, AP); 3240 3241 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 3242 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 3243 3244 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 3245 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 3246 3247 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 3248 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 3249 // vectors). 3250 if (CE->getOpcode() == Instruction::BitCast) 3251 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 3252 3253 if (Size > 8) { 3254 // If the constant expression's size is greater than 64-bits, then we have 3255 // to emit the value in chunks. Try to constant fold the value and emit it 3256 // that way. 3257 Constant *New = ConstantFoldConstant(CE, DL); 3258 if (New != CE) 3259 return emitGlobalConstantImpl(DL, New, AP); 3260 } 3261 } 3262 3263 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 3264 return emitGlobalConstantVector(DL, V, AP); 3265 3266 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 3267 // thread the streamer with EmitValue. 3268 const MCExpr *ME = AP.lowerConstant(CV); 3269 3270 // Since lowerConstant already folded and got rid of all IR pointer and 3271 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 3272 // directly. 3273 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 3274 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 3275 3276 AP.OutStreamer->emitValue(ME, Size); 3277 } 3278 3279 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 3280 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) { 3281 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 3282 if (Size) 3283 emitGlobalConstantImpl(DL, CV, *this); 3284 else if (MAI->hasSubsectionsViaSymbols()) { 3285 // If the global has zero size, emit a single byte so that two labels don't 3286 // look like they are at the same location. 3287 OutStreamer->emitIntValue(0, 1); 3288 } 3289 } 3290 3291 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 3292 // Target doesn't support this yet! 3293 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 3294 } 3295 3296 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 3297 if (Offset > 0) 3298 OS << '+' << Offset; 3299 else if (Offset < 0) 3300 OS << Offset; 3301 } 3302 3303 void AsmPrinter::emitNops(unsigned N) { 3304 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop(); 3305 for (; N; --N) 3306 EmitToStreamer(*OutStreamer, Nop); 3307 } 3308 3309 //===----------------------------------------------------------------------===// 3310 // Symbol Lowering Routines. 3311 //===----------------------------------------------------------------------===// 3312 3313 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 3314 return OutContext.createTempSymbol(Name, true); 3315 } 3316 3317 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 3318 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol( 3319 BA->getBasicBlock()); 3320 } 3321 3322 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 3323 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB); 3324 } 3325 3326 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 3327 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 3328 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) { 3329 const MachineConstantPoolEntry &CPE = 3330 MF->getConstantPool()->getConstants()[CPID]; 3331 if (!CPE.isMachineConstantPoolEntry()) { 3332 const DataLayout &DL = MF->getDataLayout(); 3333 SectionKind Kind = CPE.getSectionKind(&DL); 3334 const Constant *C = CPE.Val.ConstVal; 3335 Align Alignment = CPE.Alignment; 3336 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>( 3337 getObjFileLowering().getSectionForConstant(DL, Kind, C, 3338 Alignment))) { 3339 if (MCSymbol *Sym = S->getCOMDATSymbol()) { 3340 if (Sym->isUndefined()) 3341 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global); 3342 return Sym; 3343 } 3344 } 3345 } 3346 } 3347 3348 const DataLayout &DL = getDataLayout(); 3349 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 3350 "CPI" + Twine(getFunctionNumber()) + "_" + 3351 Twine(CPID)); 3352 } 3353 3354 /// GetJTISymbol - Return the symbol for the specified jump table entry. 3355 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 3356 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 3357 } 3358 3359 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 3360 /// FIXME: privatize to AsmPrinter. 3361 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 3362 const DataLayout &DL = getDataLayout(); 3363 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 3364 Twine(getFunctionNumber()) + "_" + 3365 Twine(UID) + "_set_" + Twine(MBBID)); 3366 } 3367 3368 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 3369 StringRef Suffix) const { 3370 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 3371 } 3372 3373 /// Return the MCSymbol for the specified ExternalSymbol. 3374 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 3375 SmallString<60> NameStr; 3376 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 3377 return OutContext.getOrCreateSymbol(NameStr); 3378 } 3379 3380 /// PrintParentLoopComment - Print comments about parent loops of this one. 3381 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 3382 unsigned FunctionNumber) { 3383 if (!Loop) return; 3384 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 3385 OS.indent(Loop->getLoopDepth()*2) 3386 << "Parent Loop BB" << FunctionNumber << "_" 3387 << Loop->getHeader()->getNumber() 3388 << " Depth=" << Loop->getLoopDepth() << '\n'; 3389 } 3390 3391 /// PrintChildLoopComment - Print comments about child loops within 3392 /// the loop for this basic block, with nesting. 3393 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 3394 unsigned FunctionNumber) { 3395 // Add child loop information 3396 for (const MachineLoop *CL : *Loop) { 3397 OS.indent(CL->getLoopDepth()*2) 3398 << "Child Loop BB" << FunctionNumber << "_" 3399 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 3400 << '\n'; 3401 PrintChildLoopComment(OS, CL, FunctionNumber); 3402 } 3403 } 3404 3405 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 3406 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 3407 const MachineLoopInfo *LI, 3408 const AsmPrinter &AP) { 3409 // Add loop depth information 3410 const MachineLoop *Loop = LI->getLoopFor(&MBB); 3411 if (!Loop) return; 3412 3413 MachineBasicBlock *Header = Loop->getHeader(); 3414 assert(Header && "No header for loop"); 3415 3416 // If this block is not a loop header, just print out what is the loop header 3417 // and return. 3418 if (Header != &MBB) { 3419 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 3420 Twine(AP.getFunctionNumber())+"_" + 3421 Twine(Loop->getHeader()->getNumber())+ 3422 " Depth="+Twine(Loop->getLoopDepth())); 3423 return; 3424 } 3425 3426 // Otherwise, it is a loop header. Print out information about child and 3427 // parent loops. 3428 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 3429 3430 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 3431 3432 OS << "=>"; 3433 OS.indent(Loop->getLoopDepth()*2-2); 3434 3435 OS << "This "; 3436 if (Loop->isInnermost()) 3437 OS << "Inner "; 3438 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 3439 3440 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 3441 } 3442 3443 /// emitBasicBlockStart - This method prints the label for the specified 3444 /// MachineBasicBlock, an alignment (if present) and a comment describing 3445 /// it if appropriate. 3446 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 3447 // End the previous funclet and start a new one. 3448 if (MBB.isEHFuncletEntry()) { 3449 for (const HandlerInfo &HI : Handlers) { 3450 HI.Handler->endFunclet(); 3451 HI.Handler->beginFunclet(MBB); 3452 } 3453 } 3454 3455 // Emit an alignment directive for this block, if needed. 3456 const Align Alignment = MBB.getAlignment(); 3457 if (Alignment != Align(1)) 3458 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment()); 3459 3460 // Switch to a new section if this basic block must begin a section. The 3461 // entry block is always placed in the function section and is handled 3462 // separately. 3463 if (MBB.isBeginSection() && !MBB.isEntryBlock()) { 3464 OutStreamer->SwitchSection( 3465 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(), 3466 MBB, TM)); 3467 CurrentSectionBeginSym = MBB.getSymbol(); 3468 } 3469 3470 // If the block has its address taken, emit any labels that were used to 3471 // reference the block. It is possible that there is more than one label 3472 // here, because multiple LLVM BB's may have been RAUW'd to this block after 3473 // the references were generated. 3474 const BasicBlock *BB = MBB.getBasicBlock(); 3475 if (MBB.hasAddressTaken()) { 3476 if (isVerbose()) 3477 OutStreamer->AddComment("Block address taken"); 3478 3479 // MBBs can have their address taken as part of CodeGen without having 3480 // their corresponding BB's address taken in IR 3481 if (BB && BB->hasAddressTaken()) 3482 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB)) 3483 OutStreamer->emitLabel(Sym); 3484 } 3485 3486 // Print some verbose block comments. 3487 if (isVerbose()) { 3488 if (BB) { 3489 if (BB->hasName()) { 3490 BB->printAsOperand(OutStreamer->GetCommentOS(), 3491 /*PrintType=*/false, BB->getModule()); 3492 OutStreamer->GetCommentOS() << '\n'; 3493 } 3494 } 3495 3496 assert(MLI != nullptr && "MachineLoopInfo should has been computed"); 3497 emitBasicBlockLoopComments(MBB, MLI, *this); 3498 } 3499 3500 // Print the main label for the block. 3501 if (shouldEmitLabelForBasicBlock(MBB)) { 3502 if (isVerbose() && MBB.hasLabelMustBeEmitted()) 3503 OutStreamer->AddComment("Label of block must be emitted"); 3504 OutStreamer->emitLabel(MBB.getSymbol()); 3505 } else { 3506 if (isVerbose()) { 3507 // NOTE: Want this comment at start of line, don't emit with AddComment. 3508 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":", 3509 false); 3510 } 3511 } 3512 3513 if (MBB.isEHCatchretTarget() && 3514 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) { 3515 OutStreamer->emitLabel(MBB.getEHCatchretSymbol()); 3516 } 3517 3518 // With BB sections, each basic block must handle CFI information on its own 3519 // if it begins a section (Entry block is handled separately by 3520 // AsmPrinterHandler::beginFunction). 3521 if (MBB.isBeginSection() && !MBB.isEntryBlock()) 3522 for (const HandlerInfo &HI : Handlers) 3523 HI.Handler->beginBasicBlock(MBB); 3524 } 3525 3526 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) { 3527 // Check if CFI information needs to be updated for this MBB with basic block 3528 // sections. 3529 if (MBB.isEndSection()) 3530 for (const HandlerInfo &HI : Handlers) 3531 HI.Handler->endBasicBlock(MBB); 3532 } 3533 3534 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility, 3535 bool IsDefinition) const { 3536 MCSymbolAttr Attr = MCSA_Invalid; 3537 3538 switch (Visibility) { 3539 default: break; 3540 case GlobalValue::HiddenVisibility: 3541 if (IsDefinition) 3542 Attr = MAI->getHiddenVisibilityAttr(); 3543 else 3544 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 3545 break; 3546 case GlobalValue::ProtectedVisibility: 3547 Attr = MAI->getProtectedVisibilityAttr(); 3548 break; 3549 } 3550 3551 if (Attr != MCSA_Invalid) 3552 OutStreamer->emitSymbolAttribute(Sym, Attr); 3553 } 3554 3555 bool AsmPrinter::shouldEmitLabelForBasicBlock( 3556 const MachineBasicBlock &MBB) const { 3557 // With `-fbasic-block-sections=`, a label is needed for every non-entry block 3558 // in the labels mode (option `=labels`) and every section beginning in the 3559 // sections mode (`=all` and `=list=`). 3560 if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock()) 3561 return true; 3562 // A label is needed for any block with at least one predecessor (when that 3563 // predecessor is not the fallthrough predecessor, or if it is an EH funclet 3564 // entry, or if a label is forced). 3565 return !MBB.pred_empty() && 3566 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() || 3567 MBB.hasLabelMustBeEmitted()); 3568 } 3569 3570 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 3571 /// exactly one predecessor and the control transfer mechanism between 3572 /// the predecessor and this block is a fall-through. 3573 bool AsmPrinter:: 3574 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 3575 // If this is a landing pad, it isn't a fall through. If it has no preds, 3576 // then nothing falls through to it. 3577 if (MBB->isEHPad() || MBB->pred_empty()) 3578 return false; 3579 3580 // If there isn't exactly one predecessor, it can't be a fall through. 3581 if (MBB->pred_size() > 1) 3582 return false; 3583 3584 // The predecessor has to be immediately before this block. 3585 MachineBasicBlock *Pred = *MBB->pred_begin(); 3586 if (!Pred->isLayoutSuccessor(MBB)) 3587 return false; 3588 3589 // If the block is completely empty, then it definitely does fall through. 3590 if (Pred->empty()) 3591 return true; 3592 3593 // Check the terminators in the previous blocks 3594 for (const auto &MI : Pred->terminators()) { 3595 // If it is not a simple branch, we are in a table somewhere. 3596 if (!MI.isBranch() || MI.isIndirectBranch()) 3597 return false; 3598 3599 // If we are the operands of one of the branches, this is not a fall 3600 // through. Note that targets with delay slots will usually bundle 3601 // terminators with the delay slot instruction. 3602 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 3603 if (OP->isJTI()) 3604 return false; 3605 if (OP->isMBB() && OP->getMBB() == MBB) 3606 return false; 3607 } 3608 } 3609 3610 return true; 3611 } 3612 3613 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 3614 if (!S.usesMetadata()) 3615 return nullptr; 3616 3617 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 3618 gcp_map_type::iterator GCPI = GCMap.find(&S); 3619 if (GCPI != GCMap.end()) 3620 return GCPI->second.get(); 3621 3622 auto Name = S.getName(); 3623 3624 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter : 3625 GCMetadataPrinterRegistry::entries()) 3626 if (Name == GCMetaPrinter.getName()) { 3627 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate(); 3628 GMP->S = &S; 3629 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 3630 return IterBool.first->second.get(); 3631 } 3632 3633 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 3634 } 3635 3636 void AsmPrinter::emitStackMaps(StackMaps &SM) { 3637 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 3638 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 3639 bool NeedsDefault = false; 3640 if (MI->begin() == MI->end()) 3641 // No GC strategy, use the default format. 3642 NeedsDefault = true; 3643 else 3644 for (auto &I : *MI) { 3645 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 3646 if (MP->emitStackMaps(SM, *this)) 3647 continue; 3648 // The strategy doesn't have printer or doesn't emit custom stack maps. 3649 // Use the default format. 3650 NeedsDefault = true; 3651 } 3652 3653 if (NeedsDefault) 3654 SM.serializeToStackMapSection(); 3655 } 3656 3657 /// Pin vtable to this file. 3658 AsmPrinterHandler::~AsmPrinterHandler() = default; 3659 3660 void AsmPrinterHandler::markFunctionEnd() {} 3661 3662 // In the binary's "xray_instr_map" section, an array of these function entries 3663 // describes each instrumentation point. When XRay patches your code, the index 3664 // into this table will be given to your handler as a patch point identifier. 3665 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const { 3666 auto Kind8 = static_cast<uint8_t>(Kind); 3667 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 3668 Out->emitBinaryData( 3669 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 3670 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1)); 3671 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3); 3672 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size"); 3673 Out->emitZeros(Padding); 3674 } 3675 3676 void AsmPrinter::emitXRayTable() { 3677 if (Sleds.empty()) 3678 return; 3679 3680 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 3681 const Function &F = MF->getFunction(); 3682 MCSection *InstMap = nullptr; 3683 MCSection *FnSledIndex = nullptr; 3684 const Triple &TT = TM.getTargetTriple(); 3685 // Use PC-relative addresses on all targets. 3686 if (TT.isOSBinFormatELF()) { 3687 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3688 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER; 3689 StringRef GroupName; 3690 if (F.hasComdat()) { 3691 Flags |= ELF::SHF_GROUP; 3692 GroupName = F.getComdat()->getName(); 3693 } 3694 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 3695 Flags, 0, GroupName, F.hasComdat(), 3696 MCSection::NonUniqueID, LinkedToSym); 3697 3698 if (!TM.Options.XRayOmitFunctionIndex) 3699 FnSledIndex = OutContext.getELFSection( 3700 "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0, 3701 GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym); 3702 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 3703 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 3704 SectionKind::getReadOnlyWithRel()); 3705 if (!TM.Options.XRayOmitFunctionIndex) 3706 FnSledIndex = OutContext.getMachOSection( 3707 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel()); 3708 } else { 3709 llvm_unreachable("Unsupported target"); 3710 } 3711 3712 auto WordSizeBytes = MAI->getCodePointerSize(); 3713 3714 // Now we switch to the instrumentation map section. Because this is done 3715 // per-function, we are able to create an index entry that will represent the 3716 // range of sleds associated with a function. 3717 auto &Ctx = OutContext; 3718 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true); 3719 OutStreamer->SwitchSection(InstMap); 3720 OutStreamer->emitLabel(SledsStart); 3721 for (const auto &Sled : Sleds) { 3722 MCSymbol *Dot = Ctx.createTempSymbol(); 3723 OutStreamer->emitLabel(Dot); 3724 OutStreamer->emitValueImpl( 3725 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx), 3726 MCSymbolRefExpr::create(Dot, Ctx), Ctx), 3727 WordSizeBytes); 3728 OutStreamer->emitValueImpl( 3729 MCBinaryExpr::createSub( 3730 MCSymbolRefExpr::create(CurrentFnBegin, Ctx), 3731 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx), 3732 MCConstantExpr::create(WordSizeBytes, Ctx), 3733 Ctx), 3734 Ctx), 3735 WordSizeBytes); 3736 Sled.emit(WordSizeBytes, OutStreamer.get()); 3737 } 3738 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true); 3739 OutStreamer->emitLabel(SledsEnd); 3740 3741 // We then emit a single entry in the index per function. We use the symbols 3742 // that bound the instrumentation map as the range for a specific function. 3743 // Each entry here will be 2 * word size aligned, as we're writing down two 3744 // pointers. This should work for both 32-bit and 64-bit platforms. 3745 if (FnSledIndex) { 3746 OutStreamer->SwitchSection(FnSledIndex); 3747 OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo()); 3748 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false); 3749 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false); 3750 OutStreamer->SwitchSection(PrevSection); 3751 } 3752 Sleds.clear(); 3753 } 3754 3755 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 3756 SledKind Kind, uint8_t Version) { 3757 const Function &F = MI.getMF()->getFunction(); 3758 auto Attr = F.getFnAttribute("function-instrument"); 3759 bool LogArgs = F.hasFnAttribute("xray-log-args"); 3760 bool AlwaysInstrument = 3761 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 3762 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 3763 Kind = SledKind::LOG_ARGS_ENTER; 3764 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind, 3765 AlwaysInstrument, &F, Version}); 3766 } 3767 3768 void AsmPrinter::emitPatchableFunctionEntries() { 3769 const Function &F = MF->getFunction(); 3770 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0; 3771 (void)F.getFnAttribute("patchable-function-prefix") 3772 .getValueAsString() 3773 .getAsInteger(10, PatchableFunctionPrefix); 3774 (void)F.getFnAttribute("patchable-function-entry") 3775 .getValueAsString() 3776 .getAsInteger(10, PatchableFunctionEntry); 3777 if (!PatchableFunctionPrefix && !PatchableFunctionEntry) 3778 return; 3779 const unsigned PointerSize = getPointerSize(); 3780 if (TM.getTargetTriple().isOSBinFormatELF()) { 3781 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC; 3782 const MCSymbolELF *LinkedToSym = nullptr; 3783 StringRef GroupName; 3784 3785 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not 3786 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections. 3787 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) { 3788 Flags |= ELF::SHF_LINK_ORDER; 3789 if (F.hasComdat()) { 3790 Flags |= ELF::SHF_GROUP; 3791 GroupName = F.getComdat()->getName(); 3792 } 3793 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3794 } 3795 OutStreamer->SwitchSection(OutContext.getELFSection( 3796 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName, 3797 F.hasComdat(), MCSection::NonUniqueID, LinkedToSym)); 3798 emitAlignment(Align(PointerSize)); 3799 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize); 3800 } 3801 } 3802 3803 uint16_t AsmPrinter::getDwarfVersion() const { 3804 return OutStreamer->getContext().getDwarfVersion(); 3805 } 3806 3807 void AsmPrinter::setDwarfVersion(uint16_t Version) { 3808 OutStreamer->getContext().setDwarfVersion(Version); 3809 } 3810 3811 bool AsmPrinter::isDwarf64() const { 3812 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64; 3813 } 3814 3815 unsigned int AsmPrinter::getDwarfOffsetByteSize() const { 3816 return dwarf::getDwarfOffsetByteSize( 3817 OutStreamer->getContext().getDwarfFormat()); 3818 } 3819 3820 dwarf::FormParams AsmPrinter::getDwarfFormParams() const { 3821 return {getDwarfVersion(), uint8_t(getPointerSize()), 3822 OutStreamer->getContext().getDwarfFormat(), 3823 MAI->doesDwarfUseRelocationsAcrossSections()}; 3824 } 3825 3826 unsigned int AsmPrinter::getUnitLengthFieldByteSize() const { 3827 return dwarf::getUnitLengthFieldByteSize( 3828 OutStreamer->getContext().getDwarfFormat()); 3829 } 3830