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/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/GCMetadataPrinter.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbolELF.h"
43 #include "llvm/MC/MCValue.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Target/TargetFrameLowering.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
57 #define DEBUG_TYPE "asm-printer"
59 static const char *const DWARFGroupName = "DWARF Emission";
60 static const char *const DbgTimerName = "Debug Info Emission";
61 static const char *const EHTimerName = "DWARF Exception Writer";
62 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
64 STATISTIC(EmittedInsts, "Number of machine instrs printed");
66 char AsmPrinter::ID = 0;
68 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
69 static gcp_map_type &getGCMap(void *&P) {
71 P = new gcp_map_type();
72 return *(gcp_map_type*)P;
76 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
77 /// value in log2 form. This rounds up to the preferred alignment if possible
79 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
80 unsigned InBits = 0) {
82 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
83 NumBits = DL.getPreferredAlignmentLog(GVar);
85 // If InBits is specified, round it to it.
89 // If the GV has a specified alignment, take it into account.
90 if (GV->getAlignment() == 0)
93 unsigned GVAlign = Log2_32(GV->getAlignment());
95 // If the GVAlign is larger than NumBits, or if we are required to obey
96 // NumBits because the GV has an assigned section, obey it.
97 if (GVAlign > NumBits || GV->hasSection())
102 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
103 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
104 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
105 LastMI(nullptr), LastFn(0), Counter(~0U) {
110 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
111 CurrentFnBegin = nullptr;
112 CurrentFnEnd = nullptr;
113 GCMetadataPrinters = nullptr;
114 VerboseAsm = OutStreamer->isVerboseAsm();
117 AsmPrinter::~AsmPrinter() {
118 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
120 if (GCMetadataPrinters) {
121 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
124 GCMetadataPrinters = nullptr;
128 /// getFunctionNumber - Return a unique ID for the current function.
130 unsigned AsmPrinter::getFunctionNumber() const {
131 return MF->getFunctionNumber();
134 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
135 return *TM.getObjFileLowering();
138 const DataLayout &AsmPrinter::getDataLayout() const {
139 return MMI->getModule()->getDataLayout();
142 // Do not use the cached DataLayout because some client use it without a Module
143 // (llmv-dsymutil, llvm-dwarfdump).
144 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); }
146 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
147 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
148 return MF->getSubtarget<MCSubtargetInfo>();
151 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
152 S.EmitInstruction(Inst, getSubtargetInfo());
155 StringRef AsmPrinter::getTargetTriple() const {
156 return TM.getTargetTriple().str();
159 /// getCurrentSection() - Return the current section we are emitting to.
160 const MCSection *AsmPrinter::getCurrentSection() const {
161 return OutStreamer->getCurrentSection().first;
166 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.setPreservesAll();
168 MachineFunctionPass::getAnalysisUsage(AU);
169 AU.addRequired<MachineModuleInfo>();
170 AU.addRequired<GCModuleInfo>();
172 AU.addRequired<MachineLoopInfo>();
175 bool AsmPrinter::doInitialization(Module &M) {
176 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
178 // Initialize TargetLoweringObjectFile.
179 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
180 .Initialize(OutContext, TM);
182 OutStreamer->InitSections(false);
184 Mang = new Mangler();
186 // Emit the version-min deplyment target directive if needed.
188 // FIXME: If we end up with a collection of these sorts of Darwin-specific
189 // or ELF-specific things, it may make sense to have a platform helper class
190 // that will work with the target helper class. For now keep it here, as the
191 // alternative is duplicated code in each of the target asm printers that
192 // use the directive, where it would need the same conditionalization
194 Triple TT(getTargetTriple());
195 if (TT.isOSDarwin()) {
196 unsigned Major, Minor, Update;
197 TT.getOSVersion(Major, Minor, Update);
198 // If there is a version specified, Major will be non-zero.
200 OutStreamer->EmitVersionMin((TT.isMacOSX() ?
201 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
202 Major, Minor, Update);
205 // Allow the target to emit any magic that it wants at the start of the file.
206 EmitStartOfAsmFile(M);
208 // Very minimal debug info. It is ignored if we emit actual debug info. If we
209 // don't, this at least helps the user find where a global came from.
210 if (MAI->hasSingleParameterDotFile()) {
212 OutStreamer->EmitFileDirective(M.getModuleIdentifier());
215 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
216 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
218 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
219 MP->beginAssembly(M, *MI, *this);
221 // Emit module-level inline asm if it exists.
222 if (!M.getModuleInlineAsm().empty()) {
223 // We're at the module level. Construct MCSubtarget from the default CPU
224 // and target triple.
225 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
226 TM.getTargetTriple().str(), TM.getTargetCPU(),
227 TM.getTargetFeatureString()));
228 OutStreamer->AddComment("Start of file scope inline assembly");
229 OutStreamer->AddBlankLine();
230 EmitInlineAsm(M.getModuleInlineAsm()+"\n", *STI, TM.Options.MCOptions);
231 OutStreamer->AddComment("End of file scope inline assembly");
232 OutStreamer->AddBlankLine();
235 if (MAI->doesSupportDebugInformation()) {
236 bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
237 if (EmitCodeView && TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) {
238 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
240 CodeViewLineTablesGroupName));
242 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
243 DD = new DwarfDebug(this, &M);
244 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
248 EHStreamer *ES = nullptr;
249 switch (MAI->getExceptionHandlingType()) {
250 case ExceptionHandling::None:
252 case ExceptionHandling::SjLj:
253 case ExceptionHandling::DwarfCFI:
254 ES = new DwarfCFIException(this);
256 case ExceptionHandling::ARM:
257 ES = new ARMException(this);
259 case ExceptionHandling::WinEH:
260 switch (MAI->getWinEHEncodingType()) {
261 default: llvm_unreachable("unsupported unwinding information encoding");
262 case WinEH::EncodingType::Invalid:
264 case WinEH::EncodingType::X86:
265 case WinEH::EncodingType::Itanium:
266 ES = new WinException(this);
272 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
276 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
277 if (!MAI.hasWeakDefCanBeHiddenDirective())
280 return canBeOmittedFromSymbolTable(GV);
283 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
284 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
286 case GlobalValue::CommonLinkage:
287 case GlobalValue::LinkOnceAnyLinkage:
288 case GlobalValue::LinkOnceODRLinkage:
289 case GlobalValue::WeakAnyLinkage:
290 case GlobalValue::WeakODRLinkage:
291 if (MAI->hasWeakDefDirective()) {
293 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
295 if (!canBeHidden(GV, *MAI))
296 // .weak_definition _foo
297 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
299 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
300 } else if (MAI->hasLinkOnceDirective()) {
302 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
303 //NOTE: linkonce is handled by the section the symbol was assigned to.
306 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
309 case GlobalValue::AppendingLinkage:
310 // FIXME: appending linkage variables should go into a section of
311 // their name or something. For now, just emit them as external.
312 case GlobalValue::ExternalLinkage:
313 // If external or appending, declare as a global symbol.
315 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
317 case GlobalValue::PrivateLinkage:
318 case GlobalValue::InternalLinkage:
320 case GlobalValue::AvailableExternallyLinkage:
321 llvm_unreachable("Should never emit this");
322 case GlobalValue::ExternalWeakLinkage:
323 llvm_unreachable("Don't know how to emit these");
325 llvm_unreachable("Unknown linkage type!");
328 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
329 const GlobalValue *GV) const {
330 TM.getNameWithPrefix(Name, GV, *Mang);
333 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
334 return TM.getSymbol(GV, *Mang);
337 static MCSymbol *getOrCreateEmuTLSControlSym(MCSymbol *GVSym, MCContext &C) {
338 return C.getOrCreateSymbol(Twine("__emutls_v.") + GVSym->getName());
341 static MCSymbol *getOrCreateEmuTLSInitSym(MCSymbol *GVSym, MCContext &C) {
342 return C.getOrCreateSymbol(Twine("__emutls_t.") + GVSym->getName());
345 /// EmitEmulatedTLSControlVariable - Emit the control variable for an emulated TLS variable.
346 void AsmPrinter::EmitEmulatedTLSControlVariable(const GlobalVariable *GV,
347 MCSymbol *EmittedSym,
348 bool AllZeroInitValue) {
349 // If there is init value, use .data.rel.local section;
350 // otherwise use the .data section.
351 MCSection *TLSVarSection = const_cast<MCSection*>(
352 (GV->hasInitializer() && !AllZeroInitValue)
353 ? getObjFileLowering().getDataRelLocalSection()
354 : getObjFileLowering().getDataSection());
355 OutStreamer->SwitchSection(TLSVarSection);
356 MCSymbol *GVSym = getSymbol(GV);
357 EmitLinkage(GV, EmittedSym); // same linkage as GV
358 const DataLayout &DL = GV->getParent()->getDataLayout();
359 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
360 unsigned AlignLog = getGVAlignmentLog2(GV, DL);
361 unsigned WordSize = DL.getPointerSize();
362 unsigned Alignment = DL.getPointerABIAlignment();
363 EmitAlignment(Log2_32(Alignment));
364 OutStreamer->EmitLabel(EmittedSym);
365 OutStreamer->EmitIntValue(Size, WordSize);
366 OutStreamer->EmitIntValue((1 << AlignLog), WordSize);
367 OutStreamer->EmitIntValue(0, WordSize);
368 if (GV->hasInitializer() && !AllZeroInitValue) {
369 OutStreamer->EmitSymbolValue(
370 getOrCreateEmuTLSInitSym(GVSym, OutContext), WordSize);
372 OutStreamer->EmitIntValue(0, WordSize);
373 if (MAI->hasDotTypeDotSizeDirective())
374 OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedSym),
375 MCConstantExpr::create(4 * WordSize, OutContext));
376 OutStreamer->AddBlankLine(); // End of the __emutls_v.* variable.
379 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
380 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
382 GV->getThreadLocalMode() != llvm::GlobalVariable::NotThreadLocal &&
383 TM.Options.EmulatedTLS;
384 assert((!IsEmuTLSVar || getObjFileLowering().getDataRelLocalSection()) &&
385 "Need relocatable local section for emulated TLS variables");
386 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
387 "No emulated TLS variables in the common section");
389 if (GV->hasInitializer()) {
390 // Check to see if this is a special global used by LLVM, if so, emit it.
391 if (EmitSpecialLLVMGlobal(GV))
394 // Skip the emission of global equivalents. The symbol can be emitted later
395 // on by emitGlobalGOTEquivs in case it turns out to be needed.
396 if (GlobalGOTEquivs.count(getSymbol(GV)))
399 if (isVerbose() && !IsEmuTLSVar) {
400 // When printing the control variable __emutls_v.*,
401 // we don't need to print the original TLS variable name.
402 GV->printAsOperand(OutStreamer->GetCommentOS(),
403 /*PrintType=*/false, GV->getParent());
404 OutStreamer->GetCommentOS() << '\n';
408 MCSymbol *GVSym = getSymbol(GV);
409 MCSymbol *EmittedSym = IsEmuTLSVar ?
410 getOrCreateEmuTLSControlSym(GVSym, OutContext) : GVSym;
411 // getOrCreateEmuTLSControlSym only creates the symbol with name and default attributes.
412 // GV's or GVSym's attributes will be used for the EmittedSym.
414 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
416 if (!GV->hasInitializer()) // External globals require no extra code.
419 GVSym->redefineIfPossible();
420 if (GVSym->isDefined() || GVSym->isVariable())
421 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
422 "' is already defined");
424 if (MAI->hasDotTypeDotSizeDirective())
425 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
427 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
429 const DataLayout &DL = GV->getParent()->getDataLayout();
430 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
432 // If the alignment is specified, we *must* obey it. Overaligning a global
433 // with a specified alignment is a prompt way to break globals emitted to
434 // sections and expected to be contiguous (e.g. ObjC metadata).
435 unsigned AlignLog = getGVAlignmentLog2(GV, DL);
437 bool AllZeroInitValue = false;
438 const Constant *InitValue = GV->getInitializer();
439 if (isa<ConstantAggregateZero>(InitValue))
440 AllZeroInitValue = true;
442 const ConstantInt *InitIntValue = dyn_cast<ConstantInt>(InitValue);
443 if (InitIntValue && InitIntValue->isZero())
444 AllZeroInitValue = true;
447 EmitEmulatedTLSControlVariable(GV, EmittedSym, AllZeroInitValue);
449 for (const HandlerInfo &HI : Handlers) {
450 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
451 HI.Handler->setSymbolSize(GVSym, Size);
454 // Handle common and BSS local symbols (.lcomm).
455 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
456 assert(!(IsEmuTLSVar && GVKind.isCommon()) &&
457 "No emulated TLS variables in the common section");
458 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
459 unsigned Align = 1 << AlignLog;
461 // Handle common symbols.
462 if (GVKind.isCommon()) {
463 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
467 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
471 // Handle local BSS symbols.
472 if (MAI->hasMachoZeroFillDirective()) {
473 MCSection *TheSection =
474 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
475 // .zerofill __DATA, __bss, _foo, 400, 5
476 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
480 // Use .lcomm only if it supports user-specified alignment.
481 // Otherwise, while it would still be correct to use .lcomm in some
482 // cases (e.g. when Align == 1), the external assembler might enfore
483 // some -unknown- default alignment behavior, which could cause
484 // spurious differences between external and integrated assembler.
485 // Prefer to simply fall back to .local / .comm in this case.
486 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
488 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
492 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
496 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
498 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
502 if (IsEmuTLSVar && AllZeroInitValue)
503 return; // No need of initialization values.
505 MCSymbol *EmittedInitSym = IsEmuTLSVar ?
506 getOrCreateEmuTLSInitSym(GVSym, OutContext) : GVSym;
507 // getOrCreateEmuTLSInitSym only creates the symbol with name and default attributes.
508 // GV's or GVSym's attributes will be used for the EmittedInitSym.
510 MCSection *TheSection = IsEmuTLSVar ?
511 getObjFileLowering().getReadOnlySection() :
512 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
514 // Handle the zerofill directive on darwin, which is a special form of BSS
516 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective() && !IsEmuTLSVar) {
517 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
520 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
521 // .zerofill __DATA, __common, _foo, 400, 5
522 OutStreamer->EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
526 // Handle thread local data for mach-o which requires us to output an
527 // additional structure of data and mangle the original symbol so that we
528 // can reference it later.
530 // TODO: This should become an "emit thread local global" method on TLOF.
531 // All of this macho specific stuff should be sunk down into TLOFMachO and
532 // stuff like "TLSExtraDataSection" should no longer be part of the parent
533 // TLOF class. This will also make it more obvious that stuff like
534 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
536 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective() && !IsEmuTLSVar) {
537 // Emit the .tbss symbol
539 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
541 if (GVKind.isThreadBSS()) {
542 TheSection = getObjFileLowering().getTLSBSSSection();
543 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
544 } else if (GVKind.isThreadData()) {
545 OutStreamer->SwitchSection(TheSection);
547 EmitAlignment(AlignLog, GV);
548 OutStreamer->EmitLabel(MangSym);
550 EmitGlobalConstant(GV->getParent()->getDataLayout(),
551 GV->getInitializer());
554 OutStreamer->AddBlankLine();
556 // Emit the variable struct for the runtime.
557 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
559 OutStreamer->SwitchSection(TLVSect);
560 // Emit the linkage here.
561 EmitLinkage(GV, GVSym);
562 OutStreamer->EmitLabel(GVSym);
564 // Three pointers in size:
565 // - __tlv_bootstrap - used to make sure support exists
566 // - spare pointer, used when mapped by the runtime
567 // - pointer to mangled symbol above with initializer
568 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
569 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
571 OutStreamer->EmitIntValue(0, PtrSize);
572 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
574 OutStreamer->AddBlankLine();
578 OutStreamer->SwitchSection(TheSection);
580 // emutls_t.* symbols are only used in the current compilation unit.
582 EmitLinkage(GV, EmittedInitSym);
583 EmitAlignment(AlignLog, GV);
585 OutStreamer->EmitLabel(EmittedInitSym);
587 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
589 if (MAI->hasDotTypeDotSizeDirective())
591 OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedInitSym),
592 MCConstantExpr::create(Size, OutContext));
594 OutStreamer->AddBlankLine();
597 /// EmitFunctionHeader - This method emits the header for the current
599 void AsmPrinter::EmitFunctionHeader() {
600 // Print out constants referenced by the function
603 // Print the 'header' of function.
604 const Function *F = MF->getFunction();
606 OutStreamer->SwitchSection(
607 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
608 EmitVisibility(CurrentFnSym, F->getVisibility());
610 EmitLinkage(F, CurrentFnSym);
611 if (MAI->hasFunctionAlignment())
612 EmitAlignment(MF->getAlignment(), F);
614 if (MAI->hasDotTypeDotSizeDirective())
615 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
618 F->printAsOperand(OutStreamer->GetCommentOS(),
619 /*PrintType=*/false, F->getParent());
620 OutStreamer->GetCommentOS() << '\n';
623 // Emit the prefix data.
624 if (F->hasPrefixData())
625 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData());
627 // Emit the CurrentFnSym. This is a virtual function to allow targets to
628 // do their wild and crazy things as required.
629 EmitFunctionEntryLabel();
631 // If the function had address-taken blocks that got deleted, then we have
632 // references to the dangling symbols. Emit them at the start of the function
633 // so that we don't get references to undefined symbols.
634 std::vector<MCSymbol*> DeadBlockSyms;
635 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
636 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
637 OutStreamer->AddComment("Address taken block that was later removed");
638 OutStreamer->EmitLabel(DeadBlockSyms[i]);
641 if (CurrentFnBegin) {
642 if (MAI->useAssignmentForEHBegin()) {
643 MCSymbol *CurPos = OutContext.createTempSymbol();
644 OutStreamer->EmitLabel(CurPos);
645 OutStreamer->EmitAssignment(CurrentFnBegin,
646 MCSymbolRefExpr::create(CurPos, OutContext));
648 OutStreamer->EmitLabel(CurrentFnBegin);
652 // Emit pre-function debug and/or EH information.
653 for (const HandlerInfo &HI : Handlers) {
654 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
655 HI.Handler->beginFunction(MF);
658 // Emit the prologue data.
659 if (F->hasPrologueData())
660 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData());
663 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
664 /// function. This can be overridden by targets as required to do custom stuff.
665 void AsmPrinter::EmitFunctionEntryLabel() {
666 CurrentFnSym->redefineIfPossible();
668 // The function label could have already been emitted if two symbols end up
669 // conflicting due to asm renaming. Detect this and emit an error.
670 if (CurrentFnSym->isVariable())
671 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
672 "' is a protected alias");
673 if (CurrentFnSym->isDefined())
674 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
675 "' label emitted multiple times to assembly file");
677 return OutStreamer->EmitLabel(CurrentFnSym);
680 /// emitComments - Pretty-print comments for instructions.
681 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
682 const MachineFunction *MF = MI.getParent()->getParent();
683 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
685 // Check for spills and reloads
688 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
690 // We assume a single instruction only has a spill or reload, not
692 const MachineMemOperand *MMO;
693 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
694 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
695 MMO = *MI.memoperands_begin();
696 CommentOS << MMO->getSize() << "-byte Reload\n";
698 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
699 if (FrameInfo->isSpillSlotObjectIndex(FI))
700 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
701 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
702 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
703 MMO = *MI.memoperands_begin();
704 CommentOS << MMO->getSize() << "-byte Spill\n";
706 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
707 if (FrameInfo->isSpillSlotObjectIndex(FI))
708 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
711 // Check for spill-induced copies
712 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
713 CommentOS << " Reload Reuse\n";
716 /// emitImplicitDef - This method emits the specified machine instruction
717 /// that is an implicit def.
718 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
719 unsigned RegNo = MI->getOperand(0).getReg();
720 OutStreamer->AddComment(Twine("implicit-def: ") +
721 MMI->getContext().getRegisterInfo()->getName(RegNo));
722 OutStreamer->AddBlankLine();
725 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
726 std::string Str = "kill:";
727 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
728 const MachineOperand &Op = MI->getOperand(i);
729 assert(Op.isReg() && "KILL instruction must have only register operands");
731 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
732 Str += (Op.isDef() ? "<def>" : "<kill>");
734 AP.OutStreamer->AddComment(Str);
735 AP.OutStreamer->AddBlankLine();
738 /// emitDebugValueComment - This method handles the target-independent form
739 /// of DBG_VALUE, returning true if it was able to do so. A false return
740 /// means the target will need to handle MI in EmitInstruction.
741 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
742 // This code handles only the 4-operand target-independent form.
743 if (MI->getNumOperands() != 4)
746 SmallString<128> Str;
747 raw_svector_ostream OS(Str);
748 OS << "DEBUG_VALUE: ";
750 const DILocalVariable *V = MI->getDebugVariable();
751 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
752 StringRef Name = SP->getDisplayName();
758 const DIExpression *Expr = MI->getDebugExpression();
759 if (Expr->isBitPiece())
760 OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
761 << " size=" << Expr->getBitPieceSize() << "]";
764 // The second operand is only an offset if it's an immediate.
765 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
766 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
768 // Register or immediate value. Register 0 means undef.
769 if (MI->getOperand(0).isFPImm()) {
770 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
771 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
772 OS << (double)APF.convertToFloat();
773 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
774 OS << APF.convertToDouble();
776 // There is no good way to print long double. Convert a copy to
777 // double. Ah well, it's only a comment.
779 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
781 OS << "(long double) " << APF.convertToDouble();
783 } else if (MI->getOperand(0).isImm()) {
784 OS << MI->getOperand(0).getImm();
785 } else if (MI->getOperand(0).isCImm()) {
786 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
789 if (MI->getOperand(0).isReg()) {
790 Reg = MI->getOperand(0).getReg();
792 assert(MI->getOperand(0).isFI() && "Unknown operand type");
793 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
794 Offset += TFI->getFrameIndexReference(*AP.MF,
795 MI->getOperand(0).getIndex(), Reg);
799 // Suppress offset, it is not meaningful here.
801 // NOTE: Want this comment at start of line, don't emit with AddComment.
802 AP.OutStreamer->emitRawComment(OS.str());
807 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
811 OS << '+' << Offset << ']';
813 // NOTE: Want this comment at start of line, don't emit with AddComment.
814 AP.OutStreamer->emitRawComment(OS.str());
818 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
819 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
820 MF->getFunction()->needsUnwindTableEntry())
823 if (MMI->hasDebugInfo())
829 bool AsmPrinter::needsSEHMoves() {
830 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
833 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
834 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
835 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
836 ExceptionHandlingType != ExceptionHandling::ARM)
839 if (needsCFIMoves() == CFI_M_None)
842 const MachineModuleInfo &MMI = MF->getMMI();
843 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
844 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
845 const MCCFIInstruction &CFI = Instrs[CFIIndex];
846 emitCFIInstruction(CFI);
849 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
850 // The operands are the MCSymbol and the frame offset of the allocation.
851 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
852 int FrameOffset = MI.getOperand(1).getImm();
854 // Emit a symbol assignment.
855 OutStreamer->EmitAssignment(FrameAllocSym,
856 MCConstantExpr::create(FrameOffset, OutContext));
859 /// EmitFunctionBody - This method emits the body and trailer for a
861 void AsmPrinter::EmitFunctionBody() {
862 EmitFunctionHeader();
864 // Emit target-specific gunk before the function body.
865 EmitFunctionBodyStart();
867 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
869 // Print out code for the function.
870 bool HasAnyRealCode = false;
871 for (auto &MBB : *MF) {
872 // Print a label for the basic block.
873 EmitBasicBlockStart(MBB);
874 for (auto &MI : MBB) {
876 // Print the assembly for the instruction.
877 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
878 !MI.isDebugValue()) {
879 HasAnyRealCode = true;
883 if (ShouldPrintDebugScopes) {
884 for (const HandlerInfo &HI : Handlers) {
885 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
886 TimePassesIsEnabled);
887 HI.Handler->beginInstruction(&MI);
892 emitComments(MI, OutStreamer->GetCommentOS());
894 switch (MI.getOpcode()) {
895 case TargetOpcode::CFI_INSTRUCTION:
896 emitCFIInstruction(MI);
899 case TargetOpcode::LOCAL_ESCAPE:
903 case TargetOpcode::EH_LABEL:
904 case TargetOpcode::GC_LABEL:
905 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
907 case TargetOpcode::INLINEASM:
910 case TargetOpcode::DBG_VALUE:
912 if (!emitDebugValueComment(&MI, *this))
913 EmitInstruction(&MI);
916 case TargetOpcode::IMPLICIT_DEF:
917 if (isVerbose()) emitImplicitDef(&MI);
919 case TargetOpcode::KILL:
920 if (isVerbose()) emitKill(&MI, *this);
923 EmitInstruction(&MI);
927 if (ShouldPrintDebugScopes) {
928 for (const HandlerInfo &HI : Handlers) {
929 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
930 TimePassesIsEnabled);
931 HI.Handler->endInstruction();
936 EmitBasicBlockEnd(MBB);
939 // If the function is empty and the object file uses .subsections_via_symbols,
940 // then we need to emit *something* to the function body to prevent the
941 // labels from collapsing together. Just emit a noop.
942 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
944 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
945 OutStreamer->AddComment("avoids zero-length function");
947 // Targets can opt-out of emitting the noop here by leaving the opcode
949 if (Noop.getOpcode())
950 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
953 const Function *F = MF->getFunction();
954 for (const auto &BB : *F) {
955 if (!BB.hasAddressTaken())
957 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
958 if (Sym->isDefined())
960 OutStreamer->AddComment("Address of block that was removed by CodeGen");
961 OutStreamer->EmitLabel(Sym);
964 // Emit target-specific gunk after the function body.
965 EmitFunctionBodyEnd();
967 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
968 MAI->hasDotTypeDotSizeDirective()) {
969 // Create a symbol for the end of function.
970 CurrentFnEnd = createTempSymbol("func_end");
971 OutStreamer->EmitLabel(CurrentFnEnd);
974 // If the target wants a .size directive for the size of the function, emit
976 if (MAI->hasDotTypeDotSizeDirective()) {
977 // We can get the size as difference between the function label and the
979 const MCExpr *SizeExp = MCBinaryExpr::createSub(
980 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
981 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
982 if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym))
983 OutStreamer->emitELFSize(Sym, SizeExp);
986 for (const HandlerInfo &HI : Handlers) {
987 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
988 HI.Handler->markFunctionEnd();
991 // Print out jump tables referenced by the function.
994 // Emit post-function debug and/or EH information.
995 for (const HandlerInfo &HI : Handlers) {
996 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
997 HI.Handler->endFunction(MF);
1001 OutStreamer->AddBlankLine();
1004 /// \brief Compute the number of Global Variables that uses a Constant.
1005 static unsigned getNumGlobalVariableUses(const Constant *C) {
1009 if (isa<GlobalVariable>(C))
1012 unsigned NumUses = 0;
1013 for (auto *CU : C->users())
1014 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1019 /// \brief Only consider global GOT equivalents if at least one user is a
1020 /// cstexpr inside an initializer of another global variables. Also, don't
1021 /// handle cstexpr inside instructions. During global variable emission,
1022 /// candidates are skipped and are emitted later in case at least one cstexpr
1023 /// isn't replaced by a PC relative GOT entry access.
1024 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1025 unsigned &NumGOTEquivUsers) {
1026 // Global GOT equivalents are unnamed private globals with a constant
1027 // pointer initializer to another global symbol. They must point to a
1028 // GlobalVariable or Function, i.e., as GlobalValue.
1029 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
1030 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
1033 // To be a got equivalent, at least one of its users need to be a constant
1034 // expression used by another global variable.
1035 for (auto *U : GV->users())
1036 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1038 return NumGOTEquivUsers > 0;
1041 /// \brief Unnamed constant global variables solely contaning a pointer to
1042 /// another globals variable is equivalent to a GOT table entry; it contains the
1043 /// the address of another symbol. Optimize it and replace accesses to these
1044 /// "GOT equivalents" by using the GOT entry for the final global instead.
1045 /// Compute GOT equivalent candidates among all global variables to avoid
1046 /// emitting them if possible later on, after it use is replaced by a GOT entry
1048 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1049 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1052 for (const auto &G : M.globals()) {
1053 unsigned NumGOTEquivUsers = 0;
1054 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1057 const MCSymbol *GOTEquivSym = getSymbol(&G);
1058 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1062 /// \brief Constant expressions using GOT equivalent globals may not be eligible
1063 /// for PC relative GOT entry conversion, in such cases we need to emit such
1064 /// globals we previously omitted in EmitGlobalVariable.
1065 void AsmPrinter::emitGlobalGOTEquivs() {
1066 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1069 SmallVector<const GlobalVariable *, 8> FailedCandidates;
1070 for (auto &I : GlobalGOTEquivs) {
1071 const GlobalVariable *GV = I.second.first;
1072 unsigned Cnt = I.second.second;
1074 FailedCandidates.push_back(GV);
1076 GlobalGOTEquivs.clear();
1078 for (auto *GV : FailedCandidates)
1079 EmitGlobalVariable(GV);
1082 bool AsmPrinter::doFinalization(Module &M) {
1083 // Set the MachineFunction to nullptr so that we can catch attempted
1084 // accesses to MF specific features at the module level and so that
1085 // we can conditionalize accesses based on whether or not it is nullptr.
1088 // Gather all GOT equivalent globals in the module. We really need two
1089 // passes over the globals: one to compute and another to avoid its emission
1090 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1091 // where the got equivalent shows up before its use.
1092 computeGlobalGOTEquivs(M);
1094 // Emit global variables.
1095 for (const auto &G : M.globals())
1096 EmitGlobalVariable(&G);
1098 // Emit remaining GOT equivalent globals.
1099 emitGlobalGOTEquivs();
1101 // Emit visibility info for declarations
1102 for (const Function &F : M) {
1103 if (!F.isDeclarationForLinker())
1105 GlobalValue::VisibilityTypes V = F.getVisibility();
1106 if (V == GlobalValue::DefaultVisibility)
1109 MCSymbol *Name = getSymbol(&F);
1110 EmitVisibility(Name, V, false);
1113 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1115 // Emit module flags.
1116 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1117 M.getModuleFlagsMetadata(ModuleFlags);
1118 if (!ModuleFlags.empty())
1119 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1121 if (TM.getTargetTriple().isOSBinFormatELF()) {
1122 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1124 // Output stubs for external and common global variables.
1125 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1126 if (!Stubs.empty()) {
1127 OutStreamer->SwitchSection(TLOF.getDataRelSection());
1128 const DataLayout &DL = M.getDataLayout();
1130 for (const auto &Stub : Stubs) {
1131 OutStreamer->EmitLabel(Stub.first);
1132 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1133 DL.getPointerSize());
1138 // Make sure we wrote out everything we need.
1139 OutStreamer->Flush();
1141 // Finalize debug and EH information.
1142 for (const HandlerInfo &HI : Handlers) {
1143 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1144 TimePassesIsEnabled);
1145 HI.Handler->endModule();
1151 // If the target wants to know about weak references, print them all.
1152 if (MAI->getWeakRefDirective()) {
1153 // FIXME: This is not lazy, it would be nice to only print weak references
1154 // to stuff that is actually used. Note that doing so would require targets
1155 // to notice uses in operands (due to constant exprs etc). This should
1156 // happen with the MC stuff eventually.
1158 // Print out module-level global variables here.
1159 for (const auto &G : M.globals()) {
1160 if (!G.hasExternalWeakLinkage())
1162 OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1165 for (const auto &F : M) {
1166 if (!F.hasExternalWeakLinkage())
1168 OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1172 OutStreamer->AddBlankLine();
1173 for (const auto &Alias : M.aliases()) {
1174 MCSymbol *Name = getSymbol(&Alias);
1176 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1177 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1178 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1179 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1181 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1183 EmitVisibility(Name, Alias.getVisibility());
1185 // Emit the directives as assignments aka .set:
1186 OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1188 // If the aliasee does not correspond to a symbol in the output, i.e. the
1189 // alias is not of an object or the aliased object is private, then set the
1190 // size of the alias symbol from the type of the alias. We don't do this in
1191 // other situations as the alias and aliasee having differing types but same
1192 // size may be intentional.
1193 const GlobalObject *BaseObject = Alias.getBaseObject();
1194 if (MAI->hasDotTypeDotSizeDirective() && Alias.getValueType()->isSized() &&
1195 (!BaseObject || BaseObject->hasPrivateLinkage())) {
1196 const DataLayout &DL = M.getDataLayout();
1197 uint64_t Size = DL.getTypeAllocSize(Alias.getValueType());
1198 OutStreamer->emitELFSize(cast<MCSymbolELF>(Name),
1199 MCConstantExpr::create(Size, OutContext));
1203 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1204 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1205 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1206 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1207 MP->finishAssembly(M, *MI, *this);
1209 // Emit llvm.ident metadata in an '.ident' directive.
1210 EmitModuleIdents(M);
1212 // Emit __morestack address if needed for indirect calls.
1213 if (MMI->usesMorestackAddr()) {
1214 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1215 getDataLayout(), SectionKind::getReadOnly(),
1217 OutStreamer->SwitchSection(ReadOnlySection);
1219 MCSymbol *AddrSymbol =
1220 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1221 OutStreamer->EmitLabel(AddrSymbol);
1223 unsigned PtrSize = M.getDataLayout().getPointerSize(0);
1224 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1228 // If we don't have any trampolines, then we don't require stack memory
1229 // to be executable. Some targets have a directive to declare this.
1230 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1231 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1232 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1233 OutStreamer->SwitchSection(S);
1235 // Allow the target to emit any magic that it wants at the end of the file,
1236 // after everything else has gone out.
1237 EmitEndOfAsmFile(M);
1239 delete Mang; Mang = nullptr;
1242 OutStreamer->Finish();
1243 OutStreamer->reset();
1248 MCSymbol *AsmPrinter::getCurExceptionSym() {
1249 if (!CurExceptionSym)
1250 CurExceptionSym = createTempSymbol("exception");
1251 return CurExceptionSym;
1254 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1256 // Get the function symbol.
1257 CurrentFnSym = getSymbol(MF.getFunction());
1258 CurrentFnSymForSize = CurrentFnSym;
1259 CurrentFnBegin = nullptr;
1260 CurExceptionSym = nullptr;
1261 bool NeedsLocalForSize = MAI->needsLocalForSize();
1262 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1263 NeedsLocalForSize) {
1264 CurrentFnBegin = createTempSymbol("func_begin");
1265 if (NeedsLocalForSize)
1266 CurrentFnSymForSize = CurrentFnBegin;
1270 LI = &getAnalysis<MachineLoopInfo>();
1274 // Keep track the alignment, constpool entries per Section.
1278 SmallVector<unsigned, 4> CPEs;
1279 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1283 /// EmitConstantPool - Print to the current output stream assembly
1284 /// representations of the constants in the constant pool MCP. This is
1285 /// used to print out constants which have been "spilled to memory" by
1286 /// the code generator.
1288 void AsmPrinter::EmitConstantPool() {
1289 const MachineConstantPool *MCP = MF->getConstantPool();
1290 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1291 if (CP.empty()) return;
1293 // Calculate sections for constant pool entries. We collect entries to go into
1294 // the same section together to reduce amount of section switch statements.
1295 SmallVector<SectionCPs, 4> CPSections;
1296 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1297 const MachineConstantPoolEntry &CPE = CP[i];
1298 unsigned Align = CPE.getAlignment();
1300 SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1302 const Constant *C = nullptr;
1303 if (!CPE.isMachineConstantPoolEntry())
1304 C = CPE.Val.ConstVal;
1307 getObjFileLowering().getSectionForConstant(getDataLayout(), Kind, C);
1309 // The number of sections are small, just do a linear search from the
1310 // last section to the first.
1312 unsigned SecIdx = CPSections.size();
1313 while (SecIdx != 0) {
1314 if (CPSections[--SecIdx].S == S) {
1320 SecIdx = CPSections.size();
1321 CPSections.push_back(SectionCPs(S, Align));
1324 if (Align > CPSections[SecIdx].Alignment)
1325 CPSections[SecIdx].Alignment = Align;
1326 CPSections[SecIdx].CPEs.push_back(i);
1329 // Now print stuff into the calculated sections.
1330 const MCSection *CurSection = nullptr;
1331 unsigned Offset = 0;
1332 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1333 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1334 unsigned CPI = CPSections[i].CPEs[j];
1335 MCSymbol *Sym = GetCPISymbol(CPI);
1336 if (!Sym->isUndefined())
1339 if (CurSection != CPSections[i].S) {
1340 OutStreamer->SwitchSection(CPSections[i].S);
1341 EmitAlignment(Log2_32(CPSections[i].Alignment));
1342 CurSection = CPSections[i].S;
1346 MachineConstantPoolEntry CPE = CP[CPI];
1348 // Emit inter-object padding for alignment.
1349 unsigned AlignMask = CPE.getAlignment() - 1;
1350 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1351 OutStreamer->EmitZeros(NewOffset - Offset);
1353 Type *Ty = CPE.getType();
1354 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1356 OutStreamer->EmitLabel(Sym);
1357 if (CPE.isMachineConstantPoolEntry())
1358 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1360 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1365 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1366 /// by the current function to the current output stream.
1368 void AsmPrinter::EmitJumpTableInfo() {
1369 const DataLayout &DL = MF->getDataLayout();
1370 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1372 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1373 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1374 if (JT.empty()) return;
1376 // Pick the directive to use to print the jump table entries, and switch to
1377 // the appropriate section.
1378 const Function *F = MF->getFunction();
1379 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1380 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1381 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1383 if (JTInDiffSection) {
1384 // Drop it in the readonly section.
1385 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1386 OutStreamer->SwitchSection(ReadOnlySection);
1389 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1391 // Jump tables in code sections are marked with a data_region directive
1392 // where that's supported.
1393 if (!JTInDiffSection)
1394 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1396 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1397 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1399 // If this jump table was deleted, ignore it.
1400 if (JTBBs.empty()) continue;
1402 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1403 /// emit a .set directive for each unique entry.
1404 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1405 MAI->doesSetDirectiveSuppressesReloc()) {
1406 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1407 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1408 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1409 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1410 const MachineBasicBlock *MBB = JTBBs[ii];
1411 if (!EmittedSets.insert(MBB).second)
1414 // .set LJTSet, LBB32-base
1416 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1417 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1418 MCBinaryExpr::createSub(LHS, Base,
1423 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1424 // before each jump table. The first label is never referenced, but tells
1425 // the assembler and linker the extents of the jump table object. The
1426 // second label is actually referenced by the code.
1427 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1428 // FIXME: This doesn't have to have any specific name, just any randomly
1429 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1430 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1432 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1434 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1435 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1437 if (!JTInDiffSection)
1438 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1441 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1443 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1444 const MachineBasicBlock *MBB,
1445 unsigned UID) const {
1446 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1447 const MCExpr *Value = nullptr;
1448 switch (MJTI->getEntryKind()) {
1449 case MachineJumpTableInfo::EK_Inline:
1450 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1451 case MachineJumpTableInfo::EK_Custom32:
1452 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1453 MJTI, MBB, UID, OutContext);
1455 case MachineJumpTableInfo::EK_BlockAddress:
1456 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1458 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1460 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1461 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1462 // with a relocation as gp-relative, e.g.:
1464 MCSymbol *MBBSym = MBB->getSymbol();
1465 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1469 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1470 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1471 // with a relocation as gp-relative, e.g.:
1473 MCSymbol *MBBSym = MBB->getSymbol();
1474 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1478 case MachineJumpTableInfo::EK_LabelDifference32: {
1479 // Each entry is the address of the block minus the address of the jump
1480 // table. This is used for PIC jump tables where gprel32 is not supported.
1482 // .word LBB123 - LJTI1_2
1483 // If the .set directive avoids relocations, this is emitted as:
1484 // .set L4_5_set_123, LBB123 - LJTI1_2
1485 // .word L4_5_set_123
1486 if (MAI->doesSetDirectiveSuppressesReloc()) {
1487 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1491 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1492 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1493 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1494 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1499 assert(Value && "Unknown entry kind!");
1501 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1502 OutStreamer->EmitValue(Value, EntrySize);
1506 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1507 /// special global used by LLVM. If so, emit it and return true, otherwise
1508 /// do nothing and return false.
1509 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1510 if (GV->getName() == "llvm.used") {
1511 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1512 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1516 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1517 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1518 GV->hasAvailableExternallyLinkage())
1521 if (!GV->hasAppendingLinkage()) return false;
1523 assert(GV->hasInitializer() && "Not a special LLVM global!");
1525 if (GV->getName() == "llvm.global_ctors") {
1526 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1529 if (TM.getRelocationModel() == Reloc::Static &&
1530 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1531 StringRef Sym(".constructors_used");
1532 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1538 if (GV->getName() == "llvm.global_dtors") {
1539 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1540 /* isCtor */ false);
1542 if (TM.getRelocationModel() == Reloc::Static &&
1543 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1544 StringRef Sym(".destructors_used");
1545 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1554 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1555 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1556 /// is true, as being used with this directive.
1557 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1558 // Should be an array of 'i8*'.
1559 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1560 const GlobalValue *GV =
1561 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1563 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1569 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1571 llvm::Constant *Func;
1572 llvm::GlobalValue *ComdatKey;
1576 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1578 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1580 // Should be an array of '{ int, void ()* }' structs. The first value is the
1582 if (!isa<ConstantArray>(List)) return;
1584 // Sanity check the structors list.
1585 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1586 if (!InitList) return; // Not an array!
1587 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1588 // FIXME: Only allow the 3-field form in LLVM 4.0.
1589 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1590 return; // Not an array of two or three elements!
1591 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1592 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1593 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1594 return; // Not (int, ptr, ptr).
1596 // Gather the structors in a form that's convenient for sorting by priority.
1597 SmallVector<Structor, 8> Structors;
1598 for (Value *O : InitList->operands()) {
1599 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1600 if (!CS) continue; // Malformed.
1601 if (CS->getOperand(1)->isNullValue())
1602 break; // Found a null terminator, skip the rest.
1603 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1604 if (!Priority) continue; // Malformed.
1605 Structors.push_back(Structor());
1606 Structor &S = Structors.back();
1607 S.Priority = Priority->getLimitedValue(65535);
1608 S.Func = CS->getOperand(1);
1609 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1610 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1613 // Emit the function pointers in the target-specific order
1614 unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1615 std::stable_sort(Structors.begin(), Structors.end(),
1616 [](const Structor &L,
1617 const Structor &R) { return L.Priority < R.Priority; });
1618 for (Structor &S : Structors) {
1619 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1620 const MCSymbol *KeySym = nullptr;
1621 if (GlobalValue *GV = S.ComdatKey) {
1622 if (GV->hasAvailableExternallyLinkage())
1623 // If the associated variable is available_externally, some other TU
1624 // will provide its dynamic initializer.
1627 KeySym = getSymbol(GV);
1629 MCSection *OutputSection =
1630 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1631 : Obj.getStaticDtorSection(S.Priority, KeySym));
1632 OutStreamer->SwitchSection(OutputSection);
1633 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1634 EmitAlignment(Align);
1635 EmitXXStructor(DL, S.Func);
1639 void AsmPrinter::EmitModuleIdents(Module &M) {
1640 if (!MAI->hasIdentDirective())
1643 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1644 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1645 const MDNode *N = NMD->getOperand(i);
1646 assert(N->getNumOperands() == 1 &&
1647 "llvm.ident metadata entry can have only one operand");
1648 const MDString *S = cast<MDString>(N->getOperand(0));
1649 OutStreamer->EmitIdent(S->getString());
1654 //===--------------------------------------------------------------------===//
1655 // Emission and print routines
1658 /// EmitInt8 - Emit a byte directive and value.
1660 void AsmPrinter::EmitInt8(int Value) const {
1661 OutStreamer->EmitIntValue(Value, 1);
1664 /// EmitInt16 - Emit a short directive and value.
1666 void AsmPrinter::EmitInt16(int Value) const {
1667 OutStreamer->EmitIntValue(Value, 2);
1670 /// EmitInt32 - Emit a long directive and value.
1672 void AsmPrinter::EmitInt32(int Value) const {
1673 OutStreamer->EmitIntValue(Value, 4);
1676 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1677 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1678 /// .set if it avoids relocations.
1679 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1680 unsigned Size) const {
1681 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1684 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1685 /// where the size in bytes of the directive is specified by Size and Label
1686 /// specifies the label. This implicitly uses .set if it is available.
1687 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1689 bool IsSectionRelative) const {
1690 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1691 OutStreamer->EmitCOFFSecRel32(Label);
1695 // Emit Label+Offset (or just Label if Offset is zero)
1696 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1698 Expr = MCBinaryExpr::createAdd(
1699 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1701 OutStreamer->EmitValue(Expr, Size);
1704 //===----------------------------------------------------------------------===//
1706 // EmitAlignment - Emit an alignment directive to the specified power of
1707 // two boundary. For example, if you pass in 3 here, you will get an 8
1708 // byte alignment. If a global value is specified, and if that global has
1709 // an explicit alignment requested, it will override the alignment request
1710 // if required for correctness.
1712 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1714 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1716 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1719 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1720 "undefined behavior");
1721 if (getCurrentSection()->getKind().isText())
1722 OutStreamer->EmitCodeAlignment(1u << NumBits);
1724 OutStreamer->EmitValueToAlignment(1u << NumBits);
1727 //===----------------------------------------------------------------------===//
1728 // Constant emission.
1729 //===----------------------------------------------------------------------===//
1731 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1732 MCContext &Ctx = OutContext;
1734 if (CV->isNullValue() || isa<UndefValue>(CV))
1735 return MCConstantExpr::create(0, Ctx);
1737 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1738 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1740 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1741 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1743 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1744 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1746 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1748 llvm_unreachable("Unknown constant value to lower!");
1751 if (const MCExpr *RelocExpr
1752 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1755 switch (CE->getOpcode()) {
1757 // If the code isn't optimized, there may be outstanding folding
1758 // opportunities. Attempt to fold the expression using DataLayout as a
1759 // last resort before giving up.
1760 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
1762 return lowerConstant(C);
1764 // Otherwise report the problem to the user.
1767 raw_string_ostream OS(S);
1768 OS << "Unsupported expression in static initializer: ";
1769 CE->printAsOperand(OS, /*PrintType=*/false,
1770 !MF ? nullptr : MF->getFunction()->getParent());
1771 report_fatal_error(OS.str());
1773 case Instruction::GetElementPtr: {
1774 // Generate a symbolic expression for the byte address
1775 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1776 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1778 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1782 int64_t Offset = OffsetAI.getSExtValue();
1783 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1787 case Instruction::Trunc:
1788 // We emit the value and depend on the assembler to truncate the generated
1789 // expression properly. This is important for differences between
1790 // blockaddress labels. Since the two labels are in the same function, it
1791 // is reasonable to treat their delta as a 32-bit value.
1793 case Instruction::BitCast:
1794 return lowerConstant(CE->getOperand(0));
1796 case Instruction::IntToPtr: {
1797 const DataLayout &DL = getDataLayout();
1799 // Handle casts to pointers by changing them into casts to the appropriate
1800 // integer type. This promotes constant folding and simplifies this code.
1801 Constant *Op = CE->getOperand(0);
1802 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1804 return lowerConstant(Op);
1807 case Instruction::PtrToInt: {
1808 const DataLayout &DL = getDataLayout();
1810 // Support only foldable casts to/from pointers that can be eliminated by
1811 // changing the pointer to the appropriately sized integer type.
1812 Constant *Op = CE->getOperand(0);
1813 Type *Ty = CE->getType();
1815 const MCExpr *OpExpr = lowerConstant(Op);
1817 // We can emit the pointer value into this slot if the slot is an
1818 // integer slot equal to the size of the pointer.
1819 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1822 // Otherwise the pointer is smaller than the resultant integer, mask off
1823 // the high bits so we are sure to get a proper truncation if the input is
1825 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1826 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1827 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1830 // The MC library also has a right-shift operator, but it isn't consistently
1831 // signed or unsigned between different targets.
1832 case Instruction::Add:
1833 case Instruction::Sub:
1834 case Instruction::Mul:
1835 case Instruction::SDiv:
1836 case Instruction::SRem:
1837 case Instruction::Shl:
1838 case Instruction::And:
1839 case Instruction::Or:
1840 case Instruction::Xor: {
1841 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1842 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1843 switch (CE->getOpcode()) {
1844 default: llvm_unreachable("Unknown binary operator constant cast expr");
1845 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1846 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1847 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1848 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1849 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1850 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1851 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1852 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1853 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1859 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
1861 const Constant *BaseCV = nullptr,
1862 uint64_t Offset = 0);
1864 /// isRepeatedByteSequence - Determine whether the given value is
1865 /// composed of a repeated sequence of identical bytes and return the
1866 /// byte value. If it is not a repeated sequence, return -1.
1867 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1868 StringRef Data = V->getRawDataValues();
1869 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1871 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1872 if (Data[i] != C) return -1;
1873 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1877 /// isRepeatedByteSequence - Determine whether the given value is
1878 /// composed of a repeated sequence of identical bytes and return the
1879 /// byte value. If it is not a repeated sequence, return -1.
1880 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
1881 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1882 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
1883 assert(Size % 8 == 0);
1885 // Extend the element to take zero padding into account.
1886 APInt Value = CI->getValue().zextOrSelf(Size);
1887 if (!Value.isSplat(8))
1890 return Value.zextOrTrunc(8).getZExtValue();
1892 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1893 // Make sure all array elements are sequences of the same repeated
1895 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1896 Constant *Op0 = CA->getOperand(0);
1897 int Byte = isRepeatedByteSequence(Op0, DL);
1901 // All array elements must be equal.
1902 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
1903 if (CA->getOperand(i) != Op0)
1908 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1909 return isRepeatedByteSequence(CDS);
1914 static void emitGlobalConstantDataSequential(const DataLayout &DL,
1915 const ConstantDataSequential *CDS,
1918 // See if we can aggregate this into a .fill, if so, emit it as such.
1919 int Value = isRepeatedByteSequence(CDS, DL);
1921 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
1922 // Don't emit a 1-byte object as a .fill.
1924 return AP.OutStreamer->EmitFill(Bytes, Value);
1927 // If this can be emitted with .ascii/.asciz, emit it as such.
1928 if (CDS->isString())
1929 return AP.OutStreamer->EmitBytes(CDS->getAsString());
1931 // Otherwise, emit the values in successive locations.
1932 unsigned ElementByteSize = CDS->getElementByteSize();
1933 if (isa<IntegerType>(CDS->getElementType())) {
1934 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1936 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1937 CDS->getElementAsInteger(i));
1938 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1941 } else if (ElementByteSize == 4) {
1942 // FP Constants are printed as integer constants to avoid losing
1944 assert(CDS->getElementType()->isFloatTy());
1945 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1951 F = CDS->getElementAsFloat(i);
1953 AP.OutStreamer->GetCommentOS() << "float " << F << '\n';
1954 AP.OutStreamer->EmitIntValue(I, 4);
1957 assert(CDS->getElementType()->isDoubleTy());
1958 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1964 F = CDS->getElementAsDouble(i);
1966 AP.OutStreamer->GetCommentOS() << "double " << F << '\n';
1967 AP.OutStreamer->EmitIntValue(I, 8);
1971 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1972 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1973 CDS->getNumElements();
1974 if (unsigned Padding = Size - EmittedSize)
1975 AP.OutStreamer->EmitZeros(Padding);
1979 static void emitGlobalConstantArray(const DataLayout &DL,
1980 const ConstantArray *CA, AsmPrinter &AP,
1981 const Constant *BaseCV, uint64_t Offset) {
1982 // See if we can aggregate some values. Make sure it can be
1983 // represented as a series of bytes of the constant value.
1984 int Value = isRepeatedByteSequence(CA, DL);
1987 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1988 AP.OutStreamer->EmitFill(Bytes, Value);
1991 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1992 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
1993 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1998 static void emitGlobalConstantVector(const DataLayout &DL,
1999 const ConstantVector *CV, AsmPrinter &AP) {
2000 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2001 emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2003 unsigned Size = DL.getTypeAllocSize(CV->getType());
2004 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2005 CV->getType()->getNumElements();
2006 if (unsigned Padding = Size - EmittedSize)
2007 AP.OutStreamer->EmitZeros(Padding);
2010 static void emitGlobalConstantStruct(const DataLayout &DL,
2011 const ConstantStruct *CS, AsmPrinter &AP,
2012 const Constant *BaseCV, uint64_t Offset) {
2013 // Print the fields in successive locations. Pad to align if needed!
2014 unsigned Size = DL.getTypeAllocSize(CS->getType());
2015 const StructLayout *Layout = DL.getStructLayout(CS->getType());
2016 uint64_t SizeSoFar = 0;
2017 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2018 const Constant *Field = CS->getOperand(i);
2020 // Print the actual field value.
2021 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2023 // Check if padding is needed and insert one or more 0s.
2024 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2025 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2026 - Layout->getElementOffset(i)) - FieldSize;
2027 SizeSoFar += FieldSize + PadSize;
2029 // Insert padding - this may include padding to increase the size of the
2030 // current field up to the ABI size (if the struct is not packed) as well
2031 // as padding to ensure that the next field starts at the right offset.
2032 AP.OutStreamer->EmitZeros(PadSize);
2034 assert(SizeSoFar == Layout->getSizeInBytes() &&
2035 "Layout of constant struct may be incorrect!");
2038 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2039 APInt API = CFP->getValueAPF().bitcastToAPInt();
2041 // First print a comment with what we think the original floating-point value
2042 // should have been.
2043 if (AP.isVerbose()) {
2044 SmallString<8> StrVal;
2045 CFP->getValueAPF().toString(StrVal);
2048 CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2050 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2051 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2054 // Now iterate through the APInt chunks, emitting them in endian-correct
2055 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2057 unsigned NumBytes = API.getBitWidth() / 8;
2058 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2059 const uint64_t *p = API.getRawData();
2061 // PPC's long double has odd notions of endianness compared to how LLVM
2062 // handles it: p[0] goes first for *big* endian on PPC.
2063 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2064 int Chunk = API.getNumWords() - 1;
2067 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2069 for (; Chunk >= 0; --Chunk)
2070 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2073 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2074 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2077 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2080 // Emit the tail padding for the long double.
2081 const DataLayout &DL = AP.getDataLayout();
2082 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2083 DL.getTypeStoreSize(CFP->getType()));
2086 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2087 const DataLayout &DL = AP.getDataLayout();
2088 unsigned BitWidth = CI->getBitWidth();
2090 // Copy the value as we may massage the layout for constants whose bit width
2091 // is not a multiple of 64-bits.
2092 APInt Realigned(CI->getValue());
2093 uint64_t ExtraBits = 0;
2094 unsigned ExtraBitsSize = BitWidth & 63;
2096 if (ExtraBitsSize) {
2097 // The bit width of the data is not a multiple of 64-bits.
2098 // The extra bits are expected to be at the end of the chunk of the memory.
2100 // * Nothing to be done, just record the extra bits to emit.
2102 // * Record the extra bits to emit.
2103 // * Realign the raw data to emit the chunks of 64-bits.
2104 if (DL.isBigEndian()) {
2105 // Basically the structure of the raw data is a chunk of 64-bits cells:
2106 // 0 1 BitWidth / 64
2107 // [chunk1][chunk2] ... [chunkN].
2108 // The most significant chunk is chunkN and it should be emitted first.
2109 // However, due to the alignment issue chunkN contains useless bits.
2110 // Realign the chunks so that they contain only useless information:
2111 // ExtraBits 0 1 (BitWidth / 64) - 1
2112 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2113 ExtraBits = Realigned.getRawData()[0] &
2114 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2115 Realigned = Realigned.lshr(ExtraBitsSize);
2117 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2120 // We don't expect assemblers to support integer data directives
2121 // for more than 64 bits, so we emit the data in at most 64-bit
2122 // quantities at a time.
2123 const uint64_t *RawData = Realigned.getRawData();
2124 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2125 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2126 AP.OutStreamer->EmitIntValue(Val, 8);
2129 if (ExtraBitsSize) {
2130 // Emit the extra bits after the 64-bits chunks.
2132 // Emit a directive that fills the expected size.
2133 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2134 Size -= (BitWidth / 64) * 8;
2135 assert(Size && Size * 8 >= ExtraBitsSize &&
2136 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2137 == ExtraBits && "Directive too small for extra bits.");
2138 AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2142 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2143 /// equivalent global, by a target specific GOT pc relative access to the
2145 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2146 const Constant *BaseCst,
2148 // The global @foo below illustrates a global that uses a got equivalent.
2150 // @bar = global i32 42
2151 // @gotequiv = private unnamed_addr constant i32* @bar
2152 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2153 // i64 ptrtoint (i32* @foo to i64))
2156 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2157 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2160 // foo = cstexpr, where
2161 // cstexpr := <gotequiv> - "." + <cst>
2162 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2164 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2166 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2167 // gotpcrelcst := <offset from @foo base> + <cst>
2170 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2172 const MCSymbolRefExpr *SymA = MV.getSymA();
2176 // Check that GOT equivalent symbol is cached.
2177 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2178 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2181 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2185 // Check for a valid base symbol
2186 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2187 const MCSymbolRefExpr *SymB = MV.getSymB();
2189 if (!SymB || BaseSym != &SymB->getSymbol())
2192 // Make sure to match:
2194 // gotpcrelcst := <offset from @foo base> + <cst>
2196 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2197 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2198 // if the target knows how to encode it.
2200 int64_t GOTPCRelCst = Offset + MV.getConstant();
2201 if (GOTPCRelCst < 0)
2203 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2206 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2213 // .long gotequiv - "." + <cst>
2215 // is replaced by the target specific equivalent to:
2220 // .long bar@GOTPCREL+<gotpcrelcst>
2222 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2223 const GlobalVariable *GV = Result.first;
2224 int NumUses = (int)Result.second;
2225 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2226 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2227 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2228 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2230 // Update GOT equivalent usage information
2233 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2236 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2237 AsmPrinter &AP, const Constant *BaseCV,
2239 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2241 // Globals with sub-elements such as combinations of arrays and structs
2242 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2243 // constant symbol base and the current position with BaseCV and Offset.
2244 if (!BaseCV && CV->hasOneUse())
2245 BaseCV = dyn_cast<Constant>(CV->user_back());
2247 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2248 return AP.OutStreamer->EmitZeros(Size);
2250 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2257 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2258 CI->getZExtValue());
2259 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2262 emitGlobalConstantLargeInt(CI, AP);
2267 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2268 return emitGlobalConstantFP(CFP, AP);
2270 if (isa<ConstantPointerNull>(CV)) {
2271 AP.OutStreamer->EmitIntValue(0, Size);
2275 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2276 return emitGlobalConstantDataSequential(DL, CDS, AP);
2278 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2279 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2281 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2282 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2284 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2285 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2287 if (CE->getOpcode() == Instruction::BitCast)
2288 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2291 // If the constant expression's size is greater than 64-bits, then we have
2292 // to emit the value in chunks. Try to constant fold the value and emit it
2294 Constant *New = ConstantFoldConstantExpression(CE, DL);
2295 if (New && New != CE)
2296 return emitGlobalConstantImpl(DL, New, AP);
2300 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2301 return emitGlobalConstantVector(DL, V, AP);
2303 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2304 // thread the streamer with EmitValue.
2305 const MCExpr *ME = AP.lowerConstant(CV);
2307 // Since lowerConstant already folded and got rid of all IR pointer and
2308 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2310 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2311 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2313 AP.OutStreamer->EmitValue(ME, Size);
2316 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2317 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2318 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2320 emitGlobalConstantImpl(DL, CV, *this);
2321 else if (MAI->hasSubsectionsViaSymbols()) {
2322 // If the global has zero size, emit a single byte so that two labels don't
2323 // look like they are at the same location.
2324 OutStreamer->EmitIntValue(0, 1);
2328 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2329 // Target doesn't support this yet!
2330 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2333 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2335 OS << '+' << Offset;
2336 else if (Offset < 0)
2340 //===----------------------------------------------------------------------===//
2341 // Symbol Lowering Routines.
2342 //===----------------------------------------------------------------------===//
2344 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2345 return OutContext.createTempSymbol(Name, true);
2348 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2349 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2352 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2353 return MMI->getAddrLabelSymbol(BB);
2356 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2357 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2358 const DataLayout &DL = getDataLayout();
2359 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2360 "CPI" + Twine(getFunctionNumber()) + "_" +
2364 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2365 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2366 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2369 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2370 /// FIXME: privatize to AsmPrinter.
2371 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2372 const DataLayout &DL = getDataLayout();
2373 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2374 Twine(getFunctionNumber()) + "_" +
2375 Twine(UID) + "_set_" + Twine(MBBID));
2378 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2379 StringRef Suffix) const {
2380 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2384 /// Return the MCSymbol for the specified ExternalSymbol.
2385 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2386 SmallString<60> NameStr;
2387 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2388 return OutContext.getOrCreateSymbol(NameStr);
2393 /// PrintParentLoopComment - Print comments about parent loops of this one.
2394 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2395 unsigned FunctionNumber) {
2397 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2398 OS.indent(Loop->getLoopDepth()*2)
2399 << "Parent Loop BB" << FunctionNumber << "_"
2400 << Loop->getHeader()->getNumber()
2401 << " Depth=" << Loop->getLoopDepth() << '\n';
2405 /// PrintChildLoopComment - Print comments about child loops within
2406 /// the loop for this basic block, with nesting.
2407 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2408 unsigned FunctionNumber) {
2409 // Add child loop information
2410 for (const MachineLoop *CL : *Loop) {
2411 OS.indent(CL->getLoopDepth()*2)
2412 << "Child Loop BB" << FunctionNumber << "_"
2413 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2415 PrintChildLoopComment(OS, CL, FunctionNumber);
2419 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2420 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2421 const MachineLoopInfo *LI,
2422 const AsmPrinter &AP) {
2423 // Add loop depth information
2424 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2427 MachineBasicBlock *Header = Loop->getHeader();
2428 assert(Header && "No header for loop");
2430 // If this block is not a loop header, just print out what is the loop header
2432 if (Header != &MBB) {
2433 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2434 Twine(AP.getFunctionNumber())+"_" +
2435 Twine(Loop->getHeader()->getNumber())+
2436 " Depth="+Twine(Loop->getLoopDepth()));
2440 // Otherwise, it is a loop header. Print out information about child and
2442 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2444 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2447 OS.indent(Loop->getLoopDepth()*2-2);
2452 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2454 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2458 /// EmitBasicBlockStart - This method prints the label for the specified
2459 /// MachineBasicBlock, an alignment (if present) and a comment describing
2460 /// it if appropriate.
2461 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2462 // Emit an alignment directive for this block, if needed.
2463 if (unsigned Align = MBB.getAlignment())
2464 EmitAlignment(Align);
2466 // If the block has its address taken, emit any labels that were used to
2467 // reference the block. It is possible that there is more than one label
2468 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2469 // the references were generated.
2470 if (MBB.hasAddressTaken()) {
2471 const BasicBlock *BB = MBB.getBasicBlock();
2473 OutStreamer->AddComment("Block address taken");
2475 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2476 OutStreamer->EmitLabel(Sym);
2479 // Print some verbose block comments.
2481 if (const BasicBlock *BB = MBB.getBasicBlock())
2483 OutStreamer->AddComment("%" + BB->getName());
2484 emitBasicBlockLoopComments(MBB, LI, *this);
2487 // Print the main label for the block.
2488 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2490 // NOTE: Want this comment at start of line, don't emit with AddComment.
2491 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2494 OutStreamer->EmitLabel(MBB.getSymbol());
2498 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2499 bool IsDefinition) const {
2500 MCSymbolAttr Attr = MCSA_Invalid;
2502 switch (Visibility) {
2504 case GlobalValue::HiddenVisibility:
2506 Attr = MAI->getHiddenVisibilityAttr();
2508 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2510 case GlobalValue::ProtectedVisibility:
2511 Attr = MAI->getProtectedVisibilityAttr();
2515 if (Attr != MCSA_Invalid)
2516 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2519 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2520 /// exactly one predecessor and the control transfer mechanism between
2521 /// the predecessor and this block is a fall-through.
2523 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2524 // If this is a landing pad, it isn't a fall through. If it has no preds,
2525 // then nothing falls through to it.
2526 if (MBB->isLandingPad() || MBB->pred_empty())
2529 // If there isn't exactly one predecessor, it can't be a fall through.
2530 if (MBB->pred_size() > 1)
2533 // The predecessor has to be immediately before this block.
2534 MachineBasicBlock *Pred = *MBB->pred_begin();
2535 if (!Pred->isLayoutSuccessor(MBB))
2538 // If the block is completely empty, then it definitely does fall through.
2542 // Check the terminators in the previous blocks
2543 for (const auto &MI : Pred->terminators()) {
2544 // If it is not a simple branch, we are in a table somewhere.
2545 if (!MI.isBranch() || MI.isIndirectBranch())
2548 // If we are the operands of one of the branches, this is not a fall
2549 // through. Note that targets with delay slots will usually bundle
2550 // terminators with the delay slot instruction.
2551 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2554 if (OP->isMBB() && OP->getMBB() == MBB)
2564 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2565 if (!S.usesMetadata())
2568 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2569 " stackmap formats, please see the documentation for a description of"
2570 " the default format. If you really need a custom serialized format,"
2571 " please file a bug");
2573 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2574 gcp_map_type::iterator GCPI = GCMap.find(&S);
2575 if (GCPI != GCMap.end())
2576 return GCPI->second.get();
2578 const char *Name = S.getName().c_str();
2580 for (GCMetadataPrinterRegistry::iterator
2581 I = GCMetadataPrinterRegistry::begin(),
2582 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2583 if (strcmp(Name, I->getName()) == 0) {
2584 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2586 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2587 return IterBool.first->second.get();
2590 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2593 /// Pin vtable to this file.
2594 AsmPrinterHandler::~AsmPrinterHandler() {}
2596 void AsmPrinterHandler::markFunctionEnd() {}