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().str();
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().str(), TM.getTargetCPU(),
225 TM.getTargetFeatureString()));
226 OutStreamer->AddComment("Start of file scope inline assembly");
227 OutStreamer->AddBlankLine();
228 EmitInlineAsm(M.getModuleInlineAsm()+"\n", *STI, TM.Options.MCOptions);
229 OutStreamer->AddComment("End of file scope inline assembly");
230 OutStreamer->AddBlankLine();
233 if (MAI->doesSupportDebugInformation()) {
234 bool skip_dwarf = false;
235 if (TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) {
236 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
238 CodeViewLineTablesGroupName));
239 // FIXME: Don't emit DWARF debug info if there's at least one function
240 // with AddressSanitizer instrumentation.
241 // This is a band-aid fix for PR22032.
242 for (auto &F : M.functions()) {
243 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
250 DD = new DwarfDebug(this, &M);
251 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
255 EHStreamer *ES = nullptr;
256 switch (MAI->getExceptionHandlingType()) {
257 case ExceptionHandling::None:
259 case ExceptionHandling::SjLj:
260 case ExceptionHandling::DwarfCFI:
261 ES = new DwarfCFIException(this);
263 case ExceptionHandling::ARM:
264 ES = new ARMException(this);
266 case ExceptionHandling::WinEH:
267 switch (MAI->getWinEHEncodingType()) {
268 default: llvm_unreachable("unsupported unwinding information encoding");
269 case WinEH::EncodingType::Invalid:
271 case WinEH::EncodingType::X86:
272 case WinEH::EncodingType::Itanium:
273 ES = new WinException(this);
279 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
283 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
284 if (!MAI.hasWeakDefCanBeHiddenDirective())
287 return canBeOmittedFromSymbolTable(GV);
290 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
291 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
293 case GlobalValue::CommonLinkage:
294 case GlobalValue::LinkOnceAnyLinkage:
295 case GlobalValue::LinkOnceODRLinkage:
296 case GlobalValue::WeakAnyLinkage:
297 case GlobalValue::WeakODRLinkage:
298 if (MAI->hasWeakDefDirective()) {
300 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
302 if (!canBeHidden(GV, *MAI))
303 // .weak_definition _foo
304 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
306 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
307 } else if (MAI->hasLinkOnceDirective()) {
309 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
310 //NOTE: linkonce is handled by the section the symbol was assigned to.
313 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
316 case GlobalValue::AppendingLinkage:
317 // FIXME: appending linkage variables should go into a section of
318 // their name or something. For now, just emit them as external.
319 case GlobalValue::ExternalLinkage:
320 // If external or appending, declare as a global symbol.
322 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
324 case GlobalValue::PrivateLinkage:
325 case GlobalValue::InternalLinkage:
327 case GlobalValue::AvailableExternallyLinkage:
328 llvm_unreachable("Should never emit this");
329 case GlobalValue::ExternalWeakLinkage:
330 llvm_unreachable("Don't know how to emit these");
332 llvm_unreachable("Unknown linkage type!");
335 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
336 const GlobalValue *GV) const {
337 TM.getNameWithPrefix(Name, GV, *Mang);
340 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
341 return TM.getSymbol(GV, *Mang);
344 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
345 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
346 if (GV->hasInitializer()) {
347 // Check to see if this is a special global used by LLVM, if so, emit it.
348 if (EmitSpecialLLVMGlobal(GV))
351 // Skip the emission of global equivalents. The symbol can be emitted later
352 // on by emitGlobalGOTEquivs in case it turns out to be needed.
353 if (GlobalGOTEquivs.count(getSymbol(GV)))
357 GV->printAsOperand(OutStreamer->GetCommentOS(),
358 /*PrintType=*/false, GV->getParent());
359 OutStreamer->GetCommentOS() << '\n';
363 MCSymbol *GVSym = getSymbol(GV);
364 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
366 if (!GV->hasInitializer()) // External globals require no extra code.
369 GVSym->redefineIfPossible();
370 if (GVSym->isDefined() || GVSym->isVariable())
371 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
372 "' is already defined");
374 if (MAI->hasDotTypeDotSizeDirective())
375 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
377 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
379 const DataLayout *DL = TM.getDataLayout();
380 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
382 // If the alignment is specified, we *must* obey it. Overaligning a global
383 // with a specified alignment is a prompt way to break globals emitted to
384 // sections and expected to be contiguous (e.g. ObjC metadata).
385 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
387 for (const HandlerInfo &HI : Handlers) {
388 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
389 HI.Handler->setSymbolSize(GVSym, Size);
392 // Handle common and BSS local symbols (.lcomm).
393 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
394 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
395 unsigned Align = 1 << AlignLog;
397 // Handle common symbols.
398 if (GVKind.isCommon()) {
399 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
403 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
407 // Handle local BSS symbols.
408 if (MAI->hasMachoZeroFillDirective()) {
409 MCSection *TheSection =
410 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
411 // .zerofill __DATA, __bss, _foo, 400, 5
412 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
416 // Use .lcomm only if it supports user-specified alignment.
417 // Otherwise, while it would still be correct to use .lcomm in some
418 // cases (e.g. when Align == 1), the external assembler might enfore
419 // some -unknown- default alignment behavior, which could cause
420 // spurious differences between external and integrated assembler.
421 // Prefer to simply fall back to .local / .comm in this case.
422 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
424 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
428 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
432 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
434 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
438 MCSection *TheSection =
439 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
441 // Handle the zerofill directive on darwin, which is a special form of BSS
443 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
444 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
447 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
448 // .zerofill __DATA, __common, _foo, 400, 5
449 OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
453 // Handle thread local data for mach-o which requires us to output an
454 // additional structure of data and mangle the original symbol so that we
455 // can reference it later.
457 // TODO: This should become an "emit thread local global" method on TLOF.
458 // All of this macho specific stuff should be sunk down into TLOFMachO and
459 // stuff like "TLSExtraDataSection" should no longer be part of the parent
460 // TLOF class. This will also make it more obvious that stuff like
461 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
463 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
464 // Emit the .tbss symbol
466 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
468 if (GVKind.isThreadBSS()) {
469 TheSection = getObjFileLowering().getTLSBSSSection();
470 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
471 } else if (GVKind.isThreadData()) {
472 OutStreamer->SwitchSection(TheSection);
474 EmitAlignment(AlignLog, GV);
475 OutStreamer->EmitLabel(MangSym);
477 EmitGlobalConstant(GV->getInitializer());
480 OutStreamer->AddBlankLine();
482 // Emit the variable struct for the runtime.
483 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
485 OutStreamer->SwitchSection(TLVSect);
486 // Emit the linkage here.
487 EmitLinkage(GV, GVSym);
488 OutStreamer->EmitLabel(GVSym);
490 // Three pointers in size:
491 // - __tlv_bootstrap - used to make sure support exists
492 // - spare pointer, used when mapped by the runtime
493 // - pointer to mangled symbol above with initializer
494 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
495 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
497 OutStreamer->EmitIntValue(0, PtrSize);
498 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
500 OutStreamer->AddBlankLine();
504 OutStreamer->SwitchSection(TheSection);
506 EmitLinkage(GV, GVSym);
507 EmitAlignment(AlignLog, GV);
509 OutStreamer->EmitLabel(GVSym);
511 EmitGlobalConstant(GV->getInitializer());
513 if (MAI->hasDotTypeDotSizeDirective())
515 OutStreamer->emitELFSize(cast<MCSymbolELF>(GVSym),
516 MCConstantExpr::create(Size, OutContext));
518 OutStreamer->AddBlankLine();
521 /// EmitFunctionHeader - This method emits the header for the current
523 void AsmPrinter::EmitFunctionHeader() {
524 // Print out constants referenced by the function
527 // Print the 'header' of function.
528 const Function *F = MF->getFunction();
530 OutStreamer->SwitchSection(
531 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
532 EmitVisibility(CurrentFnSym, F->getVisibility());
534 EmitLinkage(F, CurrentFnSym);
535 if (MAI->hasFunctionAlignment())
536 EmitAlignment(MF->getAlignment(), F);
538 if (MAI->hasDotTypeDotSizeDirective())
539 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
542 F->printAsOperand(OutStreamer->GetCommentOS(),
543 /*PrintType=*/false, F->getParent());
544 OutStreamer->GetCommentOS() << '\n';
547 // Emit the prefix data.
548 if (F->hasPrefixData())
549 EmitGlobalConstant(F->getPrefixData());
551 // Emit the personality function.
552 if (F->hasPersonalityFn())
553 EmitGlobalConstant(F->getPersonalityFn());
555 // Emit the CurrentFnSym. This is a virtual function to allow targets to
556 // do their wild and crazy things as required.
557 EmitFunctionEntryLabel();
559 // If the function had address-taken blocks that got deleted, then we have
560 // references to the dangling symbols. Emit them at the start of the function
561 // so that we don't get references to undefined symbols.
562 std::vector<MCSymbol*> DeadBlockSyms;
563 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
564 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
565 OutStreamer->AddComment("Address taken block that was later removed");
566 OutStreamer->EmitLabel(DeadBlockSyms[i]);
569 if (CurrentFnBegin) {
570 if (MAI->useAssignmentForEHBegin()) {
571 MCSymbol *CurPos = OutContext.createTempSymbol();
572 OutStreamer->EmitLabel(CurPos);
573 OutStreamer->EmitAssignment(CurrentFnBegin,
574 MCSymbolRefExpr::create(CurPos, OutContext));
576 OutStreamer->EmitLabel(CurrentFnBegin);
580 // Emit pre-function debug and/or EH information.
581 for (const HandlerInfo &HI : Handlers) {
582 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
583 HI.Handler->beginFunction(MF);
586 // Emit the prologue data.
587 if (F->hasPrologueData())
588 EmitGlobalConstant(F->getPrologueData());
591 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
592 /// function. This can be overridden by targets as required to do custom stuff.
593 void AsmPrinter::EmitFunctionEntryLabel() {
594 CurrentFnSym->redefineIfPossible();
596 // The function label could have already been emitted if two symbols end up
597 // conflicting due to asm renaming. Detect this and emit an error.
598 if (CurrentFnSym->isVariable())
599 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
600 "' is a protected alias");
601 if (CurrentFnSym->isDefined())
602 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
603 "' label emitted multiple times to assembly file");
605 return OutStreamer->EmitLabel(CurrentFnSym);
608 /// emitComments - Pretty-print comments for instructions.
609 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
610 const MachineFunction *MF = MI.getParent()->getParent();
611 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
613 // Check for spills and reloads
616 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
618 // We assume a single instruction only has a spill or reload, not
620 const MachineMemOperand *MMO;
621 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
622 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
623 MMO = *MI.memoperands_begin();
624 CommentOS << MMO->getSize() << "-byte Reload\n";
626 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
627 if (FrameInfo->isSpillSlotObjectIndex(FI))
628 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
629 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
630 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
631 MMO = *MI.memoperands_begin();
632 CommentOS << MMO->getSize() << "-byte Spill\n";
634 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
635 if (FrameInfo->isSpillSlotObjectIndex(FI))
636 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
639 // Check for spill-induced copies
640 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
641 CommentOS << " Reload Reuse\n";
644 /// emitImplicitDef - This method emits the specified machine instruction
645 /// that is an implicit def.
646 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
647 unsigned RegNo = MI->getOperand(0).getReg();
648 OutStreamer->AddComment(Twine("implicit-def: ") +
649 MMI->getContext().getRegisterInfo()->getName(RegNo));
650 OutStreamer->AddBlankLine();
653 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
654 std::string Str = "kill:";
655 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
656 const MachineOperand &Op = MI->getOperand(i);
657 assert(Op.isReg() && "KILL instruction must have only register operands");
659 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
660 Str += (Op.isDef() ? "<def>" : "<kill>");
662 AP.OutStreamer->AddComment(Str);
663 AP.OutStreamer->AddBlankLine();
666 /// emitDebugValueComment - This method handles the target-independent form
667 /// of DBG_VALUE, returning true if it was able to do so. A false return
668 /// means the target will need to handle MI in EmitInstruction.
669 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
670 // This code handles only the 4-operand target-independent form.
671 if (MI->getNumOperands() != 4)
674 SmallString<128> Str;
675 raw_svector_ostream OS(Str);
676 OS << "DEBUG_VALUE: ";
678 const DILocalVariable *V = MI->getDebugVariable();
679 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
680 StringRef Name = SP->getDisplayName();
686 const DIExpression *Expr = MI->getDebugExpression();
687 if (Expr->isBitPiece())
688 OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
689 << " size=" << Expr->getBitPieceSize() << "]";
692 // The second operand is only an offset if it's an immediate.
693 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
694 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
696 // Register or immediate value. Register 0 means undef.
697 if (MI->getOperand(0).isFPImm()) {
698 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
699 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
700 OS << (double)APF.convertToFloat();
701 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
702 OS << APF.convertToDouble();
704 // There is no good way to print long double. Convert a copy to
705 // double. Ah well, it's only a comment.
707 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
709 OS << "(long double) " << APF.convertToDouble();
711 } else if (MI->getOperand(0).isImm()) {
712 OS << MI->getOperand(0).getImm();
713 } else if (MI->getOperand(0).isCImm()) {
714 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
717 if (MI->getOperand(0).isReg()) {
718 Reg = MI->getOperand(0).getReg();
720 assert(MI->getOperand(0).isFI() && "Unknown operand type");
721 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
722 Offset += TFI->getFrameIndexReference(*AP.MF,
723 MI->getOperand(0).getIndex(), Reg);
727 // Suppress offset, it is not meaningful here.
729 // NOTE: Want this comment at start of line, don't emit with AddComment.
730 AP.OutStreamer->emitRawComment(OS.str());
735 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
739 OS << '+' << Offset << ']';
741 // NOTE: Want this comment at start of line, don't emit with AddComment.
742 AP.OutStreamer->emitRawComment(OS.str());
746 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
747 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
748 MF->getFunction()->needsUnwindTableEntry())
751 if (MMI->hasDebugInfo())
757 bool AsmPrinter::needsSEHMoves() {
758 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
761 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
762 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
763 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
764 ExceptionHandlingType != ExceptionHandling::ARM)
767 if (needsCFIMoves() == CFI_M_None)
770 const MachineModuleInfo &MMI = MF->getMMI();
771 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
772 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
773 const MCCFIInstruction &CFI = Instrs[CFIIndex];
774 emitCFIInstruction(CFI);
777 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
778 // The operands are the MCSymbol and the frame offset of the allocation.
779 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
780 int FrameOffset = MI.getOperand(1).getImm();
782 // Emit a symbol assignment.
783 OutStreamer->EmitAssignment(FrameAllocSym,
784 MCConstantExpr::create(FrameOffset, OutContext));
787 /// EmitFunctionBody - This method emits the body and trailer for a
789 void AsmPrinter::EmitFunctionBody() {
790 EmitFunctionHeader();
792 // Emit target-specific gunk before the function body.
793 EmitFunctionBodyStart();
795 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
797 // Print out code for the function.
798 bool HasAnyRealCode = false;
799 for (auto &MBB : *MF) {
800 // Print a label for the basic block.
801 EmitBasicBlockStart(MBB);
802 for (auto &MI : MBB) {
804 // Print the assembly for the instruction.
805 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
806 !MI.isDebugValue()) {
807 HasAnyRealCode = true;
811 if (ShouldPrintDebugScopes) {
812 for (const HandlerInfo &HI : Handlers) {
813 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
814 TimePassesIsEnabled);
815 HI.Handler->beginInstruction(&MI);
820 emitComments(MI, OutStreamer->GetCommentOS());
822 switch (MI.getOpcode()) {
823 case TargetOpcode::CFI_INSTRUCTION:
824 emitCFIInstruction(MI);
827 case TargetOpcode::FRAME_ALLOC:
831 case TargetOpcode::EH_LABEL:
832 case TargetOpcode::GC_LABEL:
833 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
835 case TargetOpcode::INLINEASM:
838 case TargetOpcode::DBG_VALUE:
840 if (!emitDebugValueComment(&MI, *this))
841 EmitInstruction(&MI);
844 case TargetOpcode::IMPLICIT_DEF:
845 if (isVerbose()) emitImplicitDef(&MI);
847 case TargetOpcode::KILL:
848 if (isVerbose()) emitKill(&MI, *this);
851 EmitInstruction(&MI);
855 if (ShouldPrintDebugScopes) {
856 for (const HandlerInfo &HI : Handlers) {
857 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
858 TimePassesIsEnabled);
859 HI.Handler->endInstruction();
864 EmitBasicBlockEnd(MBB);
867 // If the function is empty and the object file uses .subsections_via_symbols,
868 // then we need to emit *something* to the function body to prevent the
869 // labels from collapsing together. Just emit a noop.
870 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
872 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
873 OutStreamer->AddComment("avoids zero-length function");
875 // Targets can opt-out of emitting the noop here by leaving the opcode
877 if (Noop.getOpcode())
878 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
881 const Function *F = MF->getFunction();
882 for (const auto &BB : *F) {
883 if (!BB.hasAddressTaken())
885 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
886 if (Sym->isDefined())
888 OutStreamer->AddComment("Address of block that was removed by CodeGen");
889 OutStreamer->EmitLabel(Sym);
892 // Emit target-specific gunk after the function body.
893 EmitFunctionBodyEnd();
895 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
896 MAI->hasDotTypeDotSizeDirective()) {
897 // Create a symbol for the end of function.
898 CurrentFnEnd = createTempSymbol("func_end");
899 OutStreamer->EmitLabel(CurrentFnEnd);
902 // If the target wants a .size directive for the size of the function, emit
904 if (MAI->hasDotTypeDotSizeDirective()) {
905 // We can get the size as difference between the function label and the
907 const MCExpr *SizeExp = MCBinaryExpr::createSub(
908 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
909 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
910 if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym))
911 OutStreamer->emitELFSize(Sym, SizeExp);
914 for (const HandlerInfo &HI : Handlers) {
915 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
916 HI.Handler->markFunctionEnd();
919 // Print out jump tables referenced by the function.
922 // Emit post-function debug and/or EH information.
923 for (const HandlerInfo &HI : Handlers) {
924 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
925 HI.Handler->endFunction(MF);
929 OutStreamer->AddBlankLine();
932 /// \brief Compute the number of Global Variables that uses a Constant.
933 static unsigned getNumGlobalVariableUses(const Constant *C) {
937 if (isa<GlobalVariable>(C))
940 unsigned NumUses = 0;
941 for (auto *CU : C->users())
942 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
947 /// \brief Only consider global GOT equivalents if at least one user is a
948 /// cstexpr inside an initializer of another global variables. Also, don't
949 /// handle cstexpr inside instructions. During global variable emission,
950 /// candidates are skipped and are emitted later in case at least one cstexpr
951 /// isn't replaced by a PC relative GOT entry access.
952 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
953 unsigned &NumGOTEquivUsers) {
954 // Global GOT equivalents are unnamed private globals with a constant
955 // pointer initializer to another global symbol. They must point to a
956 // GlobalVariable or Function, i.e., as GlobalValue.
957 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
958 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
961 // To be a got equivalent, at least one of its users need to be a constant
962 // expression used by another global variable.
963 for (auto *U : GV->users())
964 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
966 return NumGOTEquivUsers > 0;
969 /// \brief Unnamed constant global variables solely contaning a pointer to
970 /// another globals variable is equivalent to a GOT table entry; it contains the
971 /// the address of another symbol. Optimize it and replace accesses to these
972 /// "GOT equivalents" by using the GOT entry for the final global instead.
973 /// Compute GOT equivalent candidates among all global variables to avoid
974 /// emitting them if possible later on, after it use is replaced by a GOT entry
976 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
977 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
980 for (const auto &G : M.globals()) {
981 unsigned NumGOTEquivUsers = 0;
982 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
985 const MCSymbol *GOTEquivSym = getSymbol(&G);
986 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
990 /// \brief Constant expressions using GOT equivalent globals may not be eligible
991 /// for PC relative GOT entry conversion, in such cases we need to emit such
992 /// globals we previously omitted in EmitGlobalVariable.
993 void AsmPrinter::emitGlobalGOTEquivs() {
994 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
997 SmallVector<const GlobalVariable *, 8> FailedCandidates;
998 for (auto &I : GlobalGOTEquivs) {
999 const GlobalVariable *GV = I.second.first;
1000 unsigned Cnt = I.second.second;
1002 FailedCandidates.push_back(GV);
1004 GlobalGOTEquivs.clear();
1006 for (auto *GV : FailedCandidates)
1007 EmitGlobalVariable(GV);
1010 bool AsmPrinter::doFinalization(Module &M) {
1011 // Set the MachineFunction to nullptr so that we can catch attempted
1012 // accesses to MF specific features at the module level and so that
1013 // we can conditionalize accesses based on whether or not it is nullptr.
1016 // Gather all GOT equivalent globals in the module. We really need two
1017 // passes over the globals: one to compute and another to avoid its emission
1018 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1019 // where the got equivalent shows up before its use.
1020 computeGlobalGOTEquivs(M);
1022 // Emit global variables.
1023 for (const auto &G : M.globals())
1024 EmitGlobalVariable(&G);
1026 // Emit remaining GOT equivalent globals.
1027 emitGlobalGOTEquivs();
1029 // Emit visibility info for declarations
1030 for (const Function &F : M) {
1031 if (!F.isDeclaration())
1033 GlobalValue::VisibilityTypes V = F.getVisibility();
1034 if (V == GlobalValue::DefaultVisibility)
1037 MCSymbol *Name = getSymbol(&F);
1038 EmitVisibility(Name, V, false);
1041 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1043 // Emit module flags.
1044 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1045 M.getModuleFlagsMetadata(ModuleFlags);
1046 if (!ModuleFlags.empty())
1047 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1049 if (TM.getTargetTriple().isOSBinFormatELF()) {
1050 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1052 // Output stubs for external and common global variables.
1053 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1054 if (!Stubs.empty()) {
1055 OutStreamer->SwitchSection(TLOF.getDataRelSection());
1056 const DataLayout *DL = TM.getDataLayout();
1058 for (const auto &Stub : Stubs) {
1059 OutStreamer->EmitLabel(Stub.first);
1060 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1061 DL->getPointerSize());
1066 // Make sure we wrote out everything we need.
1067 OutStreamer->Flush();
1069 // Finalize debug and EH information.
1070 for (const HandlerInfo &HI : Handlers) {
1071 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1072 TimePassesIsEnabled);
1073 HI.Handler->endModule();
1079 // If the target wants to know about weak references, print them all.
1080 if (MAI->getWeakRefDirective()) {
1081 // FIXME: This is not lazy, it would be nice to only print weak references
1082 // to stuff that is actually used. Note that doing so would require targets
1083 // to notice uses in operands (due to constant exprs etc). This should
1084 // happen with the MC stuff eventually.
1086 // Print out module-level global variables here.
1087 for (const auto &G : M.globals()) {
1088 if (!G.hasExternalWeakLinkage())
1090 OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1093 for (const auto &F : M) {
1094 if (!F.hasExternalWeakLinkage())
1096 OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1100 OutStreamer->AddBlankLine();
1101 for (const auto &Alias : M.aliases()) {
1102 MCSymbol *Name = getSymbol(&Alias);
1104 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1105 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1106 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1107 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1109 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1111 EmitVisibility(Name, Alias.getVisibility());
1113 // Emit the directives as assignments aka .set:
1114 OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1117 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1118 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1119 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1120 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1121 MP->finishAssembly(M, *MI, *this);
1123 // Emit llvm.ident metadata in an '.ident' directive.
1124 EmitModuleIdents(M);
1126 // Emit __morestack address if needed for indirect calls.
1127 if (MMI->usesMorestackAddr()) {
1128 MCSection *ReadOnlySection =
1129 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1131 OutStreamer->SwitchSection(ReadOnlySection);
1133 MCSymbol *AddrSymbol =
1134 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1135 OutStreamer->EmitLabel(AddrSymbol);
1137 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1138 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1142 // If we don't have any trampolines, then we don't require stack memory
1143 // to be executable. Some targets have a directive to declare this.
1144 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1145 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1146 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1147 OutStreamer->SwitchSection(S);
1149 // Allow the target to emit any magic that it wants at the end of the file,
1150 // after everything else has gone out.
1151 EmitEndOfAsmFile(M);
1153 delete Mang; Mang = nullptr;
1156 OutStreamer->Finish();
1157 OutStreamer->reset();
1162 MCSymbol *AsmPrinter::getCurExceptionSym() {
1163 if (!CurExceptionSym)
1164 CurExceptionSym = createTempSymbol("exception");
1165 return CurExceptionSym;
1168 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1170 // Get the function symbol.
1171 CurrentFnSym = getSymbol(MF.getFunction());
1172 CurrentFnSymForSize = CurrentFnSym;
1173 CurrentFnBegin = nullptr;
1174 CurExceptionSym = nullptr;
1175 bool NeedsLocalForSize = MAI->needsLocalForSize();
1176 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1177 NeedsLocalForSize) {
1178 CurrentFnBegin = createTempSymbol("func_begin");
1179 if (NeedsLocalForSize)
1180 CurrentFnSymForSize = CurrentFnBegin;
1184 LI = &getAnalysis<MachineLoopInfo>();
1188 // Keep track the alignment, constpool entries per Section.
1192 SmallVector<unsigned, 4> CPEs;
1193 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1197 /// EmitConstantPool - Print to the current output stream assembly
1198 /// representations of the constants in the constant pool MCP. This is
1199 /// used to print out constants which have been "spilled to memory" by
1200 /// the code generator.
1202 void AsmPrinter::EmitConstantPool() {
1203 const MachineConstantPool *MCP = MF->getConstantPool();
1204 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1205 if (CP.empty()) return;
1207 // Calculate sections for constant pool entries. We collect entries to go into
1208 // the same section together to reduce amount of section switch statements.
1209 SmallVector<SectionCPs, 4> CPSections;
1210 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1211 const MachineConstantPoolEntry &CPE = CP[i];
1212 unsigned Align = CPE.getAlignment();
1215 CPE.getSectionKind(TM.getDataLayout());
1217 const Constant *C = nullptr;
1218 if (!CPE.isMachineConstantPoolEntry())
1219 C = CPE.Val.ConstVal;
1221 MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1223 // The number of sections are small, just do a linear search from the
1224 // last section to the first.
1226 unsigned SecIdx = CPSections.size();
1227 while (SecIdx != 0) {
1228 if (CPSections[--SecIdx].S == S) {
1234 SecIdx = CPSections.size();
1235 CPSections.push_back(SectionCPs(S, Align));
1238 if (Align > CPSections[SecIdx].Alignment)
1239 CPSections[SecIdx].Alignment = Align;
1240 CPSections[SecIdx].CPEs.push_back(i);
1243 // Now print stuff into the calculated sections.
1244 const MCSection *CurSection = nullptr;
1245 unsigned Offset = 0;
1246 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1247 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1248 unsigned CPI = CPSections[i].CPEs[j];
1249 MCSymbol *Sym = GetCPISymbol(CPI);
1250 if (!Sym->isUndefined())
1253 if (CurSection != CPSections[i].S) {
1254 OutStreamer->SwitchSection(CPSections[i].S);
1255 EmitAlignment(Log2_32(CPSections[i].Alignment));
1256 CurSection = CPSections[i].S;
1260 MachineConstantPoolEntry CPE = CP[CPI];
1262 // Emit inter-object padding for alignment.
1263 unsigned AlignMask = CPE.getAlignment() - 1;
1264 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1265 OutStreamer->EmitZeros(NewOffset - Offset);
1267 Type *Ty = CPE.getType();
1268 Offset = NewOffset +
1269 TM.getDataLayout()->getTypeAllocSize(Ty);
1271 OutStreamer->EmitLabel(Sym);
1272 if (CPE.isMachineConstantPoolEntry())
1273 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1275 EmitGlobalConstant(CPE.Val.ConstVal);
1280 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1281 /// by the current function to the current output stream.
1283 void AsmPrinter::EmitJumpTableInfo() {
1284 const DataLayout *DL = MF->getTarget().getDataLayout();
1285 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1287 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1288 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1289 if (JT.empty()) return;
1291 // Pick the directive to use to print the jump table entries, and switch to
1292 // the appropriate section.
1293 const Function *F = MF->getFunction();
1294 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1295 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1296 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1298 if (JTInDiffSection) {
1299 // Drop it in the readonly section.
1300 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1301 OutStreamer->SwitchSection(ReadOnlySection);
1304 EmitAlignment(Log2_32(
1305 MJTI->getEntryAlignment(*TM.getDataLayout())));
1307 // Jump tables in code sections are marked with a data_region directive
1308 // where that's supported.
1309 if (!JTInDiffSection)
1310 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1312 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1313 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1315 // If this jump table was deleted, ignore it.
1316 if (JTBBs.empty()) continue;
1318 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1319 /// emit a .set directive for each unique entry.
1320 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1321 MAI->doesSetDirectiveSuppressesReloc()) {
1322 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1323 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1324 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1325 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1326 const MachineBasicBlock *MBB = JTBBs[ii];
1327 if (!EmittedSets.insert(MBB).second)
1330 // .set LJTSet, LBB32-base
1332 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1333 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1334 MCBinaryExpr::createSub(LHS, Base,
1339 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1340 // before each jump table. The first label is never referenced, but tells
1341 // the assembler and linker the extents of the jump table object. The
1342 // second label is actually referenced by the code.
1343 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1344 // FIXME: This doesn't have to have any specific name, just any randomly
1345 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1346 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1348 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1350 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1351 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1353 if (!JTInDiffSection)
1354 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1357 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1359 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1360 const MachineBasicBlock *MBB,
1361 unsigned UID) const {
1362 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1363 const MCExpr *Value = nullptr;
1364 switch (MJTI->getEntryKind()) {
1365 case MachineJumpTableInfo::EK_Inline:
1366 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1367 case MachineJumpTableInfo::EK_Custom32:
1368 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1369 MJTI, MBB, UID, OutContext);
1371 case MachineJumpTableInfo::EK_BlockAddress:
1372 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1374 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1376 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1377 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1378 // with a relocation as gp-relative, e.g.:
1380 MCSymbol *MBBSym = MBB->getSymbol();
1381 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1385 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1386 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1387 // with a relocation as gp-relative, e.g.:
1389 MCSymbol *MBBSym = MBB->getSymbol();
1390 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1394 case MachineJumpTableInfo::EK_LabelDifference32: {
1395 // Each entry is the address of the block minus the address of the jump
1396 // table. This is used for PIC jump tables where gprel32 is not supported.
1398 // .word LBB123 - LJTI1_2
1399 // If the .set directive avoids relocations, this is emitted as:
1400 // .set L4_5_set_123, LBB123 - LJTI1_2
1401 // .word L4_5_set_123
1402 if (MAI->doesSetDirectiveSuppressesReloc()) {
1403 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1407 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1408 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1409 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1410 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1415 assert(Value && "Unknown entry kind!");
1417 unsigned EntrySize =
1418 MJTI->getEntrySize(*TM.getDataLayout());
1419 OutStreamer->EmitValue(Value, EntrySize);
1423 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1424 /// special global used by LLVM. If so, emit it and return true, otherwise
1425 /// do nothing and return false.
1426 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1427 if (GV->getName() == "llvm.used") {
1428 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1429 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1433 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1434 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1435 GV->hasAvailableExternallyLinkage())
1438 if (!GV->hasAppendingLinkage()) return false;
1440 assert(GV->hasInitializer() && "Not a special LLVM global!");
1442 if (GV->getName() == "llvm.global_ctors") {
1443 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1445 if (TM.getRelocationModel() == Reloc::Static &&
1446 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1447 StringRef Sym(".constructors_used");
1448 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1454 if (GV->getName() == "llvm.global_dtors") {
1455 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1457 if (TM.getRelocationModel() == Reloc::Static &&
1458 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1459 StringRef Sym(".destructors_used");
1460 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1469 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1470 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1471 /// is true, as being used with this directive.
1472 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1473 // Should be an array of 'i8*'.
1474 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1475 const GlobalValue *GV =
1476 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1478 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1484 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1486 llvm::Constant *Func;
1487 llvm::GlobalValue *ComdatKey;
1491 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1493 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1494 // Should be an array of '{ int, void ()* }' structs. The first value is the
1496 if (!isa<ConstantArray>(List)) return;
1498 // Sanity check the structors list.
1499 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1500 if (!InitList) return; // Not an array!
1501 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1502 // FIXME: Only allow the 3-field form in LLVM 4.0.
1503 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1504 return; // Not an array of two or three elements!
1505 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1506 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1507 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1508 return; // Not (int, ptr, ptr).
1510 // Gather the structors in a form that's convenient for sorting by priority.
1511 SmallVector<Structor, 8> Structors;
1512 for (Value *O : InitList->operands()) {
1513 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1514 if (!CS) continue; // Malformed.
1515 if (CS->getOperand(1)->isNullValue())
1516 break; // Found a null terminator, skip the rest.
1517 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1518 if (!Priority) continue; // Malformed.
1519 Structors.push_back(Structor());
1520 Structor &S = Structors.back();
1521 S.Priority = Priority->getLimitedValue(65535);
1522 S.Func = CS->getOperand(1);
1523 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1524 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1527 // Emit the function pointers in the target-specific order
1528 const DataLayout *DL = TM.getDataLayout();
1529 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1530 std::stable_sort(Structors.begin(), Structors.end(),
1531 [](const Structor &L,
1532 const Structor &R) { return L.Priority < R.Priority; });
1533 for (Structor &S : Structors) {
1534 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1535 const MCSymbol *KeySym = nullptr;
1536 if (GlobalValue *GV = S.ComdatKey) {
1537 if (GV->hasAvailableExternallyLinkage())
1538 // If the associated variable is available_externally, some other TU
1539 // will provide its dynamic initializer.
1542 KeySym = getSymbol(GV);
1544 MCSection *OutputSection =
1545 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1546 : Obj.getStaticDtorSection(S.Priority, KeySym));
1547 OutStreamer->SwitchSection(OutputSection);
1548 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1549 EmitAlignment(Align);
1550 EmitXXStructor(S.Func);
1554 void AsmPrinter::EmitModuleIdents(Module &M) {
1555 if (!MAI->hasIdentDirective())
1558 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1559 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1560 const MDNode *N = NMD->getOperand(i);
1561 assert(N->getNumOperands() == 1 &&
1562 "llvm.ident metadata entry can have only one operand");
1563 const MDString *S = cast<MDString>(N->getOperand(0));
1564 OutStreamer->EmitIdent(S->getString());
1569 //===--------------------------------------------------------------------===//
1570 // Emission and print routines
1573 /// EmitInt8 - Emit a byte directive and value.
1575 void AsmPrinter::EmitInt8(int Value) const {
1576 OutStreamer->EmitIntValue(Value, 1);
1579 /// EmitInt16 - Emit a short directive and value.
1581 void AsmPrinter::EmitInt16(int Value) const {
1582 OutStreamer->EmitIntValue(Value, 2);
1585 /// EmitInt32 - Emit a long directive and value.
1587 void AsmPrinter::EmitInt32(int Value) const {
1588 OutStreamer->EmitIntValue(Value, 4);
1591 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1592 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1593 /// .set if it avoids relocations.
1594 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1595 unsigned Size) const {
1596 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1599 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1600 /// where the size in bytes of the directive is specified by Size and Label
1601 /// specifies the label. This implicitly uses .set if it is available.
1602 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1604 bool IsSectionRelative) const {
1605 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1606 OutStreamer->EmitCOFFSecRel32(Label);
1610 // Emit Label+Offset (or just Label if Offset is zero)
1611 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1613 Expr = MCBinaryExpr::createAdd(
1614 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1616 OutStreamer->EmitValue(Expr, Size);
1619 //===----------------------------------------------------------------------===//
1621 // EmitAlignment - Emit an alignment directive to the specified power of
1622 // two boundary. For example, if you pass in 3 here, you will get an 8
1623 // byte alignment. If a global value is specified, and if that global has
1624 // an explicit alignment requested, it will override the alignment request
1625 // if required for correctness.
1627 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1629 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1632 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1635 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1636 "undefined behavior");
1637 if (getCurrentSection()->getKind().isText())
1638 OutStreamer->EmitCodeAlignment(1u << NumBits);
1640 OutStreamer->EmitValueToAlignment(1u << NumBits);
1643 //===----------------------------------------------------------------------===//
1644 // Constant emission.
1645 //===----------------------------------------------------------------------===//
1647 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1648 MCContext &Ctx = OutContext;
1650 if (CV->isNullValue() || isa<UndefValue>(CV))
1651 return MCConstantExpr::create(0, Ctx);
1653 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1654 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1656 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1657 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1659 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1660 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1662 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1664 llvm_unreachable("Unknown constant value to lower!");
1667 if (const MCExpr *RelocExpr
1668 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1671 switch (CE->getOpcode()) {
1673 // If the code isn't optimized, there may be outstanding folding
1674 // opportunities. Attempt to fold the expression using DataLayout as a
1675 // last resort before giving up.
1676 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
1678 return lowerConstant(C);
1680 // Otherwise report the problem to the user.
1683 raw_string_ostream OS(S);
1684 OS << "Unsupported expression in static initializer: ";
1685 CE->printAsOperand(OS, /*PrintType=*/false,
1686 !MF ? nullptr : MF->getFunction()->getParent());
1687 report_fatal_error(OS.str());
1689 case Instruction::GetElementPtr: {
1690 const DataLayout &DL = *TM.getDataLayout();
1692 // Generate a symbolic expression for the byte address
1693 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1694 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1696 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1700 int64_t Offset = OffsetAI.getSExtValue();
1701 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1705 case Instruction::Trunc:
1706 // We emit the value and depend on the assembler to truncate the generated
1707 // expression properly. This is important for differences between
1708 // blockaddress labels. Since the two labels are in the same function, it
1709 // is reasonable to treat their delta as a 32-bit value.
1711 case Instruction::BitCast:
1712 return lowerConstant(CE->getOperand(0));
1714 case Instruction::IntToPtr: {
1715 const DataLayout &DL = *TM.getDataLayout();
1717 // Handle casts to pointers by changing them into casts to the appropriate
1718 // integer type. This promotes constant folding and simplifies this code.
1719 Constant *Op = CE->getOperand(0);
1720 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1722 return lowerConstant(Op);
1725 case Instruction::PtrToInt: {
1726 const DataLayout &DL = *TM.getDataLayout();
1728 // Support only foldable casts to/from pointers that can be eliminated by
1729 // changing the pointer to the appropriately sized integer type.
1730 Constant *Op = CE->getOperand(0);
1731 Type *Ty = CE->getType();
1733 const MCExpr *OpExpr = lowerConstant(Op);
1735 // We can emit the pointer value into this slot if the slot is an
1736 // integer slot equal to the size of the pointer.
1737 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1740 // Otherwise the pointer is smaller than the resultant integer, mask off
1741 // the high bits so we are sure to get a proper truncation if the input is
1743 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1744 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1745 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1748 // The MC library also has a right-shift operator, but it isn't consistently
1749 // signed or unsigned between different targets.
1750 case Instruction::Add:
1751 case Instruction::Sub:
1752 case Instruction::Mul:
1753 case Instruction::SDiv:
1754 case Instruction::SRem:
1755 case Instruction::Shl:
1756 case Instruction::And:
1757 case Instruction::Or:
1758 case Instruction::Xor: {
1759 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1760 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1761 switch (CE->getOpcode()) {
1762 default: llvm_unreachable("Unknown binary operator constant cast expr");
1763 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1764 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1765 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1766 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1767 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1768 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1769 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1770 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1771 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1777 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1778 const Constant *BaseCV = nullptr,
1779 uint64_t Offset = 0);
1781 /// isRepeatedByteSequence - Determine whether the given value is
1782 /// composed of a repeated sequence of identical bytes and return the
1783 /// byte value. If it is not a repeated sequence, return -1.
1784 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1785 StringRef Data = V->getRawDataValues();
1786 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1788 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1789 if (Data[i] != C) return -1;
1790 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1794 /// isRepeatedByteSequence - Determine whether the given value is
1795 /// composed of a repeated sequence of identical bytes and return the
1796 /// byte value. If it is not a repeated sequence, return -1.
1797 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1799 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1800 if (CI->getBitWidth() > 64) return -1;
1803 TM.getDataLayout()->getTypeAllocSize(V->getType());
1804 uint64_t Value = CI->getZExtValue();
1806 // Make sure the constant is at least 8 bits long and has a power
1807 // of 2 bit width. This guarantees the constant bit width is
1808 // always a multiple of 8 bits, avoiding issues with padding out
1809 // to Size and other such corner cases.
1810 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1812 uint8_t Byte = static_cast<uint8_t>(Value);
1814 for (unsigned i = 1; i < Size; ++i) {
1816 if (static_cast<uint8_t>(Value) != Byte) return -1;
1820 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1821 // Make sure all array elements are sequences of the same repeated
1823 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1824 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1825 if (Byte == -1) return -1;
1827 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1828 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1829 if (ThisByte == -1) return -1;
1830 if (Byte != ThisByte) return -1;
1835 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1836 return isRepeatedByteSequence(CDS);
1841 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1844 // See if we can aggregate this into a .fill, if so, emit it as such.
1845 int Value = isRepeatedByteSequence(CDS, AP.TM);
1848 AP.TM.getDataLayout()->getTypeAllocSize(
1850 // Don't emit a 1-byte object as a .fill.
1852 return AP.OutStreamer->EmitFill(Bytes, Value);
1855 // If this can be emitted with .ascii/.asciz, emit it as such.
1856 if (CDS->isString())
1857 return AP.OutStreamer->EmitBytes(CDS->getAsString());
1859 // Otherwise, emit the values in successive locations.
1860 unsigned ElementByteSize = CDS->getElementByteSize();
1861 if (isa<IntegerType>(CDS->getElementType())) {
1862 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1864 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1865 CDS->getElementAsInteger(i));
1866 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1869 } else if (ElementByteSize == 4) {
1870 // FP Constants are printed as integer constants to avoid losing
1872 assert(CDS->getElementType()->isFloatTy());
1873 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1879 F = CDS->getElementAsFloat(i);
1881 AP.OutStreamer->GetCommentOS() << "float " << F << '\n';
1882 AP.OutStreamer->EmitIntValue(I, 4);
1885 assert(CDS->getElementType()->isDoubleTy());
1886 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1892 F = CDS->getElementAsDouble(i);
1894 AP.OutStreamer->GetCommentOS() << "double " << F << '\n';
1895 AP.OutStreamer->EmitIntValue(I, 8);
1899 const DataLayout &DL = *AP.TM.getDataLayout();
1900 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1901 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1902 CDS->getNumElements();
1903 if (unsigned Padding = Size - EmittedSize)
1904 AP.OutStreamer->EmitZeros(Padding);
1908 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1909 const Constant *BaseCV, uint64_t Offset) {
1910 // See if we can aggregate some values. Make sure it can be
1911 // represented as a series of bytes of the constant value.
1912 int Value = isRepeatedByteSequence(CA, AP.TM);
1913 const DataLayout &DL = *AP.TM.getDataLayout();
1916 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1917 AP.OutStreamer->EmitFill(Bytes, Value);
1920 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1921 emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1922 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1927 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1928 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1929 emitGlobalConstantImpl(CV->getOperand(i), AP);
1931 const DataLayout &DL = *AP.TM.getDataLayout();
1932 unsigned Size = DL.getTypeAllocSize(CV->getType());
1933 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1934 CV->getType()->getNumElements();
1935 if (unsigned Padding = Size - EmittedSize)
1936 AP.OutStreamer->EmitZeros(Padding);
1939 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1940 const Constant *BaseCV, uint64_t Offset) {
1941 // Print the fields in successive locations. Pad to align if needed!
1942 const DataLayout *DL = AP.TM.getDataLayout();
1943 unsigned Size = DL->getTypeAllocSize(CS->getType());
1944 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1945 uint64_t SizeSoFar = 0;
1946 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1947 const Constant *Field = CS->getOperand(i);
1949 // Print the actual field value.
1950 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1952 // Check if padding is needed and insert one or more 0s.
1953 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1954 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1955 - Layout->getElementOffset(i)) - FieldSize;
1956 SizeSoFar += FieldSize + PadSize;
1958 // Insert padding - this may include padding to increase the size of the
1959 // current field up to the ABI size (if the struct is not packed) as well
1960 // as padding to ensure that the next field starts at the right offset.
1961 AP.OutStreamer->EmitZeros(PadSize);
1963 assert(SizeSoFar == Layout->getSizeInBytes() &&
1964 "Layout of constant struct may be incorrect!");
1967 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1968 APInt API = CFP->getValueAPF().bitcastToAPInt();
1970 // First print a comment with what we think the original floating-point value
1971 // should have been.
1972 if (AP.isVerbose()) {
1973 SmallString<8> StrVal;
1974 CFP->getValueAPF().toString(StrVal);
1977 CFP->getType()->print(AP.OutStreamer->GetCommentOS());
1979 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
1980 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
1983 // Now iterate through the APInt chunks, emitting them in endian-correct
1984 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1986 unsigned NumBytes = API.getBitWidth() / 8;
1987 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1988 const uint64_t *p = API.getRawData();
1990 // PPC's long double has odd notions of endianness compared to how LLVM
1991 // handles it: p[0] goes first for *big* endian on PPC.
1992 if (AP.TM.getDataLayout()->isBigEndian() &&
1993 !CFP->getType()->isPPC_FP128Ty()) {
1994 int Chunk = API.getNumWords() - 1;
1997 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
1999 for (; Chunk >= 0; --Chunk)
2000 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2003 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2004 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2007 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2010 // Emit the tail padding for the long double.
2011 const DataLayout &DL = *AP.TM.getDataLayout();
2012 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2013 DL.getTypeStoreSize(CFP->getType()));
2016 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2017 const DataLayout *DL = AP.TM.getDataLayout();
2018 unsigned BitWidth = CI->getBitWidth();
2020 // Copy the value as we may massage the layout for constants whose bit width
2021 // is not a multiple of 64-bits.
2022 APInt Realigned(CI->getValue());
2023 uint64_t ExtraBits = 0;
2024 unsigned ExtraBitsSize = BitWidth & 63;
2026 if (ExtraBitsSize) {
2027 // The bit width of the data is not a multiple of 64-bits.
2028 // The extra bits are expected to be at the end of the chunk of the memory.
2030 // * Nothing to be done, just record the extra bits to emit.
2032 // * Record the extra bits to emit.
2033 // * Realign the raw data to emit the chunks of 64-bits.
2034 if (DL->isBigEndian()) {
2035 // Basically the structure of the raw data is a chunk of 64-bits cells:
2036 // 0 1 BitWidth / 64
2037 // [chunk1][chunk2] ... [chunkN].
2038 // The most significant chunk is chunkN and it should be emitted first.
2039 // However, due to the alignment issue chunkN contains useless bits.
2040 // Realign the chunks so that they contain only useless information:
2041 // ExtraBits 0 1 (BitWidth / 64) - 1
2042 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2043 ExtraBits = Realigned.getRawData()[0] &
2044 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2045 Realigned = Realigned.lshr(ExtraBitsSize);
2047 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2050 // We don't expect assemblers to support integer data directives
2051 // for more than 64 bits, so we emit the data in at most 64-bit
2052 // quantities at a time.
2053 const uint64_t *RawData = Realigned.getRawData();
2054 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2055 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2056 AP.OutStreamer->EmitIntValue(Val, 8);
2059 if (ExtraBitsSize) {
2060 // Emit the extra bits after the 64-bits chunks.
2062 // Emit a directive that fills the expected size.
2063 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2065 Size -= (BitWidth / 64) * 8;
2066 assert(Size && Size * 8 >= ExtraBitsSize &&
2067 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2068 == ExtraBits && "Directive too small for extra bits.");
2069 AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2073 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2074 /// equivalent global, by a target specific GOT pc relative access to the
2076 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2077 const Constant *BaseCst,
2079 // The global @foo below illustrates a global that uses a got equivalent.
2081 // @bar = global i32 42
2082 // @gotequiv = private unnamed_addr constant i32* @bar
2083 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2084 // i64 ptrtoint (i32* @foo to i64))
2087 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2088 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2091 // foo = cstexpr, where
2092 // cstexpr := <gotequiv> - "." + <cst>
2093 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2095 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2097 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2098 // gotpcrelcst := <offset from @foo base> + <cst>
2101 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2104 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2105 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2108 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2112 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2113 if (BaseSym != &MV.getSymB()->getSymbol())
2116 // Make sure to match:
2118 // gotpcrelcst := <offset from @foo base> + <cst>
2120 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2121 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2122 // if the target knows how to encode it.
2124 int64_t GOTPCRelCst = Offset + MV.getConstant();
2125 if (GOTPCRelCst < 0)
2127 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2130 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2137 // .long gotequiv - "." + <cst>
2139 // is replaced by the target specific equivalent to:
2144 // .long bar@GOTPCREL+<gotpcrelcst>
2146 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2147 const GlobalVariable *GV = Result.first;
2148 int NumUses = (int)Result.second;
2149 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2150 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2151 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2152 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2154 // Update GOT equivalent usage information
2157 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2160 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2161 const Constant *BaseCV, uint64_t Offset) {
2162 const DataLayout *DL = AP.TM.getDataLayout();
2163 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2165 // Globals with sub-elements such as combinations of arrays and structs
2166 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2167 // constant symbol base and the current position with BaseCV and Offset.
2168 if (!BaseCV && CV->hasOneUse())
2169 BaseCV = dyn_cast<Constant>(CV->user_back());
2171 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2172 return AP.OutStreamer->EmitZeros(Size);
2174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2181 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2182 CI->getZExtValue());
2183 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2186 emitGlobalConstantLargeInt(CI, AP);
2191 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2192 return emitGlobalConstantFP(CFP, AP);
2194 if (isa<ConstantPointerNull>(CV)) {
2195 AP.OutStreamer->EmitIntValue(0, Size);
2199 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2200 return emitGlobalConstantDataSequential(CDS, AP);
2202 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2203 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2205 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2206 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2208 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2209 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2211 if (CE->getOpcode() == Instruction::BitCast)
2212 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2215 // If the constant expression's size is greater than 64-bits, then we have
2216 // to emit the value in chunks. Try to constant fold the value and emit it
2218 Constant *New = ConstantFoldConstantExpression(CE, *DL);
2219 if (New && New != CE)
2220 return emitGlobalConstantImpl(New, AP);
2224 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2225 return emitGlobalConstantVector(V, AP);
2227 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2228 // thread the streamer with EmitValue.
2229 const MCExpr *ME = AP.lowerConstant(CV);
2231 // Since lowerConstant already folded and got rid of all IR pointer and
2232 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2234 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2235 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2237 AP.OutStreamer->EmitValue(ME, Size);
2240 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2241 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2243 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2245 emitGlobalConstantImpl(CV, *this);
2246 else if (MAI->hasSubsectionsViaSymbols()) {
2247 // If the global has zero size, emit a single byte so that two labels don't
2248 // look like they are at the same location.
2249 OutStreamer->EmitIntValue(0, 1);
2253 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2254 // Target doesn't support this yet!
2255 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2258 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2260 OS << '+' << Offset;
2261 else if (Offset < 0)
2265 //===----------------------------------------------------------------------===//
2266 // Symbol Lowering Routines.
2267 //===----------------------------------------------------------------------===//
2269 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2270 return OutContext.createTempSymbol(Name, true);
2273 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2274 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2277 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2278 return MMI->getAddrLabelSymbol(BB);
2281 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2282 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2283 const DataLayout *DL = TM.getDataLayout();
2284 return OutContext.getOrCreateSymbol
2285 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2286 + "_" + Twine(CPID));
2289 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2290 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2291 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2294 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2295 /// FIXME: privatize to AsmPrinter.
2296 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2297 const DataLayout *DL = TM.getDataLayout();
2298 return OutContext.getOrCreateSymbol
2299 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2300 Twine(UID) + "_set_" + Twine(MBBID));
2303 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2304 StringRef Suffix) const {
2305 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2309 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2311 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2312 SmallString<60> NameStr;
2313 Mang->getNameWithPrefix(NameStr, Sym);
2314 return OutContext.getOrCreateSymbol(NameStr);
2319 /// PrintParentLoopComment - Print comments about parent loops of this one.
2320 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2321 unsigned FunctionNumber) {
2323 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2324 OS.indent(Loop->getLoopDepth()*2)
2325 << "Parent Loop BB" << FunctionNumber << "_"
2326 << Loop->getHeader()->getNumber()
2327 << " Depth=" << Loop->getLoopDepth() << '\n';
2331 /// PrintChildLoopComment - Print comments about child loops within
2332 /// the loop for this basic block, with nesting.
2333 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2334 unsigned FunctionNumber) {
2335 // Add child loop information
2336 for (const MachineLoop *CL : *Loop) {
2337 OS.indent(CL->getLoopDepth()*2)
2338 << "Child Loop BB" << FunctionNumber << "_"
2339 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2341 PrintChildLoopComment(OS, CL, FunctionNumber);
2345 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2346 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2347 const MachineLoopInfo *LI,
2348 const AsmPrinter &AP) {
2349 // Add loop depth information
2350 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2353 MachineBasicBlock *Header = Loop->getHeader();
2354 assert(Header && "No header for loop");
2356 // If this block is not a loop header, just print out what is the loop header
2358 if (Header != &MBB) {
2359 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2360 Twine(AP.getFunctionNumber())+"_" +
2361 Twine(Loop->getHeader()->getNumber())+
2362 " Depth="+Twine(Loop->getLoopDepth()));
2366 // Otherwise, it is a loop header. Print out information about child and
2368 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2370 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2373 OS.indent(Loop->getLoopDepth()*2-2);
2378 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2380 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2384 /// EmitBasicBlockStart - This method prints the label for the specified
2385 /// MachineBasicBlock, an alignment (if present) and a comment describing
2386 /// it if appropriate.
2387 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2388 // Emit an alignment directive for this block, if needed.
2389 if (unsigned Align = MBB.getAlignment())
2390 EmitAlignment(Align);
2392 // If the block has its address taken, emit any labels that were used to
2393 // reference the block. It is possible that there is more than one label
2394 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2395 // the references were generated.
2396 if (MBB.hasAddressTaken()) {
2397 const BasicBlock *BB = MBB.getBasicBlock();
2399 OutStreamer->AddComment("Block address taken");
2401 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2402 for (auto *Sym : Symbols)
2403 OutStreamer->EmitLabel(Sym);
2406 // Print some verbose block comments.
2408 if (const BasicBlock *BB = MBB.getBasicBlock())
2410 OutStreamer->AddComment("%" + BB->getName());
2411 emitBasicBlockLoopComments(MBB, LI, *this);
2414 // Print the main label for the block.
2415 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2417 // NOTE: Want this comment at start of line, don't emit with AddComment.
2418 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2421 OutStreamer->EmitLabel(MBB.getSymbol());
2425 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2426 bool IsDefinition) const {
2427 MCSymbolAttr Attr = MCSA_Invalid;
2429 switch (Visibility) {
2431 case GlobalValue::HiddenVisibility:
2433 Attr = MAI->getHiddenVisibilityAttr();
2435 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2437 case GlobalValue::ProtectedVisibility:
2438 Attr = MAI->getProtectedVisibilityAttr();
2442 if (Attr != MCSA_Invalid)
2443 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2446 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2447 /// exactly one predecessor and the control transfer mechanism between
2448 /// the predecessor and this block is a fall-through.
2450 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2451 // If this is a landing pad, it isn't a fall through. If it has no preds,
2452 // then nothing falls through to it.
2453 if (MBB->isLandingPad() || MBB->pred_empty())
2456 // If there isn't exactly one predecessor, it can't be a fall through.
2457 if (MBB->pred_size() > 1)
2460 // The predecessor has to be immediately before this block.
2461 MachineBasicBlock *Pred = *MBB->pred_begin();
2462 if (!Pred->isLayoutSuccessor(MBB))
2465 // If the block is completely empty, then it definitely does fall through.
2469 // Check the terminators in the previous blocks
2470 for (const auto &MI : Pred->terminators()) {
2471 // If it is not a simple branch, we are in a table somewhere.
2472 if (!MI.isBranch() || MI.isIndirectBranch())
2475 // If we are the operands of one of the branches, this is not a fall
2476 // through. Note that targets with delay slots will usually bundle
2477 // terminators with the delay slot instruction.
2478 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2481 if (OP->isMBB() && OP->getMBB() == MBB)
2491 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2492 if (!S.usesMetadata())
2495 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2496 " stackmap formats, please see the documentation for a description of"
2497 " the default format. If you really need a custom serialized format,"
2498 " please file a bug");
2500 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2501 gcp_map_type::iterator GCPI = GCMap.find(&S);
2502 if (GCPI != GCMap.end())
2503 return GCPI->second.get();
2505 const char *Name = S.getName().c_str();
2507 for (GCMetadataPrinterRegistry::iterator
2508 I = GCMetadataPrinterRegistry::begin(),
2509 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2510 if (strcmp(Name, I->getName()) == 0) {
2511 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2513 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2514 return IterBool.first->second.get();
2517 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2520 /// Pin vtable to this file.
2521 AsmPrinterHandler::~AsmPrinterHandler() {}
2523 void AsmPrinterHandler::markFunctionEnd() {}