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/TargetAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Assembly/Writer.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/Timer.h"
51 static const char *DWARFGroupName = "DWARF Emission";
52 static const char *DbgTimerName = "DWARF Debug Writer";
53 static const char *EHTimerName = "DWARF Exception Writer";
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
57 char AsmPrinter::ID = 0;
59 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
60 static gcp_map_type &getGCMap(void *&P) {
62 P = new gcp_map_type();
63 return *(gcp_map_type*)P;
67 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
68 /// value in log2 form. This rounds up to the preferred alignment if possible
70 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
71 unsigned InBits = 0) {
73 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
74 NumBits = TD.getPreferredAlignmentLog(GVar);
76 // If InBits is specified, round it to it.
80 // If the GV has a specified alignment, take it into account.
81 if (GV->getAlignment() == 0)
84 unsigned GVAlign = Log2_32(GV->getAlignment());
86 // If the GVAlign is larger than NumBits, or if we are required to obey
87 // NumBits because the GV has an assigned section, obey it.
88 if (GVAlign > NumBits || GV->hasSection())
96 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97 : MachineFunctionPass(ID),
98 TM(tm), MAI(tm.getMCAsmInfo()),
99 OutContext(Streamer.getContext()),
100 OutStreamer(Streamer),
101 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102 DD = 0; DE = 0; MMI = 0; LI = 0;
103 GCMetadataPrinters = 0;
104 VerboseAsm = Streamer.isVerboseAsm();
107 AsmPrinter::~AsmPrinter() {
108 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
110 if (GCMetadataPrinters != 0) {
111 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
113 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
116 GCMetadataPrinters = 0;
122 /// getFunctionNumber - Return a unique ID for the current function.
124 unsigned AsmPrinter::getFunctionNumber() const {
125 return MF->getFunctionNumber();
128 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
129 return TM.getTargetLowering()->getObjFileLowering();
133 /// getTargetData - Return information about data layout.
134 const TargetData &AsmPrinter::getTargetData() const {
135 return *TM.getTargetData();
138 /// getCurrentSection() - Return the current section we are emitting to.
139 const MCSection *AsmPrinter::getCurrentSection() const {
140 return OutStreamer.getCurrentSection();
145 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
146 AU.setPreservesAll();
147 MachineFunctionPass::getAnalysisUsage(AU);
148 AU.addRequired<MachineModuleInfo>();
149 AU.addRequired<GCModuleInfo>();
151 AU.addRequired<MachineLoopInfo>();
154 bool AsmPrinter::doInitialization(Module &M) {
155 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
156 MMI->AnalyzeModule(M);
158 // Initialize TargetLoweringObjectFile.
159 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
160 .Initialize(OutContext, TM);
162 Mang = new Mangler(OutContext, *TM.getTargetData());
164 // Allow the target to emit any magic that it wants at the start of the file.
165 EmitStartOfAsmFile(M);
167 // Very minimal debug info. It is ignored if we emit actual debug info. If we
168 // don't, this at least helps the user find where a global came from.
169 if (MAI->hasSingleParameterDotFile()) {
171 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
174 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
175 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
176 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
177 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
178 MP->beginAssembly(*this);
180 // Emit module-level inline asm if it exists.
181 if (!M.getModuleInlineAsm().empty()) {
182 OutStreamer.AddComment("Start of file scope inline assembly");
183 OutStreamer.AddBlankLine();
184 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
185 OutStreamer.AddComment("End of file scope inline assembly");
186 OutStreamer.AddBlankLine();
189 if (MAI->doesSupportDebugInformation())
190 DD = new DwarfDebug(this, &M);
192 switch (MAI->getExceptionHandlingType()) {
193 case ExceptionHandling::None:
195 case ExceptionHandling::SjLj:
196 case ExceptionHandling::DwarfCFI:
197 DE = new DwarfCFIException(this);
199 case ExceptionHandling::ARM:
200 DE = new ARMException(this);
204 llvm_unreachable("Unknown exception type.");
207 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
208 switch ((GlobalValue::LinkageTypes)Linkage) {
209 case GlobalValue::CommonLinkage:
210 case GlobalValue::LinkOnceAnyLinkage:
211 case GlobalValue::LinkOnceODRLinkage:
212 case GlobalValue::WeakAnyLinkage:
213 case GlobalValue::WeakODRLinkage:
214 case GlobalValue::LinkerPrivateWeakLinkage:
215 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
216 if (MAI->getWeakDefDirective() != 0) {
218 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
220 if ((GlobalValue::LinkageTypes)Linkage !=
221 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
222 // .weak_definition _foo
223 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
225 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
226 } else if (MAI->getLinkOnceDirective() != 0) {
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229 //NOTE: linkonce is handled by the section the symbol was assigned to.
232 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
235 case GlobalValue::DLLExportLinkage:
236 case GlobalValue::AppendingLinkage:
237 // FIXME: appending linkage variables should go into a section of
238 // their name or something. For now, just emit them as external.
239 case GlobalValue::ExternalLinkage:
240 // If external or appending, declare as a global symbol.
242 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
244 case GlobalValue::PrivateLinkage:
245 case GlobalValue::InternalLinkage:
246 case GlobalValue::LinkerPrivateLinkage:
249 llvm_unreachable("Unknown linkage type!");
254 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
255 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
256 if (GV->hasInitializer()) {
257 // Check to see if this is a special global used by LLVM, if so, emit it.
258 if (EmitSpecialLLVMGlobal(GV))
262 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
263 /*PrintType=*/false, GV->getParent());
264 OutStreamer.GetCommentOS() << '\n';
268 MCSymbol *GVSym = Mang->getSymbol(GV);
269 EmitVisibility(GVSym, GV->getVisibility());
271 if (!GV->hasInitializer()) // External globals require no extra code.
274 if (MAI->hasDotTypeDotSizeDirective())
275 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
277 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
279 const TargetData *TD = TM.getTargetData();
280 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
282 // If the alignment is specified, we *must* obey it. Overaligning a global
283 // with a specified alignment is a prompt way to break globals emitted to
284 // sections and expected to be contiguous (e.g. ObjC metadata).
285 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
287 // Handle common and BSS local symbols (.lcomm).
288 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
289 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
291 // Handle common symbols.
292 if (GVKind.isCommon()) {
293 unsigned Align = 1 << AlignLog;
294 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
298 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
302 // Handle local BSS symbols.
303 if (MAI->hasMachoZeroFillDirective()) {
304 const MCSection *TheSection =
305 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
306 // .zerofill __DATA, __bss, _foo, 400, 5
307 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
311 if (MAI->hasLCOMMDirective()) {
313 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
317 unsigned Align = 1 << AlignLog;
318 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
322 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
324 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
328 const MCSection *TheSection =
329 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
331 // Handle the zerofill directive on darwin, which is a special form of BSS
333 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
334 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
337 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
338 // .zerofill __DATA, __common, _foo, 400, 5
339 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
343 // Handle thread local data for mach-o which requires us to output an
344 // additional structure of data and mangle the original symbol so that we
345 // can reference it later.
347 // TODO: This should become an "emit thread local global" method on TLOF.
348 // All of this macho specific stuff should be sunk down into TLOFMachO and
349 // stuff like "TLSExtraDataSection" should no longer be part of the parent
350 // TLOF class. This will also make it more obvious that stuff like
351 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
353 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
354 // Emit the .tbss symbol
356 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
358 if (GVKind.isThreadBSS())
359 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
360 else if (GVKind.isThreadData()) {
361 OutStreamer.SwitchSection(TheSection);
363 EmitAlignment(AlignLog, GV);
364 OutStreamer.EmitLabel(MangSym);
366 EmitGlobalConstant(GV->getInitializer());
369 OutStreamer.AddBlankLine();
371 // Emit the variable struct for the runtime.
372 const MCSection *TLVSect
373 = getObjFileLowering().getTLSExtraDataSection();
375 OutStreamer.SwitchSection(TLVSect);
376 // Emit the linkage here.
377 EmitLinkage(GV->getLinkage(), GVSym);
378 OutStreamer.EmitLabel(GVSym);
380 // Three pointers in size:
381 // - __tlv_bootstrap - used to make sure support exists
382 // - spare pointer, used when mapped by the runtime
383 // - pointer to mangled symbol above with initializer
384 unsigned PtrSize = TD->getPointerSizeInBits()/8;
385 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
387 OutStreamer.EmitIntValue(0, PtrSize, 0);
388 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
390 OutStreamer.AddBlankLine();
394 OutStreamer.SwitchSection(TheSection);
396 EmitLinkage(GV->getLinkage(), GVSym);
397 EmitAlignment(AlignLog, GV);
399 OutStreamer.EmitLabel(GVSym);
401 EmitGlobalConstant(GV->getInitializer());
403 if (MAI->hasDotTypeDotSizeDirective())
405 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
407 OutStreamer.AddBlankLine();
410 /// EmitFunctionHeader - This method emits the header for the current
412 void AsmPrinter::EmitFunctionHeader() {
413 // Print out constants referenced by the function
416 // Print the 'header' of function.
417 const Function *F = MF->getFunction();
419 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
420 EmitVisibility(CurrentFnSym, F->getVisibility());
422 EmitLinkage(F->getLinkage(), CurrentFnSym);
423 EmitAlignment(MF->getAlignment(), F);
425 if (MAI->hasDotTypeDotSizeDirective())
426 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
429 WriteAsOperand(OutStreamer.GetCommentOS(), F,
430 /*PrintType=*/false, F->getParent());
431 OutStreamer.GetCommentOS() << '\n';
434 // Emit the CurrentFnSym. This is a virtual function to allow targets to
435 // do their wild and crazy things as required.
436 EmitFunctionEntryLabel();
438 // If the function had address-taken blocks that got deleted, then we have
439 // references to the dangling symbols. Emit them at the start of the function
440 // so that we don't get references to undefined symbols.
441 std::vector<MCSymbol*> DeadBlockSyms;
442 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
443 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
444 OutStreamer.AddComment("Address taken block that was later removed");
445 OutStreamer.EmitLabel(DeadBlockSyms[i]);
448 // Add some workaround for linkonce linkage on Cygwin\MinGW.
449 if (MAI->getLinkOnceDirective() != 0 &&
450 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
451 // FIXME: What is this?
453 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
454 CurrentFnSym->getName());
455 OutStreamer.EmitLabel(FakeStub);
458 // Emit pre-function debug and/or EH information.
460 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
461 DE->BeginFunction(MF);
464 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
465 DD->beginFunction(MF);
469 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
470 /// function. This can be overridden by targets as required to do custom stuff.
471 void AsmPrinter::EmitFunctionEntryLabel() {
472 // The function label could have already been emitted if two symbols end up
473 // conflicting due to asm renaming. Detect this and emit an error.
474 if (CurrentFnSym->isUndefined())
475 return OutStreamer.EmitLabel(CurrentFnSym);
477 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
478 "' label emitted multiple times to assembly file");
482 /// EmitComments - Pretty-print comments for instructions.
483 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
484 const MachineFunction *MF = MI.getParent()->getParent();
485 const TargetMachine &TM = MF->getTarget();
487 // Check for spills and reloads
490 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
492 // We assume a single instruction only has a spill or reload, not
494 const MachineMemOperand *MMO;
495 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
496 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
497 MMO = *MI.memoperands_begin();
498 CommentOS << MMO->getSize() << "-byte Reload\n";
500 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
501 if (FrameInfo->isSpillSlotObjectIndex(FI))
502 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
503 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
504 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
505 MMO = *MI.memoperands_begin();
506 CommentOS << MMO->getSize() << "-byte Spill\n";
508 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
509 if (FrameInfo->isSpillSlotObjectIndex(FI))
510 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
513 // Check for spill-induced copies
514 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
515 CommentOS << " Reload Reuse\n";
518 /// EmitImplicitDef - This method emits the specified machine instruction
519 /// that is an implicit def.
520 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
521 unsigned RegNo = MI->getOperand(0).getReg();
522 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
523 AP.TM.getRegisterInfo()->getName(RegNo));
524 AP.OutStreamer.AddBlankLine();
527 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
528 std::string Str = "kill:";
529 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
530 const MachineOperand &Op = MI->getOperand(i);
531 assert(Op.isReg() && "KILL instruction must have only register operands");
533 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
534 Str += (Op.isDef() ? "<def>" : "<kill>");
536 AP.OutStreamer.AddComment(Str);
537 AP.OutStreamer.AddBlankLine();
540 /// EmitDebugValueComment - This method handles the target-independent form
541 /// of DBG_VALUE, returning true if it was able to do so. A false return
542 /// means the target will need to handle MI in EmitInstruction.
543 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
544 // This code handles only the 3-operand target-independent form.
545 if (MI->getNumOperands() != 3)
548 SmallString<128> Str;
549 raw_svector_ostream OS(Str);
550 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
552 // cast away const; DIetc do not take const operands for some reason.
553 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
554 if (V.getContext().isSubprogram())
555 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
556 OS << V.getName() << " <- ";
558 // Register or immediate value. Register 0 means undef.
559 if (MI->getOperand(0).isFPImm()) {
560 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
561 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
562 OS << (double)APF.convertToFloat();
563 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
564 OS << APF.convertToDouble();
566 // There is no good way to print long double. Convert a copy to
567 // double. Ah well, it's only a comment.
569 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
571 OS << "(long double) " << APF.convertToDouble();
573 } else if (MI->getOperand(0).isImm()) {
574 OS << MI->getOperand(0).getImm();
576 assert(MI->getOperand(0).isReg() && "Unknown operand type");
577 if (MI->getOperand(0).getReg() == 0) {
578 // Suppress offset, it is not meaningful here.
580 // NOTE: Want this comment at start of line, don't emit with AddComment.
581 AP.OutStreamer.EmitRawText(OS.str());
584 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
587 OS << '+' << MI->getOperand(1).getImm();
588 // NOTE: Want this comment at start of line, don't emit with AddComment.
589 AP.OutStreamer.EmitRawText(OS.str());
593 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
594 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
595 MF->getFunction()->needsUnwindTableEntry())
598 if (MMI->hasDebugInfo())
604 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
605 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
607 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
610 if (needsCFIMoves() == CFI_M_None)
613 MachineModuleInfo &MMI = MF->getMMI();
614 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
615 bool FoundOne = false;
617 for (std::vector<MachineMove>::iterator I = Moves.begin(),
618 E = Moves.end(); I != E; ++I) {
619 if (I->getLabel() == Label) {
620 EmitCFIFrameMove(*I);
627 /// EmitFunctionBody - This method emits the body and trailer for a
629 void AsmPrinter::EmitFunctionBody() {
630 // Emit target-specific gunk before the function body.
631 EmitFunctionBodyStart();
633 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
635 // Print out code for the function.
636 bool HasAnyRealCode = false;
637 const MachineInstr *LastMI = 0;
638 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
640 // Print a label for the basic block.
641 EmitBasicBlockStart(I);
642 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
646 // Print the assembly for the instruction.
647 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
648 !II->isDebugValue()) {
649 HasAnyRealCode = true;
653 if (ShouldPrintDebugScopes) {
654 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
655 DD->beginInstruction(II);
659 EmitComments(*II, OutStreamer.GetCommentOS());
661 switch (II->getOpcode()) {
662 case TargetOpcode::PROLOG_LABEL:
663 emitPrologLabel(*II);
666 case TargetOpcode::EH_LABEL:
667 case TargetOpcode::GC_LABEL:
668 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
670 case TargetOpcode::INLINEASM:
673 case TargetOpcode::DBG_VALUE:
675 if (!EmitDebugValueComment(II, *this))
679 case TargetOpcode::IMPLICIT_DEF:
680 if (isVerbose()) EmitImplicitDef(II, *this);
682 case TargetOpcode::KILL:
683 if (isVerbose()) EmitKill(II, *this);
686 if (!TM.hasMCUseLoc())
687 MCLineEntry::Make(&OutStreamer, getCurrentSection());
693 if (ShouldPrintDebugScopes) {
694 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
695 DD->endInstruction(II);
700 // If the last instruction was a prolog label, then we have a situation where
701 // we emitted a prolog but no function body. This results in the ending prolog
702 // label equaling the end of function label and an invalid "row" in the
703 // FDE. We need to emit a noop in this situation so that the FDE's rows are
705 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
707 // If the function is empty and the object file uses .subsections_via_symbols,
708 // then we need to emit *something* to the function body to prevent the
709 // labels from collapsing together. Just emit a noop.
710 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
712 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
713 if (Noop.getOpcode()) {
714 OutStreamer.AddComment("avoids zero-length function");
715 OutStreamer.EmitInstruction(Noop);
716 } else // Target not mc-ized yet.
717 OutStreamer.EmitRawText(StringRef("\tnop\n"));
720 // Emit target-specific gunk after the function body.
721 EmitFunctionBodyEnd();
723 // If the target wants a .size directive for the size of the function, emit
725 if (MAI->hasDotTypeDotSizeDirective()) {
726 // Create a symbol for the end of function, so we can get the size as
727 // difference between the function label and the temp label.
728 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
729 OutStreamer.EmitLabel(FnEndLabel);
731 const MCExpr *SizeExp =
732 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
733 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
735 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
738 // Emit post-function debug information.
740 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
744 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
749 // Print out jump tables referenced by the function.
752 OutStreamer.AddBlankLine();
755 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
757 MachineLocation AsmPrinter::
758 getDebugValueLocation(const MachineInstr *MI) const {
759 // Target specific DBG_VALUE instructions are handled by each target.
760 return MachineLocation();
763 /// EmitDwarfRegOp - Emit dwarf register operation.
764 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
765 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
766 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
768 for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
769 *SR && Reg == -1; ++SR) {
770 Reg = TRI->getDwarfRegNum(*SR, false);
771 // FIXME: Get the bit range this register uses of the superregister
772 // so that we can produce a DW_OP_bit_piece
775 // FIXME: Handle cases like a super register being encoded as
776 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
778 // FIXME: We have no reasonable way of handling errors in here. The
779 // caller might be in the middle of an dwarf expression. We should
780 // probably assert that Reg >= 0 once debug info generation is more mature.
782 if (int Offset = MLoc.getOffset()) {
784 OutStreamer.AddComment(
785 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
786 EmitInt8(dwarf::DW_OP_breg0 + Reg);
788 OutStreamer.AddComment("DW_OP_bregx");
789 EmitInt8(dwarf::DW_OP_bregx);
790 OutStreamer.AddComment(Twine(Reg));
796 OutStreamer.AddComment(
797 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
798 EmitInt8(dwarf::DW_OP_reg0 + Reg);
800 OutStreamer.AddComment("DW_OP_regx");
801 EmitInt8(dwarf::DW_OP_regx);
802 OutStreamer.AddComment(Twine(Reg));
807 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
810 bool AsmPrinter::doFinalization(Module &M) {
811 // Emit global variables.
812 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
814 EmitGlobalVariable(I);
816 // Emit visibility info for declarations
817 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
818 const Function &F = *I;
819 if (!F.isDeclaration())
821 GlobalValue::VisibilityTypes V = F.getVisibility();
822 if (V == GlobalValue::DefaultVisibility)
825 MCSymbol *Name = Mang->getSymbol(&F);
826 EmitVisibility(Name, V, false);
829 // Finalize debug and EH information.
832 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
839 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
845 // If the target wants to know about weak references, print them all.
846 if (MAI->getWeakRefDirective()) {
847 // FIXME: This is not lazy, it would be nice to only print weak references
848 // to stuff that is actually used. Note that doing so would require targets
849 // to notice uses in operands (due to constant exprs etc). This should
850 // happen with the MC stuff eventually.
852 // Print out module-level global variables here.
853 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
855 if (!I->hasExternalWeakLinkage()) continue;
856 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
859 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
860 if (!I->hasExternalWeakLinkage()) continue;
861 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
865 if (MAI->hasSetDirective()) {
866 OutStreamer.AddBlankLine();
867 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
869 MCSymbol *Name = Mang->getSymbol(I);
871 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
872 MCSymbol *Target = Mang->getSymbol(GV);
874 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
875 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
876 else if (I->hasWeakLinkage())
877 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
879 assert(I->hasLocalLinkage() && "Invalid alias linkage");
881 EmitVisibility(Name, I->getVisibility());
883 // Emit the directives as assignments aka .set:
884 OutStreamer.EmitAssignment(Name,
885 MCSymbolRefExpr::Create(Target, OutContext));
889 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
890 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
891 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
892 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
893 MP->finishAssembly(*this);
895 // If we don't have any trampolines, then we don't require stack memory
896 // to be executable. Some targets have a directive to declare this.
897 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
898 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
899 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
900 OutStreamer.SwitchSection(S);
902 // Allow the target to emit any magic that it wants at the end of the file,
903 // after everything else has gone out.
906 delete Mang; Mang = 0;
909 OutStreamer.Finish();
913 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
915 // Get the function symbol.
916 CurrentFnSym = Mang->getSymbol(MF.getFunction());
919 LI = &getAnalysis<MachineLoopInfo>();
923 // SectionCPs - Keep track the alignment, constpool entries per Section.
927 SmallVector<unsigned, 4> CPEs;
928 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
932 /// EmitConstantPool - Print to the current output stream assembly
933 /// representations of the constants in the constant pool MCP. This is
934 /// used to print out constants which have been "spilled to memory" by
935 /// the code generator.
937 void AsmPrinter::EmitConstantPool() {
938 const MachineConstantPool *MCP = MF->getConstantPool();
939 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
940 if (CP.empty()) return;
942 // Calculate sections for constant pool entries. We collect entries to go into
943 // the same section together to reduce amount of section switch statements.
944 SmallVector<SectionCPs, 4> CPSections;
945 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
946 const MachineConstantPoolEntry &CPE = CP[i];
947 unsigned Align = CPE.getAlignment();
950 switch (CPE.getRelocationInfo()) {
951 default: llvm_unreachable("Unknown section kind");
952 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
954 Kind = SectionKind::getReadOnlyWithRelLocal();
957 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
958 case 4: Kind = SectionKind::getMergeableConst4(); break;
959 case 8: Kind = SectionKind::getMergeableConst8(); break;
960 case 16: Kind = SectionKind::getMergeableConst16();break;
961 default: Kind = SectionKind::getMergeableConst(); break;
965 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
967 // The number of sections are small, just do a linear search from the
968 // last section to the first.
970 unsigned SecIdx = CPSections.size();
971 while (SecIdx != 0) {
972 if (CPSections[--SecIdx].S == S) {
978 SecIdx = CPSections.size();
979 CPSections.push_back(SectionCPs(S, Align));
982 if (Align > CPSections[SecIdx].Alignment)
983 CPSections[SecIdx].Alignment = Align;
984 CPSections[SecIdx].CPEs.push_back(i);
987 // Now print stuff into the calculated sections.
988 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
989 OutStreamer.SwitchSection(CPSections[i].S);
990 EmitAlignment(Log2_32(CPSections[i].Alignment));
993 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
994 unsigned CPI = CPSections[i].CPEs[j];
995 MachineConstantPoolEntry CPE = CP[CPI];
997 // Emit inter-object padding for alignment.
998 unsigned AlignMask = CPE.getAlignment() - 1;
999 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1000 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1002 const Type *Ty = CPE.getType();
1003 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1004 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1006 if (CPE.isMachineConstantPoolEntry())
1007 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1009 EmitGlobalConstant(CPE.Val.ConstVal);
1014 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1015 /// by the current function to the current output stream.
1017 void AsmPrinter::EmitJumpTableInfo() {
1018 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1019 if (MJTI == 0) return;
1020 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1021 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1022 if (JT.empty()) return;
1024 // Pick the directive to use to print the jump table entries, and switch to
1025 // the appropriate section.
1026 const Function *F = MF->getFunction();
1027 bool JTInDiffSection = false;
1028 if (// In PIC mode, we need to emit the jump table to the same section as the
1029 // function body itself, otherwise the label differences won't make sense.
1030 // FIXME: Need a better predicate for this: what about custom entries?
1031 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1032 // We should also do if the section name is NULL or function is declared
1033 // in discardable section
1034 // FIXME: this isn't the right predicate, should be based on the MCSection
1035 // for the function.
1036 F->isWeakForLinker()) {
1037 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1039 // Otherwise, drop it in the readonly section.
1040 const MCSection *ReadOnlySection =
1041 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1042 OutStreamer.SwitchSection(ReadOnlySection);
1043 JTInDiffSection = true;
1046 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1048 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1049 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1051 // If this jump table was deleted, ignore it.
1052 if (JTBBs.empty()) continue;
1054 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1055 // .set directive for each unique entry. This reduces the number of
1056 // relocations the assembler will generate for the jump table.
1057 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1058 MAI->hasSetDirective()) {
1059 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1060 const TargetLowering *TLI = TM.getTargetLowering();
1061 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1062 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1063 const MachineBasicBlock *MBB = JTBBs[ii];
1064 if (!EmittedSets.insert(MBB)) continue;
1066 // .set LJTSet, LBB32-base
1068 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1069 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1070 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1074 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1075 // before each jump table. The first label is never referenced, but tells
1076 // the assembler and linker the extents of the jump table object. The
1077 // second label is actually referenced by the code.
1078 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1079 // FIXME: This doesn't have to have any specific name, just any randomly
1080 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1081 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1083 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1085 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1086 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1090 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1092 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1093 const MachineBasicBlock *MBB,
1094 unsigned UID) const {
1095 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1096 const MCExpr *Value = 0;
1097 switch (MJTI->getEntryKind()) {
1098 case MachineJumpTableInfo::EK_Inline:
1099 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1100 case MachineJumpTableInfo::EK_Custom32:
1101 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1104 case MachineJumpTableInfo::EK_BlockAddress:
1105 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1107 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1109 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1110 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1111 // with a relocation as gp-relative, e.g.:
1113 MCSymbol *MBBSym = MBB->getSymbol();
1114 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1118 case MachineJumpTableInfo::EK_LabelDifference32: {
1119 // EK_LabelDifference32 - Each entry is the address of the block minus
1120 // the address of the jump table. This is used for PIC jump tables where
1121 // gprel32 is not supported. e.g.:
1122 // .word LBB123 - LJTI1_2
1123 // If the .set directive is supported, this is emitted as:
1124 // .set L4_5_set_123, LBB123 - LJTI1_2
1125 // .word L4_5_set_123
1127 // If we have emitted set directives for the jump table entries, print
1128 // them rather than the entries themselves. If we're emitting PIC, then
1129 // emit the table entries as differences between two text section labels.
1130 if (MAI->hasSetDirective()) {
1131 // If we used .set, reference the .set's symbol.
1132 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1136 // Otherwise, use the difference as the jump table entry.
1137 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1138 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1139 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1144 assert(Value && "Unknown entry kind!");
1146 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1147 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1151 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1152 /// special global used by LLVM. If so, emit it and return true, otherwise
1153 /// do nothing and return false.
1154 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1155 if (GV->getName() == "llvm.used") {
1156 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1157 EmitLLVMUsedList(GV->getInitializer());
1161 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1162 if (GV->getSection() == "llvm.metadata" ||
1163 GV->hasAvailableExternallyLinkage())
1166 if (!GV->hasAppendingLinkage()) return false;
1168 assert(GV->hasInitializer() && "Not a special LLVM global!");
1170 const TargetData *TD = TM.getTargetData();
1171 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1172 if (GV->getName() == "llvm.global_ctors") {
1173 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1174 EmitAlignment(Align);
1175 EmitXXStructorList(GV->getInitializer());
1177 if (TM.getRelocationModel() == Reloc::Static &&
1178 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1179 StringRef Sym(".constructors_used");
1180 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1186 if (GV->getName() == "llvm.global_dtors") {
1187 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1188 EmitAlignment(Align);
1189 EmitXXStructorList(GV->getInitializer());
1191 if (TM.getRelocationModel() == Reloc::Static &&
1192 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1193 StringRef Sym(".destructors_used");
1194 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1203 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1204 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1205 /// is true, as being used with this directive.
1206 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1207 // Should be an array of 'i8*'.
1208 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1209 if (InitList == 0) return;
1211 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1212 const GlobalValue *GV =
1213 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1214 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1215 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1219 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1220 /// function pointers, ignoring the init priority.
1221 void AsmPrinter::EmitXXStructorList(Constant *List) {
1222 // Should be an array of '{ int, void ()* }' structs. The first value is the
1223 // init priority, which we ignore.
1224 if (!isa<ConstantArray>(List)) return;
1225 ConstantArray *InitList = cast<ConstantArray>(List);
1226 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1227 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1228 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1230 if (CS->getOperand(1)->isNullValue())
1231 return; // Found a null terminator, exit printing.
1232 // Emit the function pointer.
1233 EmitGlobalConstant(CS->getOperand(1));
1237 //===--------------------------------------------------------------------===//
1238 // Emission and print routines
1241 /// EmitInt8 - Emit a byte directive and value.
1243 void AsmPrinter::EmitInt8(int Value) const {
1244 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1247 /// EmitInt16 - Emit a short directive and value.
1249 void AsmPrinter::EmitInt16(int Value) const {
1250 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1253 /// EmitInt32 - Emit a long directive and value.
1255 void AsmPrinter::EmitInt32(int Value) const {
1256 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1259 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1260 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1261 /// labels. This implicitly uses .set if it is available.
1262 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1263 unsigned Size) const {
1264 // Get the Hi-Lo expression.
1265 const MCExpr *Diff =
1266 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1267 MCSymbolRefExpr::Create(Lo, OutContext),
1270 if (!MAI->hasSetDirective()) {
1271 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1275 // Otherwise, emit with .set (aka assignment).
1276 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1277 OutStreamer.EmitAssignment(SetLabel, Diff);
1278 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1281 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1282 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1283 /// specify the labels. This implicitly uses .set if it is available.
1284 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1285 const MCSymbol *Lo, unsigned Size)
1288 // Emit Hi+Offset - Lo
1289 // Get the Hi+Offset expression.
1290 const MCExpr *Plus =
1291 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1292 MCConstantExpr::Create(Offset, OutContext),
1295 // Get the Hi+Offset-Lo expression.
1296 const MCExpr *Diff =
1297 MCBinaryExpr::CreateSub(Plus,
1298 MCSymbolRefExpr::Create(Lo, OutContext),
1301 if (!MAI->hasSetDirective())
1302 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1304 // Otherwise, emit with .set (aka assignment).
1305 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1306 OutStreamer.EmitAssignment(SetLabel, Diff);
1307 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1311 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1312 /// where the size in bytes of the directive is specified by Size and Label
1313 /// specifies the label. This implicitly uses .set if it is available.
1314 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1318 // Emit Label+Offset
1319 const MCExpr *Plus =
1320 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1321 MCConstantExpr::Create(Offset, OutContext),
1324 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1328 //===----------------------------------------------------------------------===//
1330 // EmitAlignment - Emit an alignment directive to the specified power of
1331 // two boundary. For example, if you pass in 3 here, you will get an 8
1332 // byte alignment. If a global value is specified, and if that global has
1333 // an explicit alignment requested, it will override the alignment request
1334 // if required for correctness.
1336 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1337 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1339 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1341 if (getCurrentSection()->getKind().isText())
1342 OutStreamer.EmitCodeAlignment(1 << NumBits);
1344 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1347 //===----------------------------------------------------------------------===//
1348 // Constant emission.
1349 //===----------------------------------------------------------------------===//
1351 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1353 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1354 MCContext &Ctx = AP.OutContext;
1356 if (CV->isNullValue() || isa<UndefValue>(CV))
1357 return MCConstantExpr::Create(0, Ctx);
1359 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1360 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1362 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1363 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1365 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1366 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1368 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1370 llvm_unreachable("Unknown constant value to lower!");
1371 return MCConstantExpr::Create(0, Ctx);
1374 switch (CE->getOpcode()) {
1376 // If the code isn't optimized, there may be outstanding folding
1377 // opportunities. Attempt to fold the expression using TargetData as a
1378 // last resort before giving up.
1380 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1382 return LowerConstant(C, AP);
1384 // Otherwise report the problem to the user.
1387 raw_string_ostream OS(S);
1388 OS << "Unsupported expression in static initializer: ";
1389 WriteAsOperand(OS, CE, /*PrintType=*/false,
1390 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1391 report_fatal_error(OS.str());
1393 return MCConstantExpr::Create(0, Ctx);
1394 case Instruction::GetElementPtr: {
1395 const TargetData &TD = *AP.TM.getTargetData();
1396 // Generate a symbolic expression for the byte address
1397 const Constant *PtrVal = CE->getOperand(0);
1398 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1399 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1402 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1406 // Truncate/sext the offset to the pointer size.
1407 if (TD.getPointerSizeInBits() != 64) {
1408 int SExtAmount = 64-TD.getPointerSizeInBits();
1409 Offset = (Offset << SExtAmount) >> SExtAmount;
1412 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1416 case Instruction::Trunc:
1417 // We emit the value and depend on the assembler to truncate the generated
1418 // expression properly. This is important for differences between
1419 // blockaddress labels. Since the two labels are in the same function, it
1420 // is reasonable to treat their delta as a 32-bit value.
1422 case Instruction::BitCast:
1423 return LowerConstant(CE->getOperand(0), AP);
1425 case Instruction::IntToPtr: {
1426 const TargetData &TD = *AP.TM.getTargetData();
1427 // Handle casts to pointers by changing them into casts to the appropriate
1428 // integer type. This promotes constant folding and simplifies this code.
1429 Constant *Op = CE->getOperand(0);
1430 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1432 return LowerConstant(Op, AP);
1435 case Instruction::PtrToInt: {
1436 const TargetData &TD = *AP.TM.getTargetData();
1437 // Support only foldable casts to/from pointers that can be eliminated by
1438 // changing the pointer to the appropriately sized integer type.
1439 Constant *Op = CE->getOperand(0);
1440 const Type *Ty = CE->getType();
1442 const MCExpr *OpExpr = LowerConstant(Op, AP);
1444 // We can emit the pointer value into this slot if the slot is an
1445 // integer slot equal to the size of the pointer.
1446 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1449 // Otherwise the pointer is smaller than the resultant integer, mask off
1450 // the high bits so we are sure to get a proper truncation if the input is
1452 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1453 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1454 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1457 // The MC library also has a right-shift operator, but it isn't consistently
1458 // signed or unsigned between different targets.
1459 case Instruction::Add:
1460 case Instruction::Sub:
1461 case Instruction::Mul:
1462 case Instruction::SDiv:
1463 case Instruction::SRem:
1464 case Instruction::Shl:
1465 case Instruction::And:
1466 case Instruction::Or:
1467 case Instruction::Xor: {
1468 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1469 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1470 switch (CE->getOpcode()) {
1471 default: llvm_unreachable("Unknown binary operator constant cast expr");
1472 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1473 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1474 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1475 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1476 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1477 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1478 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1479 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1480 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1486 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1489 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1491 if (AddrSpace != 0 || !CA->isString()) {
1492 // Not a string. Print the values in successive locations
1493 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1494 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1498 // Otherwise, it can be emitted as .ascii.
1499 SmallVector<char, 128> TmpVec;
1500 TmpVec.reserve(CA->getNumOperands());
1501 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1502 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1504 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1507 static void EmitGlobalConstantVector(const ConstantVector *CV,
1508 unsigned AddrSpace, AsmPrinter &AP) {
1509 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1510 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1513 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1514 unsigned AddrSpace, AsmPrinter &AP) {
1515 // Print the fields in successive locations. Pad to align if needed!
1516 const TargetData *TD = AP.TM.getTargetData();
1517 unsigned Size = TD->getTypeAllocSize(CS->getType());
1518 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1519 uint64_t SizeSoFar = 0;
1520 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1521 const Constant *Field = CS->getOperand(i);
1523 // Check if padding is needed and insert one or more 0s.
1524 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1525 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1526 - Layout->getElementOffset(i)) - FieldSize;
1527 SizeSoFar += FieldSize + PadSize;
1529 // Now print the actual field value.
1530 EmitGlobalConstantImpl(Field, AddrSpace, AP);
1532 // Insert padding - this may include padding to increase the size of the
1533 // current field up to the ABI size (if the struct is not packed) as well
1534 // as padding to ensure that the next field starts at the right offset.
1535 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1537 assert(SizeSoFar == Layout->getSizeInBytes() &&
1538 "Layout of constant struct may be incorrect!");
1541 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1543 // FP Constants are printed as integer constants to avoid losing
1545 if (CFP->getType()->isDoubleTy()) {
1546 if (AP.isVerbose()) {
1547 double Val = CFP->getValueAPF().convertToDouble();
1548 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1551 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1552 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1556 if (CFP->getType()->isFloatTy()) {
1557 if (AP.isVerbose()) {
1558 float Val = CFP->getValueAPF().convertToFloat();
1559 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1561 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1562 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1566 if (CFP->getType()->isX86_FP80Ty()) {
1567 // all long double variants are printed as hex
1568 // API needed to prevent premature destruction
1569 APInt API = CFP->getValueAPF().bitcastToAPInt();
1570 const uint64_t *p = API.getRawData();
1571 if (AP.isVerbose()) {
1572 // Convert to double so we can print the approximate val as a comment.
1573 APFloat DoubleVal = CFP->getValueAPF();
1575 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1577 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1578 << DoubleVal.convertToDouble() << '\n';
1581 if (AP.TM.getTargetData()->isBigEndian()) {
1582 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1583 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1585 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1586 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1589 // Emit the tail padding for the long double.
1590 const TargetData &TD = *AP.TM.getTargetData();
1591 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1592 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1596 assert(CFP->getType()->isPPC_FP128Ty() &&
1597 "Floating point constant type not handled");
1598 // All long double variants are printed as hex
1599 // API needed to prevent premature destruction.
1600 APInt API = CFP->getValueAPF().bitcastToAPInt();
1601 const uint64_t *p = API.getRawData();
1602 if (AP.TM.getTargetData()->isBigEndian()) {
1603 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1604 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1606 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1607 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1611 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1612 unsigned AddrSpace, AsmPrinter &AP) {
1613 const TargetData *TD = AP.TM.getTargetData();
1614 unsigned BitWidth = CI->getBitWidth();
1615 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1617 // We don't expect assemblers to support integer data directives
1618 // for more than 64 bits, so we emit the data in at most 64-bit
1619 // quantities at a time.
1620 const uint64_t *RawData = CI->getValue().getRawData();
1621 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1622 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1623 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1627 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1629 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1630 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1631 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1634 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1635 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1642 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1643 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1646 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1651 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1652 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1654 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1655 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1657 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1658 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1660 if (isa<ConstantPointerNull>(CV)) {
1661 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1662 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1666 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1667 return EmitGlobalConstantVector(V, AddrSpace, AP);
1669 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1670 // thread the streamer with EmitValue.
1671 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1672 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1676 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1677 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1678 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1680 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1681 else if (MAI->hasSubsectionsViaSymbols()) {
1682 // If the global has zero size, emit a single byte so that two labels don't
1683 // look like they are at the same location.
1684 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1688 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1689 // Target doesn't support this yet!
1690 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1693 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1695 OS << '+' << Offset;
1696 else if (Offset < 0)
1700 //===----------------------------------------------------------------------===//
1701 // Symbol Lowering Routines.
1702 //===----------------------------------------------------------------------===//
1704 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1705 /// temporary label with the specified stem and unique ID.
1706 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1707 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1711 /// GetTempSymbol - Return an assembler temporary label with the specified
1713 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1714 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1719 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1720 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1723 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1724 return MMI->getAddrLabelSymbol(BB);
1727 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1728 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1729 return OutContext.GetOrCreateSymbol
1730 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1731 + "_" + Twine(CPID));
1734 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1735 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1736 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1739 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1740 /// FIXME: privatize to AsmPrinter.
1741 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1742 return OutContext.GetOrCreateSymbol
1743 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1744 Twine(UID) + "_set_" + Twine(MBBID));
1747 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1748 /// global value name as its base, with the specified suffix, and where the
1749 /// symbol is forced to have private linkage if ForcePrivate is true.
1750 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1752 bool ForcePrivate) const {
1753 SmallString<60> NameStr;
1754 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1755 NameStr.append(Suffix.begin(), Suffix.end());
1756 return OutContext.GetOrCreateSymbol(NameStr.str());
1759 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1761 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1762 SmallString<60> NameStr;
1763 Mang->getNameWithPrefix(NameStr, Sym);
1764 return OutContext.GetOrCreateSymbol(NameStr.str());
1769 /// PrintParentLoopComment - Print comments about parent loops of this one.
1770 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1771 unsigned FunctionNumber) {
1772 if (Loop == 0) return;
1773 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1774 OS.indent(Loop->getLoopDepth()*2)
1775 << "Parent Loop BB" << FunctionNumber << "_"
1776 << Loop->getHeader()->getNumber()
1777 << " Depth=" << Loop->getLoopDepth() << '\n';
1781 /// PrintChildLoopComment - Print comments about child loops within
1782 /// the loop for this basic block, with nesting.
1783 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1784 unsigned FunctionNumber) {
1785 // Add child loop information
1786 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1787 OS.indent((*CL)->getLoopDepth()*2)
1788 << "Child Loop BB" << FunctionNumber << "_"
1789 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1791 PrintChildLoopComment(OS, *CL, FunctionNumber);
1795 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1796 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1797 const MachineLoopInfo *LI,
1798 const AsmPrinter &AP) {
1799 // Add loop depth information
1800 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1801 if (Loop == 0) return;
1803 MachineBasicBlock *Header = Loop->getHeader();
1804 assert(Header && "No header for loop");
1806 // If this block is not a loop header, just print out what is the loop header
1808 if (Header != &MBB) {
1809 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1810 Twine(AP.getFunctionNumber())+"_" +
1811 Twine(Loop->getHeader()->getNumber())+
1812 " Depth="+Twine(Loop->getLoopDepth()));
1816 // Otherwise, it is a loop header. Print out information about child and
1818 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1820 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1823 OS.indent(Loop->getLoopDepth()*2-2);
1828 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1830 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1834 /// EmitBasicBlockStart - This method prints the label for the specified
1835 /// MachineBasicBlock, an alignment (if present) and a comment describing
1836 /// it if appropriate.
1837 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1838 // Emit an alignment directive for this block, if needed.
1839 if (unsigned Align = MBB->getAlignment())
1840 EmitAlignment(Log2_32(Align));
1842 // If the block has its address taken, emit any labels that were used to
1843 // reference the block. It is possible that there is more than one label
1844 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1845 // the references were generated.
1846 if (MBB->hasAddressTaken()) {
1847 const BasicBlock *BB = MBB->getBasicBlock();
1849 OutStreamer.AddComment("Block address taken");
1851 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1853 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1854 OutStreamer.EmitLabel(Syms[i]);
1857 // Print the main label for the block.
1858 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1859 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1860 if (const BasicBlock *BB = MBB->getBasicBlock())
1862 OutStreamer.AddComment("%" + BB->getName());
1864 EmitBasicBlockLoopComments(*MBB, LI, *this);
1866 // NOTE: Want this comment at start of line, don't emit with AddComment.
1867 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1868 Twine(MBB->getNumber()) + ":");
1872 if (const BasicBlock *BB = MBB->getBasicBlock())
1874 OutStreamer.AddComment("%" + BB->getName());
1875 EmitBasicBlockLoopComments(*MBB, LI, *this);
1878 OutStreamer.EmitLabel(MBB->getSymbol());
1882 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1883 bool IsDefinition) const {
1884 MCSymbolAttr Attr = MCSA_Invalid;
1886 switch (Visibility) {
1888 case GlobalValue::HiddenVisibility:
1890 Attr = MAI->getHiddenVisibilityAttr();
1892 Attr = MAI->getHiddenDeclarationVisibilityAttr();
1894 case GlobalValue::ProtectedVisibility:
1895 Attr = MAI->getProtectedVisibilityAttr();
1899 if (Attr != MCSA_Invalid)
1900 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1903 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1904 /// exactly one predecessor and the control transfer mechanism between
1905 /// the predecessor and this block is a fall-through.
1907 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1908 // If this is a landing pad, it isn't a fall through. If it has no preds,
1909 // then nothing falls through to it.
1910 if (MBB->isLandingPad() || MBB->pred_empty())
1913 // If there isn't exactly one predecessor, it can't be a fall through.
1914 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1916 if (PI2 != MBB->pred_end())
1919 // The predecessor has to be immediately before this block.
1920 const MachineBasicBlock *Pred = *PI;
1922 if (!Pred->isLayoutSuccessor(MBB))
1925 // If the block is completely empty, then it definitely does fall through.
1929 // Otherwise, check the last instruction.
1930 const MachineInstr &LastInst = Pred->back();
1931 return !LastInst.getDesc().isBarrier();
1936 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1937 if (!S->usesMetadata())
1940 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1941 gcp_map_type::iterator GCPI = GCMap.find(S);
1942 if (GCPI != GCMap.end())
1943 return GCPI->second;
1945 const char *Name = S->getName().c_str();
1947 for (GCMetadataPrinterRegistry::iterator
1948 I = GCMetadataPrinterRegistry::begin(),
1949 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1950 if (strcmp(Name, I->getName()) == 0) {
1951 GCMetadataPrinter *GMP = I->instantiate();
1953 GCMap.insert(std::make_pair(S, GMP));
1957 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));