1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the AsmPrinter class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/AsmPrinter.h" 15 #include "CodeViewDebug.h" 16 #include "DwarfDebug.h" 17 #include "DwarfException.h" 18 #include "WinException.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/ConstantFolding.h" 21 #include "llvm/CodeGen/Analysis.h" 22 #include "llvm/CodeGen/GCMetadataPrinter.h" 23 #include "llvm/CodeGen/MachineConstantPool.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBundle.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/Mangler.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/MC/MCAsmInfo.h" 36 #include "llvm/MC/MCContext.h" 37 #include "llvm/MC/MCExpr.h" 38 #include "llvm/MC/MCInst.h" 39 #include "llvm/MC/MCSection.h" 40 #include "llvm/MC/MCSectionELF.h" 41 #include "llvm/MC/MCSectionMachO.h" 42 #include "llvm/MC/MCStreamer.h" 43 #include "llvm/MC/MCSymbolELF.h" 44 #include "llvm/MC/MCValue.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/Format.h" 47 #include "llvm/Support/MathExtras.h" 48 #include "llvm/Support/TargetRegistry.h" 49 #include "llvm/Support/Timer.h" 50 #include "llvm/Target/TargetFrameLowering.h" 51 #include "llvm/Target/TargetInstrInfo.h" 52 #include "llvm/Target/TargetLowering.h" 53 #include "llvm/Target/TargetLoweringObjectFile.h" 54 #include "llvm/Target/TargetRegisterInfo.h" 55 #include "llvm/Target/TargetSubtargetInfo.h" 56 using namespace llvm; 57 58 #define DEBUG_TYPE "asm-printer" 59 60 static const char *const DWARFGroupName = "dwarf"; 61 static const char *const DWARFGroupDescription = "DWARF Emission"; 62 static const char *const DbgTimerName = "emit"; 63 static const char *const DbgTimerDescription = "Debug Info Emission"; 64 static const char *const EHTimerName = "write_exception"; 65 static const char *const EHTimerDescription = "DWARF Exception Writer"; 66 static const char *const CodeViewLineTablesGroupName = "linetables"; 67 static const char *const CodeViewLineTablesGroupDescription = 68 "CodeView Line Tables"; 69 70 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 71 72 char AsmPrinter::ID = 0; 73 74 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type; 75 static gcp_map_type &getGCMap(void *&P) { 76 if (!P) 77 P = new gcp_map_type(); 78 return *(gcp_map_type*)P; 79 } 80 81 82 /// getGVAlignmentLog2 - Return the alignment to use for the specified global 83 /// value in log2 form. This rounds up to the preferred alignment if possible 84 /// and legal. 85 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL, 86 unsigned InBits = 0) { 87 unsigned NumBits = 0; 88 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 89 NumBits = DL.getPreferredAlignmentLog(GVar); 90 91 // If InBits is specified, round it to it. 92 if (InBits > NumBits) 93 NumBits = InBits; 94 95 // If the GV has a specified alignment, take it into account. 96 if (GV->getAlignment() == 0) 97 return NumBits; 98 99 unsigned GVAlign = Log2_32(GV->getAlignment()); 100 101 // If the GVAlign is larger than NumBits, or if we are required to obey 102 // NumBits because the GV has an assigned section, obey it. 103 if (GVAlign > NumBits || GV->hasSection()) 104 NumBits = GVAlign; 105 return NumBits; 106 } 107 108 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 109 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 110 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)), 111 isCFIMoveForDebugging(false), LastMI(nullptr), LastFn(0), Counter(~0U) { 112 DD = nullptr; 113 MMI = nullptr; 114 LI = nullptr; 115 MF = nullptr; 116 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr; 117 CurrentFnBegin = nullptr; 118 CurrentFnEnd = nullptr; 119 GCMetadataPrinters = nullptr; 120 VerboseAsm = OutStreamer->isVerboseAsm(); 121 } 122 123 AsmPrinter::~AsmPrinter() { 124 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 125 126 if (GCMetadataPrinters) { 127 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 128 129 delete &GCMap; 130 GCMetadataPrinters = nullptr; 131 } 132 } 133 134 bool AsmPrinter::isPositionIndependent() const { 135 return TM.isPositionIndependent(); 136 } 137 138 /// getFunctionNumber - Return a unique ID for the current function. 139 /// 140 unsigned AsmPrinter::getFunctionNumber() const { 141 return MF->getFunctionNumber(); 142 } 143 144 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 145 return *TM.getObjFileLowering(); 146 } 147 148 const DataLayout &AsmPrinter::getDataLayout() const { 149 return MMI->getModule()->getDataLayout(); 150 } 151 152 // Do not use the cached DataLayout because some client use it without a Module 153 // (llvm-dsymutil, llvm-dwarfdump). 154 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); } 155 156 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 157 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 158 return MF->getSubtarget<MCSubtargetInfo>(); 159 } 160 161 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 162 S.EmitInstruction(Inst, getSubtargetInfo()); 163 } 164 165 /// getCurrentSection() - Return the current section we are emitting to. 166 const MCSection *AsmPrinter::getCurrentSection() const { 167 return OutStreamer->getCurrentSectionOnly(); 168 } 169 170 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 171 AU.setPreservesAll(); 172 MachineFunctionPass::getAnalysisUsage(AU); 173 AU.addRequired<MachineModuleInfo>(); 174 AU.addRequired<GCModuleInfo>(); 175 if (isVerbose()) 176 AU.addRequired<MachineLoopInfo>(); 177 } 178 179 bool AsmPrinter::doInitialization(Module &M) { 180 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 181 182 // Initialize TargetLoweringObjectFile. 183 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 184 .Initialize(OutContext, TM); 185 186 OutStreamer->InitSections(false); 187 188 // Emit the version-min deplyment target directive if needed. 189 // 190 // FIXME: If we end up with a collection of these sorts of Darwin-specific 191 // or ELF-specific things, it may make sense to have a platform helper class 192 // that will work with the target helper class. For now keep it here, as the 193 // alternative is duplicated code in each of the target asm printers that 194 // use the directive, where it would need the same conditionalization 195 // anyway. 196 const Triple &TT = TM.getTargetTriple(); 197 // If there is a version specified, Major will be non-zero. 198 if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) { 199 unsigned Major, Minor, Update; 200 MCVersionMinType VersionType; 201 if (TT.isWatchOS()) { 202 VersionType = MCVM_WatchOSVersionMin; 203 TT.getWatchOSVersion(Major, Minor, Update); 204 } else if (TT.isTvOS()) { 205 VersionType = MCVM_TvOSVersionMin; 206 TT.getiOSVersion(Major, Minor, Update); 207 } else if (TT.isMacOSX()) { 208 VersionType = MCVM_OSXVersionMin; 209 if (!TT.getMacOSXVersion(Major, Minor, Update)) 210 Major = 0; 211 } else { 212 VersionType = MCVM_IOSVersionMin; 213 TT.getiOSVersion(Major, Minor, Update); 214 } 215 if (Major != 0) 216 OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update); 217 } 218 219 // Allow the target to emit any magic that it wants at the start of the file. 220 EmitStartOfAsmFile(M); 221 222 // Very minimal debug info. It is ignored if we emit actual debug info. If we 223 // don't, this at least helps the user find where a global came from. 224 if (MAI->hasSingleParameterDotFile()) { 225 // .file "foo.c" 226 OutStreamer->EmitFileDirective(M.getModuleIdentifier()); 227 } 228 229 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 230 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 231 for (auto &I : *MI) 232 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 233 MP->beginAssembly(M, *MI, *this); 234 235 // Emit module-level inline asm if it exists. 236 if (!M.getModuleInlineAsm().empty()) { 237 // We're at the module level. Construct MCSubtarget from the default CPU 238 // and target triple. 239 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 240 TM.getTargetTriple().str(), TM.getTargetCPU(), 241 TM.getTargetFeatureString())); 242 OutStreamer->AddComment("Start of file scope inline assembly"); 243 OutStreamer->AddBlankLine(); 244 EmitInlineAsm(M.getModuleInlineAsm()+"\n", 245 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 246 OutStreamer->AddComment("End of file scope inline assembly"); 247 OutStreamer->AddBlankLine(); 248 } 249 250 if (MAI->doesSupportDebugInformation()) { 251 bool EmitCodeView = MMI->getModule()->getCodeViewFlag(); 252 if (EmitCodeView && (TM.getTargetTriple().isKnownWindowsMSVCEnvironment() || 253 TM.getTargetTriple().isWindowsItaniumEnvironment())) { 254 Handlers.push_back(HandlerInfo(new CodeViewDebug(this), 255 DbgTimerName, DbgTimerDescription, 256 CodeViewLineTablesGroupName, 257 CodeViewLineTablesGroupDescription)); 258 } 259 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) { 260 DD = new DwarfDebug(this, &M); 261 DD->beginModule(); 262 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DbgTimerDescription, 263 DWARFGroupName, DWARFGroupDescription)); 264 } 265 } 266 267 switch (MAI->getExceptionHandlingType()) { 268 case ExceptionHandling::SjLj: 269 case ExceptionHandling::DwarfCFI: 270 case ExceptionHandling::ARM: 271 isCFIMoveForDebugging = true; 272 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 273 break; 274 for (auto &F: M.getFunctionList()) { 275 // If the module contains any function with unwind data, 276 // .eh_frame has to be emitted. 277 // Ignore functions that won't get emitted. 278 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) { 279 isCFIMoveForDebugging = false; 280 break; 281 } 282 } 283 break; 284 default: 285 isCFIMoveForDebugging = false; 286 break; 287 } 288 289 EHStreamer *ES = nullptr; 290 switch (MAI->getExceptionHandlingType()) { 291 case ExceptionHandling::None: 292 break; 293 case ExceptionHandling::SjLj: 294 case ExceptionHandling::DwarfCFI: 295 ES = new DwarfCFIException(this); 296 break; 297 case ExceptionHandling::ARM: 298 ES = new ARMException(this); 299 break; 300 case ExceptionHandling::WinEH: 301 switch (MAI->getWinEHEncodingType()) { 302 default: llvm_unreachable("unsupported unwinding information encoding"); 303 case WinEH::EncodingType::Invalid: 304 break; 305 case WinEH::EncodingType::X86: 306 case WinEH::EncodingType::Itanium: 307 ES = new WinException(this); 308 break; 309 } 310 break; 311 } 312 if (ES) 313 Handlers.push_back(HandlerInfo(ES, EHTimerName, EHTimerDescription, 314 DWARFGroupName, DWARFGroupDescription)); 315 return false; 316 } 317 318 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 319 if (!MAI.hasWeakDefCanBeHiddenDirective()) 320 return false; 321 322 return canBeOmittedFromSymbolTable(GV); 323 } 324 325 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 326 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 327 switch (Linkage) { 328 case GlobalValue::CommonLinkage: 329 case GlobalValue::LinkOnceAnyLinkage: 330 case GlobalValue::LinkOnceODRLinkage: 331 case GlobalValue::WeakAnyLinkage: 332 case GlobalValue::WeakODRLinkage: 333 if (MAI->hasWeakDefDirective()) { 334 // .globl _foo 335 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 336 337 if (!canBeHidden(GV, *MAI)) 338 // .weak_definition _foo 339 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 340 else 341 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 342 } else if (MAI->hasLinkOnceDirective()) { 343 // .globl _foo 344 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 345 //NOTE: linkonce is handled by the section the symbol was assigned to. 346 } else { 347 // .weak _foo 348 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak); 349 } 350 return; 351 case GlobalValue::ExternalLinkage: 352 // If external, declare as a global symbol: .globl _foo 353 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 354 return; 355 case GlobalValue::PrivateLinkage: 356 case GlobalValue::InternalLinkage: 357 return; 358 case GlobalValue::AppendingLinkage: 359 case GlobalValue::AvailableExternallyLinkage: 360 case GlobalValue::ExternalWeakLinkage: 361 llvm_unreachable("Should never emit this"); 362 } 363 llvm_unreachable("Unknown linkage type!"); 364 } 365 366 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 367 const GlobalValue *GV) const { 368 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler()); 369 } 370 371 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 372 return TM.getSymbol(GV); 373 } 374 375 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 376 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 377 bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal(); 378 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 379 "No emulated TLS variables in the common section"); 380 381 // Never emit TLS variable xyz in emulated TLS model. 382 // The initialization value is in __emutls_t.xyz instead of xyz. 383 if (IsEmuTLSVar) 384 return; 385 386 if (GV->hasInitializer()) { 387 // Check to see if this is a special global used by LLVM, if so, emit it. 388 if (EmitSpecialLLVMGlobal(GV)) 389 return; 390 391 // Skip the emission of global equivalents. The symbol can be emitted later 392 // on by emitGlobalGOTEquivs in case it turns out to be needed. 393 if (GlobalGOTEquivs.count(getSymbol(GV))) 394 return; 395 396 if (isVerbose()) { 397 // When printing the control variable __emutls_v.*, 398 // we don't need to print the original TLS variable name. 399 GV->printAsOperand(OutStreamer->GetCommentOS(), 400 /*PrintType=*/false, GV->getParent()); 401 OutStreamer->GetCommentOS() << '\n'; 402 } 403 } 404 405 MCSymbol *GVSym = getSymbol(GV); 406 MCSymbol *EmittedSym = GVSym; 407 408 // getOrCreateEmuTLSControlSym only creates the symbol with name and default 409 // attributes. 410 // GV's or GVSym's attributes will be used for the EmittedSym. 411 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 412 413 if (!GV->hasInitializer()) // External globals require no extra code. 414 return; 415 416 GVSym->redefineIfPossible(); 417 if (GVSym->isDefined() || GVSym->isVariable()) 418 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 419 "' is already defined"); 420 421 if (MAI->hasDotTypeDotSizeDirective()) 422 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 423 424 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 425 426 const DataLayout &DL = GV->getParent()->getDataLayout(); 427 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 428 429 // If the alignment is specified, we *must* obey it. Overaligning a global 430 // with a specified alignment is a prompt way to break globals emitted to 431 // sections and expected to be contiguous (e.g. ObjC metadata). 432 unsigned AlignLog = getGVAlignmentLog2(GV, DL); 433 434 for (const HandlerInfo &HI : Handlers) { 435 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 436 HI.TimerGroupName, HI.TimerGroupDescription, 437 TimePassesIsEnabled); 438 HI.Handler->setSymbolSize(GVSym, Size); 439 } 440 441 // Handle common symbols 442 if (GVKind.isCommon()) { 443 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 444 unsigned Align = 1 << AlignLog; 445 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 446 Align = 0; 447 448 // .comm _foo, 42, 4 449 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 450 return; 451 } 452 453 // Determine to which section this global should be emitted. 454 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM); 455 456 // If we have a bss global going to a section that supports the 457 // zerofill directive, do so here. 458 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 459 TheSection->isVirtualSection()) { 460 if (Size == 0) 461 Size = 1; // zerofill of 0 bytes is undefined. 462 unsigned Align = 1 << AlignLog; 463 EmitLinkage(GV, GVSym); 464 // .zerofill __DATA, __bss, _foo, 400, 5 465 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align); 466 return; 467 } 468 469 // If this is a BSS local symbol and we are emitting in the BSS 470 // section use .lcomm/.comm directive. 471 if (GVKind.isBSSLocal() && 472 getObjFileLowering().getBSSSection() == TheSection) { 473 if (Size == 0) 474 Size = 1; // .comm Foo, 0 is undefined, avoid it. 475 unsigned Align = 1 << AlignLog; 476 477 // Use .lcomm only if it supports user-specified alignment. 478 // Otherwise, while it would still be correct to use .lcomm in some 479 // cases (e.g. when Align == 1), the external assembler might enfore 480 // some -unknown- default alignment behavior, which could cause 481 // spurious differences between external and integrated assembler. 482 // Prefer to simply fall back to .local / .comm in this case. 483 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 484 // .lcomm _foo, 42 485 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align); 486 return; 487 } 488 489 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 490 Align = 0; 491 492 // .local _foo 493 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local); 494 // .comm _foo, 42, 4 495 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 496 return; 497 } 498 499 // Handle thread local data for mach-o which requires us to output an 500 // additional structure of data and mangle the original symbol so that we 501 // can reference it later. 502 // 503 // TODO: This should become an "emit thread local global" method on TLOF. 504 // All of this macho specific stuff should be sunk down into TLOFMachO and 505 // stuff like "TLSExtraDataSection" should no longer be part of the parent 506 // TLOF class. This will also make it more obvious that stuff like 507 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 508 // specific code. 509 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 510 // Emit the .tbss symbol 511 MCSymbol *MangSym = 512 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 513 514 if (GVKind.isThreadBSS()) { 515 TheSection = getObjFileLowering().getTLSBSSSection(); 516 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog); 517 } else if (GVKind.isThreadData()) { 518 OutStreamer->SwitchSection(TheSection); 519 520 EmitAlignment(AlignLog, GV); 521 OutStreamer->EmitLabel(MangSym); 522 523 EmitGlobalConstant(GV->getParent()->getDataLayout(), 524 GV->getInitializer()); 525 } 526 527 OutStreamer->AddBlankLine(); 528 529 // Emit the variable struct for the runtime. 530 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 531 532 OutStreamer->SwitchSection(TLVSect); 533 // Emit the linkage here. 534 EmitLinkage(GV, GVSym); 535 OutStreamer->EmitLabel(GVSym); 536 537 // Three pointers in size: 538 // - __tlv_bootstrap - used to make sure support exists 539 // - spare pointer, used when mapped by the runtime 540 // - pointer to mangled symbol above with initializer 541 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 542 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 543 PtrSize); 544 OutStreamer->EmitIntValue(0, PtrSize); 545 OutStreamer->EmitSymbolValue(MangSym, PtrSize); 546 547 OutStreamer->AddBlankLine(); 548 return; 549 } 550 551 MCSymbol *EmittedInitSym = GVSym; 552 553 OutStreamer->SwitchSection(TheSection); 554 555 EmitLinkage(GV, EmittedInitSym); 556 EmitAlignment(AlignLog, GV); 557 558 OutStreamer->EmitLabel(EmittedInitSym); 559 560 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 561 562 if (MAI->hasDotTypeDotSizeDirective()) 563 // .size foo, 42 564 OutStreamer->emitELFSize(EmittedInitSym, 565 MCConstantExpr::create(Size, OutContext)); 566 567 OutStreamer->AddBlankLine(); 568 } 569 570 /// EmitFunctionHeader - This method emits the header for the current 571 /// function. 572 void AsmPrinter::EmitFunctionHeader() { 573 // Print out constants referenced by the function 574 EmitConstantPool(); 575 576 // Print the 'header' of function. 577 const Function *F = MF->getFunction(); 578 579 OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(F, TM)); 580 EmitVisibility(CurrentFnSym, F->getVisibility()); 581 582 EmitLinkage(F, CurrentFnSym); 583 if (MAI->hasFunctionAlignment()) 584 EmitAlignment(MF->getAlignment(), F); 585 586 if (MAI->hasDotTypeDotSizeDirective()) 587 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 588 589 if (isVerbose()) { 590 F->printAsOperand(OutStreamer->GetCommentOS(), 591 /*PrintType=*/false, F->getParent()); 592 OutStreamer->GetCommentOS() << '\n'; 593 } 594 595 // Emit the prefix data. 596 if (F->hasPrefixData()) 597 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData()); 598 599 // Emit the CurrentFnSym. This is a virtual function to allow targets to 600 // do their wild and crazy things as required. 601 EmitFunctionEntryLabel(); 602 603 // If the function had address-taken blocks that got deleted, then we have 604 // references to the dangling symbols. Emit them at the start of the function 605 // so that we don't get references to undefined symbols. 606 std::vector<MCSymbol*> DeadBlockSyms; 607 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms); 608 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 609 OutStreamer->AddComment("Address taken block that was later removed"); 610 OutStreamer->EmitLabel(DeadBlockSyms[i]); 611 } 612 613 if (CurrentFnBegin) { 614 if (MAI->useAssignmentForEHBegin()) { 615 MCSymbol *CurPos = OutContext.createTempSymbol(); 616 OutStreamer->EmitLabel(CurPos); 617 OutStreamer->EmitAssignment(CurrentFnBegin, 618 MCSymbolRefExpr::create(CurPos, OutContext)); 619 } else { 620 OutStreamer->EmitLabel(CurrentFnBegin); 621 } 622 } 623 624 // Emit pre-function debug and/or EH information. 625 for (const HandlerInfo &HI : Handlers) { 626 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 627 HI.TimerGroupDescription, TimePassesIsEnabled); 628 HI.Handler->beginFunction(MF); 629 } 630 631 // Emit the prologue data. 632 if (F->hasPrologueData()) 633 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData()); 634 } 635 636 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 637 /// function. This can be overridden by targets as required to do custom stuff. 638 void AsmPrinter::EmitFunctionEntryLabel() { 639 CurrentFnSym->redefineIfPossible(); 640 641 // The function label could have already been emitted if two symbols end up 642 // conflicting due to asm renaming. Detect this and emit an error. 643 if (CurrentFnSym->isVariable()) 644 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 645 "' is a protected alias"); 646 if (CurrentFnSym->isDefined()) 647 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 648 "' label emitted multiple times to assembly file"); 649 650 return OutStreamer->EmitLabel(CurrentFnSym); 651 } 652 653 /// emitComments - Pretty-print comments for instructions. 654 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 655 const MachineFunction *MF = MI.getParent()->getParent(); 656 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 657 658 // Check for spills and reloads 659 int FI; 660 661 const MachineFrameInfo &MFI = MF->getFrameInfo(); 662 663 // We assume a single instruction only has a spill or reload, not 664 // both. 665 const MachineMemOperand *MMO; 666 if (TII->isLoadFromStackSlotPostFE(MI, FI)) { 667 if (MFI.isSpillSlotObjectIndex(FI)) { 668 MMO = *MI.memoperands_begin(); 669 CommentOS << MMO->getSize() << "-byte Reload\n"; 670 } 671 } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) { 672 if (MFI.isSpillSlotObjectIndex(FI)) 673 CommentOS << MMO->getSize() << "-byte Folded Reload\n"; 674 } else if (TII->isStoreToStackSlotPostFE(MI, FI)) { 675 if (MFI.isSpillSlotObjectIndex(FI)) { 676 MMO = *MI.memoperands_begin(); 677 CommentOS << MMO->getSize() << "-byte Spill\n"; 678 } 679 } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) { 680 if (MFI.isSpillSlotObjectIndex(FI)) 681 CommentOS << MMO->getSize() << "-byte Folded Spill\n"; 682 } 683 684 // Check for spill-induced copies 685 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 686 CommentOS << " Reload Reuse\n"; 687 } 688 689 /// emitImplicitDef - This method emits the specified machine instruction 690 /// that is an implicit def. 691 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 692 unsigned RegNo = MI->getOperand(0).getReg(); 693 694 SmallString<128> Str; 695 raw_svector_ostream OS(Str); 696 OS << "implicit-def: " 697 << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo()); 698 699 OutStreamer->AddComment(OS.str()); 700 OutStreamer->AddBlankLine(); 701 } 702 703 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 704 std::string Str; 705 raw_string_ostream OS(Str); 706 OS << "kill:"; 707 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 708 const MachineOperand &Op = MI->getOperand(i); 709 assert(Op.isReg() && "KILL instruction must have only register operands"); 710 OS << ' ' 711 << PrintReg(Op.getReg(), 712 AP.MF->getSubtarget().getRegisterInfo()) 713 << (Op.isDef() ? "<def>" : "<kill>"); 714 } 715 AP.OutStreamer->AddComment(OS.str()); 716 AP.OutStreamer->AddBlankLine(); 717 } 718 719 /// emitDebugValueComment - This method handles the target-independent form 720 /// of DBG_VALUE, returning true if it was able to do so. A false return 721 /// means the target will need to handle MI in EmitInstruction. 722 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 723 // This code handles only the 4-operand target-independent form. 724 if (MI->getNumOperands() != 4) 725 return false; 726 727 SmallString<128> Str; 728 raw_svector_ostream OS(Str); 729 OS << "DEBUG_VALUE: "; 730 731 const DILocalVariable *V = MI->getDebugVariable(); 732 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 733 StringRef Name = SP->getDisplayName(); 734 if (!Name.empty()) 735 OS << Name << ":"; 736 } 737 OS << V->getName(); 738 739 const DIExpression *Expr = MI->getDebugExpression(); 740 auto Fragment = Expr->getFragmentInfo(); 741 if (Fragment) 742 OS << " [fragment offset=" << Fragment->OffsetInBits 743 << " size=" << Fragment->SizeInBits << "]"; 744 OS << " <- "; 745 746 // The second operand is only an offset if it's an immediate. 747 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 748 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0; 749 750 for (unsigned i = 0; i < Expr->getNumElements(); ++i) { 751 uint64_t Op = Expr->getElement(i); 752 if (Op == dwarf::DW_OP_LLVM_fragment) { 753 // There can't be any operands after this in a valid expression 754 break; 755 } else if (Deref) { 756 // We currently don't support extra Offsets or derefs after the first 757 // one. Bail out early instead of emitting an incorrect comment 758 OS << " [complex expression]"; 759 AP.OutStreamer->emitRawComment(OS.str()); 760 return true; 761 } else if (Op == dwarf::DW_OP_deref) { 762 Deref = true; 763 continue; 764 } 765 766 uint64_t ExtraOffset = Expr->getElement(i++); 767 if (Op == dwarf::DW_OP_plus) 768 Offset += ExtraOffset; 769 else { 770 assert(Op == dwarf::DW_OP_minus); 771 Offset -= ExtraOffset; 772 } 773 } 774 775 // Register or immediate value. Register 0 means undef. 776 if (MI->getOperand(0).isFPImm()) { 777 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 778 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 779 OS << (double)APF.convertToFloat(); 780 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 781 OS << APF.convertToDouble(); 782 } else { 783 // There is no good way to print long double. Convert a copy to 784 // double. Ah well, it's only a comment. 785 bool ignored; 786 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 787 &ignored); 788 OS << "(long double) " << APF.convertToDouble(); 789 } 790 } else if (MI->getOperand(0).isImm()) { 791 OS << MI->getOperand(0).getImm(); 792 } else if (MI->getOperand(0).isCImm()) { 793 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 794 } else { 795 unsigned Reg; 796 if (MI->getOperand(0).isReg()) { 797 Reg = MI->getOperand(0).getReg(); 798 } else { 799 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 800 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 801 Offset += TFI->getFrameIndexReference(*AP.MF, 802 MI->getOperand(0).getIndex(), Reg); 803 Deref = true; 804 } 805 if (Reg == 0) { 806 // Suppress offset, it is not meaningful here. 807 OS << "undef"; 808 // NOTE: Want this comment at start of line, don't emit with AddComment. 809 AP.OutStreamer->emitRawComment(OS.str()); 810 return true; 811 } 812 if (Deref) 813 OS << '['; 814 OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 815 } 816 817 if (Deref) 818 OS << '+' << Offset << ']'; 819 820 // NOTE: Want this comment at start of line, don't emit with AddComment. 821 AP.OutStreamer->emitRawComment(OS.str()); 822 return true; 823 } 824 825 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() { 826 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 827 MF->getFunction()->needsUnwindTableEntry()) 828 return CFI_M_EH; 829 830 if (MMI->hasDebugInfo()) 831 return CFI_M_Debug; 832 833 return CFI_M_None; 834 } 835 836 bool AsmPrinter::needsSEHMoves() { 837 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry(); 838 } 839 840 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 841 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 842 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 843 ExceptionHandlingType != ExceptionHandling::ARM) 844 return; 845 846 if (needsCFIMoves() == CFI_M_None) 847 return; 848 849 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions(); 850 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 851 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 852 emitCFIInstruction(CFI); 853 } 854 855 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 856 // The operands are the MCSymbol and the frame offset of the allocation. 857 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 858 int FrameOffset = MI.getOperand(1).getImm(); 859 860 // Emit a symbol assignment. 861 OutStreamer->EmitAssignment(FrameAllocSym, 862 MCConstantExpr::create(FrameOffset, OutContext)); 863 } 864 865 /// EmitFunctionBody - This method emits the body and trailer for a 866 /// function. 867 void AsmPrinter::EmitFunctionBody() { 868 EmitFunctionHeader(); 869 870 // Emit target-specific gunk before the function body. 871 EmitFunctionBodyStart(); 872 873 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 874 875 // Print out code for the function. 876 bool HasAnyRealCode = false; 877 for (auto &MBB : *MF) { 878 // Print a label for the basic block. 879 EmitBasicBlockStart(MBB); 880 for (auto &MI : MBB) { 881 882 // Print the assembly for the instruction. 883 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 884 !MI.isDebugValue()) { 885 HasAnyRealCode = true; 886 ++EmittedInsts; 887 } 888 889 if (ShouldPrintDebugScopes) { 890 for (const HandlerInfo &HI : Handlers) { 891 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 892 HI.TimerGroupName, HI.TimerGroupDescription, 893 TimePassesIsEnabled); 894 HI.Handler->beginInstruction(&MI); 895 } 896 } 897 898 if (isVerbose()) 899 emitComments(MI, OutStreamer->GetCommentOS()); 900 901 switch (MI.getOpcode()) { 902 case TargetOpcode::CFI_INSTRUCTION: 903 emitCFIInstruction(MI); 904 break; 905 906 case TargetOpcode::LOCAL_ESCAPE: 907 emitFrameAlloc(MI); 908 break; 909 910 case TargetOpcode::EH_LABEL: 911 case TargetOpcode::GC_LABEL: 912 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol()); 913 break; 914 case TargetOpcode::INLINEASM: 915 EmitInlineAsm(&MI); 916 break; 917 case TargetOpcode::DBG_VALUE: 918 if (isVerbose()) { 919 if (!emitDebugValueComment(&MI, *this)) 920 EmitInstruction(&MI); 921 } 922 break; 923 case TargetOpcode::IMPLICIT_DEF: 924 if (isVerbose()) emitImplicitDef(&MI); 925 break; 926 case TargetOpcode::KILL: 927 if (isVerbose()) emitKill(&MI, *this); 928 break; 929 default: 930 EmitInstruction(&MI); 931 break; 932 } 933 934 if (ShouldPrintDebugScopes) { 935 for (const HandlerInfo &HI : Handlers) { 936 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 937 HI.TimerGroupName, HI.TimerGroupDescription, 938 TimePassesIsEnabled); 939 HI.Handler->endInstruction(); 940 } 941 } 942 } 943 944 EmitBasicBlockEnd(MBB); 945 } 946 947 // If the function is empty and the object file uses .subsections_via_symbols, 948 // then we need to emit *something* to the function body to prevent the 949 // labels from collapsing together. Just emit a noop. 950 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) { 951 MCInst Noop; 952 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop); 953 OutStreamer->AddComment("avoids zero-length function"); 954 955 // Targets can opt-out of emitting the noop here by leaving the opcode 956 // unspecified. 957 if (Noop.getOpcode()) 958 OutStreamer->EmitInstruction(Noop, getSubtargetInfo()); 959 } 960 961 const Function *F = MF->getFunction(); 962 for (const auto &BB : *F) { 963 if (!BB.hasAddressTaken()) 964 continue; 965 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 966 if (Sym->isDefined()) 967 continue; 968 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 969 OutStreamer->EmitLabel(Sym); 970 } 971 972 // Emit target-specific gunk after the function body. 973 EmitFunctionBodyEnd(); 974 975 if (!MF->getLandingPads().empty() || MMI->hasDebugInfo() || 976 MF->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) { 977 // Create a symbol for the end of function. 978 CurrentFnEnd = createTempSymbol("func_end"); 979 OutStreamer->EmitLabel(CurrentFnEnd); 980 } 981 982 // If the target wants a .size directive for the size of the function, emit 983 // it. 984 if (MAI->hasDotTypeDotSizeDirective()) { 985 // We can get the size as difference between the function label and the 986 // temp label. 987 const MCExpr *SizeExp = MCBinaryExpr::createSub( 988 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 989 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 990 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 991 } 992 993 for (const HandlerInfo &HI : Handlers) { 994 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 995 HI.TimerGroupDescription, TimePassesIsEnabled); 996 HI.Handler->markFunctionEnd(); 997 } 998 999 // Print out jump tables referenced by the function. 1000 EmitJumpTableInfo(); 1001 1002 // Emit post-function debug and/or EH information. 1003 for (const HandlerInfo &HI : Handlers) { 1004 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1005 HI.TimerGroupDescription, TimePassesIsEnabled); 1006 HI.Handler->endFunction(MF); 1007 } 1008 1009 OutStreamer->AddBlankLine(); 1010 } 1011 1012 /// \brief Compute the number of Global Variables that uses a Constant. 1013 static unsigned getNumGlobalVariableUses(const Constant *C) { 1014 if (!C) 1015 return 0; 1016 1017 if (isa<GlobalVariable>(C)) 1018 return 1; 1019 1020 unsigned NumUses = 0; 1021 for (auto *CU : C->users()) 1022 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1023 1024 return NumUses; 1025 } 1026 1027 /// \brief Only consider global GOT equivalents if at least one user is a 1028 /// cstexpr inside an initializer of another global variables. Also, don't 1029 /// handle cstexpr inside instructions. During global variable emission, 1030 /// candidates are skipped and are emitted later in case at least one cstexpr 1031 /// isn't replaced by a PC relative GOT entry access. 1032 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1033 unsigned &NumGOTEquivUsers) { 1034 // Global GOT equivalents are unnamed private globals with a constant 1035 // pointer initializer to another global symbol. They must point to a 1036 // GlobalVariable or Function, i.e., as GlobalValue. 1037 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1038 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1039 !dyn_cast<GlobalValue>(GV->getOperand(0))) 1040 return false; 1041 1042 // To be a got equivalent, at least one of its users need to be a constant 1043 // expression used by another global variable. 1044 for (auto *U : GV->users()) 1045 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1046 1047 return NumGOTEquivUsers > 0; 1048 } 1049 1050 /// \brief Unnamed constant global variables solely contaning a pointer to 1051 /// another globals variable is equivalent to a GOT table entry; it contains the 1052 /// the address of another symbol. Optimize it and replace accesses to these 1053 /// "GOT equivalents" by using the GOT entry for the final global instead. 1054 /// Compute GOT equivalent candidates among all global variables to avoid 1055 /// emitting them if possible later on, after it use is replaced by a GOT entry 1056 /// access. 1057 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1058 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1059 return; 1060 1061 for (const auto &G : M.globals()) { 1062 unsigned NumGOTEquivUsers = 0; 1063 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1064 continue; 1065 1066 const MCSymbol *GOTEquivSym = getSymbol(&G); 1067 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1068 } 1069 } 1070 1071 /// \brief Constant expressions using GOT equivalent globals may not be eligible 1072 /// for PC relative GOT entry conversion, in such cases we need to emit such 1073 /// globals we previously omitted in EmitGlobalVariable. 1074 void AsmPrinter::emitGlobalGOTEquivs() { 1075 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1076 return; 1077 1078 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1079 for (auto &I : GlobalGOTEquivs) { 1080 const GlobalVariable *GV = I.second.first; 1081 unsigned Cnt = I.second.second; 1082 if (Cnt) 1083 FailedCandidates.push_back(GV); 1084 } 1085 GlobalGOTEquivs.clear(); 1086 1087 for (auto *GV : FailedCandidates) 1088 EmitGlobalVariable(GV); 1089 } 1090 1091 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1092 const GlobalIndirectSymbol& GIS) { 1093 MCSymbol *Name = getSymbol(&GIS); 1094 1095 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1096 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global); 1097 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1098 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference); 1099 else 1100 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1101 1102 // Set the symbol type to function if the alias has a function type. 1103 // This affects codegen when the aliasee is not a function. 1104 if (GIS.getType()->getPointerElementType()->isFunctionTy()) { 1105 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction); 1106 if (isa<GlobalIFunc>(GIS)) 1107 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction); 1108 } 1109 1110 EmitVisibility(Name, GIS.getVisibility()); 1111 1112 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1113 1114 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1115 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry); 1116 1117 // Emit the directives as assignments aka .set: 1118 OutStreamer->EmitAssignment(Name, Expr); 1119 1120 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1121 // If the aliasee does not correspond to a symbol in the output, i.e. the 1122 // alias is not of an object or the aliased object is private, then set the 1123 // size of the alias symbol from the type of the alias. We don't do this in 1124 // other situations as the alias and aliasee having differing types but same 1125 // size may be intentional. 1126 const GlobalObject *BaseObject = GA->getBaseObject(); 1127 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1128 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1129 const DataLayout &DL = M.getDataLayout(); 1130 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1131 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1132 } 1133 } 1134 } 1135 1136 bool AsmPrinter::doFinalization(Module &M) { 1137 // Set the MachineFunction to nullptr so that we can catch attempted 1138 // accesses to MF specific features at the module level and so that 1139 // we can conditionalize accesses based on whether or not it is nullptr. 1140 MF = nullptr; 1141 1142 // Gather all GOT equivalent globals in the module. We really need two 1143 // passes over the globals: one to compute and another to avoid its emission 1144 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1145 // where the got equivalent shows up before its use. 1146 computeGlobalGOTEquivs(M); 1147 1148 // Emit global variables. 1149 for (const auto &G : M.globals()) 1150 EmitGlobalVariable(&G); 1151 1152 // Emit remaining GOT equivalent globals. 1153 emitGlobalGOTEquivs(); 1154 1155 // Emit visibility info for declarations 1156 for (const Function &F : M) { 1157 if (!F.isDeclarationForLinker()) 1158 continue; 1159 GlobalValue::VisibilityTypes V = F.getVisibility(); 1160 if (V == GlobalValue::DefaultVisibility) 1161 continue; 1162 1163 MCSymbol *Name = getSymbol(&F); 1164 EmitVisibility(Name, V, false); 1165 } 1166 1167 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1168 1169 // Emit module flags. 1170 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 1171 M.getModuleFlagsMetadata(ModuleFlags); 1172 if (!ModuleFlags.empty()) 1173 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, TM); 1174 1175 if (TM.getTargetTriple().isOSBinFormatELF()) { 1176 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1177 1178 // Output stubs for external and common global variables. 1179 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1180 if (!Stubs.empty()) { 1181 OutStreamer->SwitchSection(TLOF.getDataSection()); 1182 const DataLayout &DL = M.getDataLayout(); 1183 1184 for (const auto &Stub : Stubs) { 1185 OutStreamer->EmitLabel(Stub.first); 1186 OutStreamer->EmitSymbolValue(Stub.second.getPointer(), 1187 DL.getPointerSize()); 1188 } 1189 } 1190 } 1191 1192 // Finalize debug and EH information. 1193 for (const HandlerInfo &HI : Handlers) { 1194 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1195 HI.TimerGroupDescription, TimePassesIsEnabled); 1196 HI.Handler->endModule(); 1197 delete HI.Handler; 1198 } 1199 Handlers.clear(); 1200 DD = nullptr; 1201 1202 // If the target wants to know about weak references, print them all. 1203 if (MAI->getWeakRefDirective()) { 1204 // FIXME: This is not lazy, it would be nice to only print weak references 1205 // to stuff that is actually used. Note that doing so would require targets 1206 // to notice uses in operands (due to constant exprs etc). This should 1207 // happen with the MC stuff eventually. 1208 1209 // Print out module-level global objects here. 1210 for (const auto &GO : M.global_objects()) { 1211 if (!GO.hasExternalWeakLinkage()) 1212 continue; 1213 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1214 } 1215 } 1216 1217 OutStreamer->AddBlankLine(); 1218 1219 // Print aliases in topological order, that is, for each alias a = b, 1220 // b must be printed before a. 1221 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1222 // such an order to generate correct TOC information. 1223 SmallVector<const GlobalAlias *, 16> AliasStack; 1224 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1225 for (const auto &Alias : M.aliases()) { 1226 for (const GlobalAlias *Cur = &Alias; Cur; 1227 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1228 if (!AliasVisited.insert(Cur).second) 1229 break; 1230 AliasStack.push_back(Cur); 1231 } 1232 for (const GlobalAlias *AncestorAlias : reverse(AliasStack)) 1233 emitGlobalIndirectSymbol(M, *AncestorAlias); 1234 AliasStack.clear(); 1235 } 1236 for (const auto &IFunc : M.ifuncs()) 1237 emitGlobalIndirectSymbol(M, IFunc); 1238 1239 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1240 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1241 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1242 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1243 MP->finishAssembly(M, *MI, *this); 1244 1245 // Emit llvm.ident metadata in an '.ident' directive. 1246 EmitModuleIdents(M); 1247 1248 // Emit __morestack address if needed for indirect calls. 1249 if (MMI->usesMorestackAddr()) { 1250 unsigned Align = 1; 1251 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1252 getDataLayout(), SectionKind::getReadOnly(), 1253 /*C=*/nullptr, Align); 1254 OutStreamer->SwitchSection(ReadOnlySection); 1255 1256 MCSymbol *AddrSymbol = 1257 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1258 OutStreamer->EmitLabel(AddrSymbol); 1259 1260 unsigned PtrSize = M.getDataLayout().getPointerSize(0); 1261 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1262 PtrSize); 1263 } 1264 1265 // If we don't have any trampolines, then we don't require stack memory 1266 // to be executable. Some targets have a directive to declare this. 1267 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1268 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1269 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1270 OutStreamer->SwitchSection(S); 1271 1272 // Allow the target to emit any magic that it wants at the end of the file, 1273 // after everything else has gone out. 1274 EmitEndOfAsmFile(M); 1275 1276 MMI = nullptr; 1277 1278 OutStreamer->Finish(); 1279 OutStreamer->reset(); 1280 1281 return false; 1282 } 1283 1284 MCSymbol *AsmPrinter::getCurExceptionSym() { 1285 if (!CurExceptionSym) 1286 CurExceptionSym = createTempSymbol("exception"); 1287 return CurExceptionSym; 1288 } 1289 1290 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1291 this->MF = &MF; 1292 // Get the function symbol. 1293 CurrentFnSym = getSymbol(MF.getFunction()); 1294 CurrentFnSymForSize = CurrentFnSym; 1295 CurrentFnBegin = nullptr; 1296 CurExceptionSym = nullptr; 1297 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1298 if (!MF.getLandingPads().empty() || MMI->hasDebugInfo() || 1299 MF.hasEHFunclets() || NeedsLocalForSize) { 1300 CurrentFnBegin = createTempSymbol("func_begin"); 1301 if (NeedsLocalForSize) 1302 CurrentFnSymForSize = CurrentFnBegin; 1303 } 1304 1305 if (isVerbose()) 1306 LI = &getAnalysis<MachineLoopInfo>(); 1307 } 1308 1309 namespace { 1310 // Keep track the alignment, constpool entries per Section. 1311 struct SectionCPs { 1312 MCSection *S; 1313 unsigned Alignment; 1314 SmallVector<unsigned, 4> CPEs; 1315 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {} 1316 }; 1317 } 1318 1319 /// EmitConstantPool - Print to the current output stream assembly 1320 /// representations of the constants in the constant pool MCP. This is 1321 /// used to print out constants which have been "spilled to memory" by 1322 /// the code generator. 1323 /// 1324 void AsmPrinter::EmitConstantPool() { 1325 const MachineConstantPool *MCP = MF->getConstantPool(); 1326 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1327 if (CP.empty()) return; 1328 1329 // Calculate sections for constant pool entries. We collect entries to go into 1330 // the same section together to reduce amount of section switch statements. 1331 SmallVector<SectionCPs, 4> CPSections; 1332 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1333 const MachineConstantPoolEntry &CPE = CP[i]; 1334 unsigned Align = CPE.getAlignment(); 1335 1336 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1337 1338 const Constant *C = nullptr; 1339 if (!CPE.isMachineConstantPoolEntry()) 1340 C = CPE.Val.ConstVal; 1341 1342 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(), 1343 Kind, C, Align); 1344 1345 // The number of sections are small, just do a linear search from the 1346 // last section to the first. 1347 bool Found = false; 1348 unsigned SecIdx = CPSections.size(); 1349 while (SecIdx != 0) { 1350 if (CPSections[--SecIdx].S == S) { 1351 Found = true; 1352 break; 1353 } 1354 } 1355 if (!Found) { 1356 SecIdx = CPSections.size(); 1357 CPSections.push_back(SectionCPs(S, Align)); 1358 } 1359 1360 if (Align > CPSections[SecIdx].Alignment) 1361 CPSections[SecIdx].Alignment = Align; 1362 CPSections[SecIdx].CPEs.push_back(i); 1363 } 1364 1365 // Now print stuff into the calculated sections. 1366 const MCSection *CurSection = nullptr; 1367 unsigned Offset = 0; 1368 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1369 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1370 unsigned CPI = CPSections[i].CPEs[j]; 1371 MCSymbol *Sym = GetCPISymbol(CPI); 1372 if (!Sym->isUndefined()) 1373 continue; 1374 1375 if (CurSection != CPSections[i].S) { 1376 OutStreamer->SwitchSection(CPSections[i].S); 1377 EmitAlignment(Log2_32(CPSections[i].Alignment)); 1378 CurSection = CPSections[i].S; 1379 Offset = 0; 1380 } 1381 1382 MachineConstantPoolEntry CPE = CP[CPI]; 1383 1384 // Emit inter-object padding for alignment. 1385 unsigned AlignMask = CPE.getAlignment() - 1; 1386 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1387 OutStreamer->EmitZeros(NewOffset - Offset); 1388 1389 Type *Ty = CPE.getType(); 1390 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1391 1392 OutStreamer->EmitLabel(Sym); 1393 if (CPE.isMachineConstantPoolEntry()) 1394 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1395 else 1396 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1397 } 1398 } 1399 } 1400 1401 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 1402 /// by the current function to the current output stream. 1403 /// 1404 void AsmPrinter::EmitJumpTableInfo() { 1405 const DataLayout &DL = MF->getDataLayout(); 1406 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1407 if (!MJTI) return; 1408 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1409 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1410 if (JT.empty()) return; 1411 1412 // Pick the directive to use to print the jump table entries, and switch to 1413 // the appropriate section. 1414 const Function *F = MF->getFunction(); 1415 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1416 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1417 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1418 *F); 1419 if (JTInDiffSection) { 1420 // Drop it in the readonly section. 1421 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, TM); 1422 OutStreamer->SwitchSection(ReadOnlySection); 1423 } 1424 1425 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL))); 1426 1427 // Jump tables in code sections are marked with a data_region directive 1428 // where that's supported. 1429 if (!JTInDiffSection) 1430 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32); 1431 1432 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1433 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1434 1435 // If this jump table was deleted, ignore it. 1436 if (JTBBs.empty()) continue; 1437 1438 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1439 /// emit a .set directive for each unique entry. 1440 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1441 MAI->doesSetDirectiveSuppressReloc()) { 1442 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1443 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1444 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1445 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1446 const MachineBasicBlock *MBB = JTBBs[ii]; 1447 if (!EmittedSets.insert(MBB).second) 1448 continue; 1449 1450 // .set LJTSet, LBB32-base 1451 const MCExpr *LHS = 1452 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1453 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1454 MCBinaryExpr::createSub(LHS, Base, 1455 OutContext)); 1456 } 1457 } 1458 1459 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1460 // before each jump table. The first label is never referenced, but tells 1461 // the assembler and linker the extents of the jump table object. The 1462 // second label is actually referenced by the code. 1463 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1464 // FIXME: This doesn't have to have any specific name, just any randomly 1465 // named and numbered 'l' label would work. Simplify GetJTISymbol. 1466 OutStreamer->EmitLabel(GetJTISymbol(JTI, true)); 1467 1468 OutStreamer->EmitLabel(GetJTISymbol(JTI)); 1469 1470 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1471 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1472 } 1473 if (!JTInDiffSection) 1474 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 1475 } 1476 1477 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1478 /// current stream. 1479 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1480 const MachineBasicBlock *MBB, 1481 unsigned UID) const { 1482 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1483 const MCExpr *Value = nullptr; 1484 switch (MJTI->getEntryKind()) { 1485 case MachineJumpTableInfo::EK_Inline: 1486 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1487 case MachineJumpTableInfo::EK_Custom32: 1488 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1489 MJTI, MBB, UID, OutContext); 1490 break; 1491 case MachineJumpTableInfo::EK_BlockAddress: 1492 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1493 // .word LBB123 1494 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1495 break; 1496 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1497 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1498 // with a relocation as gp-relative, e.g.: 1499 // .gprel32 LBB123 1500 MCSymbol *MBBSym = MBB->getSymbol(); 1501 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1502 return; 1503 } 1504 1505 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1506 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1507 // with a relocation as gp-relative, e.g.: 1508 // .gpdword LBB123 1509 MCSymbol *MBBSym = MBB->getSymbol(); 1510 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1511 return; 1512 } 1513 1514 case MachineJumpTableInfo::EK_LabelDifference32: { 1515 // Each entry is the address of the block minus the address of the jump 1516 // table. This is used for PIC jump tables where gprel32 is not supported. 1517 // e.g.: 1518 // .word LBB123 - LJTI1_2 1519 // If the .set directive avoids relocations, this is emitted as: 1520 // .set L4_5_set_123, LBB123 - LJTI1_2 1521 // .word L4_5_set_123 1522 if (MAI->doesSetDirectiveSuppressReloc()) { 1523 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 1524 OutContext); 1525 break; 1526 } 1527 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1528 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1529 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 1530 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 1531 break; 1532 } 1533 } 1534 1535 assert(Value && "Unknown entry kind!"); 1536 1537 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 1538 OutStreamer->EmitValue(Value, EntrySize); 1539 } 1540 1541 1542 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1543 /// special global used by LLVM. If so, emit it and return true, otherwise 1544 /// do nothing and return false. 1545 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1546 if (GV->getName() == "llvm.used") { 1547 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1548 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1549 return true; 1550 } 1551 1552 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1553 if (GV->getSection() == "llvm.metadata" || 1554 GV->hasAvailableExternallyLinkage()) 1555 return true; 1556 1557 if (!GV->hasAppendingLinkage()) return false; 1558 1559 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1560 1561 if (GV->getName() == "llvm.global_ctors") { 1562 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1563 /* isCtor */ true); 1564 1565 return true; 1566 } 1567 1568 if (GV->getName() == "llvm.global_dtors") { 1569 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1570 /* isCtor */ false); 1571 1572 return true; 1573 } 1574 1575 report_fatal_error("unknown special variable"); 1576 } 1577 1578 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1579 /// global in the specified llvm.used list for which emitUsedDirectiveFor 1580 /// is true, as being used with this directive. 1581 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 1582 // Should be an array of 'i8*'. 1583 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1584 const GlobalValue *GV = 1585 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1586 if (GV) 1587 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 1588 } 1589 } 1590 1591 namespace { 1592 struct Structor { 1593 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {} 1594 int Priority; 1595 llvm::Constant *Func; 1596 llvm::GlobalValue *ComdatKey; 1597 }; 1598 } // end namespace 1599 1600 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 1601 /// priority. 1602 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List, 1603 bool isCtor) { 1604 // Should be an array of '{ int, void ()* }' structs. The first value is the 1605 // init priority. 1606 if (!isa<ConstantArray>(List)) return; 1607 1608 // Sanity check the structors list. 1609 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1610 if (!InitList) return; // Not an array! 1611 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 1612 // FIXME: Only allow the 3-field form in LLVM 4.0. 1613 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3) 1614 return; // Not an array of two or three elements! 1615 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 1616 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr). 1617 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U))) 1618 return; // Not (int, ptr, ptr). 1619 1620 // Gather the structors in a form that's convenient for sorting by priority. 1621 SmallVector<Structor, 8> Structors; 1622 for (Value *O : InitList->operands()) { 1623 ConstantStruct *CS = dyn_cast<ConstantStruct>(O); 1624 if (!CS) continue; // Malformed. 1625 if (CS->getOperand(1)->isNullValue()) 1626 break; // Found a null terminator, skip the rest. 1627 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 1628 if (!Priority) continue; // Malformed. 1629 Structors.push_back(Structor()); 1630 Structor &S = Structors.back(); 1631 S.Priority = Priority->getLimitedValue(65535); 1632 S.Func = CS->getOperand(1); 1633 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue()) 1634 S.ComdatKey = 1635 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 1636 } 1637 1638 // Emit the function pointers in the target-specific order 1639 unsigned Align = Log2_32(DL.getPointerPrefAlignment()); 1640 std::stable_sort(Structors.begin(), Structors.end(), 1641 [](const Structor &L, 1642 const Structor &R) { return L.Priority < R.Priority; }); 1643 for (Structor &S : Structors) { 1644 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 1645 const MCSymbol *KeySym = nullptr; 1646 if (GlobalValue *GV = S.ComdatKey) { 1647 if (GV->isDeclarationForLinker()) 1648 // If the associated variable is not defined in this module 1649 // (it might be available_externally, or have been an 1650 // available_externally definition that was dropped by the 1651 // EliminateAvailableExternally pass), some other TU 1652 // will provide its dynamic initializer. 1653 continue; 1654 1655 KeySym = getSymbol(GV); 1656 } 1657 MCSection *OutputSection = 1658 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 1659 : Obj.getStaticDtorSection(S.Priority, KeySym)); 1660 OutStreamer->SwitchSection(OutputSection); 1661 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 1662 EmitAlignment(Align); 1663 EmitXXStructor(DL, S.Func); 1664 } 1665 } 1666 1667 void AsmPrinter::EmitModuleIdents(Module &M) { 1668 if (!MAI->hasIdentDirective()) 1669 return; 1670 1671 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 1672 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1673 const MDNode *N = NMD->getOperand(i); 1674 assert(N->getNumOperands() == 1 && 1675 "llvm.ident metadata entry can have only one operand"); 1676 const MDString *S = cast<MDString>(N->getOperand(0)); 1677 OutStreamer->EmitIdent(S->getString()); 1678 } 1679 } 1680 } 1681 1682 //===--------------------------------------------------------------------===// 1683 // Emission and print routines 1684 // 1685 1686 /// EmitInt8 - Emit a byte directive and value. 1687 /// 1688 void AsmPrinter::EmitInt8(int Value) const { 1689 OutStreamer->EmitIntValue(Value, 1); 1690 } 1691 1692 /// EmitInt16 - Emit a short directive and value. 1693 /// 1694 void AsmPrinter::EmitInt16(int Value) const { 1695 OutStreamer->EmitIntValue(Value, 2); 1696 } 1697 1698 /// EmitInt32 - Emit a long directive and value. 1699 /// 1700 void AsmPrinter::EmitInt32(int Value) const { 1701 OutStreamer->EmitIntValue(Value, 4); 1702 } 1703 1704 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 1705 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 1706 /// .set if it avoids relocations. 1707 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1708 unsigned Size) const { 1709 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 1710 } 1711 1712 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 1713 /// where the size in bytes of the directive is specified by Size and Label 1714 /// specifies the label. This implicitly uses .set if it is available. 1715 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 1716 unsigned Size, 1717 bool IsSectionRelative) const { 1718 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 1719 OutStreamer->EmitCOFFSecRel32(Label, Offset); 1720 if (Size > 4) 1721 OutStreamer->EmitZeros(Size - 4); 1722 return; 1723 } 1724 1725 // Emit Label+Offset (or just Label if Offset is zero) 1726 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 1727 if (Offset) 1728 Expr = MCBinaryExpr::createAdd( 1729 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 1730 1731 OutStreamer->EmitValue(Expr, Size); 1732 } 1733 1734 //===----------------------------------------------------------------------===// 1735 1736 // EmitAlignment - Emit an alignment directive to the specified power of 1737 // two boundary. For example, if you pass in 3 here, you will get an 8 1738 // byte alignment. If a global value is specified, and if that global has 1739 // an explicit alignment requested, it will override the alignment request 1740 // if required for correctness. 1741 // 1742 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const { 1743 if (GV) 1744 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits); 1745 1746 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1747 1748 assert(NumBits < 1749 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 1750 "undefined behavior"); 1751 if (getCurrentSection()->getKind().isText()) 1752 OutStreamer->EmitCodeAlignment(1u << NumBits); 1753 else 1754 OutStreamer->EmitValueToAlignment(1u << NumBits); 1755 } 1756 1757 //===----------------------------------------------------------------------===// 1758 // Constant emission. 1759 //===----------------------------------------------------------------------===// 1760 1761 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 1762 MCContext &Ctx = OutContext; 1763 1764 if (CV->isNullValue() || isa<UndefValue>(CV)) 1765 return MCConstantExpr::create(0, Ctx); 1766 1767 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1768 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 1769 1770 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1771 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 1772 1773 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1774 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 1775 1776 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1777 if (!CE) { 1778 llvm_unreachable("Unknown constant value to lower!"); 1779 } 1780 1781 switch (CE->getOpcode()) { 1782 default: 1783 // If the code isn't optimized, there may be outstanding folding 1784 // opportunities. Attempt to fold the expression using DataLayout as a 1785 // last resort before giving up. 1786 if (Constant *C = ConstantFoldConstant(CE, getDataLayout())) 1787 if (C != CE) 1788 return lowerConstant(C); 1789 1790 // Otherwise report the problem to the user. 1791 { 1792 std::string S; 1793 raw_string_ostream OS(S); 1794 OS << "Unsupported expression in static initializer: "; 1795 CE->printAsOperand(OS, /*PrintType=*/false, 1796 !MF ? nullptr : MF->getFunction()->getParent()); 1797 report_fatal_error(OS.str()); 1798 } 1799 case Instruction::GetElementPtr: { 1800 // Generate a symbolic expression for the byte address 1801 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 1802 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 1803 1804 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 1805 if (!OffsetAI) 1806 return Base; 1807 1808 int64_t Offset = OffsetAI.getSExtValue(); 1809 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 1810 Ctx); 1811 } 1812 1813 case Instruction::Trunc: 1814 // We emit the value and depend on the assembler to truncate the generated 1815 // expression properly. This is important for differences between 1816 // blockaddress labels. Since the two labels are in the same function, it 1817 // is reasonable to treat their delta as a 32-bit value. 1818 LLVM_FALLTHROUGH; 1819 case Instruction::BitCast: 1820 return lowerConstant(CE->getOperand(0)); 1821 1822 case Instruction::IntToPtr: { 1823 const DataLayout &DL = getDataLayout(); 1824 1825 // Handle casts to pointers by changing them into casts to the appropriate 1826 // integer type. This promotes constant folding and simplifies this code. 1827 Constant *Op = CE->getOperand(0); 1828 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 1829 false/*ZExt*/); 1830 return lowerConstant(Op); 1831 } 1832 1833 case Instruction::PtrToInt: { 1834 const DataLayout &DL = getDataLayout(); 1835 1836 // Support only foldable casts to/from pointers that can be eliminated by 1837 // changing the pointer to the appropriately sized integer type. 1838 Constant *Op = CE->getOperand(0); 1839 Type *Ty = CE->getType(); 1840 1841 const MCExpr *OpExpr = lowerConstant(Op); 1842 1843 // We can emit the pointer value into this slot if the slot is an 1844 // integer slot equal to the size of the pointer. 1845 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType())) 1846 return OpExpr; 1847 1848 // Otherwise the pointer is smaller than the resultant integer, mask off 1849 // the high bits so we are sure to get a proper truncation if the input is 1850 // a constant expr. 1851 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 1852 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 1853 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 1854 } 1855 1856 case Instruction::Sub: { 1857 GlobalValue *LHSGV; 1858 APInt LHSOffset; 1859 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 1860 getDataLayout())) { 1861 GlobalValue *RHSGV; 1862 APInt RHSOffset; 1863 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 1864 getDataLayout())) { 1865 const MCExpr *RelocExpr = 1866 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 1867 if (!RelocExpr) 1868 RelocExpr = MCBinaryExpr::createSub( 1869 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 1870 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 1871 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 1872 if (Addend != 0) 1873 RelocExpr = MCBinaryExpr::createAdd( 1874 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 1875 return RelocExpr; 1876 } 1877 } 1878 } 1879 // else fallthrough 1880 1881 // The MC library also has a right-shift operator, but it isn't consistently 1882 // signed or unsigned between different targets. 1883 case Instruction::Add: 1884 case Instruction::Mul: 1885 case Instruction::SDiv: 1886 case Instruction::SRem: 1887 case Instruction::Shl: 1888 case Instruction::And: 1889 case Instruction::Or: 1890 case Instruction::Xor: { 1891 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 1892 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 1893 switch (CE->getOpcode()) { 1894 default: llvm_unreachable("Unknown binary operator constant cast expr"); 1895 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 1896 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1897 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 1898 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 1899 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 1900 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 1901 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 1902 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 1903 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 1904 } 1905 } 1906 } 1907 } 1908 1909 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 1910 AsmPrinter &AP, 1911 const Constant *BaseCV = nullptr, 1912 uint64_t Offset = 0); 1913 1914 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 1915 1916 /// isRepeatedByteSequence - Determine whether the given value is 1917 /// composed of a repeated sequence of identical bytes and return the 1918 /// byte value. If it is not a repeated sequence, return -1. 1919 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 1920 StringRef Data = V->getRawDataValues(); 1921 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 1922 char C = Data[0]; 1923 for (unsigned i = 1, e = Data.size(); i != e; ++i) 1924 if (Data[i] != C) return -1; 1925 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 1926 } 1927 1928 1929 /// isRepeatedByteSequence - Determine whether the given value is 1930 /// composed of a repeated sequence of identical bytes and return the 1931 /// byte value. If it is not a repeated sequence, return -1. 1932 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 1933 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 1934 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 1935 assert(Size % 8 == 0); 1936 1937 // Extend the element to take zero padding into account. 1938 APInt Value = CI->getValue().zextOrSelf(Size); 1939 if (!Value.isSplat(8)) 1940 return -1; 1941 1942 return Value.zextOrTrunc(8).getZExtValue(); 1943 } 1944 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 1945 // Make sure all array elements are sequences of the same repeated 1946 // byte. 1947 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 1948 Constant *Op0 = CA->getOperand(0); 1949 int Byte = isRepeatedByteSequence(Op0, DL); 1950 if (Byte == -1) 1951 return -1; 1952 1953 // All array elements must be equal. 1954 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 1955 if (CA->getOperand(i) != Op0) 1956 return -1; 1957 return Byte; 1958 } 1959 1960 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 1961 return isRepeatedByteSequence(CDS); 1962 1963 return -1; 1964 } 1965 1966 static void emitGlobalConstantDataSequential(const DataLayout &DL, 1967 const ConstantDataSequential *CDS, 1968 AsmPrinter &AP) { 1969 1970 // See if we can aggregate this into a .fill, if so, emit it as such. 1971 int Value = isRepeatedByteSequence(CDS, DL); 1972 if (Value != -1) { 1973 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 1974 // Don't emit a 1-byte object as a .fill. 1975 if (Bytes > 1) 1976 return AP.OutStreamer->emitFill(Bytes, Value); 1977 } 1978 1979 // If this can be emitted with .ascii/.asciz, emit it as such. 1980 if (CDS->isString()) 1981 return AP.OutStreamer->EmitBytes(CDS->getAsString()); 1982 1983 // Otherwise, emit the values in successive locations. 1984 unsigned ElementByteSize = CDS->getElementByteSize(); 1985 if (isa<IntegerType>(CDS->getElementType())) { 1986 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1987 if (AP.isVerbose()) 1988 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 1989 CDS->getElementAsInteger(i)); 1990 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i), 1991 ElementByteSize); 1992 } 1993 } else { 1994 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 1995 emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP); 1996 } 1997 1998 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 1999 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 2000 CDS->getNumElements(); 2001 if (unsigned Padding = Size - EmittedSize) 2002 AP.OutStreamer->EmitZeros(Padding); 2003 2004 } 2005 2006 static void emitGlobalConstantArray(const DataLayout &DL, 2007 const ConstantArray *CA, AsmPrinter &AP, 2008 const Constant *BaseCV, uint64_t Offset) { 2009 // See if we can aggregate some values. Make sure it can be 2010 // represented as a series of bytes of the constant value. 2011 int Value = isRepeatedByteSequence(CA, DL); 2012 2013 if (Value != -1) { 2014 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2015 AP.OutStreamer->emitFill(Bytes, Value); 2016 } 2017 else { 2018 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2019 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2020 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2021 } 2022 } 2023 } 2024 2025 static void emitGlobalConstantVector(const DataLayout &DL, 2026 const ConstantVector *CV, AsmPrinter &AP) { 2027 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2028 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2029 2030 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2031 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2032 CV->getType()->getNumElements(); 2033 if (unsigned Padding = Size - EmittedSize) 2034 AP.OutStreamer->EmitZeros(Padding); 2035 } 2036 2037 static void emitGlobalConstantStruct(const DataLayout &DL, 2038 const ConstantStruct *CS, AsmPrinter &AP, 2039 const Constant *BaseCV, uint64_t Offset) { 2040 // Print the fields in successive locations. Pad to align if needed! 2041 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2042 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2043 uint64_t SizeSoFar = 0; 2044 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2045 const Constant *Field = CS->getOperand(i); 2046 2047 // Print the actual field value. 2048 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2049 2050 // Check if padding is needed and insert one or more 0s. 2051 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2052 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2053 - Layout->getElementOffset(i)) - FieldSize; 2054 SizeSoFar += FieldSize + PadSize; 2055 2056 // Insert padding - this may include padding to increase the size of the 2057 // current field up to the ABI size (if the struct is not packed) as well 2058 // as padding to ensure that the next field starts at the right offset. 2059 AP.OutStreamer->EmitZeros(PadSize); 2060 } 2061 assert(SizeSoFar == Layout->getSizeInBytes() && 2062 "Layout of constant struct may be incorrect!"); 2063 } 2064 2065 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2066 APInt API = CFP->getValueAPF().bitcastToAPInt(); 2067 2068 // First print a comment with what we think the original floating-point value 2069 // should have been. 2070 if (AP.isVerbose()) { 2071 SmallString<8> StrVal; 2072 CFP->getValueAPF().toString(StrVal); 2073 2074 if (CFP->getType()) 2075 CFP->getType()->print(AP.OutStreamer->GetCommentOS()); 2076 else 2077 AP.OutStreamer->GetCommentOS() << "Printing <null> Type"; 2078 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2079 } 2080 2081 // Now iterate through the APInt chunks, emitting them in endian-correct 2082 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2083 // floats). 2084 unsigned NumBytes = API.getBitWidth() / 8; 2085 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2086 const uint64_t *p = API.getRawData(); 2087 2088 // PPC's long double has odd notions of endianness compared to how LLVM 2089 // handles it: p[0] goes first for *big* endian on PPC. 2090 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) { 2091 int Chunk = API.getNumWords() - 1; 2092 2093 if (TrailingBytes) 2094 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes); 2095 2096 for (; Chunk >= 0; --Chunk) 2097 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2098 } else { 2099 unsigned Chunk; 2100 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2101 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2102 2103 if (TrailingBytes) 2104 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes); 2105 } 2106 2107 // Emit the tail padding for the long double. 2108 const DataLayout &DL = AP.getDataLayout(); 2109 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) - 2110 DL.getTypeStoreSize(CFP->getType())); 2111 } 2112 2113 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2114 const DataLayout &DL = AP.getDataLayout(); 2115 unsigned BitWidth = CI->getBitWidth(); 2116 2117 // Copy the value as we may massage the layout for constants whose bit width 2118 // is not a multiple of 64-bits. 2119 APInt Realigned(CI->getValue()); 2120 uint64_t ExtraBits = 0; 2121 unsigned ExtraBitsSize = BitWidth & 63; 2122 2123 if (ExtraBitsSize) { 2124 // The bit width of the data is not a multiple of 64-bits. 2125 // The extra bits are expected to be at the end of the chunk of the memory. 2126 // Little endian: 2127 // * Nothing to be done, just record the extra bits to emit. 2128 // Big endian: 2129 // * Record the extra bits to emit. 2130 // * Realign the raw data to emit the chunks of 64-bits. 2131 if (DL.isBigEndian()) { 2132 // Basically the structure of the raw data is a chunk of 64-bits cells: 2133 // 0 1 BitWidth / 64 2134 // [chunk1][chunk2] ... [chunkN]. 2135 // The most significant chunk is chunkN and it should be emitted first. 2136 // However, due to the alignment issue chunkN contains useless bits. 2137 // Realign the chunks so that they contain only useless information: 2138 // ExtraBits 0 1 (BitWidth / 64) - 1 2139 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2140 ExtraBits = Realigned.getRawData()[0] & 2141 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2142 Realigned = Realigned.lshr(ExtraBitsSize); 2143 } else 2144 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2145 } 2146 2147 // We don't expect assemblers to support integer data directives 2148 // for more than 64 bits, so we emit the data in at most 64-bit 2149 // quantities at a time. 2150 const uint64_t *RawData = Realigned.getRawData(); 2151 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2152 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2153 AP.OutStreamer->EmitIntValue(Val, 8); 2154 } 2155 2156 if (ExtraBitsSize) { 2157 // Emit the extra bits after the 64-bits chunks. 2158 2159 // Emit a directive that fills the expected size. 2160 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType()); 2161 Size -= (BitWidth / 64) * 8; 2162 assert(Size && Size * 8 >= ExtraBitsSize && 2163 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2164 == ExtraBits && "Directive too small for extra bits."); 2165 AP.OutStreamer->EmitIntValue(ExtraBits, Size); 2166 } 2167 } 2168 2169 /// \brief Transform a not absolute MCExpr containing a reference to a GOT 2170 /// equivalent global, by a target specific GOT pc relative access to the 2171 /// final symbol. 2172 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2173 const Constant *BaseCst, 2174 uint64_t Offset) { 2175 // The global @foo below illustrates a global that uses a got equivalent. 2176 // 2177 // @bar = global i32 42 2178 // @gotequiv = private unnamed_addr constant i32* @bar 2179 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2180 // i64 ptrtoint (i32* @foo to i64)) 2181 // to i32) 2182 // 2183 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2184 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2185 // form: 2186 // 2187 // foo = cstexpr, where 2188 // cstexpr := <gotequiv> - "." + <cst> 2189 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2190 // 2191 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2192 // 2193 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2194 // gotpcrelcst := <offset from @foo base> + <cst> 2195 // 2196 MCValue MV; 2197 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2198 return; 2199 const MCSymbolRefExpr *SymA = MV.getSymA(); 2200 if (!SymA) 2201 return; 2202 2203 // Check that GOT equivalent symbol is cached. 2204 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2205 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2206 return; 2207 2208 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2209 if (!BaseGV) 2210 return; 2211 2212 // Check for a valid base symbol 2213 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2214 const MCSymbolRefExpr *SymB = MV.getSymB(); 2215 2216 if (!SymB || BaseSym != &SymB->getSymbol()) 2217 return; 2218 2219 // Make sure to match: 2220 // 2221 // gotpcrelcst := <offset from @foo base> + <cst> 2222 // 2223 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2224 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2225 // if the target knows how to encode it. 2226 // 2227 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2228 if (GOTPCRelCst < 0) 2229 return; 2230 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2231 return; 2232 2233 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2234 // 2235 // bar: 2236 // .long 42 2237 // gotequiv: 2238 // .quad bar 2239 // foo: 2240 // .long gotequiv - "." + <cst> 2241 // 2242 // is replaced by the target specific equivalent to: 2243 // 2244 // bar: 2245 // .long 42 2246 // foo: 2247 // .long bar@GOTPCREL+<gotpcrelcst> 2248 // 2249 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2250 const GlobalVariable *GV = Result.first; 2251 int NumUses = (int)Result.second; 2252 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2253 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2254 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2255 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2256 2257 // Update GOT equivalent usage information 2258 --NumUses; 2259 if (NumUses >= 0) 2260 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2261 } 2262 2263 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2264 AsmPrinter &AP, const Constant *BaseCV, 2265 uint64_t Offset) { 2266 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2267 2268 // Globals with sub-elements such as combinations of arrays and structs 2269 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2270 // constant symbol base and the current position with BaseCV and Offset. 2271 if (!BaseCV && CV->hasOneUse()) 2272 BaseCV = dyn_cast<Constant>(CV->user_back()); 2273 2274 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2275 return AP.OutStreamer->EmitZeros(Size); 2276 2277 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2278 switch (Size) { 2279 case 1: 2280 case 2: 2281 case 4: 2282 case 8: 2283 if (AP.isVerbose()) 2284 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2285 CI->getZExtValue()); 2286 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size); 2287 return; 2288 default: 2289 emitGlobalConstantLargeInt(CI, AP); 2290 return; 2291 } 2292 } 2293 2294 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2295 return emitGlobalConstantFP(CFP, AP); 2296 2297 if (isa<ConstantPointerNull>(CV)) { 2298 AP.OutStreamer->EmitIntValue(0, Size); 2299 return; 2300 } 2301 2302 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2303 return emitGlobalConstantDataSequential(DL, CDS, AP); 2304 2305 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2306 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2307 2308 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2309 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2310 2311 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2312 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2313 // vectors). 2314 if (CE->getOpcode() == Instruction::BitCast) 2315 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2316 2317 if (Size > 8) { 2318 // If the constant expression's size is greater than 64-bits, then we have 2319 // to emit the value in chunks. Try to constant fold the value and emit it 2320 // that way. 2321 Constant *New = ConstantFoldConstant(CE, DL); 2322 if (New && New != CE) 2323 return emitGlobalConstantImpl(DL, New, AP); 2324 } 2325 } 2326 2327 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2328 return emitGlobalConstantVector(DL, V, AP); 2329 2330 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2331 // thread the streamer with EmitValue. 2332 const MCExpr *ME = AP.lowerConstant(CV); 2333 2334 // Since lowerConstant already folded and got rid of all IR pointer and 2335 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2336 // directly. 2337 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2338 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2339 2340 AP.OutStreamer->EmitValue(ME, Size); 2341 } 2342 2343 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2344 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2345 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2346 if (Size) 2347 emitGlobalConstantImpl(DL, CV, *this); 2348 else if (MAI->hasSubsectionsViaSymbols()) { 2349 // If the global has zero size, emit a single byte so that two labels don't 2350 // look like they are at the same location. 2351 OutStreamer->EmitIntValue(0, 1); 2352 } 2353 } 2354 2355 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2356 // Target doesn't support this yet! 2357 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2358 } 2359 2360 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2361 if (Offset > 0) 2362 OS << '+' << Offset; 2363 else if (Offset < 0) 2364 OS << Offset; 2365 } 2366 2367 //===----------------------------------------------------------------------===// 2368 // Symbol Lowering Routines. 2369 //===----------------------------------------------------------------------===// 2370 2371 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2372 return OutContext.createTempSymbol(Name, true); 2373 } 2374 2375 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2376 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2377 } 2378 2379 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2380 return MMI->getAddrLabelSymbol(BB); 2381 } 2382 2383 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2384 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2385 const DataLayout &DL = getDataLayout(); 2386 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2387 "CPI" + Twine(getFunctionNumber()) + "_" + 2388 Twine(CPID)); 2389 } 2390 2391 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2392 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2393 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2394 } 2395 2396 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2397 /// FIXME: privatize to AsmPrinter. 2398 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2399 const DataLayout &DL = getDataLayout(); 2400 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2401 Twine(getFunctionNumber()) + "_" + 2402 Twine(UID) + "_set_" + Twine(MBBID)); 2403 } 2404 2405 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2406 StringRef Suffix) const { 2407 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 2408 } 2409 2410 /// Return the MCSymbol for the specified ExternalSymbol. 2411 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2412 SmallString<60> NameStr; 2413 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2414 return OutContext.getOrCreateSymbol(NameStr); 2415 } 2416 2417 2418 2419 /// PrintParentLoopComment - Print comments about parent loops of this one. 2420 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2421 unsigned FunctionNumber) { 2422 if (!Loop) return; 2423 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2424 OS.indent(Loop->getLoopDepth()*2) 2425 << "Parent Loop BB" << FunctionNumber << "_" 2426 << Loop->getHeader()->getNumber() 2427 << " Depth=" << Loop->getLoopDepth() << '\n'; 2428 } 2429 2430 2431 /// PrintChildLoopComment - Print comments about child loops within 2432 /// the loop for this basic block, with nesting. 2433 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2434 unsigned FunctionNumber) { 2435 // Add child loop information 2436 for (const MachineLoop *CL : *Loop) { 2437 OS.indent(CL->getLoopDepth()*2) 2438 << "Child Loop BB" << FunctionNumber << "_" 2439 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2440 << '\n'; 2441 PrintChildLoopComment(OS, CL, FunctionNumber); 2442 } 2443 } 2444 2445 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2446 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2447 const MachineLoopInfo *LI, 2448 const AsmPrinter &AP) { 2449 // Add loop depth information 2450 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2451 if (!Loop) return; 2452 2453 MachineBasicBlock *Header = Loop->getHeader(); 2454 assert(Header && "No header for loop"); 2455 2456 // If this block is not a loop header, just print out what is the loop header 2457 // and return. 2458 if (Header != &MBB) { 2459 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2460 Twine(AP.getFunctionNumber())+"_" + 2461 Twine(Loop->getHeader()->getNumber())+ 2462 " Depth="+Twine(Loop->getLoopDepth())); 2463 return; 2464 } 2465 2466 // Otherwise, it is a loop header. Print out information about child and 2467 // parent loops. 2468 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2469 2470 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2471 2472 OS << "=>"; 2473 OS.indent(Loop->getLoopDepth()*2-2); 2474 2475 OS << "This "; 2476 if (Loop->empty()) 2477 OS << "Inner "; 2478 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2479 2480 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2481 } 2482 2483 2484 /// EmitBasicBlockStart - This method prints the label for the specified 2485 /// MachineBasicBlock, an alignment (if present) and a comment describing 2486 /// it if appropriate. 2487 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 2488 // End the previous funclet and start a new one. 2489 if (MBB.isEHFuncletEntry()) { 2490 for (const HandlerInfo &HI : Handlers) { 2491 HI.Handler->endFunclet(); 2492 HI.Handler->beginFunclet(MBB); 2493 } 2494 } 2495 2496 // Emit an alignment directive for this block, if needed. 2497 if (unsigned Align = MBB.getAlignment()) 2498 EmitAlignment(Align); 2499 2500 // If the block has its address taken, emit any labels that were used to 2501 // reference the block. It is possible that there is more than one label 2502 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2503 // the references were generated. 2504 if (MBB.hasAddressTaken()) { 2505 const BasicBlock *BB = MBB.getBasicBlock(); 2506 if (isVerbose()) 2507 OutStreamer->AddComment("Block address taken"); 2508 2509 // MBBs can have their address taken as part of CodeGen without having 2510 // their corresponding BB's address taken in IR 2511 if (BB->hasAddressTaken()) 2512 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 2513 OutStreamer->EmitLabel(Sym); 2514 } 2515 2516 // Print some verbose block comments. 2517 if (isVerbose()) { 2518 if (const BasicBlock *BB = MBB.getBasicBlock()) { 2519 if (BB->hasName()) { 2520 BB->printAsOperand(OutStreamer->GetCommentOS(), 2521 /*PrintType=*/false, BB->getModule()); 2522 OutStreamer->GetCommentOS() << '\n'; 2523 } 2524 } 2525 emitBasicBlockLoopComments(MBB, LI, *this); 2526 } 2527 2528 // Print the main label for the block. 2529 if (MBB.pred_empty() || 2530 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) { 2531 if (isVerbose()) { 2532 // NOTE: Want this comment at start of line, don't emit with AddComment. 2533 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false); 2534 } 2535 } else { 2536 OutStreamer->EmitLabel(MBB.getSymbol()); 2537 } 2538 } 2539 2540 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 2541 bool IsDefinition) const { 2542 MCSymbolAttr Attr = MCSA_Invalid; 2543 2544 switch (Visibility) { 2545 default: break; 2546 case GlobalValue::HiddenVisibility: 2547 if (IsDefinition) 2548 Attr = MAI->getHiddenVisibilityAttr(); 2549 else 2550 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 2551 break; 2552 case GlobalValue::ProtectedVisibility: 2553 Attr = MAI->getProtectedVisibilityAttr(); 2554 break; 2555 } 2556 2557 if (Attr != MCSA_Invalid) 2558 OutStreamer->EmitSymbolAttribute(Sym, Attr); 2559 } 2560 2561 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 2562 /// exactly one predecessor and the control transfer mechanism between 2563 /// the predecessor and this block is a fall-through. 2564 bool AsmPrinter:: 2565 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 2566 // If this is a landing pad, it isn't a fall through. If it has no preds, 2567 // then nothing falls through to it. 2568 if (MBB->isEHPad() || MBB->pred_empty()) 2569 return false; 2570 2571 // If there isn't exactly one predecessor, it can't be a fall through. 2572 if (MBB->pred_size() > 1) 2573 return false; 2574 2575 // The predecessor has to be immediately before this block. 2576 MachineBasicBlock *Pred = *MBB->pred_begin(); 2577 if (!Pred->isLayoutSuccessor(MBB)) 2578 return false; 2579 2580 // If the block is completely empty, then it definitely does fall through. 2581 if (Pred->empty()) 2582 return true; 2583 2584 // Check the terminators in the previous blocks 2585 for (const auto &MI : Pred->terminators()) { 2586 // If it is not a simple branch, we are in a table somewhere. 2587 if (!MI.isBranch() || MI.isIndirectBranch()) 2588 return false; 2589 2590 // If we are the operands of one of the branches, this is not a fall 2591 // through. Note that targets with delay slots will usually bundle 2592 // terminators with the delay slot instruction. 2593 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 2594 if (OP->isJTI()) 2595 return false; 2596 if (OP->isMBB() && OP->getMBB() == MBB) 2597 return false; 2598 } 2599 } 2600 2601 return true; 2602 } 2603 2604 2605 2606 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 2607 if (!S.usesMetadata()) 2608 return nullptr; 2609 2610 assert(!S.useStatepoints() && "statepoints do not currently support custom" 2611 " stackmap formats, please see the documentation for a description of" 2612 " the default format. If you really need a custom serialized format," 2613 " please file a bug"); 2614 2615 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 2616 gcp_map_type::iterator GCPI = GCMap.find(&S); 2617 if (GCPI != GCMap.end()) 2618 return GCPI->second.get(); 2619 2620 auto Name = S.getName(); 2621 2622 for (GCMetadataPrinterRegistry::iterator 2623 I = GCMetadataPrinterRegistry::begin(), 2624 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 2625 if (Name == I->getName()) { 2626 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 2627 GMP->S = &S; 2628 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 2629 return IterBool.first->second.get(); 2630 } 2631 2632 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 2633 } 2634 2635 /// Pin vtable to this file. 2636 AsmPrinterHandler::~AsmPrinterHandler() {} 2637 2638 void AsmPrinterHandler::markFunctionEnd() {} 2639 2640 // In the binary's "xray_instr_map" section, an array of these function entries 2641 // describes each instrumentation point. When XRay patches your code, the index 2642 // into this table will be given to your handler as a patch point identifier. 2643 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out, 2644 const MCSymbol *CurrentFnSym) const { 2645 Out->EmitSymbolValue(Sled, Bytes); 2646 Out->EmitSymbolValue(CurrentFnSym, Bytes); 2647 auto Kind8 = static_cast<uint8_t>(Kind); 2648 Out->EmitBytes(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 2649 Out->EmitBytes( 2650 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 2651 Out->EmitZeros(2 * Bytes - 2); // Pad the previous two entries 2652 } 2653 2654 void AsmPrinter::emitXRayTable() { 2655 if (Sleds.empty()) 2656 return; 2657 2658 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 2659 auto Fn = MF->getFunction(); 2660 MCSection *Section = nullptr; 2661 if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) { 2662 if (Fn->hasComdat()) { 2663 Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 2664 ELF::SHF_ALLOC | ELF::SHF_GROUP, 0, 2665 Fn->getComdat()->getName()); 2666 } else { 2667 Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 2668 ELF::SHF_ALLOC); 2669 } 2670 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 2671 Section = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 2672 SectionKind::getReadOnlyWithRel()); 2673 } else { 2674 llvm_unreachable("Unsupported target"); 2675 } 2676 2677 // Before we switch over, we force a reference to a label inside the 2678 // xray_instr_map section. Since this function is always called just 2679 // before the function's end, we assume that this is happening after 2680 // the last return instruction. 2681 2682 auto WordSizeBytes = TM.getPointerSize(); 2683 MCSymbol *Tmp = OutContext.createTempSymbol("xray_synthetic_", true); 2684 OutStreamer->EmitCodeAlignment(16); 2685 OutStreamer->EmitSymbolValue(Tmp, WordSizeBytes, false); 2686 OutStreamer->SwitchSection(Section); 2687 OutStreamer->EmitLabel(Tmp); 2688 for (const auto &Sled : Sleds) 2689 Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym); 2690 2691 OutStreamer->SwitchSection(PrevSection); 2692 Sleds.clear(); 2693 } 2694 2695 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 2696 SledKind Kind) { 2697 auto Fn = MI.getParent()->getParent()->getFunction(); 2698 auto Attr = Fn->getFnAttribute("function-instrument"); 2699 bool AlwaysInstrument = 2700 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 2701 Sleds.emplace_back( 2702 XRayFunctionEntry{ Sled, CurrentFnSym, Kind, AlwaysInstrument, Fn }); 2703 } 2704 2705 uint16_t AsmPrinter::getDwarfVersion() const { 2706 return OutStreamer->getContext().getDwarfVersion(); 2707 } 2708 2709 void AsmPrinter::setDwarfVersion(uint16_t Version) { 2710 OutStreamer->getContext().setDwarfVersion(Version); 2711 } 2712