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