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