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 const MCExpr *Expr = lowerConstant(Alias.getAliasee()); 1169 1170 if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1171 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry); 1172 1173 // Emit the directives as assignments aka .set: 1174 OutStreamer->EmitAssignment(Name, Expr); 1175 1176 // If the aliasee does not correspond to a symbol in the output, i.e. the 1177 // alias is not of an object or the aliased object is private, then set the 1178 // size of the alias symbol from the type of the alias. We don't do this in 1179 // other situations as the alias and aliasee having differing types but same 1180 // size may be intentional. 1181 const GlobalObject *BaseObject = Alias.getBaseObject(); 1182 if (MAI->hasDotTypeDotSizeDirective() && Alias.getValueType()->isSized() && 1183 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1184 const DataLayout &DL = M.getDataLayout(); 1185 uint64_t Size = DL.getTypeAllocSize(Alias.getValueType()); 1186 OutStreamer->emitELFSize(cast<MCSymbolELF>(Name), 1187 MCConstantExpr::create(Size, OutContext)); 1188 } 1189 } 1190 1191 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1192 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1193 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1194 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1195 MP->finishAssembly(M, *MI, *this); 1196 1197 // Emit llvm.ident metadata in an '.ident' directive. 1198 EmitModuleIdents(M); 1199 1200 // Emit __morestack address if needed for indirect calls. 1201 if (MMI->usesMorestackAddr()) { 1202 unsigned Align = 1; 1203 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1204 getDataLayout(), SectionKind::getReadOnly(), 1205 /*C=*/nullptr, Align); 1206 OutStreamer->SwitchSection(ReadOnlySection); 1207 1208 MCSymbol *AddrSymbol = 1209 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1210 OutStreamer->EmitLabel(AddrSymbol); 1211 1212 unsigned PtrSize = M.getDataLayout().getPointerSize(0); 1213 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1214 PtrSize); 1215 } 1216 1217 // If we don't have any trampolines, then we don't require stack memory 1218 // to be executable. Some targets have a directive to declare this. 1219 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1220 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1221 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1222 OutStreamer->SwitchSection(S); 1223 1224 // Allow the target to emit any magic that it wants at the end of the file, 1225 // after everything else has gone out. 1226 EmitEndOfAsmFile(M); 1227 1228 delete Mang; Mang = nullptr; 1229 MMI = nullptr; 1230 1231 OutStreamer->Finish(); 1232 OutStreamer->reset(); 1233 1234 return false; 1235 } 1236 1237 MCSymbol *AsmPrinter::getCurExceptionSym() { 1238 if (!CurExceptionSym) 1239 CurExceptionSym = createTempSymbol("exception"); 1240 return CurExceptionSym; 1241 } 1242 1243 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1244 this->MF = &MF; 1245 // Get the function symbol. 1246 CurrentFnSym = getSymbol(MF.getFunction()); 1247 CurrentFnSymForSize = CurrentFnSym; 1248 CurrentFnBegin = nullptr; 1249 CurExceptionSym = nullptr; 1250 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1251 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() || 1252 MMI->hasEHFunclets() || NeedsLocalForSize) { 1253 CurrentFnBegin = createTempSymbol("func_begin"); 1254 if (NeedsLocalForSize) 1255 CurrentFnSymForSize = CurrentFnBegin; 1256 } 1257 1258 if (isVerbose()) 1259 LI = &getAnalysis<MachineLoopInfo>(); 1260 } 1261 1262 namespace { 1263 // Keep track the alignment, constpool entries per Section. 1264 struct SectionCPs { 1265 MCSection *S; 1266 unsigned Alignment; 1267 SmallVector<unsigned, 4> CPEs; 1268 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {} 1269 }; 1270 } 1271 1272 /// EmitConstantPool - Print to the current output stream assembly 1273 /// representations of the constants in the constant pool MCP. This is 1274 /// used to print out constants which have been "spilled to memory" by 1275 /// the code generator. 1276 /// 1277 void AsmPrinter::EmitConstantPool() { 1278 const MachineConstantPool *MCP = MF->getConstantPool(); 1279 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1280 if (CP.empty()) return; 1281 1282 // Calculate sections for constant pool entries. We collect entries to go into 1283 // the same section together to reduce amount of section switch statements. 1284 SmallVector<SectionCPs, 4> CPSections; 1285 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1286 const MachineConstantPoolEntry &CPE = CP[i]; 1287 unsigned Align = CPE.getAlignment(); 1288 1289 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1290 1291 const Constant *C = nullptr; 1292 if (!CPE.isMachineConstantPoolEntry()) 1293 C = CPE.Val.ConstVal; 1294 1295 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(), 1296 Kind, C, Align); 1297 1298 // The number of sections are small, just do a linear search from the 1299 // last section to the first. 1300 bool Found = false; 1301 unsigned SecIdx = CPSections.size(); 1302 while (SecIdx != 0) { 1303 if (CPSections[--SecIdx].S == S) { 1304 Found = true; 1305 break; 1306 } 1307 } 1308 if (!Found) { 1309 SecIdx = CPSections.size(); 1310 CPSections.push_back(SectionCPs(S, Align)); 1311 } 1312 1313 if (Align > CPSections[SecIdx].Alignment) 1314 CPSections[SecIdx].Alignment = Align; 1315 CPSections[SecIdx].CPEs.push_back(i); 1316 } 1317 1318 // Now print stuff into the calculated sections. 1319 const MCSection *CurSection = nullptr; 1320 unsigned Offset = 0; 1321 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1322 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1323 unsigned CPI = CPSections[i].CPEs[j]; 1324 MCSymbol *Sym = GetCPISymbol(CPI); 1325 if (!Sym->isUndefined()) 1326 continue; 1327 1328 if (CurSection != CPSections[i].S) { 1329 OutStreamer->SwitchSection(CPSections[i].S); 1330 EmitAlignment(Log2_32(CPSections[i].Alignment)); 1331 CurSection = CPSections[i].S; 1332 Offset = 0; 1333 } 1334 1335 MachineConstantPoolEntry CPE = CP[CPI]; 1336 1337 // Emit inter-object padding for alignment. 1338 unsigned AlignMask = CPE.getAlignment() - 1; 1339 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1340 OutStreamer->EmitZeros(NewOffset - Offset); 1341 1342 Type *Ty = CPE.getType(); 1343 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1344 1345 OutStreamer->EmitLabel(Sym); 1346 if (CPE.isMachineConstantPoolEntry()) 1347 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1348 else 1349 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1350 } 1351 } 1352 } 1353 1354 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 1355 /// by the current function to the current output stream. 1356 /// 1357 void AsmPrinter::EmitJumpTableInfo() { 1358 const DataLayout &DL = MF->getDataLayout(); 1359 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1360 if (!MJTI) return; 1361 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1362 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1363 if (JT.empty()) return; 1364 1365 // Pick the directive to use to print the jump table entries, and switch to 1366 // the appropriate section. 1367 const Function *F = MF->getFunction(); 1368 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1369 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1370 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1371 *F); 1372 if (JTInDiffSection) { 1373 // Drop it in the readonly section. 1374 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM); 1375 OutStreamer->SwitchSection(ReadOnlySection); 1376 } 1377 1378 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL))); 1379 1380 // Jump tables in code sections are marked with a data_region directive 1381 // where that's supported. 1382 if (!JTInDiffSection) 1383 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32); 1384 1385 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1386 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1387 1388 // If this jump table was deleted, ignore it. 1389 if (JTBBs.empty()) continue; 1390 1391 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1392 /// emit a .set directive for each unique entry. 1393 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1394 MAI->doesSetDirectiveSuppressesReloc()) { 1395 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1396 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1397 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1398 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1399 const MachineBasicBlock *MBB = JTBBs[ii]; 1400 if (!EmittedSets.insert(MBB).second) 1401 continue; 1402 1403 // .set LJTSet, LBB32-base 1404 const MCExpr *LHS = 1405 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1406 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1407 MCBinaryExpr::createSub(LHS, Base, 1408 OutContext)); 1409 } 1410 } 1411 1412 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1413 // before each jump table. The first label is never referenced, but tells 1414 // the assembler and linker the extents of the jump table object. The 1415 // second label is actually referenced by the code. 1416 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1417 // FIXME: This doesn't have to have any specific name, just any randomly 1418 // named and numbered 'l' label would work. Simplify GetJTISymbol. 1419 OutStreamer->EmitLabel(GetJTISymbol(JTI, true)); 1420 1421 OutStreamer->EmitLabel(GetJTISymbol(JTI)); 1422 1423 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1424 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1425 } 1426 if (!JTInDiffSection) 1427 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 1428 } 1429 1430 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1431 /// current stream. 1432 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1433 const MachineBasicBlock *MBB, 1434 unsigned UID) const { 1435 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1436 const MCExpr *Value = nullptr; 1437 switch (MJTI->getEntryKind()) { 1438 case MachineJumpTableInfo::EK_Inline: 1439 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1440 case MachineJumpTableInfo::EK_Custom32: 1441 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1442 MJTI, MBB, UID, OutContext); 1443 break; 1444 case MachineJumpTableInfo::EK_BlockAddress: 1445 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1446 // .word LBB123 1447 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1448 break; 1449 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1450 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1451 // with a relocation as gp-relative, e.g.: 1452 // .gprel32 LBB123 1453 MCSymbol *MBBSym = MBB->getSymbol(); 1454 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1455 return; 1456 } 1457 1458 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1459 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1460 // with a relocation as gp-relative, e.g.: 1461 // .gpdword LBB123 1462 MCSymbol *MBBSym = MBB->getSymbol(); 1463 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1464 return; 1465 } 1466 1467 case MachineJumpTableInfo::EK_LabelDifference32: { 1468 // Each entry is the address of the block minus the address of the jump 1469 // table. This is used for PIC jump tables where gprel32 is not supported. 1470 // e.g.: 1471 // .word LBB123 - LJTI1_2 1472 // If the .set directive avoids relocations, this is emitted as: 1473 // .set L4_5_set_123, LBB123 - LJTI1_2 1474 // .word L4_5_set_123 1475 if (MAI->doesSetDirectiveSuppressesReloc()) { 1476 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 1477 OutContext); 1478 break; 1479 } 1480 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1481 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1482 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 1483 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 1484 break; 1485 } 1486 } 1487 1488 assert(Value && "Unknown entry kind!"); 1489 1490 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 1491 OutStreamer->EmitValue(Value, EntrySize); 1492 } 1493 1494 1495 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1496 /// special global used by LLVM. If so, emit it and return true, otherwise 1497 /// do nothing and return false. 1498 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1499 if (GV->getName() == "llvm.used") { 1500 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1501 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1502 return true; 1503 } 1504 1505 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1506 if (StringRef(GV->getSection()) == "llvm.metadata" || 1507 GV->hasAvailableExternallyLinkage()) 1508 return true; 1509 1510 if (!GV->hasAppendingLinkage()) return false; 1511 1512 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1513 1514 if (GV->getName() == "llvm.global_ctors") { 1515 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1516 /* isCtor */ true); 1517 1518 if (TM.getRelocationModel() == Reloc::Static && 1519 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1520 StringRef Sym(".constructors_used"); 1521 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym), 1522 MCSA_Reference); 1523 } 1524 return true; 1525 } 1526 1527 if (GV->getName() == "llvm.global_dtors") { 1528 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1529 /* isCtor */ false); 1530 1531 if (TM.getRelocationModel() == Reloc::Static && 1532 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1533 StringRef Sym(".destructors_used"); 1534 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym), 1535 MCSA_Reference); 1536 } 1537 return true; 1538 } 1539 1540 return false; 1541 } 1542 1543 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1544 /// global in the specified llvm.used list for which emitUsedDirectiveFor 1545 /// is true, as being used with this directive. 1546 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 1547 // Should be an array of 'i8*'. 1548 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1549 const GlobalValue *GV = 1550 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1551 if (GV) 1552 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 1553 } 1554 } 1555 1556 namespace { 1557 struct Structor { 1558 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {} 1559 int Priority; 1560 llvm::Constant *Func; 1561 llvm::GlobalValue *ComdatKey; 1562 }; 1563 } // end namespace 1564 1565 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 1566 /// priority. 1567 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List, 1568 bool isCtor) { 1569 // Should be an array of '{ int, void ()* }' structs. The first value is the 1570 // init priority. 1571 if (!isa<ConstantArray>(List)) return; 1572 1573 // Sanity check the structors list. 1574 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1575 if (!InitList) return; // Not an array! 1576 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 1577 // FIXME: Only allow the 3-field form in LLVM 4.0. 1578 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3) 1579 return; // Not an array of two or three elements! 1580 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 1581 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr). 1582 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U))) 1583 return; // Not (int, ptr, ptr). 1584 1585 // Gather the structors in a form that's convenient for sorting by priority. 1586 SmallVector<Structor, 8> Structors; 1587 for (Value *O : InitList->operands()) { 1588 ConstantStruct *CS = dyn_cast<ConstantStruct>(O); 1589 if (!CS) continue; // Malformed. 1590 if (CS->getOperand(1)->isNullValue()) 1591 break; // Found a null terminator, skip the rest. 1592 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 1593 if (!Priority) continue; // Malformed. 1594 Structors.push_back(Structor()); 1595 Structor &S = Structors.back(); 1596 S.Priority = Priority->getLimitedValue(65535); 1597 S.Func = CS->getOperand(1); 1598 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue()) 1599 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 1600 } 1601 1602 // Emit the function pointers in the target-specific order 1603 unsigned Align = Log2_32(DL.getPointerPrefAlignment()); 1604 std::stable_sort(Structors.begin(), Structors.end(), 1605 [](const Structor &L, 1606 const Structor &R) { return L.Priority < R.Priority; }); 1607 for (Structor &S : Structors) { 1608 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 1609 const MCSymbol *KeySym = nullptr; 1610 if (GlobalValue *GV = S.ComdatKey) { 1611 if (GV->hasAvailableExternallyLinkage()) 1612 // If the associated variable is available_externally, some other TU 1613 // will provide its dynamic initializer. 1614 continue; 1615 1616 KeySym = getSymbol(GV); 1617 } 1618 MCSection *OutputSection = 1619 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 1620 : Obj.getStaticDtorSection(S.Priority, KeySym)); 1621 OutStreamer->SwitchSection(OutputSection); 1622 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 1623 EmitAlignment(Align); 1624 EmitXXStructor(DL, S.Func); 1625 } 1626 } 1627 1628 void AsmPrinter::EmitModuleIdents(Module &M) { 1629 if (!MAI->hasIdentDirective()) 1630 return; 1631 1632 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 1633 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1634 const MDNode *N = NMD->getOperand(i); 1635 assert(N->getNumOperands() == 1 && 1636 "llvm.ident metadata entry can have only one operand"); 1637 const MDString *S = cast<MDString>(N->getOperand(0)); 1638 OutStreamer->EmitIdent(S->getString()); 1639 } 1640 } 1641 } 1642 1643 //===--------------------------------------------------------------------===// 1644 // Emission and print routines 1645 // 1646 1647 /// EmitInt8 - Emit a byte directive and value. 1648 /// 1649 void AsmPrinter::EmitInt8(int Value) const { 1650 OutStreamer->EmitIntValue(Value, 1); 1651 } 1652 1653 /// EmitInt16 - Emit a short directive and value. 1654 /// 1655 void AsmPrinter::EmitInt16(int Value) const { 1656 OutStreamer->EmitIntValue(Value, 2); 1657 } 1658 1659 /// EmitInt32 - Emit a long directive and value. 1660 /// 1661 void AsmPrinter::EmitInt32(int Value) const { 1662 OutStreamer->EmitIntValue(Value, 4); 1663 } 1664 1665 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 1666 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 1667 /// .set if it avoids relocations. 1668 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1669 unsigned Size) const { 1670 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 1671 } 1672 1673 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 1674 /// where the size in bytes of the directive is specified by Size and Label 1675 /// specifies the label. This implicitly uses .set if it is available. 1676 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 1677 unsigned Size, 1678 bool IsSectionRelative) const { 1679 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 1680 OutStreamer->EmitCOFFSecRel32(Label); 1681 return; 1682 } 1683 1684 // Emit Label+Offset (or just Label if Offset is zero) 1685 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 1686 if (Offset) 1687 Expr = MCBinaryExpr::createAdd( 1688 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 1689 1690 OutStreamer->EmitValue(Expr, Size); 1691 } 1692 1693 //===----------------------------------------------------------------------===// 1694 1695 // EmitAlignment - Emit an alignment directive to the specified power of 1696 // two boundary. For example, if you pass in 3 here, you will get an 8 1697 // byte alignment. If a global value is specified, and if that global has 1698 // an explicit alignment requested, it will override the alignment request 1699 // if required for correctness. 1700 // 1701 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const { 1702 if (GV) 1703 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits); 1704 1705 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1706 1707 assert(NumBits < 1708 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 1709 "undefined behavior"); 1710 if (getCurrentSection()->getKind().isText()) 1711 OutStreamer->EmitCodeAlignment(1u << NumBits); 1712 else 1713 OutStreamer->EmitValueToAlignment(1u << NumBits); 1714 } 1715 1716 //===----------------------------------------------------------------------===// 1717 // Constant emission. 1718 //===----------------------------------------------------------------------===// 1719 1720 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 1721 MCContext &Ctx = OutContext; 1722 1723 if (CV->isNullValue() || isa<UndefValue>(CV)) 1724 return MCConstantExpr::create(0, Ctx); 1725 1726 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1727 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 1728 1729 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1730 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 1731 1732 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1733 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 1734 1735 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1736 if (!CE) { 1737 llvm_unreachable("Unknown constant value to lower!"); 1738 } 1739 1740 if (const MCExpr *RelocExpr 1741 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM)) 1742 return RelocExpr; 1743 1744 switch (CE->getOpcode()) { 1745 default: 1746 // If the code isn't optimized, there may be outstanding folding 1747 // opportunities. Attempt to fold the expression using DataLayout as a 1748 // last resort before giving up. 1749 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout())) 1750 if (C != CE) 1751 return lowerConstant(C); 1752 1753 // Otherwise report the problem to the user. 1754 { 1755 std::string S; 1756 raw_string_ostream OS(S); 1757 OS << "Unsupported expression in static initializer: "; 1758 CE->printAsOperand(OS, /*PrintType=*/false, 1759 !MF ? nullptr : MF->getFunction()->getParent()); 1760 report_fatal_error(OS.str()); 1761 } 1762 case Instruction::GetElementPtr: { 1763 // Generate a symbolic expression for the byte address 1764 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 1765 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 1766 1767 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 1768 if (!OffsetAI) 1769 return Base; 1770 1771 int64_t Offset = OffsetAI.getSExtValue(); 1772 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 1773 Ctx); 1774 } 1775 1776 case Instruction::Trunc: 1777 // We emit the value and depend on the assembler to truncate the generated 1778 // expression properly. This is important for differences between 1779 // blockaddress labels. Since the two labels are in the same function, it 1780 // is reasonable to treat their delta as a 32-bit value. 1781 // FALL THROUGH. 1782 case Instruction::BitCast: 1783 return lowerConstant(CE->getOperand(0)); 1784 1785 case Instruction::IntToPtr: { 1786 const DataLayout &DL = getDataLayout(); 1787 1788 // Handle casts to pointers by changing them into casts to the appropriate 1789 // integer type. This promotes constant folding and simplifies this code. 1790 Constant *Op = CE->getOperand(0); 1791 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 1792 false/*ZExt*/); 1793 return lowerConstant(Op); 1794 } 1795 1796 case Instruction::PtrToInt: { 1797 const DataLayout &DL = getDataLayout(); 1798 1799 // Support only foldable casts to/from pointers that can be eliminated by 1800 // changing the pointer to the appropriately sized integer type. 1801 Constant *Op = CE->getOperand(0); 1802 Type *Ty = CE->getType(); 1803 1804 const MCExpr *OpExpr = lowerConstant(Op); 1805 1806 // We can emit the pointer value into this slot if the slot is an 1807 // integer slot equal to the size of the pointer. 1808 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType())) 1809 return OpExpr; 1810 1811 // Otherwise the pointer is smaller than the resultant integer, mask off 1812 // the high bits so we are sure to get a proper truncation if the input is 1813 // a constant expr. 1814 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 1815 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 1816 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 1817 } 1818 1819 // The MC library also has a right-shift operator, but it isn't consistently 1820 // signed or unsigned between different targets. 1821 case Instruction::Add: 1822 case Instruction::Sub: 1823 case Instruction::Mul: 1824 case Instruction::SDiv: 1825 case Instruction::SRem: 1826 case Instruction::Shl: 1827 case Instruction::And: 1828 case Instruction::Or: 1829 case Instruction::Xor: { 1830 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 1831 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 1832 switch (CE->getOpcode()) { 1833 default: llvm_unreachable("Unknown binary operator constant cast expr"); 1834 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 1835 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1836 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 1837 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 1838 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 1839 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 1840 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 1841 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 1842 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 1843 } 1844 } 1845 } 1846 } 1847 1848 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 1849 AsmPrinter &AP, 1850 const Constant *BaseCV = nullptr, 1851 uint64_t Offset = 0); 1852 1853 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 1854 1855 /// isRepeatedByteSequence - Determine whether the given value is 1856 /// composed of a repeated sequence of identical bytes and return the 1857 /// byte value. If it is not a repeated sequence, return -1. 1858 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 1859 StringRef Data = V->getRawDataValues(); 1860 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 1861 char C = Data[0]; 1862 for (unsigned i = 1, e = Data.size(); i != e; ++i) 1863 if (Data[i] != C) return -1; 1864 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 1865 } 1866 1867 1868 /// isRepeatedByteSequence - Determine whether the given value is 1869 /// composed of a repeated sequence of identical bytes and return the 1870 /// byte value. If it is not a repeated sequence, return -1. 1871 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 1872 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 1873 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 1874 assert(Size % 8 == 0); 1875 1876 // Extend the element to take zero padding into account. 1877 APInt Value = CI->getValue().zextOrSelf(Size); 1878 if (!Value.isSplat(8)) 1879 return -1; 1880 1881 return Value.zextOrTrunc(8).getZExtValue(); 1882 } 1883 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 1884 // Make sure all array elements are sequences of the same repeated 1885 // byte. 1886 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 1887 Constant *Op0 = CA->getOperand(0); 1888 int Byte = isRepeatedByteSequence(Op0, DL); 1889 if (Byte == -1) 1890 return -1; 1891 1892 // All array elements must be equal. 1893 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 1894 if (CA->getOperand(i) != Op0) 1895 return -1; 1896 return Byte; 1897 } 1898 1899 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 1900 return isRepeatedByteSequence(CDS); 1901 1902 return -1; 1903 } 1904 1905 static void emitGlobalConstantDataSequential(const DataLayout &DL, 1906 const ConstantDataSequential *CDS, 1907 AsmPrinter &AP) { 1908 1909 // See if we can aggregate this into a .fill, if so, emit it as such. 1910 int Value = isRepeatedByteSequence(CDS, DL); 1911 if (Value != -1) { 1912 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 1913 // Don't emit a 1-byte object as a .fill. 1914 if (Bytes > 1) 1915 return AP.OutStreamer->EmitFill(Bytes, Value); 1916 } 1917 1918 // If this can be emitted with .ascii/.asciz, emit it as such. 1919 if (CDS->isString()) 1920 return AP.OutStreamer->EmitBytes(CDS->getAsString()); 1921 1922 // Otherwise, emit the values in successive locations. 1923 unsigned ElementByteSize = CDS->getElementByteSize(); 1924 if (isa<IntegerType>(CDS->getElementType())) { 1925 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1926 if (AP.isVerbose()) 1927 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 1928 CDS->getElementAsInteger(i)); 1929 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i), 1930 ElementByteSize); 1931 } 1932 } else { 1933 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 1934 emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP); 1935 } 1936 1937 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 1938 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 1939 CDS->getNumElements(); 1940 if (unsigned Padding = Size - EmittedSize) 1941 AP.OutStreamer->EmitZeros(Padding); 1942 1943 } 1944 1945 static void emitGlobalConstantArray(const DataLayout &DL, 1946 const ConstantArray *CA, AsmPrinter &AP, 1947 const Constant *BaseCV, uint64_t Offset) { 1948 // See if we can aggregate some values. Make sure it can be 1949 // represented as a series of bytes of the constant value. 1950 int Value = isRepeatedByteSequence(CA, DL); 1951 1952 if (Value != -1) { 1953 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 1954 AP.OutStreamer->EmitFill(Bytes, Value); 1955 } 1956 else { 1957 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 1958 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 1959 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 1960 } 1961 } 1962 } 1963 1964 static void emitGlobalConstantVector(const DataLayout &DL, 1965 const ConstantVector *CV, AsmPrinter &AP) { 1966 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 1967 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 1968 1969 unsigned Size = DL.getTypeAllocSize(CV->getType()); 1970 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 1971 CV->getType()->getNumElements(); 1972 if (unsigned Padding = Size - EmittedSize) 1973 AP.OutStreamer->EmitZeros(Padding); 1974 } 1975 1976 static void emitGlobalConstantStruct(const DataLayout &DL, 1977 const ConstantStruct *CS, AsmPrinter &AP, 1978 const Constant *BaseCV, uint64_t Offset) { 1979 // Print the fields in successive locations. Pad to align if needed! 1980 unsigned Size = DL.getTypeAllocSize(CS->getType()); 1981 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 1982 uint64_t SizeSoFar = 0; 1983 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 1984 const Constant *Field = CS->getOperand(i); 1985 1986 // Print the actual field value. 1987 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 1988 1989 // Check if padding is needed and insert one or more 0s. 1990 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 1991 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 1992 - Layout->getElementOffset(i)) - FieldSize; 1993 SizeSoFar += FieldSize + PadSize; 1994 1995 // Insert padding - this may include padding to increase the size of the 1996 // current field up to the ABI size (if the struct is not packed) as well 1997 // as padding to ensure that the next field starts at the right offset. 1998 AP.OutStreamer->EmitZeros(PadSize); 1999 } 2000 assert(SizeSoFar == Layout->getSizeInBytes() && 2001 "Layout of constant struct may be incorrect!"); 2002 } 2003 2004 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2005 APInt API = CFP->getValueAPF().bitcastToAPInt(); 2006 2007 // First print a comment with what we think the original floating-point value 2008 // should have been. 2009 if (AP.isVerbose()) { 2010 SmallString<8> StrVal; 2011 CFP->getValueAPF().toString(StrVal); 2012 2013 if (CFP->getType()) 2014 CFP->getType()->print(AP.OutStreamer->GetCommentOS()); 2015 else 2016 AP.OutStreamer->GetCommentOS() << "Printing <null> Type"; 2017 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2018 } 2019 2020 // Now iterate through the APInt chunks, emitting them in endian-correct 2021 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2022 // floats). 2023 unsigned NumBytes = API.getBitWidth() / 8; 2024 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2025 const uint64_t *p = API.getRawData(); 2026 2027 // PPC's long double has odd notions of endianness compared to how LLVM 2028 // handles it: p[0] goes first for *big* endian on PPC. 2029 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) { 2030 int Chunk = API.getNumWords() - 1; 2031 2032 if (TrailingBytes) 2033 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes); 2034 2035 for (; Chunk >= 0; --Chunk) 2036 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2037 } else { 2038 unsigned Chunk; 2039 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2040 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2041 2042 if (TrailingBytes) 2043 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes); 2044 } 2045 2046 // Emit the tail padding for the long double. 2047 const DataLayout &DL = AP.getDataLayout(); 2048 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) - 2049 DL.getTypeStoreSize(CFP->getType())); 2050 } 2051 2052 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2053 const DataLayout &DL = AP.getDataLayout(); 2054 unsigned BitWidth = CI->getBitWidth(); 2055 2056 // Copy the value as we may massage the layout for constants whose bit width 2057 // is not a multiple of 64-bits. 2058 APInt Realigned(CI->getValue()); 2059 uint64_t ExtraBits = 0; 2060 unsigned ExtraBitsSize = BitWidth & 63; 2061 2062 if (ExtraBitsSize) { 2063 // The bit width of the data is not a multiple of 64-bits. 2064 // The extra bits are expected to be at the end of the chunk of the memory. 2065 // Little endian: 2066 // * Nothing to be done, just record the extra bits to emit. 2067 // Big endian: 2068 // * Record the extra bits to emit. 2069 // * Realign the raw data to emit the chunks of 64-bits. 2070 if (DL.isBigEndian()) { 2071 // Basically the structure of the raw data is a chunk of 64-bits cells: 2072 // 0 1 BitWidth / 64 2073 // [chunk1][chunk2] ... [chunkN]. 2074 // The most significant chunk is chunkN and it should be emitted first. 2075 // However, due to the alignment issue chunkN contains useless bits. 2076 // Realign the chunks so that they contain only useless information: 2077 // ExtraBits 0 1 (BitWidth / 64) - 1 2078 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2079 ExtraBits = Realigned.getRawData()[0] & 2080 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2081 Realigned = Realigned.lshr(ExtraBitsSize); 2082 } else 2083 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2084 } 2085 2086 // We don't expect assemblers to support integer data directives 2087 // for more than 64 bits, so we emit the data in at most 64-bit 2088 // quantities at a time. 2089 const uint64_t *RawData = Realigned.getRawData(); 2090 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2091 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2092 AP.OutStreamer->EmitIntValue(Val, 8); 2093 } 2094 2095 if (ExtraBitsSize) { 2096 // Emit the extra bits after the 64-bits chunks. 2097 2098 // Emit a directive that fills the expected size. 2099 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType()); 2100 Size -= (BitWidth / 64) * 8; 2101 assert(Size && Size * 8 >= ExtraBitsSize && 2102 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2103 == ExtraBits && "Directive too small for extra bits."); 2104 AP.OutStreamer->EmitIntValue(ExtraBits, Size); 2105 } 2106 } 2107 2108 /// \brief Transform a not absolute MCExpr containing a reference to a GOT 2109 /// equivalent global, by a target specific GOT pc relative access to the 2110 /// final symbol. 2111 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2112 const Constant *BaseCst, 2113 uint64_t Offset) { 2114 // The global @foo below illustrates a global that uses a got equivalent. 2115 // 2116 // @bar = global i32 42 2117 // @gotequiv = private unnamed_addr constant i32* @bar 2118 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2119 // i64 ptrtoint (i32* @foo to i64)) 2120 // to i32) 2121 // 2122 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2123 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2124 // form: 2125 // 2126 // foo = cstexpr, where 2127 // cstexpr := <gotequiv> - "." + <cst> 2128 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2129 // 2130 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2131 // 2132 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2133 // gotpcrelcst := <offset from @foo base> + <cst> 2134 // 2135 MCValue MV; 2136 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2137 return; 2138 const MCSymbolRefExpr *SymA = MV.getSymA(); 2139 if (!SymA) 2140 return; 2141 2142 // Check that GOT equivalent symbol is cached. 2143 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2144 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2145 return; 2146 2147 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2148 if (!BaseGV) 2149 return; 2150 2151 // Check for a valid base symbol 2152 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2153 const MCSymbolRefExpr *SymB = MV.getSymB(); 2154 2155 if (!SymB || BaseSym != &SymB->getSymbol()) 2156 return; 2157 2158 // Make sure to match: 2159 // 2160 // gotpcrelcst := <offset from @foo base> + <cst> 2161 // 2162 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2163 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2164 // if the target knows how to encode it. 2165 // 2166 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2167 if (GOTPCRelCst < 0) 2168 return; 2169 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2170 return; 2171 2172 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2173 // 2174 // bar: 2175 // .long 42 2176 // gotequiv: 2177 // .quad bar 2178 // foo: 2179 // .long gotequiv - "." + <cst> 2180 // 2181 // is replaced by the target specific equivalent to: 2182 // 2183 // bar: 2184 // .long 42 2185 // foo: 2186 // .long bar@GOTPCREL+<gotpcrelcst> 2187 // 2188 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2189 const GlobalVariable *GV = Result.first; 2190 int NumUses = (int)Result.second; 2191 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2192 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2193 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2194 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2195 2196 // Update GOT equivalent usage information 2197 --NumUses; 2198 if (NumUses >= 0) 2199 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2200 } 2201 2202 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2203 AsmPrinter &AP, const Constant *BaseCV, 2204 uint64_t Offset) { 2205 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2206 2207 // Globals with sub-elements such as combinations of arrays and structs 2208 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2209 // constant symbol base and the current position with BaseCV and Offset. 2210 if (!BaseCV && CV->hasOneUse()) 2211 BaseCV = dyn_cast<Constant>(CV->user_back()); 2212 2213 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2214 return AP.OutStreamer->EmitZeros(Size); 2215 2216 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2217 switch (Size) { 2218 case 1: 2219 case 2: 2220 case 4: 2221 case 8: 2222 if (AP.isVerbose()) 2223 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2224 CI->getZExtValue()); 2225 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size); 2226 return; 2227 default: 2228 emitGlobalConstantLargeInt(CI, AP); 2229 return; 2230 } 2231 } 2232 2233 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2234 return emitGlobalConstantFP(CFP, AP); 2235 2236 if (isa<ConstantPointerNull>(CV)) { 2237 AP.OutStreamer->EmitIntValue(0, Size); 2238 return; 2239 } 2240 2241 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2242 return emitGlobalConstantDataSequential(DL, CDS, AP); 2243 2244 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2245 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2246 2247 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2248 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2249 2250 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2251 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2252 // vectors). 2253 if (CE->getOpcode() == Instruction::BitCast) 2254 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2255 2256 if (Size > 8) { 2257 // If the constant expression's size is greater than 64-bits, then we have 2258 // to emit the value in chunks. Try to constant fold the value and emit it 2259 // that way. 2260 Constant *New = ConstantFoldConstantExpression(CE, DL); 2261 if (New && New != CE) 2262 return emitGlobalConstantImpl(DL, New, AP); 2263 } 2264 } 2265 2266 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2267 return emitGlobalConstantVector(DL, V, AP); 2268 2269 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2270 // thread the streamer with EmitValue. 2271 const MCExpr *ME = AP.lowerConstant(CV); 2272 2273 // Since lowerConstant already folded and got rid of all IR pointer and 2274 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2275 // directly. 2276 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2277 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2278 2279 AP.OutStreamer->EmitValue(ME, Size); 2280 } 2281 2282 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2283 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2284 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2285 if (Size) 2286 emitGlobalConstantImpl(DL, CV, *this); 2287 else if (MAI->hasSubsectionsViaSymbols()) { 2288 // If the global has zero size, emit a single byte so that two labels don't 2289 // look like they are at the same location. 2290 OutStreamer->EmitIntValue(0, 1); 2291 } 2292 } 2293 2294 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2295 // Target doesn't support this yet! 2296 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2297 } 2298 2299 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2300 if (Offset > 0) 2301 OS << '+' << Offset; 2302 else if (Offset < 0) 2303 OS << Offset; 2304 } 2305 2306 //===----------------------------------------------------------------------===// 2307 // Symbol Lowering Routines. 2308 //===----------------------------------------------------------------------===// 2309 2310 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2311 return OutContext.createTempSymbol(Name, true); 2312 } 2313 2314 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2315 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2316 } 2317 2318 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2319 return MMI->getAddrLabelSymbol(BB); 2320 } 2321 2322 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2323 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2324 const DataLayout &DL = getDataLayout(); 2325 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2326 "CPI" + Twine(getFunctionNumber()) + "_" + 2327 Twine(CPID)); 2328 } 2329 2330 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2331 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2332 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2333 } 2334 2335 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2336 /// FIXME: privatize to AsmPrinter. 2337 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2338 const DataLayout &DL = getDataLayout(); 2339 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2340 Twine(getFunctionNumber()) + "_" + 2341 Twine(UID) + "_set_" + Twine(MBBID)); 2342 } 2343 2344 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2345 StringRef Suffix) const { 2346 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang, 2347 TM); 2348 } 2349 2350 /// Return the MCSymbol for the specified ExternalSymbol. 2351 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2352 SmallString<60> NameStr; 2353 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2354 return OutContext.getOrCreateSymbol(NameStr); 2355 } 2356 2357 2358 2359 /// PrintParentLoopComment - Print comments about parent loops of this one. 2360 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2361 unsigned FunctionNumber) { 2362 if (!Loop) return; 2363 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2364 OS.indent(Loop->getLoopDepth()*2) 2365 << "Parent Loop BB" << FunctionNumber << "_" 2366 << Loop->getHeader()->getNumber() 2367 << " Depth=" << Loop->getLoopDepth() << '\n'; 2368 } 2369 2370 2371 /// PrintChildLoopComment - Print comments about child loops within 2372 /// the loop for this basic block, with nesting. 2373 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2374 unsigned FunctionNumber) { 2375 // Add child loop information 2376 for (const MachineLoop *CL : *Loop) { 2377 OS.indent(CL->getLoopDepth()*2) 2378 << "Child Loop BB" << FunctionNumber << "_" 2379 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2380 << '\n'; 2381 PrintChildLoopComment(OS, CL, FunctionNumber); 2382 } 2383 } 2384 2385 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2386 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2387 const MachineLoopInfo *LI, 2388 const AsmPrinter &AP) { 2389 // Add loop depth information 2390 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2391 if (!Loop) return; 2392 2393 MachineBasicBlock *Header = Loop->getHeader(); 2394 assert(Header && "No header for loop"); 2395 2396 // If this block is not a loop header, just print out what is the loop header 2397 // and return. 2398 if (Header != &MBB) { 2399 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2400 Twine(AP.getFunctionNumber())+"_" + 2401 Twine(Loop->getHeader()->getNumber())+ 2402 " Depth="+Twine(Loop->getLoopDepth())); 2403 return; 2404 } 2405 2406 // Otherwise, it is a loop header. Print out information about child and 2407 // parent loops. 2408 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2409 2410 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2411 2412 OS << "=>"; 2413 OS.indent(Loop->getLoopDepth()*2-2); 2414 2415 OS << "This "; 2416 if (Loop->empty()) 2417 OS << "Inner "; 2418 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2419 2420 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2421 } 2422 2423 2424 /// EmitBasicBlockStart - This method prints the label for the specified 2425 /// MachineBasicBlock, an alignment (if present) and a comment describing 2426 /// it if appropriate. 2427 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 2428 // End the previous funclet and start a new one. 2429 if (MBB.isEHFuncletEntry()) { 2430 for (const HandlerInfo &HI : Handlers) { 2431 HI.Handler->endFunclet(); 2432 HI.Handler->beginFunclet(MBB); 2433 } 2434 } 2435 2436 // Emit an alignment directive for this block, if needed. 2437 if (unsigned Align = MBB.getAlignment()) 2438 EmitAlignment(Align); 2439 2440 // If the block has its address taken, emit any labels that were used to 2441 // reference the block. It is possible that there is more than one label 2442 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2443 // the references were generated. 2444 if (MBB.hasAddressTaken()) { 2445 const BasicBlock *BB = MBB.getBasicBlock(); 2446 if (isVerbose()) 2447 OutStreamer->AddComment("Block address taken"); 2448 2449 // MBBs can have their address taken as part of CodeGen without having 2450 // their corresponding BB's address taken in IR 2451 if (BB->hasAddressTaken()) 2452 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 2453 OutStreamer->EmitLabel(Sym); 2454 } 2455 2456 // Print some verbose block comments. 2457 if (isVerbose()) { 2458 if (const BasicBlock *BB = MBB.getBasicBlock()) { 2459 if (BB->hasName()) { 2460 BB->printAsOperand(OutStreamer->GetCommentOS(), 2461 /*PrintType=*/false, BB->getModule()); 2462 OutStreamer->GetCommentOS() << '\n'; 2463 } 2464 } 2465 emitBasicBlockLoopComments(MBB, LI, *this); 2466 } 2467 2468 // Print the main label for the block. 2469 if (MBB.pred_empty() || 2470 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) { 2471 if (isVerbose()) { 2472 // NOTE: Want this comment at start of line, don't emit with AddComment. 2473 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false); 2474 } 2475 } else { 2476 OutStreamer->EmitLabel(MBB.getSymbol()); 2477 } 2478 } 2479 2480 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 2481 bool IsDefinition) const { 2482 MCSymbolAttr Attr = MCSA_Invalid; 2483 2484 switch (Visibility) { 2485 default: break; 2486 case GlobalValue::HiddenVisibility: 2487 if (IsDefinition) 2488 Attr = MAI->getHiddenVisibilityAttr(); 2489 else 2490 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 2491 break; 2492 case GlobalValue::ProtectedVisibility: 2493 Attr = MAI->getProtectedVisibilityAttr(); 2494 break; 2495 } 2496 2497 if (Attr != MCSA_Invalid) 2498 OutStreamer->EmitSymbolAttribute(Sym, Attr); 2499 } 2500 2501 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 2502 /// exactly one predecessor and the control transfer mechanism between 2503 /// the predecessor and this block is a fall-through. 2504 bool AsmPrinter:: 2505 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 2506 // If this is a landing pad, it isn't a fall through. If it has no preds, 2507 // then nothing falls through to it. 2508 if (MBB->isEHPad() || MBB->pred_empty()) 2509 return false; 2510 2511 // If there isn't exactly one predecessor, it can't be a fall through. 2512 if (MBB->pred_size() > 1) 2513 return false; 2514 2515 // The predecessor has to be immediately before this block. 2516 MachineBasicBlock *Pred = *MBB->pred_begin(); 2517 if (!Pred->isLayoutSuccessor(MBB)) 2518 return false; 2519 2520 // If the block is completely empty, then it definitely does fall through. 2521 if (Pred->empty()) 2522 return true; 2523 2524 // Check the terminators in the previous blocks 2525 for (const auto &MI : Pred->terminators()) { 2526 // If it is not a simple branch, we are in a table somewhere. 2527 if (!MI.isBranch() || MI.isIndirectBranch()) 2528 return false; 2529 2530 // If we are the operands of one of the branches, this is not a fall 2531 // through. Note that targets with delay slots will usually bundle 2532 // terminators with the delay slot instruction. 2533 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 2534 if (OP->isJTI()) 2535 return false; 2536 if (OP->isMBB() && OP->getMBB() == MBB) 2537 return false; 2538 } 2539 } 2540 2541 return true; 2542 } 2543 2544 2545 2546 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 2547 if (!S.usesMetadata()) 2548 return nullptr; 2549 2550 assert(!S.useStatepoints() && "statepoints do not currently support custom" 2551 " stackmap formats, please see the documentation for a description of" 2552 " the default format. If you really need a custom serialized format," 2553 " please file a bug"); 2554 2555 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 2556 gcp_map_type::iterator GCPI = GCMap.find(&S); 2557 if (GCPI != GCMap.end()) 2558 return GCPI->second.get(); 2559 2560 const char *Name = S.getName().c_str(); 2561 2562 for (GCMetadataPrinterRegistry::iterator 2563 I = GCMetadataPrinterRegistry::begin(), 2564 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 2565 if (strcmp(Name, I->getName()) == 0) { 2566 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 2567 GMP->S = &S; 2568 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 2569 return IterBool.first->second.get(); 2570 } 2571 2572 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 2573 } 2574 2575 /// Pin vtable to this file. 2576 AsmPrinterHandler::~AsmPrinterHandler() {} 2577 2578 void AsmPrinterHandler::markFunctionEnd() {} 2579