1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallString.h"
51 static cl::opt<cl::boolOrDefault>
52 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
53 cl::init(cl::BOU_UNSET));
55 static bool getVerboseAsm(bool VDef) {
58 case cl::BOU_UNSET: return VDef;
59 case cl::BOU_TRUE: return true;
60 case cl::BOU_FALSE: return false;
64 char AsmPrinter::ID = 0;
65 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
66 const MCAsmInfo *T, bool VDef)
67 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
68 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
70 OutContext(*new MCContext()),
71 // FIXME: Pass instprinter to streamer.
72 OutStreamer(*createAsmStreamer(OutContext, O, *T,
73 TM.getTargetData()->isLittleEndian(),
74 getVerboseAsm(VDef), 0)),
76 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
78 VerboseAsm = getVerboseAsm(VDef);
81 AsmPrinter::~AsmPrinter() {
82 for (gcp_iterator I = GCMetadataPrinters.begin(),
83 E = GCMetadataPrinters.end(); I != E; ++I)
90 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
91 return TM.getTargetLowering()->getObjFileLowering();
94 /// getCurrentSection() - Return the current section we are emitting to.
95 const MCSection *AsmPrinter::getCurrentSection() const {
96 return OutStreamer.getCurrentSection();
100 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesAll();
102 MachineFunctionPass::getAnalysisUsage(AU);
103 AU.addRequired<GCModuleInfo>();
105 AU.addRequired<MachineLoopInfo>();
108 bool AsmPrinter::doInitialization(Module &M) {
109 // Initialize TargetLoweringObjectFile.
110 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
111 .Initialize(OutContext, TM);
113 Mang = new Mangler(*MAI);
115 // Allow the target to emit any magic that it wants at the start of the file.
116 EmitStartOfAsmFile(M);
118 if (MAI->hasSingleParameterDotFile()) {
119 // Very minimal debug info. It is ignored if we emit actual
120 // debug info. If we don't, this at least helps the user find where
121 // a function came from.
122 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
125 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
126 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
127 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
128 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
129 MP->beginAssembly(O, *this, *MAI);
131 if (!M.getModuleInlineAsm().empty())
132 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
133 << M.getModuleInlineAsm()
134 << '\n' << MAI->getCommentString()
135 << " End of file scope inline assembly\n";
137 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
139 MMI->AnalyzeModule(M);
140 DW = getAnalysisIfAvailable<DwarfWriter>();
142 DW->BeginModule(&M, MMI, O, this, MAI);
147 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
148 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
149 if (!GV->hasInitializer()) // External globals require no code.
152 // Check to see if this is a special global used by LLVM, if so, emit it.
153 if (EmitSpecialLLVMGlobal(GV))
156 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
157 printVisibility(GVSym, GV->getVisibility());
159 if (MAI->hasDotTypeDotSizeDirective())
160 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
162 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
164 const TargetData *TD = TM.getTargetData();
165 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
166 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
168 // Handle common and BSS local symbols (.lcomm).
169 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
170 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
173 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
174 /*PrintType=*/false, GV->getParent());
175 OutStreamer.GetCommentOS() << '\n';
178 // Handle common symbols.
179 if (GVKind.isCommon()) {
181 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
185 // Handle local BSS symbols.
186 if (MAI->hasMachoZeroFillDirective()) {
187 const MCSection *TheSection =
188 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
189 // .zerofill __DATA, __bss, _foo, 400, 5
190 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
194 if (MAI->hasLCOMMDirective()) {
196 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
201 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
203 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
207 const MCSection *TheSection =
208 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
210 // Handle the zerofill directive on darwin, which is a special form of BSS
212 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
214 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
215 // .zerofill __DATA, __common, _foo, 400, 5
216 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
220 OutStreamer.SwitchSection(TheSection);
222 // TODO: Factor into an 'emit linkage' thing that is shared with function
224 switch (GV->getLinkage()) {
225 case GlobalValue::CommonLinkage:
226 case GlobalValue::LinkOnceAnyLinkage:
227 case GlobalValue::LinkOnceODRLinkage:
228 case GlobalValue::WeakAnyLinkage:
229 case GlobalValue::WeakODRLinkage:
230 case GlobalValue::LinkerPrivateLinkage:
231 if (MAI->getWeakDefDirective() != 0) {
233 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
234 // .weak_definition _foo
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
236 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
238 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
239 // .linkonce same_size
243 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
246 case GlobalValue::DLLExportLinkage:
247 case GlobalValue::AppendingLinkage:
248 // FIXME: appending linkage variables should go into a section of
249 // their name or something. For now, just emit them as external.
250 case GlobalValue::ExternalLinkage:
251 // If external or appending, declare as a global symbol.
253 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
255 case GlobalValue::PrivateLinkage:
256 case GlobalValue::InternalLinkage:
259 llvm_unreachable("Unknown linkage type!");
262 EmitAlignment(AlignLog, GV);
264 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
265 /*PrintType=*/false, GV->getParent());
266 OutStreamer.GetCommentOS() << '\n';
268 OutStreamer.EmitLabel(GVSym);
270 EmitGlobalConstant(GV->getInitializer());
272 if (MAI->hasDotTypeDotSizeDirective())
274 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
276 OutStreamer.AddBlankLine();
280 bool AsmPrinter::doFinalization(Module &M) {
281 // Emit global variables.
282 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
284 EmitGlobalVariable(I);
286 // Emit final debug information.
287 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
290 // If the target wants to know about weak references, print them all.
291 if (MAI->getWeakRefDirective()) {
292 // FIXME: This is not lazy, it would be nice to only print weak references
293 // to stuff that is actually used. Note that doing so would require targets
294 // to notice uses in operands (due to constant exprs etc). This should
295 // happen with the MC stuff eventually.
297 // Print out module-level global variables here.
298 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
300 if (!I->hasExternalWeakLinkage()) continue;
301 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
305 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
306 if (!I->hasExternalWeakLinkage()) continue;
307 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
312 if (MAI->getSetDirective()) {
313 OutStreamer.AddBlankLine();
314 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
316 MCSymbol *Name = GetGlobalValueSymbol(I);
318 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
319 MCSymbol *Target = GetGlobalValueSymbol(GV);
321 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
322 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
323 else if (I->hasWeakLinkage())
324 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
326 assert(I->hasLocalLinkage() && "Invalid alias linkage");
328 printVisibility(Name, I->getVisibility());
330 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
334 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
335 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
336 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
337 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
338 MP->finishAssembly(O, *this, *MAI);
340 // If we don't have any trampolines, then we don't require stack memory
341 // to be executable. Some targets have a directive to declare this.
342 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
343 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
344 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
345 OutStreamer.SwitchSection(S);
347 // Allow the target to emit any magic that it wants at the end of the file,
348 // after everything else has gone out.
351 delete Mang; Mang = 0;
354 OutStreamer.Finish();
358 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
359 // Get the function symbol.
360 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
361 IncrementFunctionNumber();
364 LI = &getAnalysis<MachineLoopInfo>();
368 // SectionCPs - Keep track the alignment, constpool entries per Section.
372 SmallVector<unsigned, 4> CPEs;
373 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
377 /// EmitConstantPool - Print to the current output stream assembly
378 /// representations of the constants in the constant pool MCP. This is
379 /// used to print out constants which have been "spilled to memory" by
380 /// the code generator.
382 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
383 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
384 if (CP.empty()) return;
386 // Calculate sections for constant pool entries. We collect entries to go into
387 // the same section together to reduce amount of section switch statements.
388 SmallVector<SectionCPs, 4> CPSections;
389 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
390 const MachineConstantPoolEntry &CPE = CP[i];
391 unsigned Align = CPE.getAlignment();
394 switch (CPE.getRelocationInfo()) {
395 default: llvm_unreachable("Unknown section kind");
396 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
398 Kind = SectionKind::getReadOnlyWithRelLocal();
401 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
402 case 4: Kind = SectionKind::getMergeableConst4(); break;
403 case 8: Kind = SectionKind::getMergeableConst8(); break;
404 case 16: Kind = SectionKind::getMergeableConst16();break;
405 default: Kind = SectionKind::getMergeableConst(); break;
409 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
411 // The number of sections are small, just do a linear search from the
412 // last section to the first.
414 unsigned SecIdx = CPSections.size();
415 while (SecIdx != 0) {
416 if (CPSections[--SecIdx].S == S) {
422 SecIdx = CPSections.size();
423 CPSections.push_back(SectionCPs(S, Align));
426 if (Align > CPSections[SecIdx].Alignment)
427 CPSections[SecIdx].Alignment = Align;
428 CPSections[SecIdx].CPEs.push_back(i);
431 // Now print stuff into the calculated sections.
432 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
433 OutStreamer.SwitchSection(CPSections[i].S);
434 EmitAlignment(Log2_32(CPSections[i].Alignment));
437 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
438 unsigned CPI = CPSections[i].CPEs[j];
439 MachineConstantPoolEntry CPE = CP[CPI];
441 // Emit inter-object padding for alignment.
442 unsigned AlignMask = CPE.getAlignment() - 1;
443 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
444 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
446 const Type *Ty = CPE.getType();
447 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
449 // Emit the label with a comment on it.
451 OutStreamer.GetCommentOS() << "constant pool ";
452 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
453 MF->getFunction()->getParent());
454 OutStreamer.GetCommentOS() << '\n';
456 OutStreamer.EmitLabel(GetCPISymbol(CPI));
458 if (CPE.isMachineConstantPoolEntry())
459 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
461 EmitGlobalConstant(CPE.Val.ConstVal);
466 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
467 /// by the current function to the current output stream.
469 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
470 MachineFunction &MF) {
471 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
472 if (JT.empty()) return;
474 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
476 // Pick the directive to use to print the jump table entries, and switch to
477 // the appropriate section.
478 TargetLowering *LoweringInfo = TM.getTargetLowering();
480 const Function *F = MF.getFunction();
481 bool JTInDiffSection = false;
482 if (F->isWeakForLinker() ||
483 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
484 // In PIC mode, we need to emit the jump table to the same section as the
485 // function body itself, otherwise the label differences won't make sense.
486 // We should also do if the section name is NULL or function is declared in
487 // discardable section.
488 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
491 // Otherwise, drop it in the readonly section.
492 const MCSection *ReadOnlySection =
493 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
494 OutStreamer.SwitchSection(ReadOnlySection);
495 JTInDiffSection = true;
498 EmitAlignment(Log2_32(MJTI->getAlignment()));
500 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
501 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
503 // If this jump table was deleted, ignore it.
504 if (JTBBs.empty()) continue;
506 // For PIC codegen, if possible we want to use the SetDirective to reduce
507 // the number of relocations the assembler will generate for the jump table.
508 // Set directives are all printed before the jump table itself.
509 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
510 if (MAI->getSetDirective() && IsPic)
511 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
512 if (EmittedSets.insert(JTBBs[ii]))
513 printPICJumpTableSetLabel(i, JTBBs[ii]);
515 // On some targets (e.g. Darwin) we want to emit two consequtive labels
516 // before each jump table. The first label is never referenced, but tells
517 // the assembler and linker the extents of the jump table object. The
518 // second label is actually referenced by the code.
519 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
520 OutStreamer.EmitLabel(GetJTISymbol(i, true));
522 OutStreamer.EmitLabel(GetJTISymbol(i));
524 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
525 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
531 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
532 const MachineBasicBlock *MBB,
533 unsigned uid) const {
534 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
536 // Use JumpTableDirective otherwise honor the entry size from the jump table
538 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
539 bool HadJTEntryDirective = JTEntryDirective != NULL;
540 if (!HadJTEntryDirective) {
541 JTEntryDirective = MJTI->getEntrySize() == 4 ?
542 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
545 O << JTEntryDirective << ' ';
547 // If we have emitted set directives for the jump table entries, print
548 // them rather than the entries themselves. If we're emitting PIC, then
549 // emit the table entries as differences between two text section labels.
550 // If we're emitting non-PIC code, then emit the entries as direct
551 // references to the target basic blocks.
553 O << *GetMBBSymbol(MBB->getNumber());
554 } else if (MAI->getSetDirective()) {
555 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
556 << '_' << uid << "_set_" << MBB->getNumber();
558 O << *GetMBBSymbol(MBB->getNumber());
559 // If the arch uses custom Jump Table directives, don't calc relative to
561 if (!HadJTEntryDirective)
562 O << '-' << *GetJTISymbol(uid);
567 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
568 /// special global used by LLVM. If so, emit it and return true, otherwise
569 /// do nothing and return false.
570 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
571 if (GV->getName() == "llvm.used") {
572 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
573 EmitLLVMUsedList(GV->getInitializer());
577 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
578 if (GV->getSection() == "llvm.metadata" ||
579 GV->hasAvailableExternallyLinkage())
582 if (!GV->hasAppendingLinkage()) return false;
584 assert(GV->hasInitializer() && "Not a special LLVM global!");
586 const TargetData *TD = TM.getTargetData();
587 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
588 if (GV->getName() == "llvm.global_ctors") {
589 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
590 EmitAlignment(Align, 0);
591 EmitXXStructorList(GV->getInitializer());
593 if (TM.getRelocationModel() == Reloc::Static &&
594 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
595 StringRef Sym(".constructors_used");
596 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
602 if (GV->getName() == "llvm.global_dtors") {
603 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
604 EmitAlignment(Align, 0);
605 EmitXXStructorList(GV->getInitializer());
607 if (TM.getRelocationModel() == Reloc::Static &&
608 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
609 StringRef Sym(".destructors_used");
610 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
619 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
620 /// global in the specified llvm.used list for which emitUsedDirectiveFor
621 /// is true, as being used with this directive.
622 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
623 // Should be an array of 'i8*'.
624 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
625 if (InitList == 0) return;
627 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
628 const GlobalValue *GV =
629 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
630 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
631 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
636 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
637 /// function pointers, ignoring the init priority.
638 void AsmPrinter::EmitXXStructorList(Constant *List) {
639 // Should be an array of '{ int, void ()* }' structs. The first value is the
640 // init priority, which we ignore.
641 if (!isa<ConstantArray>(List)) return;
642 ConstantArray *InitList = cast<ConstantArray>(List);
643 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
644 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
645 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
647 if (CS->getOperand(1)->isNullValue())
648 return; // Found a null terminator, exit printing.
649 // Emit the function pointer.
650 EmitGlobalConstant(CS->getOperand(1));
654 //===--------------------------------------------------------------------===//
655 // Emission and print routines
658 /// EmitInt8 - Emit a byte directive and value.
660 void AsmPrinter::EmitInt8(int Value) const {
661 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
664 /// EmitInt16 - Emit a short directive and value.
666 void AsmPrinter::EmitInt16(int Value) const {
667 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
670 /// EmitInt32 - Emit a long directive and value.
672 void AsmPrinter::EmitInt32(int Value) const {
673 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
676 /// EmitInt64 - Emit a long long directive and value.
678 void AsmPrinter::EmitInt64(uint64_t Value) const {
679 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
683 /// toOctal - Convert the low order bits of X into an octal digit.
685 static inline char toOctal(int X) {
689 /// printStringChar - Print a char, escaped if necessary.
691 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
694 } else if (C == '\\') {
696 } else if (isprint((unsigned char)C)) {
700 case '\b': O << "\\b"; break;
701 case '\f': O << "\\f"; break;
702 case '\n': O << "\\n"; break;
703 case '\r': O << "\\r"; break;
704 case '\t': O << "\\t"; break;
707 O << toOctal(C >> 6);
708 O << toOctal(C >> 3);
709 O << toOctal(C >> 0);
715 /// EmitFile - Emit a .file directive.
716 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
717 O << "\t.file\t" << Number << " \"";
718 for (unsigned i = 0, N = Name.size(); i < N; ++i)
719 printStringChar(O, Name[i]);
724 //===----------------------------------------------------------------------===//
726 // EmitAlignment - Emit an alignment directive to the specified power of
727 // two boundary. For example, if you pass in 3 here, you will get an 8
728 // byte alignment. If a global value is specified, and if that global has
729 // an explicit alignment requested, it will unconditionally override the
730 // alignment request. However, if ForcedAlignBits is specified, this value
731 // has final say: the ultimate alignment will be the max of ForcedAlignBits
732 // and the alignment computed with NumBits and the global.
736 // if (GV && GV->hasalignment) Align = GV->getalignment();
737 // Align = std::max(Align, ForcedAlignBits);
739 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
740 unsigned ForcedAlignBits,
741 bool UseFillExpr) const {
742 if (GV && GV->getAlignment())
743 NumBits = Log2_32(GV->getAlignment());
744 NumBits = std::max(NumBits, ForcedAlignBits);
746 if (NumBits == 0) return; // No need to emit alignment.
748 unsigned FillValue = 0;
749 if (getCurrentSection()->getKind().isText())
750 FillValue = MAI->getTextAlignFillValue();
752 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
755 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
757 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
758 MCContext &Ctx = AP.OutContext;
760 if (CV->isNullValue() || isa<UndefValue>(CV))
761 return MCConstantExpr::Create(0, Ctx);
763 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
764 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
766 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
767 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
768 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
769 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
771 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
773 llvm_unreachable("Unknown constant value to lower!");
774 return MCConstantExpr::Create(0, Ctx);
777 switch (CE->getOpcode()) {
778 case Instruction::ZExt:
779 case Instruction::SExt:
780 case Instruction::FPTrunc:
781 case Instruction::FPExt:
782 case Instruction::UIToFP:
783 case Instruction::SIToFP:
784 case Instruction::FPToUI:
785 case Instruction::FPToSI:
786 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
787 case Instruction::GetElementPtr: {
788 const TargetData &TD = *AP.TM.getTargetData();
789 // Generate a symbolic expression for the byte address
790 const Constant *PtrVal = CE->getOperand(0);
791 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
792 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
795 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
799 // Truncate/sext the offset to the pointer size.
800 if (TD.getPointerSizeInBits() != 64) {
801 int SExtAmount = 64-TD.getPointerSizeInBits();
802 Offset = (Offset << SExtAmount) >> SExtAmount;
805 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
809 case Instruction::Trunc:
810 // We emit the value and depend on the assembler to truncate the generated
811 // expression properly. This is important for differences between
812 // blockaddress labels. Since the two labels are in the same function, it
813 // is reasonable to treat their delta as a 32-bit value.
815 case Instruction::BitCast:
816 return LowerConstant(CE->getOperand(0), AP);
818 case Instruction::IntToPtr: {
819 const TargetData &TD = *AP.TM.getTargetData();
820 // Handle casts to pointers by changing them into casts to the appropriate
821 // integer type. This promotes constant folding and simplifies this code.
822 Constant *Op = CE->getOperand(0);
823 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
825 return LowerConstant(Op, AP);
828 case Instruction::PtrToInt: {
829 const TargetData &TD = *AP.TM.getTargetData();
830 // Support only foldable casts to/from pointers that can be eliminated by
831 // changing the pointer to the appropriately sized integer type.
832 Constant *Op = CE->getOperand(0);
833 const Type *Ty = CE->getType();
835 const MCExpr *OpExpr = LowerConstant(Op, AP);
837 // We can emit the pointer value into this slot if the slot is an
838 // integer slot equal to the size of the pointer.
839 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
842 // Otherwise the pointer is smaller than the resultant integer, mask off
843 // the high bits so we are sure to get a proper truncation if the input is
845 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
846 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
847 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
850 case Instruction::Add:
851 case Instruction::Sub:
852 case Instruction::And:
853 case Instruction::Or:
854 case Instruction::Xor: {
855 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
856 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
857 switch (CE->getOpcode()) {
858 default: llvm_unreachable("Unknown binary operator constant cast expr");
859 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
860 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
861 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
862 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
863 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
869 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
871 if (AddrSpace != 0 || !CA->isString()) {
872 // Not a string. Print the values in successive locations
873 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
874 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
878 // Otherwise, it can be emitted as .ascii.
879 SmallVector<char, 128> TmpVec;
880 TmpVec.reserve(CA->getNumOperands());
881 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
882 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
884 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
887 static void EmitGlobalConstantVector(const ConstantVector *CV,
888 unsigned AddrSpace, AsmPrinter &AP) {
889 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
890 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
893 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
894 unsigned AddrSpace, AsmPrinter &AP) {
895 // Print the fields in successive locations. Pad to align if needed!
896 const TargetData *TD = AP.TM.getTargetData();
897 unsigned Size = TD->getTypeAllocSize(CS->getType());
898 const StructLayout *Layout = TD->getStructLayout(CS->getType());
899 uint64_t SizeSoFar = 0;
900 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
901 const Constant *Field = CS->getOperand(i);
903 // Check if padding is needed and insert one or more 0s.
904 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
905 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
906 - Layout->getElementOffset(i)) - FieldSize;
907 SizeSoFar += FieldSize + PadSize;
909 // Now print the actual field value.
910 AP.EmitGlobalConstant(Field, AddrSpace);
912 // Insert padding - this may include padding to increase the size of the
913 // current field up to the ABI size (if the struct is not packed) as well
914 // as padding to ensure that the next field starts at the right offset.
915 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
917 assert(SizeSoFar == Layout->getSizeInBytes() &&
918 "Layout of constant struct may be incorrect!");
921 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
923 // FP Constants are printed as integer constants to avoid losing
925 if (CFP->getType()->isDoubleTy()) {
927 double Val = CFP->getValueAPF().convertToDouble();
928 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
931 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
932 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
936 if (CFP->getType()->isFloatTy()) {
938 float Val = CFP->getValueAPF().convertToFloat();
939 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
941 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
942 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
946 if (CFP->getType()->isX86_FP80Ty()) {
947 // all long double variants are printed as hex
948 // api needed to prevent premature destruction
949 APInt API = CFP->getValueAPF().bitcastToAPInt();
950 const uint64_t *p = API.getRawData();
952 // Convert to double so we can print the approximate val as a comment.
953 APFloat DoubleVal = CFP->getValueAPF();
955 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
957 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
958 << DoubleVal.convertToDouble() << '\n';
961 if (AP.TM.getTargetData()->isBigEndian()) {
962 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
963 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
965 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
966 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
969 // Emit the tail padding for the long double.
970 const TargetData &TD = *AP.TM.getTargetData();
971 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
972 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
976 assert(CFP->getType()->isPPC_FP128Ty() &&
977 "Floating point constant type not handled");
978 // All long double variants are printed as hex api needed to prevent
979 // premature destruction.
980 APInt API = CFP->getValueAPF().bitcastToAPInt();
981 const uint64_t *p = API.getRawData();
982 if (AP.TM.getTargetData()->isBigEndian()) {
983 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
984 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
986 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
987 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
991 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
992 unsigned AddrSpace, AsmPrinter &AP) {
993 const TargetData *TD = AP.TM.getTargetData();
994 unsigned BitWidth = CI->getBitWidth();
995 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
997 // We don't expect assemblers to support integer data directives
998 // for more than 64 bits, so we emit the data in at most 64-bit
999 // quantities at a time.
1000 const uint64_t *RawData = CI->getValue().getRawData();
1001 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1002 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1003 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1007 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1008 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1009 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1010 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1011 return OutStreamer.EmitZeros(Size, AddrSpace);
1014 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1015 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1022 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1023 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1026 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1031 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1032 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1034 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1035 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1037 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1038 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1040 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1041 return EmitGlobalConstantVector(V, AddrSpace, *this);
1043 if (isa<ConstantPointerNull>(CV)) {
1044 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1045 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1049 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1050 // thread the streamer with EmitValue.
1051 OutStreamer.EmitValue(LowerConstant(CV, *this),
1052 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1056 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1057 // Target doesn't support this yet!
1058 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1061 /// PrintSpecial - Print information related to the specified machine instr
1062 /// that is independent of the operand, and may be independent of the instr
1063 /// itself. This can be useful for portably encoding the comment character
1064 /// or other bits of target-specific knowledge into the asmstrings. The
1065 /// syntax used is ${:comment}. Targets can override this to add support
1066 /// for their own strange codes.
1067 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1068 if (!strcmp(Code, "private")) {
1069 O << MAI->getPrivateGlobalPrefix();
1070 } else if (!strcmp(Code, "comment")) {
1072 O << MAI->getCommentString();
1073 } else if (!strcmp(Code, "uid")) {
1074 // Comparing the address of MI isn't sufficient, because machineinstrs may
1075 // be allocated to the same address across functions.
1076 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1078 // If this is a new LastFn instruction, bump the counter.
1079 if (LastMI != MI || LastFn != ThisF) {
1087 raw_string_ostream Msg(msg);
1088 Msg << "Unknown special formatter '" << Code
1089 << "' for machine instr: " << *MI;
1090 llvm_report_error(Msg.str());
1094 /// processDebugLoc - Processes the debug information of each machine
1095 /// instruction's DebugLoc.
1096 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1097 bool BeforePrintingInsn) {
1098 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1099 || !DW->ShouldEmitDwarfDebug())
1101 DebugLoc DL = MI->getDebugLoc();
1104 DILocation CurDLT = MF->getDILocation(DL);
1105 if (CurDLT.getScope().isNull())
1108 if (!BeforePrintingInsn) {
1109 // After printing instruction
1111 } else if (CurDLT.getNode() != PrevDLT) {
1112 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1113 CurDLT.getColumnNumber(),
1114 CurDLT.getScope().getNode());
1117 DW->BeginScope(MI, L);
1118 PrevDLT = CurDLT.getNode();
1123 /// printInlineAsm - This method formats and prints the specified machine
1124 /// instruction that is an inline asm.
1125 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1126 unsigned NumOperands = MI->getNumOperands();
1128 // Count the number of register definitions.
1129 unsigned NumDefs = 0;
1130 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1132 assert(NumDefs != NumOperands-1 && "No asm string?");
1134 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1136 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1137 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1141 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1142 // These are useful to see where empty asm's wound up.
1143 if (AsmStr[0] == 0) {
1144 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1145 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1149 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1151 // The variant of the current asmprinter.
1152 int AsmPrinterVariant = MAI->getAssemblerDialect();
1154 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1155 const char *LastEmitted = AsmStr; // One past the last character emitted.
1157 while (*LastEmitted) {
1158 switch (*LastEmitted) {
1160 // Not a special case, emit the string section literally.
1161 const char *LiteralEnd = LastEmitted+1;
1162 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1163 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1165 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1166 O.write(LastEmitted, LiteralEnd-LastEmitted);
1167 LastEmitted = LiteralEnd;
1171 ++LastEmitted; // Consume newline character.
1172 O << '\n'; // Indent code with newline.
1175 ++LastEmitted; // Consume '$' character.
1179 switch (*LastEmitted) {
1180 default: Done = false; break;
1181 case '$': // $$ -> $
1182 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1184 ++LastEmitted; // Consume second '$' character.
1186 case '(': // $( -> same as GCC's { character.
1187 ++LastEmitted; // Consume '(' character.
1188 if (CurVariant != -1) {
1189 llvm_report_error("Nested variants found in inline asm string: '"
1190 + std::string(AsmStr) + "'");
1192 CurVariant = 0; // We're in the first variant now.
1195 ++LastEmitted; // consume '|' character.
1196 if (CurVariant == -1)
1197 O << '|'; // this is gcc's behavior for | outside a variant
1199 ++CurVariant; // We're in the next variant.
1201 case ')': // $) -> same as GCC's } char.
1202 ++LastEmitted; // consume ')' character.
1203 if (CurVariant == -1)
1204 O << '}'; // this is gcc's behavior for } outside a variant
1211 bool HasCurlyBraces = false;
1212 if (*LastEmitted == '{') { // ${variable}
1213 ++LastEmitted; // Consume '{' character.
1214 HasCurlyBraces = true;
1217 // If we have ${:foo}, then this is not a real operand reference, it is a
1218 // "magic" string reference, just like in .td files. Arrange to call
1220 if (HasCurlyBraces && *LastEmitted == ':') {
1222 const char *StrStart = LastEmitted;
1223 const char *StrEnd = strchr(StrStart, '}');
1225 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1226 + std::string(AsmStr) + "'");
1229 std::string Val(StrStart, StrEnd);
1230 PrintSpecial(MI, Val.c_str());
1231 LastEmitted = StrEnd+1;
1235 const char *IDStart = LastEmitted;
1238 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1239 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1240 llvm_report_error("Bad $ operand number in inline asm string: '"
1241 + std::string(AsmStr) + "'");
1243 LastEmitted = IDEnd;
1245 char Modifier[2] = { 0, 0 };
1247 if (HasCurlyBraces) {
1248 // If we have curly braces, check for a modifier character. This
1249 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1250 if (*LastEmitted == ':') {
1251 ++LastEmitted; // Consume ':' character.
1252 if (*LastEmitted == 0) {
1253 llvm_report_error("Bad ${:} expression in inline asm string: '"
1254 + std::string(AsmStr) + "'");
1257 Modifier[0] = *LastEmitted;
1258 ++LastEmitted; // Consume modifier character.
1261 if (*LastEmitted != '}') {
1262 llvm_report_error("Bad ${} expression in inline asm string: '"
1263 + std::string(AsmStr) + "'");
1265 ++LastEmitted; // Consume '}' character.
1268 if ((unsigned)Val >= NumOperands-1) {
1269 llvm_report_error("Invalid $ operand number in inline asm string: '"
1270 + std::string(AsmStr) + "'");
1273 // Okay, we finally have a value number. Ask the target to print this
1275 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1280 // Scan to find the machine operand number for the operand.
1281 for (; Val; --Val) {
1282 if (OpNo >= MI->getNumOperands()) break;
1283 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1284 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1287 if (OpNo >= MI->getNumOperands()) {
1290 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1291 ++OpNo; // Skip over the ID number.
1293 if (Modifier[0] == 'l') // labels are target independent
1294 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1296 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1297 if ((OpFlags & 7) == 4) {
1298 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1299 Modifier[0] ? Modifier : 0);
1301 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1302 Modifier[0] ? Modifier : 0);
1308 raw_string_ostream Msg(msg);
1309 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1311 llvm_report_error(Msg.str());
1318 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1321 /// printImplicitDef - This method prints the specified machine instruction
1322 /// that is an implicit def.
1323 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1324 if (!VerboseAsm) return;
1325 O.PadToColumn(MAI->getCommentColumn());
1326 O << MAI->getCommentString() << " implicit-def: "
1327 << TRI->getName(MI->getOperand(0).getReg());
1330 void AsmPrinter::printKill(const MachineInstr *MI) const {
1331 if (!VerboseAsm) return;
1332 O.PadToColumn(MAI->getCommentColumn());
1333 O << MAI->getCommentString() << " kill:";
1334 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1335 const MachineOperand &op = MI->getOperand(n);
1336 assert(op.isReg() && "KILL instruction must have only register operands");
1337 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1341 /// printLabel - This method prints a local label used by debug and
1342 /// exception handling tables.
1343 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1344 printLabel(MI->getOperand(0).getImm());
1347 void AsmPrinter::printLabel(unsigned Id) const {
1348 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1351 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1352 /// instruction, using the specified assembler variant. Targets should
1353 /// override this to format as appropriate.
1354 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1355 unsigned AsmVariant, const char *ExtraCode) {
1356 // Target doesn't support this yet!
1360 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1361 unsigned AsmVariant,
1362 const char *ExtraCode) {
1363 // Target doesn't support this yet!
1367 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1368 const char *Suffix) const {
1369 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1372 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1373 const BasicBlock *BB,
1374 const char *Suffix) const {
1375 assert(BB->hasName() &&
1376 "Address of anonymous basic block not supported yet!");
1378 // This code must use the function name itself, and not the function number,
1379 // since it must be possible to generate the label name from within other
1381 SmallString<60> FnName;
1382 Mang->getNameWithPrefix(FnName, F, false);
1384 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1385 SmallString<60> NameResult;
1386 Mang->getNameWithPrefix(NameResult,
1387 StringRef("BA") + Twine((unsigned)FnName.size()) +
1388 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1391 return OutContext.GetOrCreateSymbol(NameResult.str());
1394 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1395 SmallString<60> Name;
1396 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1397 << getFunctionNumber() << '_' << MBBID;
1398 return OutContext.GetOrCreateSymbol(Name.str());
1401 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1402 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1403 SmallString<60> Name;
1404 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1405 << getFunctionNumber() << '_' << CPID;
1406 return OutContext.GetOrCreateSymbol(Name.str());
1409 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1410 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1411 const char *Prefix = isLinkerPrivate ? MAI->getLinkerPrivateGlobalPrefix() :
1412 MAI->getPrivateGlobalPrefix();
1413 SmallString<60> Name;
1414 raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_'
1416 return OutContext.GetOrCreateSymbol(Name.str());
1419 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1421 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1422 SmallString<60> NameStr;
1423 Mang->getNameWithPrefix(NameStr, GV, false);
1424 return OutContext.GetOrCreateSymbol(NameStr.str());
1427 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1428 /// global value name as its base, with the specified suffix, and where the
1429 /// symbol is forced to have private linkage if ForcePrivate is true.
1430 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1432 bool ForcePrivate) const {
1433 SmallString<60> NameStr;
1434 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1435 NameStr.append(Suffix.begin(), Suffix.end());
1436 return OutContext.GetOrCreateSymbol(NameStr.str());
1439 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1441 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1442 SmallString<60> NameStr;
1443 Mang->getNameWithPrefix(NameStr, Sym);
1444 return OutContext.GetOrCreateSymbol(NameStr.str());
1449 /// PrintParentLoopComment - Print comments about parent loops of this one.
1450 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1451 unsigned FunctionNumber) {
1452 if (Loop == 0) return;
1453 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1454 OS.indent(Loop->getLoopDepth()*2)
1455 << "Parent Loop BB" << FunctionNumber << "_"
1456 << Loop->getHeader()->getNumber()
1457 << " Depth=" << Loop->getLoopDepth() << '\n';
1461 /// PrintChildLoopComment - Print comments about child loops within
1462 /// the loop for this basic block, with nesting.
1463 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1464 unsigned FunctionNumber) {
1465 // Add child loop information
1466 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1467 OS.indent((*CL)->getLoopDepth()*2)
1468 << "Child Loop BB" << FunctionNumber << "_"
1469 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1471 PrintChildLoopComment(OS, *CL, FunctionNumber);
1475 /// EmitComments - Pretty-print comments for basic blocks.
1476 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1477 const MachineLoopInfo *LI,
1478 const AsmPrinter &AP) {
1479 // Add loop depth information
1480 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1481 if (Loop == 0) return;
1483 MachineBasicBlock *Header = Loop->getHeader();
1484 assert(Header && "No header for loop");
1486 // If this block is not a loop header, just print out what is the loop header
1488 if (Header != &MBB) {
1489 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1490 Twine(AP.getFunctionNumber())+"_" +
1491 Twine(Loop->getHeader()->getNumber())+
1492 " Depth="+Twine(Loop->getLoopDepth()));
1496 // Otherwise, it is a loop header. Print out information about child and
1498 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1500 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1503 OS.indent(Loop->getLoopDepth()*2-2);
1508 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1510 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1514 /// EmitBasicBlockStart - This method prints the label for the specified
1515 /// MachineBasicBlock, an alignment (if present) and a comment describing
1516 /// it if appropriate.
1517 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1518 // Emit an alignment directive for this block, if needed.
1519 if (unsigned Align = MBB->getAlignment())
1520 EmitAlignment(Log2_32(Align));
1522 // If the block has its address taken, emit a special label to satisfy
1523 // references to the block. This is done so that we don't need to
1524 // remember the number of this label, and so that we can make
1525 // forward references to labels without knowing what their numbers
1527 if (MBB->hasAddressTaken()) {
1528 const BasicBlock *BB = MBB->getBasicBlock();
1530 OutStreamer.AddComment("Address Taken");
1531 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1534 // Print the main label for the block.
1535 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1537 // NOTE: Want this comment at start of line.
1538 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1539 if (const BasicBlock *BB = MBB->getBasicBlock())
1541 OutStreamer.AddComment("%" + BB->getName());
1543 PrintBasicBlockLoopComments(*MBB, LI, *this);
1544 OutStreamer.AddBlankLine();
1548 if (const BasicBlock *BB = MBB->getBasicBlock())
1550 OutStreamer.AddComment("%" + BB->getName());
1551 PrintBasicBlockLoopComments(*MBB, LI, *this);
1554 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1558 /// printPICJumpTableSetLabel - This method prints a set label for the
1559 /// specified MachineBasicBlock for a jumptable entry.
1560 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1561 const MachineBasicBlock *MBB) const {
1562 if (!MAI->getSetDirective())
1565 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1566 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1567 << *GetMBBSymbol(MBB->getNumber())
1568 << '-' << *GetJTISymbol(uid) << '\n';
1571 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1572 const MachineBasicBlock *MBB) const {
1573 if (!MAI->getSetDirective())
1576 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1577 << getFunctionNumber() << '_' << uid << '_' << uid2
1578 << "_set_" << MBB->getNumber() << ','
1579 << *GetMBBSymbol(MBB->getNumber())
1580 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1581 << '_' << uid << '_' << uid2 << '\n';
1584 void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1585 MCSymbolAttr Attr = MCSA_Invalid;
1587 switch (Visibility) {
1589 case GlobalValue::HiddenVisibility:
1590 Attr = MAI->getHiddenVisibilityAttr();
1592 case GlobalValue::ProtectedVisibility:
1593 Attr = MAI->getProtectedVisibilityAttr();
1597 if (Attr != MCSA_Invalid)
1598 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1601 void AsmPrinter::printOffset(int64_t Offset) const {
1604 else if (Offset < 0)
1608 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1609 if (!S->usesMetadata())
1612 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1613 if (GCPI != GCMetadataPrinters.end())
1614 return GCPI->second;
1616 const char *Name = S->getName().c_str();
1618 for (GCMetadataPrinterRegistry::iterator
1619 I = GCMetadataPrinterRegistry::begin(),
1620 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1621 if (strcmp(Name, I->getName()) == 0) {
1622 GCMetadataPrinter *GMP = I->instantiate();
1624 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1628 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1632 /// EmitComments - Pretty-print comments for instructions
1633 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1637 bool Newline = false;
1639 if (!MI.getDebugLoc().isUnknown()) {
1640 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1642 // Print source line info.
1643 O.PadToColumn(MAI->getCommentColumn());
1644 O << MAI->getCommentString() << ' ';
1645 DIScope Scope = DLT.getScope();
1646 // Omit the directory, because it's likely to be long and uninteresting.
1647 if (!Scope.isNull())
1648 O << Scope.getFilename();
1651 O << ':' << DLT.getLineNumber();
1652 if (DLT.getColumnNumber() != 0)
1653 O << ':' << DLT.getColumnNumber();
1657 // Check for spills and reloads
1660 const MachineFrameInfo *FrameInfo =
1661 MI.getParent()->getParent()->getFrameInfo();
1663 // We assume a single instruction only has a spill or reload, not
1665 const MachineMemOperand *MMO;
1666 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1667 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1668 MMO = *MI.memoperands_begin();
1669 if (Newline) O << '\n';
1670 O.PadToColumn(MAI->getCommentColumn());
1671 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1675 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1676 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1677 if (Newline) O << '\n';
1678 O.PadToColumn(MAI->getCommentColumn());
1679 O << MAI->getCommentString() << ' '
1680 << MMO->getSize() << "-byte Folded Reload";
1684 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1685 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1686 MMO = *MI.memoperands_begin();
1687 if (Newline) O << '\n';
1688 O.PadToColumn(MAI->getCommentColumn());
1689 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1693 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1694 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1695 if (Newline) O << '\n';
1696 O.PadToColumn(MAI->getCommentColumn());
1697 O << MAI->getCommentString() << ' '
1698 << MMO->getSize() << "-byte Folded Spill";
1703 // Check for spill-induced copies
1704 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1705 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1706 SrcSubIdx, DstSubIdx)) {
1707 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1708 if (Newline) O << '\n';
1709 O.PadToColumn(MAI->getCommentColumn());
1710 O << MAI->getCommentString() << " Reload Reuse";