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