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 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Target/Mangler.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Assembly/Writer.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/Timer.h"
49 static const char *DWARFGroupName = "DWARF Emission";
50 static const char *DbgTimerName = "DWARF Debug Writer";
51 static const char *EHTimerName = "DWARF Exception Writer";
53 STATISTIC(EmittedInsts, "Number of machine instrs printed");
55 char AsmPrinter::ID = 0;
57 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
58 static gcp_map_type &getGCMap(void *&P) {
60 P = new gcp_map_type();
61 return *(gcp_map_type*)P;
65 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
66 /// value in log2 form. This rounds up to the preferred alignment if possible
68 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
69 unsigned InBits = 0) {
71 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
72 NumBits = TD.getPreferredAlignmentLog(GVar);
74 // If InBits is specified, round it to it.
78 // If the GV has a specified alignment, take it into account.
79 if (GV->getAlignment() == 0)
82 unsigned GVAlign = Log2_32(GV->getAlignment());
84 // If the GVAlign is larger than NumBits, or if we are required to obey
85 // NumBits because the GV has an assigned section, obey it.
86 if (GVAlign > NumBits || GV->hasSection())
94 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
95 : MachineFunctionPass(ID),
96 TM(tm), MAI(tm.getMCAsmInfo()),
97 OutContext(Streamer.getContext()),
98 OutStreamer(Streamer),
99 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
100 DD = 0; DE = 0; MMI = 0; LI = 0;
101 GCMetadataPrinters = 0;
102 VerboseAsm = Streamer.isVerboseAsm();
105 AsmPrinter::~AsmPrinter() {
106 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
108 if (GCMetadataPrinters != 0) {
109 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
111 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
114 GCMetadataPrinters = 0;
120 /// getFunctionNumber - Return a unique ID for the current function.
122 unsigned AsmPrinter::getFunctionNumber() const {
123 return MF->getFunctionNumber();
126 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
127 return TM.getTargetLowering()->getObjFileLowering();
131 /// getTargetData - Return information about data layout.
132 const TargetData &AsmPrinter::getTargetData() const {
133 return *TM.getTargetData();
136 /// getCurrentSection() - Return the current section we are emitting to.
137 const MCSection *AsmPrinter::getCurrentSection() const {
138 return OutStreamer.getCurrentSection();
143 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
144 AU.setPreservesAll();
145 MachineFunctionPass::getAnalysisUsage(AU);
146 AU.addRequired<MachineModuleInfo>();
147 AU.addRequired<GCModuleInfo>();
149 AU.addRequired<MachineLoopInfo>();
152 bool AsmPrinter::doInitialization(Module &M) {
153 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
154 MMI->AnalyzeModule(M);
156 // Initialize TargetLoweringObjectFile.
157 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
158 .Initialize(OutContext, TM);
160 Mang = new Mangler(OutContext, *TM.getTargetData());
162 // Allow the target to emit any magic that it wants at the start of the file.
163 EmitStartOfAsmFile(M);
165 // Very minimal debug info. It is ignored if we emit actual debug info. If we
166 // don't, this at least helps the user find where a global came from.
167 if (MAI->hasSingleParameterDotFile()) {
169 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
172 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
173 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
174 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
175 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
176 MP->beginAssembly(*this);
178 // Emit module-level inline asm if it exists.
179 if (!M.getModuleInlineAsm().empty()) {
180 OutStreamer.AddComment("Start of file scope inline assembly");
181 OutStreamer.AddBlankLine();
182 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
183 OutStreamer.AddComment("End of file scope inline assembly");
184 OutStreamer.AddBlankLine();
187 if (MAI->doesSupportDebugInformation())
188 DD = new DwarfDebug(this, &M);
190 if (MAI->doesSupportExceptionHandling())
191 DE = new DwarfTableException(this);
196 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
197 switch ((GlobalValue::LinkageTypes)Linkage) {
198 case GlobalValue::CommonLinkage:
199 case GlobalValue::LinkOnceAnyLinkage:
200 case GlobalValue::LinkOnceODRLinkage:
201 case GlobalValue::WeakAnyLinkage:
202 case GlobalValue::WeakODRLinkage:
203 case GlobalValue::LinkerPrivateWeakLinkage:
204 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
205 if (MAI->getWeakDefDirective() != 0) {
207 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
209 if ((GlobalValue::LinkageTypes)Linkage !=
210 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
211 // .weak_definition _foo
212 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
214 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
215 } else if (MAI->getLinkOnceDirective() != 0) {
217 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
218 //NOTE: linkonce is handled by the section the symbol was assigned to.
221 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
224 case GlobalValue::DLLExportLinkage:
225 case GlobalValue::AppendingLinkage:
226 // FIXME: appending linkage variables should go into a section of
227 // their name or something. For now, just emit them as external.
228 case GlobalValue::ExternalLinkage:
229 // If external or appending, declare as a global symbol.
231 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
233 case GlobalValue::PrivateLinkage:
234 case GlobalValue::InternalLinkage:
235 case GlobalValue::LinkerPrivateLinkage:
238 llvm_unreachable("Unknown linkage type!");
243 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
244 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
245 if (!GV->hasInitializer()) // External globals require no code.
248 // Check to see if this is a special global used by LLVM, if so, emit it.
249 if (EmitSpecialLLVMGlobal(GV))
253 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
254 /*PrintType=*/false, GV->getParent());
255 OutStreamer.GetCommentOS() << '\n';
258 MCSymbol *GVSym = Mang->getSymbol(GV);
259 EmitVisibility(GVSym, GV->getVisibility());
261 if (MAI->hasDotTypeDotSizeDirective())
262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
264 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
266 const TargetData *TD = TM.getTargetData();
267 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
269 // If the alignment is specified, we *must* obey it. Overaligning a global
270 // with a specified alignment is a prompt way to break globals emitted to
271 // sections and expected to be contiguous (e.g. ObjC metadata).
272 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
274 // Handle common and BSS local symbols (.lcomm).
275 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
276 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
279 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
280 /*PrintType=*/false, GV->getParent());
281 OutStreamer.GetCommentOS() << '\n';
284 // Handle common symbols.
285 if (GVKind.isCommon()) {
286 unsigned Align = 1 << AlignLog;
287 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
291 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
295 // Handle local BSS symbols.
296 if (MAI->hasMachoZeroFillDirective()) {
297 const MCSection *TheSection =
298 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
299 // .zerofill __DATA, __bss, _foo, 400, 5
300 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
304 if (MAI->hasLCOMMDirective()) {
306 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
310 unsigned Align = 1 << AlignLog;
311 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
315 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
317 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
321 const MCSection *TheSection =
322 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
324 // Handle the zerofill directive on darwin, which is a special form of BSS
326 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
327 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
330 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
331 // .zerofill __DATA, __common, _foo, 400, 5
332 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
336 // Handle thread local data for mach-o which requires us to output an
337 // additional structure of data and mangle the original symbol so that we
338 // can reference it later.
340 // TODO: This should become an "emit thread local global" method on TLOF.
341 // All of this macho specific stuff should be sunk down into TLOFMachO and
342 // stuff like "TLSExtraDataSection" should no longer be part of the parent
343 // TLOF class. This will also make it more obvious that stuff like
344 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
346 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
347 // Emit the .tbss symbol
349 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
351 if (GVKind.isThreadBSS())
352 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
353 else if (GVKind.isThreadData()) {
354 OutStreamer.SwitchSection(TheSection);
356 EmitAlignment(AlignLog, GV);
357 OutStreamer.EmitLabel(MangSym);
359 EmitGlobalConstant(GV->getInitializer());
362 OutStreamer.AddBlankLine();
364 // Emit the variable struct for the runtime.
365 const MCSection *TLVSect
366 = getObjFileLowering().getTLSExtraDataSection();
368 OutStreamer.SwitchSection(TLVSect);
369 // Emit the linkage here.
370 EmitLinkage(GV->getLinkage(), GVSym);
371 OutStreamer.EmitLabel(GVSym);
373 // Three pointers in size:
374 // - __tlv_bootstrap - used to make sure support exists
375 // - spare pointer, used when mapped by the runtime
376 // - pointer to mangled symbol above with initializer
377 unsigned PtrSize = TD->getPointerSizeInBits()/8;
378 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
380 OutStreamer.EmitIntValue(0, PtrSize, 0);
381 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
383 OutStreamer.AddBlankLine();
387 OutStreamer.SwitchSection(TheSection);
389 EmitLinkage(GV->getLinkage(), GVSym);
390 EmitAlignment(AlignLog, GV);
392 OutStreamer.EmitLabel(GVSym);
394 EmitGlobalConstant(GV->getInitializer());
396 if (MAI->hasDotTypeDotSizeDirective())
398 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
400 OutStreamer.AddBlankLine();
403 /// EmitFunctionHeader - This method emits the header for the current
405 void AsmPrinter::EmitFunctionHeader() {
406 // Print out constants referenced by the function
409 // Print the 'header' of function.
410 const Function *F = MF->getFunction();
412 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
413 EmitVisibility(CurrentFnSym, F->getVisibility());
415 EmitLinkage(F->getLinkage(), CurrentFnSym);
416 EmitAlignment(MF->getAlignment(), F);
418 if (MAI->hasDotTypeDotSizeDirective())
419 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
422 WriteAsOperand(OutStreamer.GetCommentOS(), F,
423 /*PrintType=*/false, F->getParent());
424 OutStreamer.GetCommentOS() << '\n';
427 // Emit the CurrentFnSym. This is a virtual function to allow targets to
428 // do their wild and crazy things as required.
429 EmitFunctionEntryLabel();
431 // If the function had address-taken blocks that got deleted, then we have
432 // references to the dangling symbols. Emit them at the start of the function
433 // so that we don't get references to undefined symbols.
434 std::vector<MCSymbol*> DeadBlockSyms;
435 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
436 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
437 OutStreamer.AddComment("Address taken block that was later removed");
438 OutStreamer.EmitLabel(DeadBlockSyms[i]);
441 // Add some workaround for linkonce linkage on Cygwin\MinGW.
442 if (MAI->getLinkOnceDirective() != 0 &&
443 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
444 // FIXME: What is this?
446 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
447 CurrentFnSym->getName());
448 OutStreamer.EmitLabel(FakeStub);
451 // Emit pre-function debug and/or EH information.
453 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
454 DE->BeginFunction(MF);
457 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
458 DD->beginFunction(MF);
462 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
463 /// function. This can be overridden by targets as required to do custom stuff.
464 void AsmPrinter::EmitFunctionEntryLabel() {
465 // The function label could have already been emitted if two symbols end up
466 // conflicting due to asm renaming. Detect this and emit an error.
467 if (CurrentFnSym->isUndefined())
468 return OutStreamer.EmitLabel(CurrentFnSym);
470 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
471 "' label emitted multiple times to assembly file");
475 static void EmitDebugLoc(DebugLoc DL, const MachineFunction *MF,
476 raw_ostream &CommentOS) {
477 const LLVMContext &Ctx = MF->getFunction()->getContext();
478 if (!DL.isUnknown()) { // Print source line info.
479 DIScope Scope(DL.getScope(Ctx));
480 // Omit the directory, because it's likely to be long and uninteresting.
482 CommentOS << Scope.getFilename();
484 CommentOS << "<unknown>";
485 CommentOS << ':' << DL.getLine();
486 if (DL.getCol() != 0)
487 CommentOS << ':' << DL.getCol();
488 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
489 if (!InlinedAtDL.isUnknown()) {
491 EmitDebugLoc(InlinedAtDL, MF, CommentOS);
497 /// EmitComments - Pretty-print comments for instructions.
498 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
499 const MachineFunction *MF = MI.getParent()->getParent();
500 const TargetMachine &TM = MF->getTarget();
502 DebugLoc DL = MI.getDebugLoc();
503 if (!DL.isUnknown()) { // Print source line info.
504 EmitDebugLoc(DL, MF, CommentOS);
508 // Check for spills and reloads
511 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
513 // We assume a single instruction only has a spill or reload, not
515 const MachineMemOperand *MMO;
516 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
517 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
518 MMO = *MI.memoperands_begin();
519 CommentOS << MMO->getSize() << "-byte Reload\n";
521 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
522 if (FrameInfo->isSpillSlotObjectIndex(FI))
523 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
524 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
525 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
526 MMO = *MI.memoperands_begin();
527 CommentOS << MMO->getSize() << "-byte Spill\n";
529 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
530 if (FrameInfo->isSpillSlotObjectIndex(FI))
531 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
534 // Check for spill-induced copies
535 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
536 CommentOS << " Reload Reuse\n";
539 /// EmitImplicitDef - This method emits the specified machine instruction
540 /// that is an implicit def.
541 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
542 unsigned RegNo = MI->getOperand(0).getReg();
543 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
544 AP.TM.getRegisterInfo()->getName(RegNo));
545 AP.OutStreamer.AddBlankLine();
548 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
549 std::string Str = "kill:";
550 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
551 const MachineOperand &Op = MI->getOperand(i);
552 assert(Op.isReg() && "KILL instruction must have only register operands");
554 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
555 Str += (Op.isDef() ? "<def>" : "<kill>");
557 AP.OutStreamer.AddComment(Str);
558 AP.OutStreamer.AddBlankLine();
561 /// EmitDebugValueComment - This method handles the target-independent form
562 /// of DBG_VALUE, returning true if it was able to do so. A false return
563 /// means the target will need to handle MI in EmitInstruction.
564 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
565 // This code handles only the 3-operand target-independent form.
566 if (MI->getNumOperands() != 3)
569 SmallString<128> Str;
570 raw_svector_ostream OS(Str);
571 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
573 // cast away const; DIetc do not take const operands for some reason.
574 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
575 if (V.getContext().isSubprogram())
576 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
577 OS << V.getName() << " <- ";
579 // Register or immediate value. Register 0 means undef.
580 if (MI->getOperand(0).isFPImm()) {
581 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
582 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
583 OS << (double)APF.convertToFloat();
584 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
585 OS << APF.convertToDouble();
587 // There is no good way to print long double. Convert a copy to
588 // double. Ah well, it's only a comment.
590 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
592 OS << "(long double) " << APF.convertToDouble();
594 } else if (MI->getOperand(0).isImm()) {
595 OS << MI->getOperand(0).getImm();
597 assert(MI->getOperand(0).isReg() && "Unknown operand type");
598 if (MI->getOperand(0).getReg() == 0) {
599 // Suppress offset, it is not meaningful here.
601 // NOTE: Want this comment at start of line, don't emit with AddComment.
602 AP.OutStreamer.EmitRawText(OS.str());
605 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
608 OS << '+' << MI->getOperand(1).getImm();
609 // NOTE: Want this comment at start of line, don't emit with AddComment.
610 AP.OutStreamer.EmitRawText(OS.str());
614 /// EmitFunctionBody - This method emits the body and trailer for a
616 void AsmPrinter::EmitFunctionBody() {
617 // Emit target-specific gunk before the function body.
618 EmitFunctionBodyStart();
620 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
622 // Print out code for the function.
623 bool HasAnyRealCode = false;
624 const MachineInstr *LastMI = 0;
625 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
627 // Print a label for the basic block.
628 EmitBasicBlockStart(I);
629 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
633 // Print the assembly for the instruction.
634 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
635 !II->isDebugValue()) {
636 HasAnyRealCode = true;
640 if (ShouldPrintDebugScopes) {
641 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
642 DD->beginInstruction(II);
646 EmitComments(*II, OutStreamer.GetCommentOS());
648 switch (II->getOpcode()) {
649 case TargetOpcode::PROLOG_LABEL:
650 case TargetOpcode::EH_LABEL:
651 case TargetOpcode::GC_LABEL:
652 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
654 case TargetOpcode::INLINEASM:
657 case TargetOpcode::DBG_VALUE:
659 if (!EmitDebugValueComment(II, *this))
663 case TargetOpcode::IMPLICIT_DEF:
664 if (isVerbose()) EmitImplicitDef(II, *this);
666 case TargetOpcode::KILL:
667 if (isVerbose()) EmitKill(II, *this);
674 if (ShouldPrintDebugScopes) {
675 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
676 DD->endInstruction(II);
681 // If the last instruction was a prolog label, then we have a situation where
682 // we emitted a prolog but no function body. This results in the ending prolog
683 // label equaling the end of function label and an invalid "row" in the
684 // FDE. We need to emit a noop in this situation so that the FDE's rows are
686 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
688 // If the function is empty and the object file uses .subsections_via_symbols,
689 // then we need to emit *something* to the function body to prevent the
690 // labels from collapsing together. Just emit a noop.
691 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
693 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
694 if (Noop.getOpcode()) {
695 OutStreamer.AddComment("avoids zero-length function");
696 OutStreamer.EmitInstruction(Noop);
697 } else // Target not mc-ized yet.
698 OutStreamer.EmitRawText(StringRef("\tnop\n"));
701 // Emit target-specific gunk after the function body.
702 EmitFunctionBodyEnd();
704 // If the target wants a .size directive for the size of the function, emit
706 if (MAI->hasDotTypeDotSizeDirective()) {
707 // Create a symbol for the end of function, so we can get the size as
708 // difference between the function label and the temp label.
709 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
710 OutStreamer.EmitLabel(FnEndLabel);
712 const MCExpr *SizeExp =
713 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
714 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
716 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
719 // Emit post-function debug information.
721 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
725 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
730 // Print out jump tables referenced by the function.
733 OutStreamer.AddBlankLine();
736 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
738 MachineLocation AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
739 // Target specific DBG_VALUE instructions are handled by each target.
740 return MachineLocation();
743 bool AsmPrinter::doFinalization(Module &M) {
744 // Emit global variables.
745 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
747 EmitGlobalVariable(I);
749 // Finalize debug and EH information.
752 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
759 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
765 // If the target wants to know about weak references, print them all.
766 if (MAI->getWeakRefDirective()) {
767 // FIXME: This is not lazy, it would be nice to only print weak references
768 // to stuff that is actually used. Note that doing so would require targets
769 // to notice uses in operands (due to constant exprs etc). This should
770 // happen with the MC stuff eventually.
772 // Print out module-level global variables here.
773 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
775 if (!I->hasExternalWeakLinkage()) continue;
776 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
779 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
780 if (!I->hasExternalWeakLinkage()) continue;
781 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
785 if (MAI->hasSetDirective()) {
786 OutStreamer.AddBlankLine();
787 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
789 MCSymbol *Name = Mang->getSymbol(I);
791 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
792 MCSymbol *Target = Mang->getSymbol(GV);
794 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
795 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
796 else if (I->hasWeakLinkage())
797 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
799 assert(I->hasLocalLinkage() && "Invalid alias linkage");
801 EmitVisibility(Name, I->getVisibility());
803 // Emit the directives as assignments aka .set:
804 OutStreamer.EmitAssignment(Name,
805 MCSymbolRefExpr::Create(Target, OutContext));
809 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
810 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
811 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
812 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
813 MP->finishAssembly(*this);
815 // If we don't have any trampolines, then we don't require stack memory
816 // to be executable. Some targets have a directive to declare this.
817 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
818 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
819 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
820 OutStreamer.SwitchSection(S);
822 // Allow the target to emit any magic that it wants at the end of the file,
823 // after everything else has gone out.
826 delete Mang; Mang = 0;
829 OutStreamer.Finish();
833 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
835 // Get the function symbol.
836 CurrentFnSym = Mang->getSymbol(MF.getFunction());
839 LI = &getAnalysis<MachineLoopInfo>();
843 // SectionCPs - Keep track the alignment, constpool entries per Section.
847 SmallVector<unsigned, 4> CPEs;
848 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
852 /// EmitConstantPool - Print to the current output stream assembly
853 /// representations of the constants in the constant pool MCP. This is
854 /// used to print out constants which have been "spilled to memory" by
855 /// the code generator.
857 void AsmPrinter::EmitConstantPool() {
858 const MachineConstantPool *MCP = MF->getConstantPool();
859 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
860 if (CP.empty()) return;
862 // Calculate sections for constant pool entries. We collect entries to go into
863 // the same section together to reduce amount of section switch statements.
864 SmallVector<SectionCPs, 4> CPSections;
865 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
866 const MachineConstantPoolEntry &CPE = CP[i];
867 unsigned Align = CPE.getAlignment();
870 switch (CPE.getRelocationInfo()) {
871 default: llvm_unreachable("Unknown section kind");
872 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
874 Kind = SectionKind::getReadOnlyWithRelLocal();
877 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
878 case 4: Kind = SectionKind::getMergeableConst4(); break;
879 case 8: Kind = SectionKind::getMergeableConst8(); break;
880 case 16: Kind = SectionKind::getMergeableConst16();break;
881 default: Kind = SectionKind::getMergeableConst(); break;
885 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
887 // The number of sections are small, just do a linear search from the
888 // last section to the first.
890 unsigned SecIdx = CPSections.size();
891 while (SecIdx != 0) {
892 if (CPSections[--SecIdx].S == S) {
898 SecIdx = CPSections.size();
899 CPSections.push_back(SectionCPs(S, Align));
902 if (Align > CPSections[SecIdx].Alignment)
903 CPSections[SecIdx].Alignment = Align;
904 CPSections[SecIdx].CPEs.push_back(i);
907 // Now print stuff into the calculated sections.
908 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
909 OutStreamer.SwitchSection(CPSections[i].S);
910 EmitAlignment(Log2_32(CPSections[i].Alignment));
913 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
914 unsigned CPI = CPSections[i].CPEs[j];
915 MachineConstantPoolEntry CPE = CP[CPI];
917 // Emit inter-object padding for alignment.
918 unsigned AlignMask = CPE.getAlignment() - 1;
919 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
920 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
922 const Type *Ty = CPE.getType();
923 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
924 OutStreamer.EmitLabel(GetCPISymbol(CPI));
926 if (CPE.isMachineConstantPoolEntry())
927 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
929 EmitGlobalConstant(CPE.Val.ConstVal);
934 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
935 /// by the current function to the current output stream.
937 void AsmPrinter::EmitJumpTableInfo() {
938 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
939 if (MJTI == 0) return;
940 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
941 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
942 if (JT.empty()) return;
944 // Pick the directive to use to print the jump table entries, and switch to
945 // the appropriate section.
946 const Function *F = MF->getFunction();
947 bool JTInDiffSection = false;
948 if (// In PIC mode, we need to emit the jump table to the same section as the
949 // function body itself, otherwise the label differences won't make sense.
950 // FIXME: Need a better predicate for this: what about custom entries?
951 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
952 // We should also do if the section name is NULL or function is declared
953 // in discardable section
954 // FIXME: this isn't the right predicate, should be based on the MCSection
956 F->isWeakForLinker()) {
957 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
959 // Otherwise, drop it in the readonly section.
960 const MCSection *ReadOnlySection =
961 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
962 OutStreamer.SwitchSection(ReadOnlySection);
963 JTInDiffSection = true;
966 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
968 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
969 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
971 // If this jump table was deleted, ignore it.
972 if (JTBBs.empty()) continue;
974 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
975 // .set directive for each unique entry. This reduces the number of
976 // relocations the assembler will generate for the jump table.
977 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
978 MAI->hasSetDirective()) {
979 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
980 const TargetLowering *TLI = TM.getTargetLowering();
981 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
982 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
983 const MachineBasicBlock *MBB = JTBBs[ii];
984 if (!EmittedSets.insert(MBB)) continue;
986 // .set LJTSet, LBB32-base
988 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
989 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
990 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
994 // On some targets (e.g. Darwin) we want to emit two consequtive labels
995 // before each jump table. The first label is never referenced, but tells
996 // the assembler and linker the extents of the jump table object. The
997 // second label is actually referenced by the code.
998 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
999 // FIXME: This doesn't have to have any specific name, just any randomly
1000 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1001 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1003 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1005 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1006 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1010 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1012 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1013 const MachineBasicBlock *MBB,
1014 unsigned UID) const {
1015 const MCExpr *Value = 0;
1016 switch (MJTI->getEntryKind()) {
1017 case MachineJumpTableInfo::EK_Inline:
1018 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1019 case MachineJumpTableInfo::EK_Custom32:
1020 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1023 case MachineJumpTableInfo::EK_BlockAddress:
1024 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1026 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1028 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1029 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1030 // with a relocation as gp-relative, e.g.:
1032 MCSymbol *MBBSym = MBB->getSymbol();
1033 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1037 case MachineJumpTableInfo::EK_LabelDifference32: {
1038 // EK_LabelDifference32 - Each entry is the address of the block minus
1039 // the address of the jump table. This is used for PIC jump tables where
1040 // gprel32 is not supported. e.g.:
1041 // .word LBB123 - LJTI1_2
1042 // If the .set directive is supported, this is emitted as:
1043 // .set L4_5_set_123, LBB123 - LJTI1_2
1044 // .word L4_5_set_123
1046 // If we have emitted set directives for the jump table entries, print
1047 // them rather than the entries themselves. If we're emitting PIC, then
1048 // emit the table entries as differences between two text section labels.
1049 if (MAI->hasSetDirective()) {
1050 // If we used .set, reference the .set's symbol.
1051 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1055 // Otherwise, use the difference as the jump table entry.
1056 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1057 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1058 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1063 assert(Value && "Unknown entry kind!");
1065 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1066 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1070 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1071 /// special global used by LLVM. If so, emit it and return true, otherwise
1072 /// do nothing and return false.
1073 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1074 if (GV->getName() == "llvm.used") {
1075 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1076 EmitLLVMUsedList(GV->getInitializer());
1080 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1081 if (GV->getSection() == "llvm.metadata" ||
1082 GV->hasAvailableExternallyLinkage())
1085 if (!GV->hasAppendingLinkage()) return false;
1087 assert(GV->hasInitializer() && "Not a special LLVM global!");
1089 const TargetData *TD = TM.getTargetData();
1090 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1091 if (GV->getName() == "llvm.global_ctors") {
1092 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1093 EmitAlignment(Align);
1094 EmitXXStructorList(GV->getInitializer());
1096 if (TM.getRelocationModel() == Reloc::Static &&
1097 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1098 StringRef Sym(".constructors_used");
1099 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1105 if (GV->getName() == "llvm.global_dtors") {
1106 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1107 EmitAlignment(Align);
1108 EmitXXStructorList(GV->getInitializer());
1110 if (TM.getRelocationModel() == Reloc::Static &&
1111 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1112 StringRef Sym(".destructors_used");
1113 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1122 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1123 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1124 /// is true, as being used with this directive.
1125 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1126 // Should be an array of 'i8*'.
1127 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1128 if (InitList == 0) return;
1130 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1131 const GlobalValue *GV =
1132 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1133 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1134 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1138 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1139 /// function pointers, ignoring the init priority.
1140 void AsmPrinter::EmitXXStructorList(Constant *List) {
1141 // Should be an array of '{ int, void ()* }' structs. The first value is the
1142 // init priority, which we ignore.
1143 if (!isa<ConstantArray>(List)) return;
1144 ConstantArray *InitList = cast<ConstantArray>(List);
1145 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1146 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1147 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1149 if (CS->getOperand(1)->isNullValue())
1150 return; // Found a null terminator, exit printing.
1151 // Emit the function pointer.
1152 EmitGlobalConstant(CS->getOperand(1));
1156 //===--------------------------------------------------------------------===//
1157 // Emission and print routines
1160 /// EmitInt8 - Emit a byte directive and value.
1162 void AsmPrinter::EmitInt8(int Value) const {
1163 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1166 /// EmitInt16 - Emit a short directive and value.
1168 void AsmPrinter::EmitInt16(int Value) const {
1169 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1172 /// EmitInt32 - Emit a long directive and value.
1174 void AsmPrinter::EmitInt32(int Value) const {
1175 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1178 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1179 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1180 /// labels. This implicitly uses .set if it is available.
1181 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1182 unsigned Size) const {
1183 // Get the Hi-Lo expression.
1184 const MCExpr *Diff =
1185 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1186 MCSymbolRefExpr::Create(Lo, OutContext),
1189 if (!MAI->hasSetDirective()) {
1190 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1194 // Otherwise, emit with .set (aka assignment).
1195 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1196 OutStreamer.EmitAssignment(SetLabel, Diff);
1197 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1200 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1201 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1202 /// specify the labels. This implicitly uses .set if it is available.
1203 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1204 const MCSymbol *Lo, unsigned Size)
1207 // Emit Hi+Offset - Lo
1208 // Get the Hi+Offset expression.
1209 const MCExpr *Plus =
1210 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1211 MCConstantExpr::Create(Offset, OutContext),
1214 // Get the Hi+Offset-Lo expression.
1215 const MCExpr *Diff =
1216 MCBinaryExpr::CreateSub(Plus,
1217 MCSymbolRefExpr::Create(Lo, OutContext),
1220 if (!MAI->hasSetDirective())
1221 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1223 // Otherwise, emit with .set (aka assignment).
1224 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1225 OutStreamer.EmitAssignment(SetLabel, Diff);
1226 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1230 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1231 /// where the size in bytes of the directive is specified by Size and Label
1232 /// specifies the label. This implicitly uses .set if it is available.
1233 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1237 // Emit Label+Offset
1238 const MCExpr *Plus =
1239 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1240 MCConstantExpr::Create(Offset, OutContext),
1243 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1247 //===----------------------------------------------------------------------===//
1249 // EmitAlignment - Emit an alignment directive to the specified power of
1250 // two boundary. For example, if you pass in 3 here, you will get an 8
1251 // byte alignment. If a global value is specified, and if that global has
1252 // an explicit alignment requested, it will override the alignment request
1253 // if required for correctness.
1255 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1256 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1258 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1260 if (getCurrentSection()->getKind().isText())
1261 OutStreamer.EmitCodeAlignment(1 << NumBits);
1263 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1266 //===----------------------------------------------------------------------===//
1267 // Constant emission.
1268 //===----------------------------------------------------------------------===//
1270 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1272 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1273 MCContext &Ctx = AP.OutContext;
1275 if (CV->isNullValue() || isa<UndefValue>(CV))
1276 return MCConstantExpr::Create(0, Ctx);
1278 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1279 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1281 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1282 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1284 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1285 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1287 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1289 llvm_unreachable("Unknown constant value to lower!");
1290 return MCConstantExpr::Create(0, Ctx);
1293 switch (CE->getOpcode()) {
1295 // If the code isn't optimized, there may be outstanding folding
1296 // opportunities. Attempt to fold the expression using TargetData as a
1297 // last resort before giving up.
1299 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1301 return LowerConstant(C, AP);
1303 // Otherwise report the problem to the user.
1306 raw_string_ostream OS(S);
1307 OS << "Unsupported expression in static initializer: ";
1308 WriteAsOperand(OS, CE, /*PrintType=*/false,
1309 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1310 report_fatal_error(OS.str());
1312 return MCConstantExpr::Create(0, Ctx);
1313 case Instruction::GetElementPtr: {
1314 const TargetData &TD = *AP.TM.getTargetData();
1315 // Generate a symbolic expression for the byte address
1316 const Constant *PtrVal = CE->getOperand(0);
1317 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1318 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1321 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1325 // Truncate/sext the offset to the pointer size.
1326 if (TD.getPointerSizeInBits() != 64) {
1327 int SExtAmount = 64-TD.getPointerSizeInBits();
1328 Offset = (Offset << SExtAmount) >> SExtAmount;
1331 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1335 case Instruction::Trunc:
1336 // We emit the value and depend on the assembler to truncate the generated
1337 // expression properly. This is important for differences between
1338 // blockaddress labels. Since the two labels are in the same function, it
1339 // is reasonable to treat their delta as a 32-bit value.
1341 case Instruction::BitCast:
1342 return LowerConstant(CE->getOperand(0), AP);
1344 case Instruction::IntToPtr: {
1345 const TargetData &TD = *AP.TM.getTargetData();
1346 // Handle casts to pointers by changing them into casts to the appropriate
1347 // integer type. This promotes constant folding and simplifies this code.
1348 Constant *Op = CE->getOperand(0);
1349 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1351 return LowerConstant(Op, AP);
1354 case Instruction::PtrToInt: {
1355 const TargetData &TD = *AP.TM.getTargetData();
1356 // Support only foldable casts to/from pointers that can be eliminated by
1357 // changing the pointer to the appropriately sized integer type.
1358 Constant *Op = CE->getOperand(0);
1359 const Type *Ty = CE->getType();
1361 const MCExpr *OpExpr = LowerConstant(Op, AP);
1363 // We can emit the pointer value into this slot if the slot is an
1364 // integer slot equal to the size of the pointer.
1365 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1368 // Otherwise the pointer is smaller than the resultant integer, mask off
1369 // the high bits so we are sure to get a proper truncation if the input is
1371 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1372 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1373 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1376 // The MC library also has a right-shift operator, but it isn't consistently
1377 // signed or unsigned between different targets.
1378 case Instruction::Add:
1379 case Instruction::Sub:
1380 case Instruction::Mul:
1381 case Instruction::SDiv:
1382 case Instruction::SRem:
1383 case Instruction::Shl:
1384 case Instruction::And:
1385 case Instruction::Or:
1386 case Instruction::Xor: {
1387 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1388 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1389 switch (CE->getOpcode()) {
1390 default: llvm_unreachable("Unknown binary operator constant cast expr");
1391 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1392 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1393 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1394 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1395 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1396 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1397 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1398 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1399 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1405 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1408 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1410 if (AddrSpace != 0 || !CA->isString()) {
1411 // Not a string. Print the values in successive locations
1412 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1413 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1417 // Otherwise, it can be emitted as .ascii.
1418 SmallVector<char, 128> TmpVec;
1419 TmpVec.reserve(CA->getNumOperands());
1420 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1421 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1423 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1426 static void EmitGlobalConstantVector(const ConstantVector *CV,
1427 unsigned AddrSpace, AsmPrinter &AP) {
1428 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1429 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1432 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1433 unsigned AddrSpace, AsmPrinter &AP) {
1434 // Print the fields in successive locations. Pad to align if needed!
1435 const TargetData *TD = AP.TM.getTargetData();
1436 unsigned Size = TD->getTypeAllocSize(CS->getType());
1437 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1438 uint64_t SizeSoFar = 0;
1439 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1440 const Constant *Field = CS->getOperand(i);
1442 // Check if padding is needed and insert one or more 0s.
1443 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1444 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1445 - Layout->getElementOffset(i)) - FieldSize;
1446 SizeSoFar += FieldSize + PadSize;
1448 // Now print the actual field value.
1449 EmitGlobalConstantImpl(Field, AddrSpace, AP);
1451 // Insert padding - this may include padding to increase the size of the
1452 // current field up to the ABI size (if the struct is not packed) as well
1453 // as padding to ensure that the next field starts at the right offset.
1454 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1456 assert(SizeSoFar == Layout->getSizeInBytes() &&
1457 "Layout of constant struct may be incorrect!");
1460 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1462 // FP Constants are printed as integer constants to avoid losing
1464 if (CFP->getType()->isDoubleTy()) {
1465 if (AP.isVerbose()) {
1466 double Val = CFP->getValueAPF().convertToDouble();
1467 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1470 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1471 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1475 if (CFP->getType()->isFloatTy()) {
1476 if (AP.isVerbose()) {
1477 float Val = CFP->getValueAPF().convertToFloat();
1478 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1480 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1481 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1485 if (CFP->getType()->isX86_FP80Ty()) {
1486 // all long double variants are printed as hex
1487 // API needed to prevent premature destruction
1488 APInt API = CFP->getValueAPF().bitcastToAPInt();
1489 const uint64_t *p = API.getRawData();
1490 if (AP.isVerbose()) {
1491 // Convert to double so we can print the approximate val as a comment.
1492 APFloat DoubleVal = CFP->getValueAPF();
1494 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1496 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1497 << DoubleVal.convertToDouble() << '\n';
1500 if (AP.TM.getTargetData()->isBigEndian()) {
1501 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1502 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1504 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1505 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1508 // Emit the tail padding for the long double.
1509 const TargetData &TD = *AP.TM.getTargetData();
1510 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1511 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1515 assert(CFP->getType()->isPPC_FP128Ty() &&
1516 "Floating point constant type not handled");
1517 // All long double variants are printed as hex
1518 // API needed to prevent premature destruction.
1519 APInt API = CFP->getValueAPF().bitcastToAPInt();
1520 const uint64_t *p = API.getRawData();
1521 if (AP.TM.getTargetData()->isBigEndian()) {
1522 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1523 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1525 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1526 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1530 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1531 unsigned AddrSpace, AsmPrinter &AP) {
1532 const TargetData *TD = AP.TM.getTargetData();
1533 unsigned BitWidth = CI->getBitWidth();
1534 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1536 // We don't expect assemblers to support integer data directives
1537 // for more than 64 bits, so we emit the data in at most 64-bit
1538 // quantities at a time.
1539 const uint64_t *RawData = CI->getValue().getRawData();
1540 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1541 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1542 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1546 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1548 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1549 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1550 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1553 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1554 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1561 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1562 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1565 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1570 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1571 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1573 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1574 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1576 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1577 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1579 if (isa<ConstantPointerNull>(CV)) {
1580 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1581 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1585 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1586 return EmitGlobalConstantVector(V, AddrSpace, AP);
1588 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1589 // thread the streamer with EmitValue.
1590 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1591 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1595 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1596 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1597 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1599 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1600 else if (MAI->hasSubsectionsViaSymbols()) {
1601 // If the global has zero size, emit a single byte so that two labels don't
1602 // look like they are at the same location.
1603 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1607 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1608 // Target doesn't support this yet!
1609 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1612 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1614 OS << '+' << Offset;
1615 else if (Offset < 0)
1619 //===----------------------------------------------------------------------===//
1620 // Symbol Lowering Routines.
1621 //===----------------------------------------------------------------------===//
1623 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1624 /// temporary label with the specified stem and unique ID.
1625 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1626 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1630 /// GetTempSymbol - Return an assembler temporary label with the specified
1632 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1633 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1638 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1639 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1642 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1643 return MMI->getAddrLabelSymbol(BB);
1646 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1647 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1648 return OutContext.GetOrCreateSymbol
1649 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1650 + "_" + Twine(CPID));
1653 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1654 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1655 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1658 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1659 /// FIXME: privatize to AsmPrinter.
1660 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1661 return OutContext.GetOrCreateSymbol
1662 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1663 Twine(UID) + "_set_" + Twine(MBBID));
1666 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1667 /// global value name as its base, with the specified suffix, and where the
1668 /// symbol is forced to have private linkage if ForcePrivate is true.
1669 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1671 bool ForcePrivate) const {
1672 SmallString<60> NameStr;
1673 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1674 NameStr.append(Suffix.begin(), Suffix.end());
1675 return OutContext.GetOrCreateSymbol(NameStr.str());
1678 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1680 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1681 SmallString<60> NameStr;
1682 Mang->getNameWithPrefix(NameStr, Sym);
1683 return OutContext.GetOrCreateSymbol(NameStr.str());
1688 /// PrintParentLoopComment - Print comments about parent loops of this one.
1689 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1690 unsigned FunctionNumber) {
1691 if (Loop == 0) return;
1692 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1693 OS.indent(Loop->getLoopDepth()*2)
1694 << "Parent Loop BB" << FunctionNumber << "_"
1695 << Loop->getHeader()->getNumber()
1696 << " Depth=" << Loop->getLoopDepth() << '\n';
1700 /// PrintChildLoopComment - Print comments about child loops within
1701 /// the loop for this basic block, with nesting.
1702 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1703 unsigned FunctionNumber) {
1704 // Add child loop information
1705 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1706 OS.indent((*CL)->getLoopDepth()*2)
1707 << "Child Loop BB" << FunctionNumber << "_"
1708 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1710 PrintChildLoopComment(OS, *CL, FunctionNumber);
1714 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1715 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1716 const MachineLoopInfo *LI,
1717 const AsmPrinter &AP) {
1718 // Add loop depth information
1719 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1720 if (Loop == 0) return;
1722 MachineBasicBlock *Header = Loop->getHeader();
1723 assert(Header && "No header for loop");
1725 // If this block is not a loop header, just print out what is the loop header
1727 if (Header != &MBB) {
1728 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1729 Twine(AP.getFunctionNumber())+"_" +
1730 Twine(Loop->getHeader()->getNumber())+
1731 " Depth="+Twine(Loop->getLoopDepth()));
1735 // Otherwise, it is a loop header. Print out information about child and
1737 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1739 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1742 OS.indent(Loop->getLoopDepth()*2-2);
1747 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1749 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1753 /// EmitBasicBlockStart - This method prints the label for the specified
1754 /// MachineBasicBlock, an alignment (if present) and a comment describing
1755 /// it if appropriate.
1756 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1757 // Emit an alignment directive for this block, if needed.
1758 if (unsigned Align = MBB->getAlignment())
1759 EmitAlignment(Log2_32(Align));
1761 // If the block has its address taken, emit any labels that were used to
1762 // reference the block. It is possible that there is more than one label
1763 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1764 // the references were generated.
1765 if (MBB->hasAddressTaken()) {
1766 const BasicBlock *BB = MBB->getBasicBlock();
1768 OutStreamer.AddComment("Block address taken");
1770 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1772 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1773 OutStreamer.EmitLabel(Syms[i]);
1776 // Print the main label for the block.
1777 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1778 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1779 if (const BasicBlock *BB = MBB->getBasicBlock())
1781 OutStreamer.AddComment("%" + BB->getName());
1783 EmitBasicBlockLoopComments(*MBB, LI, *this);
1785 // NOTE: Want this comment at start of line, don't emit with AddComment.
1786 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1787 Twine(MBB->getNumber()) + ":");
1791 if (const BasicBlock *BB = MBB->getBasicBlock())
1793 OutStreamer.AddComment("%" + BB->getName());
1794 EmitBasicBlockLoopComments(*MBB, LI, *this);
1797 OutStreamer.EmitLabel(MBB->getSymbol());
1801 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1802 MCSymbolAttr Attr = MCSA_Invalid;
1804 switch (Visibility) {
1806 case GlobalValue::HiddenVisibility:
1807 Attr = MAI->getHiddenVisibilityAttr();
1809 case GlobalValue::ProtectedVisibility:
1810 Attr = MAI->getProtectedVisibilityAttr();
1814 if (Attr != MCSA_Invalid)
1815 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1818 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1819 /// exactly one predecessor and the control transfer mechanism between
1820 /// the predecessor and this block is a fall-through.
1822 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1823 // If this is a landing pad, it isn't a fall through. If it has no preds,
1824 // then nothing falls through to it.
1825 if (MBB->isLandingPad() || MBB->pred_empty())
1828 // If there isn't exactly one predecessor, it can't be a fall through.
1829 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1831 if (PI2 != MBB->pred_end())
1834 // The predecessor has to be immediately before this block.
1835 const MachineBasicBlock *Pred = *PI;
1837 if (!Pred->isLayoutSuccessor(MBB))
1840 // If the block is completely empty, then it definitely does fall through.
1844 // Otherwise, check the last instruction.
1845 const MachineInstr &LastInst = Pred->back();
1846 return !LastInst.getDesc().isBarrier();
1851 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1852 if (!S->usesMetadata())
1855 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1856 gcp_map_type::iterator GCPI = GCMap.find(S);
1857 if (GCPI != GCMap.end())
1858 return GCPI->second;
1860 const char *Name = S->getName().c_str();
1862 for (GCMetadataPrinterRegistry::iterator
1863 I = GCMetadataPrinterRegistry::begin(),
1864 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1865 if (strcmp(Name, I->getName()) == 0) {
1866 GCMetadataPrinter *GMP = I->instantiate();
1868 GCMap.insert(std::make_pair(S, GMP));
1872 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));