1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "WinException.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/MachineModuleInfoImpls.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/MCSymbolELF.h"
44 #include "llvm/MC/MCValue.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetLoweringObjectFile.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
58 #define DEBUG_TYPE "asm-printer"
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";
65 STATISTIC(EmittedInsts, "Number of machine instrs printed");
67 char AsmPrinter::ID = 0;
69 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
70 static gcp_map_type &getGCMap(void *&P) {
72 P = new gcp_map_type();
73 return *(gcp_map_type*)P;
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
80 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
81 unsigned InBits = 0) {
83 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84 NumBits = DL.getPreferredAlignmentLog(GVar);
86 // If InBits is specified, round it to it.
90 // If the GV has a specified alignment, take it into account.
91 if (GV->getAlignment() == 0)
94 unsigned GVAlign = Log2_32(GV->getAlignment());
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())
103 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
104 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
105 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
106 LastMI(nullptr), LastFn(0), Counter(~0U) {
111 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
112 CurrentFnBegin = nullptr;
113 CurrentFnEnd = nullptr;
114 GCMetadataPrinters = nullptr;
115 VerboseAsm = OutStreamer->isVerboseAsm();
118 AsmPrinter::~AsmPrinter() {
119 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
121 if (GCMetadataPrinters) {
122 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
125 GCMetadataPrinters = nullptr;
129 /// getFunctionNumber - Return a unique ID for the current function.
131 unsigned AsmPrinter::getFunctionNumber() const {
132 return MF->getFunctionNumber();
135 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
136 return *TM.getObjFileLowering();
139 /// getDataLayout - Return information about data layout.
140 const DataLayout &AsmPrinter::getDataLayout() const {
141 return *TM.getDataLayout();
144 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
145 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
146 return MF->getSubtarget<MCSubtargetInfo>();
149 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
150 S.EmitInstruction(Inst, getSubtargetInfo());
153 StringRef AsmPrinter::getTargetTriple() const {
154 return TM.getTargetTriple();
157 /// getCurrentSection() - Return the current section we are emitting to.
158 const MCSection *AsmPrinter::getCurrentSection() const {
159 return OutStreamer->getCurrentSection().first;
164 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.setPreservesAll();
166 MachineFunctionPass::getAnalysisUsage(AU);
167 AU.addRequired<MachineModuleInfo>();
168 AU.addRequired<GCModuleInfo>();
170 AU.addRequired<MachineLoopInfo>();
173 bool AsmPrinter::doInitialization(Module &M) {
174 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
176 // Initialize TargetLoweringObjectFile.
177 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
178 .Initialize(OutContext, TM);
180 OutStreamer->InitSections(false);
182 Mang = new Mangler(TM.getDataLayout());
184 // Emit the version-min deplyment target directive if needed.
186 // FIXME: If we end up with a collection of these sorts of Darwin-specific
187 // or ELF-specific things, it may make sense to have a platform helper class
188 // that will work with the target helper class. For now keep it here, as the
189 // alternative is duplicated code in each of the target asm printers that
190 // use the directive, where it would need the same conditionalization
192 Triple TT(getTargetTriple());
193 if (TT.isOSDarwin()) {
194 unsigned Major, Minor, Update;
195 TT.getOSVersion(Major, Minor, Update);
196 // If there is a version specified, Major will be non-zero.
198 OutStreamer->EmitVersionMin((TT.isMacOSX() ?
199 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
200 Major, Minor, Update);
203 // Allow the target to emit any magic that it wants at the start of the file.
204 EmitStartOfAsmFile(M);
206 // Very minimal debug info. It is ignored if we emit actual debug info. If we
207 // don't, this at least helps the user find where a global came from.
208 if (MAI->hasSingleParameterDotFile()) {
210 OutStreamer->EmitFileDirective(M.getModuleIdentifier());
213 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
214 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
216 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
217 MP->beginAssembly(M, *MI, *this);
219 // Emit module-level inline asm if it exists.
220 if (!M.getModuleInlineAsm().empty()) {
221 // We're at the module level. Construct MCSubtarget from the default CPU
222 // and target triple.
223 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
224 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
225 OutStreamer->AddComment("Start of file scope inline assembly");
226 OutStreamer->AddBlankLine();
227 EmitInlineAsm(M.getModuleInlineAsm()+"\n", *STI, TM.Options.MCOptions);
228 OutStreamer->AddComment("End of file scope inline assembly");
229 OutStreamer->AddBlankLine();
232 if (MAI->doesSupportDebugInformation()) {
233 bool skip_dwarf = false;
234 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
235 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
237 CodeViewLineTablesGroupName));
238 // FIXME: Don't emit DWARF debug info if there's at least one function
239 // with AddressSanitizer instrumentation.
240 // This is a band-aid fix for PR22032.
241 for (auto &F : M.functions()) {
242 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
249 DD = new DwarfDebug(this, &M);
250 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
254 EHStreamer *ES = nullptr;
255 switch (MAI->getExceptionHandlingType()) {
256 case ExceptionHandling::None:
258 case ExceptionHandling::SjLj:
259 case ExceptionHandling::DwarfCFI:
260 ES = new DwarfCFIException(this);
262 case ExceptionHandling::ARM:
263 ES = new ARMException(this);
265 case ExceptionHandling::WinEH:
266 switch (MAI->getWinEHEncodingType()) {
267 default: llvm_unreachable("unsupported unwinding information encoding");
268 case WinEH::EncodingType::Invalid:
270 case WinEH::EncodingType::X86:
271 case WinEH::EncodingType::Itanium:
272 ES = new WinException(this);
278 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
282 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
283 if (!MAI.hasWeakDefCanBeHiddenDirective())
286 return canBeOmittedFromSymbolTable(GV);
289 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
290 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
292 case GlobalValue::CommonLinkage:
293 case GlobalValue::LinkOnceAnyLinkage:
294 case GlobalValue::LinkOnceODRLinkage:
295 case GlobalValue::WeakAnyLinkage:
296 case GlobalValue::WeakODRLinkage:
297 if (MAI->hasWeakDefDirective()) {
299 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
301 if (!canBeHidden(GV, *MAI))
302 // .weak_definition _foo
303 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
305 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
306 } else if (MAI->hasLinkOnceDirective()) {
308 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
309 //NOTE: linkonce is handled by the section the symbol was assigned to.
312 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
315 case GlobalValue::AppendingLinkage:
316 // FIXME: appending linkage variables should go into a section of
317 // their name or something. For now, just emit them as external.
318 case GlobalValue::ExternalLinkage:
319 // If external or appending, declare as a global symbol.
321 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
323 case GlobalValue::PrivateLinkage:
324 case GlobalValue::InternalLinkage:
326 case GlobalValue::AvailableExternallyLinkage:
327 llvm_unreachable("Should never emit this");
328 case GlobalValue::ExternalWeakLinkage:
329 llvm_unreachable("Don't know how to emit these");
331 llvm_unreachable("Unknown linkage type!");
334 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
335 const GlobalValue *GV) const {
336 TM.getNameWithPrefix(Name, GV, *Mang);
339 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
340 return TM.getSymbol(GV, *Mang);
343 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
344 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
345 if (GV->hasInitializer()) {
346 // Check to see if this is a special global used by LLVM, if so, emit it.
347 if (EmitSpecialLLVMGlobal(GV))
350 // Skip the emission of global equivalents. The symbol can be emitted later
351 // on by emitGlobalGOTEquivs in case it turns out to be needed.
352 if (GlobalGOTEquivs.count(getSymbol(GV)))
356 GV->printAsOperand(OutStreamer->GetCommentOS(),
357 /*PrintType=*/false, GV->getParent());
358 OutStreamer->GetCommentOS() << '\n';
362 MCSymbol *GVSym = getSymbol(GV);
363 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
365 if (!GV->hasInitializer()) // External globals require no extra code.
368 GVSym->redefineIfPossible();
369 if (GVSym->isDefined() || GVSym->isVariable())
370 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
371 "' is already defined");
373 if (MAI->hasDotTypeDotSizeDirective())
374 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
376 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
378 const DataLayout *DL = TM.getDataLayout();
379 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
381 // If the alignment is specified, we *must* obey it. Overaligning a global
382 // with a specified alignment is a prompt way to break globals emitted to
383 // sections and expected to be contiguous (e.g. ObjC metadata).
384 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
386 for (const HandlerInfo &HI : Handlers) {
387 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
388 HI.Handler->setSymbolSize(GVSym, Size);
391 // Handle common and BSS local symbols (.lcomm).
392 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
393 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
394 unsigned Align = 1 << AlignLog;
396 // Handle common symbols.
397 if (GVKind.isCommon()) {
398 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
402 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
406 // Handle local BSS symbols.
407 if (MAI->hasMachoZeroFillDirective()) {
408 MCSection *TheSection =
409 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
410 // .zerofill __DATA, __bss, _foo, 400, 5
411 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
415 // Use .lcomm only if it supports user-specified alignment.
416 // Otherwise, while it would still be correct to use .lcomm in some
417 // cases (e.g. when Align == 1), the external assembler might enfore
418 // some -unknown- default alignment behavior, which could cause
419 // spurious differences between external and integrated assembler.
420 // Prefer to simply fall back to .local / .comm in this case.
421 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
423 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
427 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
431 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
433 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
437 MCSection *TheSection =
438 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
440 // Handle the zerofill directive on darwin, which is a special form of BSS
442 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
443 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
446 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
447 // .zerofill __DATA, __common, _foo, 400, 5
448 OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
452 // Handle thread local data for mach-o which requires us to output an
453 // additional structure of data and mangle the original symbol so that we
454 // can reference it later.
456 // TODO: This should become an "emit thread local global" method on TLOF.
457 // All of this macho specific stuff should be sunk down into TLOFMachO and
458 // stuff like "TLSExtraDataSection" should no longer be part of the parent
459 // TLOF class. This will also make it more obvious that stuff like
460 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
462 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
463 // Emit the .tbss symbol
465 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
467 if (GVKind.isThreadBSS()) {
468 TheSection = getObjFileLowering().getTLSBSSSection();
469 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
470 } else if (GVKind.isThreadData()) {
471 OutStreamer->SwitchSection(TheSection);
473 EmitAlignment(AlignLog, GV);
474 OutStreamer->EmitLabel(MangSym);
476 EmitGlobalConstant(GV->getInitializer());
479 OutStreamer->AddBlankLine();
481 // Emit the variable struct for the runtime.
482 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
484 OutStreamer->SwitchSection(TLVSect);
485 // Emit the linkage here.
486 EmitLinkage(GV, GVSym);
487 OutStreamer->EmitLabel(GVSym);
489 // Three pointers in size:
490 // - __tlv_bootstrap - used to make sure support exists
491 // - spare pointer, used when mapped by the runtime
492 // - pointer to mangled symbol above with initializer
493 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
494 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
496 OutStreamer->EmitIntValue(0, PtrSize);
497 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
499 OutStreamer->AddBlankLine();
503 OutStreamer->SwitchSection(TheSection);
505 EmitLinkage(GV, GVSym);
506 EmitAlignment(AlignLog, GV);
508 OutStreamer->EmitLabel(GVSym);
510 EmitGlobalConstant(GV->getInitializer());
512 if (MAI->hasDotTypeDotSizeDirective())
514 OutStreamer->emitELFSize(cast<MCSymbolELF>(GVSym),
515 MCConstantExpr::create(Size, OutContext));
517 OutStreamer->AddBlankLine();
520 /// EmitFunctionHeader - This method emits the header for the current
522 void AsmPrinter::EmitFunctionHeader() {
523 // Print out constants referenced by the function
526 // Print the 'header' of function.
527 const Function *F = MF->getFunction();
529 OutStreamer->SwitchSection(
530 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
531 EmitVisibility(CurrentFnSym, F->getVisibility());
533 EmitLinkage(F, CurrentFnSym);
534 if (MAI->hasFunctionAlignment())
535 EmitAlignment(MF->getAlignment(), F);
537 if (MAI->hasDotTypeDotSizeDirective())
538 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
541 F->printAsOperand(OutStreamer->GetCommentOS(),
542 /*PrintType=*/false, F->getParent());
543 OutStreamer->GetCommentOS() << '\n';
546 // Emit the prefix data.
547 if (F->hasPrefixData())
548 EmitGlobalConstant(F->getPrefixData());
550 // Emit the CurrentFnSym. This is a virtual function to allow targets to
551 // do their wild and crazy things as required.
552 EmitFunctionEntryLabel();
554 // If the function had address-taken blocks that got deleted, then we have
555 // references to the dangling symbols. Emit them at the start of the function
556 // so that we don't get references to undefined symbols.
557 std::vector<MCSymbol*> DeadBlockSyms;
558 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
559 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
560 OutStreamer->AddComment("Address taken block that was later removed");
561 OutStreamer->EmitLabel(DeadBlockSyms[i]);
564 if (CurrentFnBegin) {
565 if (MAI->useAssignmentForEHBegin()) {
566 MCSymbol *CurPos = OutContext.createTempSymbol();
567 OutStreamer->EmitLabel(CurPos);
568 OutStreamer->EmitAssignment(CurrentFnBegin,
569 MCSymbolRefExpr::create(CurPos, OutContext));
571 OutStreamer->EmitLabel(CurrentFnBegin);
575 // Emit pre-function debug and/or EH information.
576 for (const HandlerInfo &HI : Handlers) {
577 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
578 HI.Handler->beginFunction(MF);
581 // Emit the prologue data.
582 if (F->hasPrologueData())
583 EmitGlobalConstant(F->getPrologueData());
586 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
587 /// function. This can be overridden by targets as required to do custom stuff.
588 void AsmPrinter::EmitFunctionEntryLabel() {
589 CurrentFnSym->redefineIfPossible();
591 // The function label could have already been emitted if two symbols end up
592 // conflicting due to asm renaming. Detect this and emit an error.
593 if (CurrentFnSym->isVariable())
594 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
595 "' is a protected alias");
596 if (CurrentFnSym->isDefined())
597 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
598 "' label emitted multiple times to assembly file");
600 return OutStreamer->EmitLabel(CurrentFnSym);
603 /// emitComments - Pretty-print comments for instructions.
604 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
605 const MachineFunction *MF = MI.getParent()->getParent();
606 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
608 // Check for spills and reloads
611 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
613 // We assume a single instruction only has a spill or reload, not
615 const MachineMemOperand *MMO;
616 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
617 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
618 MMO = *MI.memoperands_begin();
619 CommentOS << MMO->getSize() << "-byte Reload\n";
621 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
622 if (FrameInfo->isSpillSlotObjectIndex(FI))
623 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
624 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
625 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
626 MMO = *MI.memoperands_begin();
627 CommentOS << MMO->getSize() << "-byte Spill\n";
629 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
630 if (FrameInfo->isSpillSlotObjectIndex(FI))
631 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
634 // Check for spill-induced copies
635 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
636 CommentOS << " Reload Reuse\n";
639 /// emitImplicitDef - This method emits the specified machine instruction
640 /// that is an implicit def.
641 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
642 unsigned RegNo = MI->getOperand(0).getReg();
643 OutStreamer->AddComment(Twine("implicit-def: ") +
644 MMI->getContext().getRegisterInfo()->getName(RegNo));
645 OutStreamer->AddBlankLine();
648 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
649 std::string Str = "kill:";
650 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
651 const MachineOperand &Op = MI->getOperand(i);
652 assert(Op.isReg() && "KILL instruction must have only register operands");
654 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
655 Str += (Op.isDef() ? "<def>" : "<kill>");
657 AP.OutStreamer->AddComment(Str);
658 AP.OutStreamer->AddBlankLine();
661 /// emitDebugValueComment - This method handles the target-independent form
662 /// of DBG_VALUE, returning true if it was able to do so. A false return
663 /// means the target will need to handle MI in EmitInstruction.
664 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
665 // This code handles only the 4-operand target-independent form.
666 if (MI->getNumOperands() != 4)
669 SmallString<128> Str;
670 raw_svector_ostream OS(Str);
671 OS << "DEBUG_VALUE: ";
673 const DILocalVariable *V = MI->getDebugVariable();
674 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
675 StringRef Name = SP->getDisplayName();
681 const DIExpression *Expr = MI->getDebugExpression();
682 if (Expr->isBitPiece())
683 OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
684 << " size=" << Expr->getBitPieceSize() << "]";
687 // The second operand is only an offset if it's an immediate.
688 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
689 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
691 // Register or immediate value. Register 0 means undef.
692 if (MI->getOperand(0).isFPImm()) {
693 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
694 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
695 OS << (double)APF.convertToFloat();
696 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
697 OS << APF.convertToDouble();
699 // There is no good way to print long double. Convert a copy to
700 // double. Ah well, it's only a comment.
702 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
704 OS << "(long double) " << APF.convertToDouble();
706 } else if (MI->getOperand(0).isImm()) {
707 OS << MI->getOperand(0).getImm();
708 } else if (MI->getOperand(0).isCImm()) {
709 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
712 if (MI->getOperand(0).isReg()) {
713 Reg = MI->getOperand(0).getReg();
715 assert(MI->getOperand(0).isFI() && "Unknown operand type");
716 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
717 Offset += TFI->getFrameIndexReference(*AP.MF,
718 MI->getOperand(0).getIndex(), Reg);
722 // Suppress offset, it is not meaningful here.
724 // NOTE: Want this comment at start of line, don't emit with AddComment.
725 AP.OutStreamer->emitRawComment(OS.str());
730 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
734 OS << '+' << Offset << ']';
736 // NOTE: Want this comment at start of line, don't emit with AddComment.
737 AP.OutStreamer->emitRawComment(OS.str());
741 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
742 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
743 MF->getFunction()->needsUnwindTableEntry())
746 if (MMI->hasDebugInfo())
752 bool AsmPrinter::needsSEHMoves() {
753 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
756 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
757 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
758 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
759 ExceptionHandlingType != ExceptionHandling::ARM)
762 if (needsCFIMoves() == CFI_M_None)
765 const MachineModuleInfo &MMI = MF->getMMI();
766 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
767 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
768 const MCCFIInstruction &CFI = Instrs[CFIIndex];
769 emitCFIInstruction(CFI);
772 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
773 // The operands are the MCSymbol and the frame offset of the allocation.
774 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
775 int FrameOffset = MI.getOperand(1).getImm();
777 // Emit a symbol assignment.
778 OutStreamer->EmitAssignment(FrameAllocSym,
779 MCConstantExpr::create(FrameOffset, OutContext));
782 /// EmitFunctionBody - This method emits the body and trailer for a
784 void AsmPrinter::EmitFunctionBody() {
785 EmitFunctionHeader();
787 // Emit target-specific gunk before the function body.
788 EmitFunctionBodyStart();
790 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
792 // Print out code for the function.
793 bool HasAnyRealCode = false;
794 for (auto &MBB : *MF) {
795 // Print a label for the basic block.
796 EmitBasicBlockStart(MBB);
797 for (auto &MI : MBB) {
799 // Print the assembly for the instruction.
800 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
801 !MI.isDebugValue()) {
802 HasAnyRealCode = true;
806 if (ShouldPrintDebugScopes) {
807 for (const HandlerInfo &HI : Handlers) {
808 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
809 TimePassesIsEnabled);
810 HI.Handler->beginInstruction(&MI);
815 emitComments(MI, OutStreamer->GetCommentOS());
817 switch (MI.getOpcode()) {
818 case TargetOpcode::CFI_INSTRUCTION:
819 emitCFIInstruction(MI);
822 case TargetOpcode::FRAME_ALLOC:
826 case TargetOpcode::EH_LABEL:
827 case TargetOpcode::GC_LABEL:
828 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
830 case TargetOpcode::INLINEASM:
833 case TargetOpcode::DBG_VALUE:
835 if (!emitDebugValueComment(&MI, *this))
836 EmitInstruction(&MI);
839 case TargetOpcode::IMPLICIT_DEF:
840 if (isVerbose()) emitImplicitDef(&MI);
842 case TargetOpcode::KILL:
843 if (isVerbose()) emitKill(&MI, *this);
846 EmitInstruction(&MI);
850 if (ShouldPrintDebugScopes) {
851 for (const HandlerInfo &HI : Handlers) {
852 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
853 TimePassesIsEnabled);
854 HI.Handler->endInstruction();
859 EmitBasicBlockEnd(MBB);
862 // If the function is empty and the object file uses .subsections_via_symbols,
863 // then we need to emit *something* to the function body to prevent the
864 // labels from collapsing together. Just emit a noop.
865 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
867 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
868 OutStreamer->AddComment("avoids zero-length function");
870 // Targets can opt-out of emitting the noop here by leaving the opcode
872 if (Noop.getOpcode())
873 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
876 const Function *F = MF->getFunction();
877 for (const auto &BB : *F) {
878 if (!BB.hasAddressTaken())
880 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
881 if (Sym->isDefined())
883 OutStreamer->AddComment("Address of block that was removed by CodeGen");
884 OutStreamer->EmitLabel(Sym);
887 // Emit target-specific gunk after the function body.
888 EmitFunctionBodyEnd();
890 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
891 MAI->hasDotTypeDotSizeDirective()) {
892 // Create a symbol for the end of function.
893 CurrentFnEnd = createTempSymbol("func_end");
894 OutStreamer->EmitLabel(CurrentFnEnd);
897 // If the target wants a .size directive for the size of the function, emit
899 if (MAI->hasDotTypeDotSizeDirective()) {
900 // We can get the size as difference between the function label and the
902 const MCExpr *SizeExp = MCBinaryExpr::createSub(
903 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
904 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
905 OutStreamer->emitELFSize(cast<MCSymbolELF>(CurrentFnSym), SizeExp);
908 for (const HandlerInfo &HI : Handlers) {
909 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
910 HI.Handler->markFunctionEnd();
913 // Print out jump tables referenced by the function.
916 // Emit post-function debug and/or EH information.
917 for (const HandlerInfo &HI : Handlers) {
918 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
919 HI.Handler->endFunction(MF);
923 OutStreamer->AddBlankLine();
926 /// \brief Compute the number of Global Variables that uses a Constant.
927 static unsigned getNumGlobalVariableUses(const Constant *C) {
931 if (isa<GlobalVariable>(C))
934 unsigned NumUses = 0;
935 for (auto *CU : C->users())
936 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
941 /// \brief Only consider global GOT equivalents if at least one user is a
942 /// cstexpr inside an initializer of another global variables. Also, don't
943 /// handle cstexpr inside instructions. During global variable emission,
944 /// candidates are skipped and are emitted later in case at least one cstexpr
945 /// isn't replaced by a PC relative GOT entry access.
946 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
947 unsigned &NumGOTEquivUsers) {
948 // Global GOT equivalents are unnamed private globals with a constant
949 // pointer initializer to another global symbol. They must point to a
950 // GlobalVariable or Function, i.e., as GlobalValue.
951 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
952 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
955 // To be a got equivalent, at least one of its users need to be a constant
956 // expression used by another global variable.
957 for (auto *U : GV->users())
958 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
960 return NumGOTEquivUsers > 0;
963 /// \brief Unnamed constant global variables solely contaning a pointer to
964 /// another globals variable is equivalent to a GOT table entry; it contains the
965 /// the address of another symbol. Optimize it and replace accesses to these
966 /// "GOT equivalents" by using the GOT entry for the final global instead.
967 /// Compute GOT equivalent candidates among all global variables to avoid
968 /// emitting them if possible later on, after it use is replaced by a GOT entry
970 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
971 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
974 for (const auto &G : M.globals()) {
975 unsigned NumGOTEquivUsers = 0;
976 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
979 const MCSymbol *GOTEquivSym = getSymbol(&G);
980 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
984 /// \brief Constant expressions using GOT equivalent globals may not be eligible
985 /// for PC relative GOT entry conversion, in such cases we need to emit such
986 /// globals we previously omitted in EmitGlobalVariable.
987 void AsmPrinter::emitGlobalGOTEquivs() {
988 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
991 SmallVector<const GlobalVariable *, 8> FailedCandidates;
992 for (auto &I : GlobalGOTEquivs) {
993 const GlobalVariable *GV = I.second.first;
994 unsigned Cnt = I.second.second;
996 FailedCandidates.push_back(GV);
998 GlobalGOTEquivs.clear();
1000 for (auto *GV : FailedCandidates)
1001 EmitGlobalVariable(GV);
1004 bool AsmPrinter::doFinalization(Module &M) {
1005 // Set the MachineFunction to nullptr so that we can catch attempted
1006 // accesses to MF specific features at the module level and so that
1007 // we can conditionalize accesses based on whether or not it is nullptr.
1010 // Gather all GOT equivalent globals in the module. We really need two
1011 // passes over the globals: one to compute and another to avoid its emission
1012 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1013 // where the got equivalent shows up before its use.
1014 computeGlobalGOTEquivs(M);
1016 // Emit global variables.
1017 for (const auto &G : M.globals())
1018 EmitGlobalVariable(&G);
1020 // Emit remaining GOT equivalent globals.
1021 emitGlobalGOTEquivs();
1023 // Emit visibility info for declarations
1024 for (const Function &F : M) {
1025 if (!F.isDeclaration())
1027 GlobalValue::VisibilityTypes V = F.getVisibility();
1028 if (V == GlobalValue::DefaultVisibility)
1031 MCSymbol *Name = getSymbol(&F);
1032 EmitVisibility(Name, V, false);
1035 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1037 // Emit module flags.
1038 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1039 M.getModuleFlagsMetadata(ModuleFlags);
1040 if (!ModuleFlags.empty())
1041 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1043 Triple TT(TM.getTargetTriple());
1044 if (TT.isOSBinFormatELF()) {
1045 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1047 // Output stubs for external and common global variables.
1048 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1049 if (!Stubs.empty()) {
1050 OutStreamer->SwitchSection(TLOF.getDataRelSection());
1051 const DataLayout *DL = TM.getDataLayout();
1053 for (const auto &Stub : Stubs) {
1054 OutStreamer->EmitLabel(Stub.first);
1055 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1056 DL->getPointerSize());
1061 // Make sure we wrote out everything we need.
1062 OutStreamer->Flush();
1064 // Finalize debug and EH information.
1065 for (const HandlerInfo &HI : Handlers) {
1066 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1067 TimePassesIsEnabled);
1068 HI.Handler->endModule();
1074 // If the target wants to know about weak references, print them all.
1075 if (MAI->getWeakRefDirective()) {
1076 // FIXME: This is not lazy, it would be nice to only print weak references
1077 // to stuff that is actually used. Note that doing so would require targets
1078 // to notice uses in operands (due to constant exprs etc). This should
1079 // happen with the MC stuff eventually.
1081 // Print out module-level global variables here.
1082 for (const auto &G : M.globals()) {
1083 if (!G.hasExternalWeakLinkage())
1085 OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1088 for (const auto &F : M) {
1089 if (!F.hasExternalWeakLinkage())
1091 OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1095 OutStreamer->AddBlankLine();
1096 for (const auto &Alias : M.aliases()) {
1097 MCSymbol *Name = getSymbol(&Alias);
1099 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1100 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1101 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1102 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1104 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1106 EmitVisibility(Name, Alias.getVisibility());
1108 // Emit the directives as assignments aka .set:
1109 OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1112 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1113 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1114 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1115 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1116 MP->finishAssembly(M, *MI, *this);
1118 // Emit llvm.ident metadata in an '.ident' directive.
1119 EmitModuleIdents(M);
1121 // Emit __morestack address if needed for indirect calls.
1122 if (MMI->usesMorestackAddr()) {
1123 MCSection *ReadOnlySection =
1124 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1126 OutStreamer->SwitchSection(ReadOnlySection);
1128 MCSymbol *AddrSymbol =
1129 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1130 OutStreamer->EmitLabel(AddrSymbol);
1132 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1133 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1137 // If we don't have any trampolines, then we don't require stack memory
1138 // to be executable. Some targets have a directive to declare this.
1139 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1140 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1141 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1142 OutStreamer->SwitchSection(S);
1144 // Allow the target to emit any magic that it wants at the end of the file,
1145 // after everything else has gone out.
1146 EmitEndOfAsmFile(M);
1148 delete Mang; Mang = nullptr;
1151 OutStreamer->Finish();
1152 OutStreamer->reset();
1157 MCSymbol *AsmPrinter::getCurExceptionSym() {
1158 if (!CurExceptionSym)
1159 CurExceptionSym = createTempSymbol("exception");
1160 return CurExceptionSym;
1163 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1165 // Get the function symbol.
1166 CurrentFnSym = getSymbol(MF.getFunction());
1167 CurrentFnSymForSize = CurrentFnSym;
1168 CurrentFnBegin = nullptr;
1169 CurExceptionSym = nullptr;
1170 bool NeedsLocalForSize = MAI->needsLocalForSize();
1171 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1172 NeedsLocalForSize) {
1173 CurrentFnBegin = createTempSymbol("func_begin");
1174 if (NeedsLocalForSize)
1175 CurrentFnSymForSize = CurrentFnBegin;
1179 LI = &getAnalysis<MachineLoopInfo>();
1183 // Keep track the alignment, constpool entries per Section.
1187 SmallVector<unsigned, 4> CPEs;
1188 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1192 /// EmitConstantPool - Print to the current output stream assembly
1193 /// representations of the constants in the constant pool MCP. This is
1194 /// used to print out constants which have been "spilled to memory" by
1195 /// the code generator.
1197 void AsmPrinter::EmitConstantPool() {
1198 const MachineConstantPool *MCP = MF->getConstantPool();
1199 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1200 if (CP.empty()) return;
1202 // Calculate sections for constant pool entries. We collect entries to go into
1203 // the same section together to reduce amount of section switch statements.
1204 SmallVector<SectionCPs, 4> CPSections;
1205 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1206 const MachineConstantPoolEntry &CPE = CP[i];
1207 unsigned Align = CPE.getAlignment();
1210 CPE.getSectionKind(TM.getDataLayout());
1212 const Constant *C = nullptr;
1213 if (!CPE.isMachineConstantPoolEntry())
1214 C = CPE.Val.ConstVal;
1216 MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1218 // The number of sections are small, just do a linear search from the
1219 // last section to the first.
1221 unsigned SecIdx = CPSections.size();
1222 while (SecIdx != 0) {
1223 if (CPSections[--SecIdx].S == S) {
1229 SecIdx = CPSections.size();
1230 CPSections.push_back(SectionCPs(S, Align));
1233 if (Align > CPSections[SecIdx].Alignment)
1234 CPSections[SecIdx].Alignment = Align;
1235 CPSections[SecIdx].CPEs.push_back(i);
1238 // Now print stuff into the calculated sections.
1239 const MCSection *CurSection = nullptr;
1240 unsigned Offset = 0;
1241 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1242 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1243 unsigned CPI = CPSections[i].CPEs[j];
1244 MCSymbol *Sym = GetCPISymbol(CPI);
1245 if (!Sym->isUndefined())
1248 if (CurSection != CPSections[i].S) {
1249 OutStreamer->SwitchSection(CPSections[i].S);
1250 EmitAlignment(Log2_32(CPSections[i].Alignment));
1251 CurSection = CPSections[i].S;
1255 MachineConstantPoolEntry CPE = CP[CPI];
1257 // Emit inter-object padding for alignment.
1258 unsigned AlignMask = CPE.getAlignment() - 1;
1259 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1260 OutStreamer->EmitZeros(NewOffset - Offset);
1262 Type *Ty = CPE.getType();
1263 Offset = NewOffset +
1264 TM.getDataLayout()->getTypeAllocSize(Ty);
1266 OutStreamer->EmitLabel(Sym);
1267 if (CPE.isMachineConstantPoolEntry())
1268 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1270 EmitGlobalConstant(CPE.Val.ConstVal);
1275 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1276 /// by the current function to the current output stream.
1278 void AsmPrinter::EmitJumpTableInfo() {
1279 const DataLayout *DL = MF->getTarget().getDataLayout();
1280 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1282 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1283 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1284 if (JT.empty()) return;
1286 // Pick the directive to use to print the jump table entries, and switch to
1287 // the appropriate section.
1288 const Function *F = MF->getFunction();
1289 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1290 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1291 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1293 if (JTInDiffSection) {
1294 // Drop it in the readonly section.
1295 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1296 OutStreamer->SwitchSection(ReadOnlySection);
1299 EmitAlignment(Log2_32(
1300 MJTI->getEntryAlignment(*TM.getDataLayout())));
1302 // Jump tables in code sections are marked with a data_region directive
1303 // where that's supported.
1304 if (!JTInDiffSection)
1305 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1307 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1308 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1310 // If this jump table was deleted, ignore it.
1311 if (JTBBs.empty()) continue;
1313 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1314 /// emit a .set directive for each unique entry.
1315 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1316 MAI->doesSetDirectiveSuppressesReloc()) {
1317 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1318 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1319 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1320 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1321 const MachineBasicBlock *MBB = JTBBs[ii];
1322 if (!EmittedSets.insert(MBB).second)
1325 // .set LJTSet, LBB32-base
1327 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1328 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1329 MCBinaryExpr::createSub(LHS, Base,
1334 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1335 // before each jump table. The first label is never referenced, but tells
1336 // the assembler and linker the extents of the jump table object. The
1337 // second label is actually referenced by the code.
1338 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1339 // FIXME: This doesn't have to have any specific name, just any randomly
1340 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1341 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1343 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1345 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1346 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1348 if (!JTInDiffSection)
1349 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1352 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1354 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1355 const MachineBasicBlock *MBB,
1356 unsigned UID) const {
1357 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1358 const MCExpr *Value = nullptr;
1359 switch (MJTI->getEntryKind()) {
1360 case MachineJumpTableInfo::EK_Inline:
1361 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1362 case MachineJumpTableInfo::EK_Custom32:
1363 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1364 MJTI, MBB, UID, OutContext);
1366 case MachineJumpTableInfo::EK_BlockAddress:
1367 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1369 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1371 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1372 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1373 // with a relocation as gp-relative, e.g.:
1375 MCSymbol *MBBSym = MBB->getSymbol();
1376 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1380 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1381 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1382 // with a relocation as gp-relative, e.g.:
1384 MCSymbol *MBBSym = MBB->getSymbol();
1385 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1389 case MachineJumpTableInfo::EK_LabelDifference32: {
1390 // Each entry is the address of the block minus the address of the jump
1391 // table. This is used for PIC jump tables where gprel32 is not supported.
1393 // .word LBB123 - LJTI1_2
1394 // If the .set directive avoids relocations, this is emitted as:
1395 // .set L4_5_set_123, LBB123 - LJTI1_2
1396 // .word L4_5_set_123
1397 if (MAI->doesSetDirectiveSuppressesReloc()) {
1398 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1402 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1403 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1404 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1405 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1410 assert(Value && "Unknown entry kind!");
1412 unsigned EntrySize =
1413 MJTI->getEntrySize(*TM.getDataLayout());
1414 OutStreamer->EmitValue(Value, EntrySize);
1418 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1419 /// special global used by LLVM. If so, emit it and return true, otherwise
1420 /// do nothing and return false.
1421 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1422 if (GV->getName() == "llvm.used") {
1423 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1424 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1428 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1429 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1430 GV->hasAvailableExternallyLinkage())
1433 if (!GV->hasAppendingLinkage()) return false;
1435 assert(GV->hasInitializer() && "Not a special LLVM global!");
1437 if (GV->getName() == "llvm.global_ctors") {
1438 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1440 if (TM.getRelocationModel() == Reloc::Static &&
1441 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1442 StringRef Sym(".constructors_used");
1443 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1449 if (GV->getName() == "llvm.global_dtors") {
1450 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1452 if (TM.getRelocationModel() == Reloc::Static &&
1453 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1454 StringRef Sym(".destructors_used");
1455 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1464 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1465 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1466 /// is true, as being used with this directive.
1467 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1468 // Should be an array of 'i8*'.
1469 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1470 const GlobalValue *GV =
1471 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1473 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1479 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1481 llvm::Constant *Func;
1482 llvm::GlobalValue *ComdatKey;
1486 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1488 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1489 // Should be an array of '{ int, void ()* }' structs. The first value is the
1491 if (!isa<ConstantArray>(List)) return;
1493 // Sanity check the structors list.
1494 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1495 if (!InitList) return; // Not an array!
1496 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1497 // FIXME: Only allow the 3-field form in LLVM 4.0.
1498 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1499 return; // Not an array of two or three elements!
1500 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1501 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1502 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1503 return; // Not (int, ptr, ptr).
1505 // Gather the structors in a form that's convenient for sorting by priority.
1506 SmallVector<Structor, 8> Structors;
1507 for (Value *O : InitList->operands()) {
1508 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1509 if (!CS) continue; // Malformed.
1510 if (CS->getOperand(1)->isNullValue())
1511 break; // Found a null terminator, skip the rest.
1512 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1513 if (!Priority) continue; // Malformed.
1514 Structors.push_back(Structor());
1515 Structor &S = Structors.back();
1516 S.Priority = Priority->getLimitedValue(65535);
1517 S.Func = CS->getOperand(1);
1518 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1519 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1522 // Emit the function pointers in the target-specific order
1523 const DataLayout *DL = TM.getDataLayout();
1524 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1525 std::stable_sort(Structors.begin(), Structors.end(),
1526 [](const Structor &L,
1527 const Structor &R) { return L.Priority < R.Priority; });
1528 for (Structor &S : Structors) {
1529 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1530 const MCSymbol *KeySym = nullptr;
1531 if (GlobalValue *GV = S.ComdatKey) {
1532 if (GV->hasAvailableExternallyLinkage())
1533 // If the associated variable is available_externally, some other TU
1534 // will provide its dynamic initializer.
1537 KeySym = getSymbol(GV);
1539 MCSection *OutputSection =
1540 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1541 : Obj.getStaticDtorSection(S.Priority, KeySym));
1542 OutStreamer->SwitchSection(OutputSection);
1543 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1544 EmitAlignment(Align);
1545 EmitXXStructor(S.Func);
1549 void AsmPrinter::EmitModuleIdents(Module &M) {
1550 if (!MAI->hasIdentDirective())
1553 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1554 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1555 const MDNode *N = NMD->getOperand(i);
1556 assert(N->getNumOperands() == 1 &&
1557 "llvm.ident metadata entry can have only one operand");
1558 const MDString *S = cast<MDString>(N->getOperand(0));
1559 OutStreamer->EmitIdent(S->getString());
1564 //===--------------------------------------------------------------------===//
1565 // Emission and print routines
1568 /// EmitInt8 - Emit a byte directive and value.
1570 void AsmPrinter::EmitInt8(int Value) const {
1571 OutStreamer->EmitIntValue(Value, 1);
1574 /// EmitInt16 - Emit a short directive and value.
1576 void AsmPrinter::EmitInt16(int Value) const {
1577 OutStreamer->EmitIntValue(Value, 2);
1580 /// EmitInt32 - Emit a long directive and value.
1582 void AsmPrinter::EmitInt32(int Value) const {
1583 OutStreamer->EmitIntValue(Value, 4);
1586 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1587 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1588 /// .set if it avoids relocations.
1589 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1590 unsigned Size) const {
1591 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1594 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1595 /// where the size in bytes of the directive is specified by Size and Label
1596 /// specifies the label. This implicitly uses .set if it is available.
1597 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1599 bool IsSectionRelative) const {
1600 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1601 OutStreamer->EmitCOFFSecRel32(Label);
1605 // Emit Label+Offset (or just Label if Offset is zero)
1606 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1608 Expr = MCBinaryExpr::createAdd(
1609 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1611 OutStreamer->EmitValue(Expr, Size);
1614 //===----------------------------------------------------------------------===//
1616 // EmitAlignment - Emit an alignment directive to the specified power of
1617 // two boundary. For example, if you pass in 3 here, you will get an 8
1618 // byte alignment. If a global value is specified, and if that global has
1619 // an explicit alignment requested, it will override the alignment request
1620 // if required for correctness.
1622 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1624 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1627 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1630 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1631 "undefined behavior");
1632 if (getCurrentSection()->getKind().isText())
1633 OutStreamer->EmitCodeAlignment(1u << NumBits);
1635 OutStreamer->EmitValueToAlignment(1u << NumBits);
1638 //===----------------------------------------------------------------------===//
1639 // Constant emission.
1640 //===----------------------------------------------------------------------===//
1642 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1643 MCContext &Ctx = OutContext;
1645 if (CV->isNullValue() || isa<UndefValue>(CV))
1646 return MCConstantExpr::create(0, Ctx);
1648 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1649 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1651 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1652 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1654 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1655 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1657 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1659 llvm_unreachable("Unknown constant value to lower!");
1662 if (const MCExpr *RelocExpr
1663 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1666 switch (CE->getOpcode()) {
1668 // If the code isn't optimized, there may be outstanding folding
1669 // opportunities. Attempt to fold the expression using DataLayout as a
1670 // last resort before giving up.
1671 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
1673 return lowerConstant(C);
1675 // Otherwise report the problem to the user.
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());
1684 case Instruction::GetElementPtr: {
1685 const DataLayout &DL = *TM.getDataLayout();
1687 // Generate a symbolic expression for the byte address
1688 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1689 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1691 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1695 int64_t Offset = OffsetAI.getSExtValue();
1696 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
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.
1706 case Instruction::BitCast:
1707 return lowerConstant(CE->getOperand(0));
1709 case Instruction::IntToPtr: {
1710 const DataLayout &DL = *TM.getDataLayout();
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()),
1717 return lowerConstant(Op);
1720 case Instruction::PtrToInt: {
1721 const DataLayout &DL = *TM.getDataLayout();
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();
1728 const MCExpr *OpExpr = lowerConstant(Op);
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()))
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
1738 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1739 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1740 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
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);
1772 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1773 const Constant *BaseCV = nullptr,
1774 uint64_t Offset = 0);
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");
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.
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) {
1794 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1795 if (CI->getBitWidth() > 64) return -1;
1798 TM.getDataLayout()->getTypeAllocSize(V->getType());
1799 uint64_t Value = CI->getZExtValue();
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;
1807 uint8_t Byte = static_cast<uint8_t>(Value);
1809 for (unsigned i = 1; i < Size; ++i) {
1811 if (static_cast<uint8_t>(Value) != Byte) return -1;
1815 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1816 // Make sure all array elements are sequences of the same repeated
1818 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1819 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1820 if (Byte == -1) return -1;
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;
1830 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1831 return isRepeatedByteSequence(CDS);
1836 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1839 // See if we can aggregate this into a .fill, if so, emit it as such.
1840 int Value = isRepeatedByteSequence(CDS, AP.TM);
1843 AP.TM.getDataLayout()->getTypeAllocSize(
1845 // Don't emit a 1-byte object as a .fill.
1847 return AP.OutStreamer->EmitFill(Bytes, Value);
1850 // If this can be emitted with .ascii/.asciz, emit it as such.
1851 if (CDS->isString())
1852 return AP.OutStreamer->EmitBytes(CDS->getAsString());
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) {
1859 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1860 CDS->getElementAsInteger(i));
1861 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1864 } else if (ElementByteSize == 4) {
1865 // FP Constants are printed as integer constants to avoid losing
1867 assert(CDS->getElementType()->isFloatTy());
1868 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1874 F = CDS->getElementAsFloat(i);
1876 AP.OutStreamer->GetCommentOS() << "float " << F << '\n';
1877 AP.OutStreamer->EmitIntValue(I, 4);
1880 assert(CDS->getElementType()->isDoubleTy());
1881 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1887 F = CDS->getElementAsDouble(i);
1889 AP.OutStreamer->GetCommentOS() << "double " << F << '\n';
1890 AP.OutStreamer->EmitIntValue(I, 8);
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);
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();
1911 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1912 AP.OutStreamer->EmitFill(Bytes, Value);
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());
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);
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);
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);
1944 // Print the actual field value.
1945 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
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;
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);
1958 assert(SizeSoFar == Layout->getSizeInBytes() &&
1959 "Layout of constant struct may be incorrect!");
1962 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1963 APInt API = CFP->getValueAPF().bitcastToAPInt();
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);
1972 CFP->getType()->print(AP.OutStreamer->GetCommentOS());
1974 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
1975 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
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
1981 unsigned NumBytes = API.getBitWidth() / 8;
1982 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1983 const uint64_t *p = API.getRawData();
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;
1992 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
1994 for (; Chunk >= 0; --Chunk)
1995 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
1998 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1999 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2002 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
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()));
2011 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2012 const DataLayout *DL = AP.TM.getDataLayout();
2013 unsigned BitWidth = CI->getBitWidth();
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;
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.
2025 // * Nothing to be done, just record the extra bits to emit.
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);
2042 ExtraBits = Realigned.getRawData()[BitWidth / 64];
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);
2054 if (ExtraBitsSize) {
2055 // Emit the extra bits after the 64-bits chunks.
2057 // Emit a directive that fills the expected size.
2058 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
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);
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
2071 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2072 const Constant *BaseCst,
2074 // The global @foo below illustrates a global that uses a got equivalent.
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))
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
2086 // foo = cstexpr, where
2087 // cstexpr := <gotequiv> - "." + <cst>
2088 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2090 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2092 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2093 // gotpcrelcst := <offset from @foo base> + <cst>
2096 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2099 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2100 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2103 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2107 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2108 if (BaseSym != &MV.getSymB()->getSymbol())
2111 // Make sure to match:
2113 // gotpcrelcst := <offset from @foo base> + <cst>
2115 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2116 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2117 // if the target knows how to encode it.
2119 int64_t GOTPCRelCst = Offset + MV.getConstant();
2120 if (GOTPCRelCst < 0)
2122 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2125 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2132 // .long gotequiv - "." + <cst>
2134 // is replaced by the target specific equivalent to:
2139 // .long bar@GOTPCREL+<gotpcrelcst>
2141 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2142 const GlobalVariable *GV = Result.first;
2143 int NumUses = (int)Result.second;
2144 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2145 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2146 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2147 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2149 // Update GOT equivalent usage information
2152 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2155 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2156 const Constant *BaseCV, uint64_t Offset) {
2157 const DataLayout *DL = AP.TM.getDataLayout();
2158 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2160 // Globals with sub-elements such as combinations of arrays and structs
2161 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2162 // constant symbol base and the current position with BaseCV and Offset.
2163 if (!BaseCV && CV->hasOneUse())
2164 BaseCV = dyn_cast<Constant>(CV->user_back());
2166 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2167 return AP.OutStreamer->EmitZeros(Size);
2169 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2176 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2177 CI->getZExtValue());
2178 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2181 emitGlobalConstantLargeInt(CI, AP);
2186 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2187 return emitGlobalConstantFP(CFP, AP);
2189 if (isa<ConstantPointerNull>(CV)) {
2190 AP.OutStreamer->EmitIntValue(0, Size);
2194 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2195 return emitGlobalConstantDataSequential(CDS, AP);
2197 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2198 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2200 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2201 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2203 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2204 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2206 if (CE->getOpcode() == Instruction::BitCast)
2207 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2210 // If the constant expression's size is greater than 64-bits, then we have
2211 // to emit the value in chunks. Try to constant fold the value and emit it
2213 Constant *New = ConstantFoldConstantExpression(CE, *DL);
2214 if (New && New != CE)
2215 return emitGlobalConstantImpl(New, AP);
2219 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2220 return emitGlobalConstantVector(V, AP);
2222 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2223 // thread the streamer with EmitValue.
2224 const MCExpr *ME = AP.lowerConstant(CV);
2226 // Since lowerConstant already folded and got rid of all IR pointer and
2227 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2229 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2230 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2232 AP.OutStreamer->EmitValue(ME, Size);
2235 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2236 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2238 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2240 emitGlobalConstantImpl(CV, *this);
2241 else if (MAI->hasSubsectionsViaSymbols()) {
2242 // If the global has zero size, emit a single byte so that two labels don't
2243 // look like they are at the same location.
2244 OutStreamer->EmitIntValue(0, 1);
2248 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2249 // Target doesn't support this yet!
2250 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2253 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2255 OS << '+' << Offset;
2256 else if (Offset < 0)
2260 //===----------------------------------------------------------------------===//
2261 // Symbol Lowering Routines.
2262 //===----------------------------------------------------------------------===//
2264 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2265 return OutContext.createTempSymbol(Name, true);
2268 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2269 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2272 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2273 return MMI->getAddrLabelSymbol(BB);
2276 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2277 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2278 const DataLayout *DL = TM.getDataLayout();
2279 return OutContext.getOrCreateSymbol
2280 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2281 + "_" + Twine(CPID));
2284 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2285 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2286 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2289 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2290 /// FIXME: privatize to AsmPrinter.
2291 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2292 const DataLayout *DL = TM.getDataLayout();
2293 return OutContext.getOrCreateSymbol
2294 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2295 Twine(UID) + "_set_" + Twine(MBBID));
2298 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2299 StringRef Suffix) const {
2300 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2304 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2306 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2307 SmallString<60> NameStr;
2308 Mang->getNameWithPrefix(NameStr, Sym);
2309 return OutContext.getOrCreateSymbol(NameStr);
2314 /// PrintParentLoopComment - Print comments about parent loops of this one.
2315 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2316 unsigned FunctionNumber) {
2318 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2319 OS.indent(Loop->getLoopDepth()*2)
2320 << "Parent Loop BB" << FunctionNumber << "_"
2321 << Loop->getHeader()->getNumber()
2322 << " Depth=" << Loop->getLoopDepth() << '\n';
2326 /// PrintChildLoopComment - Print comments about child loops within
2327 /// the loop for this basic block, with nesting.
2328 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2329 unsigned FunctionNumber) {
2330 // Add child loop information
2331 for (const MachineLoop *CL : *Loop) {
2332 OS.indent(CL->getLoopDepth()*2)
2333 << "Child Loop BB" << FunctionNumber << "_"
2334 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2336 PrintChildLoopComment(OS, CL, FunctionNumber);
2340 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2341 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2342 const MachineLoopInfo *LI,
2343 const AsmPrinter &AP) {
2344 // Add loop depth information
2345 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2348 MachineBasicBlock *Header = Loop->getHeader();
2349 assert(Header && "No header for loop");
2351 // If this block is not a loop header, just print out what is the loop header
2353 if (Header != &MBB) {
2354 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2355 Twine(AP.getFunctionNumber())+"_" +
2356 Twine(Loop->getHeader()->getNumber())+
2357 " Depth="+Twine(Loop->getLoopDepth()));
2361 // Otherwise, it is a loop header. Print out information about child and
2363 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2365 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2368 OS.indent(Loop->getLoopDepth()*2-2);
2373 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2375 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2379 /// EmitBasicBlockStart - This method prints the label for the specified
2380 /// MachineBasicBlock, an alignment (if present) and a comment describing
2381 /// it if appropriate.
2382 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2383 // Emit an alignment directive for this block, if needed.
2384 if (unsigned Align = MBB.getAlignment())
2385 EmitAlignment(Align);
2387 // If the block has its address taken, emit any labels that were used to
2388 // reference the block. It is possible that there is more than one label
2389 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2390 // the references were generated.
2391 if (MBB.hasAddressTaken()) {
2392 const BasicBlock *BB = MBB.getBasicBlock();
2394 OutStreamer->AddComment("Block address taken");
2396 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2397 for (auto *Sym : Symbols)
2398 OutStreamer->EmitLabel(Sym);
2401 // Print some verbose block comments.
2403 if (const BasicBlock *BB = MBB.getBasicBlock())
2405 OutStreamer->AddComment("%" + BB->getName());
2406 emitBasicBlockLoopComments(MBB, LI, *this);
2409 // Print the main label for the block.
2410 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2412 // NOTE: Want this comment at start of line, don't emit with AddComment.
2413 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2416 OutStreamer->EmitLabel(MBB.getSymbol());
2420 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2421 bool IsDefinition) const {
2422 MCSymbolAttr Attr = MCSA_Invalid;
2424 switch (Visibility) {
2426 case GlobalValue::HiddenVisibility:
2428 Attr = MAI->getHiddenVisibilityAttr();
2430 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2432 case GlobalValue::ProtectedVisibility:
2433 Attr = MAI->getProtectedVisibilityAttr();
2437 if (Attr != MCSA_Invalid)
2438 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2441 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2442 /// exactly one predecessor and the control transfer mechanism between
2443 /// the predecessor and this block is a fall-through.
2445 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2446 // If this is a landing pad, it isn't a fall through. If it has no preds,
2447 // then nothing falls through to it.
2448 if (MBB->isLandingPad() || MBB->pred_empty())
2451 // If there isn't exactly one predecessor, it can't be a fall through.
2452 if (MBB->pred_size() > 1)
2455 // The predecessor has to be immediately before this block.
2456 MachineBasicBlock *Pred = *MBB->pred_begin();
2457 if (!Pred->isLayoutSuccessor(MBB))
2460 // If the block is completely empty, then it definitely does fall through.
2464 // Check the terminators in the previous blocks
2465 for (const auto &MI : Pred->terminators()) {
2466 // If it is not a simple branch, we are in a table somewhere.
2467 if (!MI.isBranch() || MI.isIndirectBranch())
2470 // If we are the operands of one of the branches, this is not a fall
2471 // through. Note that targets with delay slots will usually bundle
2472 // terminators with the delay slot instruction.
2473 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2476 if (OP->isMBB() && OP->getMBB() == MBB)
2486 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2487 if (!S.usesMetadata())
2490 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2491 " stackmap formats, please see the documentation for a description of"
2492 " the default format. If you really need a custom serialized format,"
2493 " please file a bug");
2495 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2496 gcp_map_type::iterator GCPI = GCMap.find(&S);
2497 if (GCPI != GCMap.end())
2498 return GCPI->second.get();
2500 const char *Name = S.getName().c_str();
2502 for (GCMetadataPrinterRegistry::iterator
2503 I = GCMetadataPrinterRegistry::begin(),
2504 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2505 if (strcmp(Name, I->getName()) == 0) {
2506 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2508 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2509 return IterBool.first->second.get();
2512 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2515 /// Pin vtable to this file.
2516 AsmPrinterHandler::~AsmPrinterHandler() {}
2518 void AsmPrinterHandler::markFunctionEnd() {}