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/MCInst.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
49 static cl::opt<cl::boolOrDefault>
50 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
51 cl::init(cl::BOU_UNSET));
53 static bool getVerboseAsm(bool VDef) {
56 case cl::BOU_UNSET: return VDef;
57 case cl::BOU_TRUE: return true;
58 case cl::BOU_FALSE: return false;
62 char AsmPrinter::ID = 0;
63 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
64 const MCAsmInfo *T, bool VDef)
65 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
66 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
68 OutContext(*new MCContext()),
69 // FIXME: Pass instprinter to streamer.
70 OutStreamer(*createAsmStreamer(OutContext, O, *T,
71 TM.getTargetData()->isLittleEndian(),
72 getVerboseAsm(VDef), 0)),
74 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
76 VerboseAsm = getVerboseAsm(VDef);
79 AsmPrinter::~AsmPrinter() {
80 for (gcp_iterator I = GCMetadataPrinters.begin(),
81 E = GCMetadataPrinters.end(); I != E; ++I)
88 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
89 return TM.getTargetLowering()->getObjFileLowering();
92 /// getCurrentSection() - Return the current section we are emitting to.
93 const MCSection *AsmPrinter::getCurrentSection() const {
94 return OutStreamer.getCurrentSection();
98 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100 MachineFunctionPass::getAnalysisUsage(AU);
101 AU.addRequired<GCModuleInfo>();
103 AU.addRequired<MachineLoopInfo>();
106 bool AsmPrinter::doInitialization(Module &M) {
107 // Initialize TargetLoweringObjectFile.
108 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
109 .Initialize(OutContext, TM);
111 Mang = new Mangler(*MAI);
113 // Allow the target to emit any magic that it wants at the start of the file.
114 EmitStartOfAsmFile(M);
116 if (MAI->hasSingleParameterDotFile()) {
117 /* Very minimal debug info. It is ignored if we emit actual
118 debug info. If we don't, this at least helps the user find where
119 a function came from. */
120 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
123 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
124 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
125 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
126 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
127 MP->beginAssembly(O, *this, *MAI);
129 if (!M.getModuleInlineAsm().empty())
130 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
131 << M.getModuleInlineAsm()
132 << '\n' << MAI->getCommentString()
133 << " End of file scope inline assembly\n";
135 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137 MMI->AnalyzeModule(M);
138 DW = getAnalysisIfAvailable<DwarfWriter>();
140 DW->BeginModule(&M, MMI, O, this, MAI);
145 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
146 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
147 if (!GV->hasInitializer()) // External globals require no code.
150 // Check to see if this is a special global used by LLVM, if so, emit it.
151 if (EmitSpecialLLVMGlobal(GV))
154 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
155 printVisibility(GVSym, GV->getVisibility());
157 if (MAI->hasDotTypeDotSizeDirective()) {
158 O << "\t.type\t" << *GVSym;
159 if (MAI->getCommentString()[0] != '@')
165 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
167 const TargetData *TD = TM.getTargetData();
168 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
169 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
171 // Handle common and BSS local symbols (.lcomm).
172 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
173 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
176 O.PadToColumn(MAI->getCommentColumn());
177 O << MAI->getCommentString() << ' ';
178 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
182 // Handle common symbols.
183 if (GVKind.isCommon()) {
185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
189 // Handle local BSS symbols.
190 if (MAI->hasMachoZeroFillDirective()) {
191 const MCSection *TheSection =
192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193 // .zerofill __DATA, __bss, _foo, 400, 5
194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
198 if (const char *LComm = MAI->getLCOMMDirective()) {
200 O << LComm << *GVSym << ',' << Size;
206 O << "\t.local\t" << *GVSym << '\n';
208 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
212 const MCSection *TheSection =
213 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
215 // Handle the zerofill directive on darwin, which is a special form of BSS
217 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
219 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
220 // .zerofill __DATA, __common, _foo, 400, 5
221 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
225 OutStreamer.SwitchSection(TheSection);
227 // TODO: Factor into an 'emit linkage' thing that is shared with function
229 switch (GV->getLinkage()) {
230 case GlobalValue::CommonLinkage:
231 case GlobalValue::LinkOnceAnyLinkage:
232 case GlobalValue::LinkOnceODRLinkage:
233 case GlobalValue::WeakAnyLinkage:
234 case GlobalValue::WeakODRLinkage:
235 case GlobalValue::LinkerPrivateLinkage:
236 if (MAI->getWeakDefDirective() != 0) {
238 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
239 // .weak_definition _foo
240 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
241 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
243 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
244 // .linkonce same_size
248 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
251 case GlobalValue::DLLExportLinkage:
252 case GlobalValue::AppendingLinkage:
253 // FIXME: appending linkage variables should go into a section of
254 // their name or something. For now, just emit them as external.
255 case GlobalValue::ExternalLinkage:
256 // If external or appending, declare as a global symbol.
258 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
260 case GlobalValue::PrivateLinkage:
261 case GlobalValue::InternalLinkage:
264 llvm_unreachable("Unknown linkage type!");
267 EmitAlignment(AlignLog, GV);
269 O.PadToColumn(MAI->getCommentColumn());
270 O << MAI->getCommentString() << ' ';
271 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
274 OutStreamer.EmitLabel(GVSym);
276 EmitGlobalConstant(GV->getInitializer());
278 if (MAI->hasDotTypeDotSizeDirective())
279 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
283 bool AsmPrinter::doFinalization(Module &M) {
284 // Emit global variables.
285 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
287 EmitGlobalVariable(I);
289 // Emit final debug information.
290 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
293 // If the target wants to know about weak references, print them all.
294 if (MAI->getWeakRefDirective()) {
295 // FIXME: This is not lazy, it would be nice to only print weak references
296 // to stuff that is actually used. Note that doing so would require targets
297 // to notice uses in operands (due to constant exprs etc). This should
298 // happen with the MC stuff eventually.
300 // Print out module-level global variables here.
301 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
303 if (!I->hasExternalWeakLinkage()) continue;
304 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
307 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
308 if (!I->hasExternalWeakLinkage()) continue;
309 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
313 if (MAI->getSetDirective()) {
315 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
317 MCSymbol *Name = GetGlobalValueSymbol(I);
319 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
320 MCSymbol *Target = GetGlobalValueSymbol(GV);
322 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
323 O << "\t.globl\t" << *Name << '\n';
324 else if (I->hasWeakLinkage())
325 O << MAI->getWeakRefDirective() << *Name << '\n';
327 assert(I->hasLocalLinkage() && "Invalid alias linkage");
329 printVisibility(Name, I->getVisibility());
331 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
335 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
336 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
337 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
338 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
339 MP->finishAssembly(O, *this, *MAI);
341 // If we don't have any trampolines, then we don't require stack memory
342 // to be executable. Some targets have a directive to declare this.
343 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
344 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
345 if (MAI->getNonexecutableStackDirective())
346 O << MAI->getNonexecutableStackDirective() << '\n';
349 // Allow the target to emit any magic that it wants at the end of the file,
350 // after everything else has gone out.
353 delete Mang; Mang = 0;
356 OutStreamer.Finish();
360 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
361 // Get the function symbol.
362 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
363 IncrementFunctionNumber();
366 LI = &getAnalysis<MachineLoopInfo>();
370 // SectionCPs - Keep track the alignment, constpool entries per Section.
374 SmallVector<unsigned, 4> CPEs;
375 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
379 /// EmitConstantPool - Print to the current output stream assembly
380 /// representations of the constants in the constant pool MCP. This is
381 /// used to print out constants which have been "spilled to memory" by
382 /// the code generator.
384 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
385 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
386 if (CP.empty()) return;
388 // Calculate sections for constant pool entries. We collect entries to go into
389 // the same section together to reduce amount of section switch statements.
390 SmallVector<SectionCPs, 4> CPSections;
391 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
392 const MachineConstantPoolEntry &CPE = CP[i];
393 unsigned Align = CPE.getAlignment();
396 switch (CPE.getRelocationInfo()) {
397 default: llvm_unreachable("Unknown section kind");
398 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
400 Kind = SectionKind::getReadOnlyWithRelLocal();
403 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
404 case 4: Kind = SectionKind::getMergeableConst4(); break;
405 case 8: Kind = SectionKind::getMergeableConst8(); break;
406 case 16: Kind = SectionKind::getMergeableConst16();break;
407 default: Kind = SectionKind::getMergeableConst(); break;
411 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
413 // The number of sections are small, just do a linear search from the
414 // last section to the first.
416 unsigned SecIdx = CPSections.size();
417 while (SecIdx != 0) {
418 if (CPSections[--SecIdx].S == S) {
424 SecIdx = CPSections.size();
425 CPSections.push_back(SectionCPs(S, Align));
428 if (Align > CPSections[SecIdx].Alignment)
429 CPSections[SecIdx].Alignment = Align;
430 CPSections[SecIdx].CPEs.push_back(i);
433 // Now print stuff into the calculated sections.
434 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
435 OutStreamer.SwitchSection(CPSections[i].S);
436 EmitAlignment(Log2_32(CPSections[i].Alignment));
439 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
440 unsigned CPI = CPSections[i].CPEs[j];
441 MachineConstantPoolEntry CPE = CP[CPI];
443 // Emit inter-object padding for alignment.
444 unsigned AlignMask = CPE.getAlignment() - 1;
445 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
446 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
448 const Type *Ty = CPE.getType();
449 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
451 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
454 O.PadToColumn(MAI->getCommentColumn());
455 O << MAI->getCommentString() << " constant ";
456 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
459 if (CPE.isMachineConstantPoolEntry())
460 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
462 EmitGlobalConstant(CPE.Val.ConstVal);
467 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
468 /// by the current function to the current output stream.
470 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
471 MachineFunction &MF) {
472 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
473 if (JT.empty()) return;
475 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
477 // Pick the directive to use to print the jump table entries, and switch to
478 // the appropriate section.
479 TargetLowering *LoweringInfo = TM.getTargetLowering();
481 const Function *F = MF.getFunction();
482 bool JTInDiffSection = false;
483 if (F->isWeakForLinker() ||
484 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
485 // In PIC mode, we need to emit the jump table to the same section as the
486 // function body itself, otherwise the label differences won't make sense.
487 // We should also do if the section name is NULL or function is declared in
488 // discardable section.
489 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
492 // Otherwise, drop it in the readonly section.
493 const MCSection *ReadOnlySection =
494 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
495 OutStreamer.SwitchSection(ReadOnlySection);
496 JTInDiffSection = true;
499 EmitAlignment(Log2_32(MJTI->getAlignment()));
501 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
502 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
504 // If this jump table was deleted, ignore it.
505 if (JTBBs.empty()) continue;
507 // For PIC codegen, if possible we want to use the SetDirective to reduce
508 // the number of relocations the assembler will generate for the jump table.
509 // Set directives are all printed before the jump table itself.
510 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
511 if (MAI->getSetDirective() && IsPic)
512 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
513 if (EmittedSets.insert(JTBBs[ii]))
514 printPICJumpTableSetLabel(i, JTBBs[ii]);
516 // On some targets (e.g. Darwin) we want to emit two consequtive labels
517 // before each jump table. The first label is never referenced, but tells
518 // the assembler and linker the extents of the jump table object. The
519 // second label is actually referenced by the code.
520 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
521 O << MAI->getLinkerPrivateGlobalPrefix()
522 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
525 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
526 << '_' << i << ":\n";
528 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
529 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
535 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
536 const MachineBasicBlock *MBB,
537 unsigned uid) const {
538 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
540 // Use JumpTableDirective otherwise honor the entry size from the jump table
542 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
543 bool HadJTEntryDirective = JTEntryDirective != NULL;
544 if (!HadJTEntryDirective) {
545 JTEntryDirective = MJTI->getEntrySize() == 4 ?
546 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
549 O << JTEntryDirective << ' ';
551 // If we have emitted set directives for the jump table entries, print
552 // them rather than the entries themselves. If we're emitting PIC, then
553 // emit the table entries as differences between two text section labels.
554 // If we're emitting non-PIC code, then emit the entries as direct
555 // references to the target basic blocks.
557 O << *GetMBBSymbol(MBB->getNumber());
558 } else if (MAI->getSetDirective()) {
559 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
560 << '_' << uid << "_set_" << MBB->getNumber();
562 O << *GetMBBSymbol(MBB->getNumber());
563 // If the arch uses custom Jump Table directives, don't calc relative to
565 if (!HadJTEntryDirective)
566 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
567 << getFunctionNumber() << '_' << uid;
572 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
573 /// special global used by LLVM. If so, emit it and return true, otherwise
574 /// do nothing and return false.
575 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
576 if (GV->getName() == "llvm.used") {
577 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
578 EmitLLVMUsedList(GV->getInitializer());
582 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
583 if (GV->getSection() == "llvm.metadata" ||
584 GV->hasAvailableExternallyLinkage())
587 if (!GV->hasAppendingLinkage()) return false;
589 assert(GV->hasInitializer() && "Not a special LLVM global!");
591 const TargetData *TD = TM.getTargetData();
592 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
593 if (GV->getName() == "llvm.global_ctors") {
594 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
595 EmitAlignment(Align, 0);
596 EmitXXStructorList(GV->getInitializer());
598 if (TM.getRelocationModel() == Reloc::Static &&
599 MAI->hasStaticCtorDtorReferenceInStaticMode())
600 O << ".reference .constructors_used\n";
604 if (GV->getName() == "llvm.global_dtors") {
605 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
606 EmitAlignment(Align, 0);
607 EmitXXStructorList(GV->getInitializer());
609 if (TM.getRelocationModel() == Reloc::Static &&
610 MAI->hasStaticCtorDtorReferenceInStaticMode())
611 O << ".reference .destructors_used\n";
618 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
619 /// global in the specified llvm.used list for which emitUsedDirectiveFor
620 /// is true, as being used with this directive.
621 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
622 const char *Directive = MAI->getUsedDirective();
624 // Should be an array of 'i8*'.
625 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
626 if (InitList == 0) return;
628 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
629 const GlobalValue *GV =
630 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
631 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
633 EmitConstantValueOnly(InitList->getOperand(i));
639 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
640 /// function pointers, ignoring the init priority.
641 void AsmPrinter::EmitXXStructorList(Constant *List) {
642 // Should be an array of '{ int, void ()* }' structs. The first value is the
643 // init priority, which we ignore.
644 if (!isa<ConstantArray>(List)) return;
645 ConstantArray *InitList = cast<ConstantArray>(List);
646 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
647 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
648 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
650 if (CS->getOperand(1)->isNullValue())
651 return; // Found a null terminator, exit printing.
652 // Emit the function pointer.
653 EmitGlobalConstant(CS->getOperand(1));
658 //===----------------------------------------------------------------------===//
659 /// LEB 128 number encoding.
661 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
662 /// representing an unsigned leb128 value.
663 void AsmPrinter::PrintULEB128(unsigned Value) const {
665 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
667 if (Value) Byte |= 0x80;
669 if (Value) O << ", ";
673 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
674 /// representing a signed leb128 value.
675 void AsmPrinter::PrintSLEB128(int Value) const {
676 int Sign = Value >> (8 * sizeof(Value) - 1);
680 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
682 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
683 if (IsMore) Byte |= 0x80;
685 if (IsMore) O << ", ";
689 //===--------------------------------------------------------------------===//
690 // Emission and print routines
693 /// PrintHex - Print a value as a hexadecimal value.
695 void AsmPrinter::PrintHex(uint64_t Value) const {
700 /// EOL - Print a newline character to asm stream. If a comment is present
701 /// then it will be printed first. Comments should not contain '\n'.
702 void AsmPrinter::EOL() const {
706 void AsmPrinter::EOL(const Twine &Comment) const {
707 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
708 O.PadToColumn(MAI->getCommentColumn());
709 O << MAI->getCommentString() << ' ' << Comment;
714 static const char *DecodeDWARFEncoding(unsigned Encoding) {
716 case dwarf::DW_EH_PE_absptr:
718 case dwarf::DW_EH_PE_omit:
720 case dwarf::DW_EH_PE_pcrel:
722 case dwarf::DW_EH_PE_udata4:
724 case dwarf::DW_EH_PE_udata8:
726 case dwarf::DW_EH_PE_sdata4:
728 case dwarf::DW_EH_PE_sdata8:
730 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
731 return "pcrel udata4";
732 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
733 return "pcrel sdata4";
734 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
735 return "pcrel udata8";
736 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
737 return "pcrel sdata8";
738 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
739 return "indirect pcrel udata4";
740 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
741 return "indirect pcrel sdata4";
742 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
743 return "indirect pcrel udata8";
744 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
745 return "indirect pcrel sdata8";
751 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
752 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
753 O.PadToColumn(MAI->getCommentColumn());
754 O << MAI->getCommentString()
758 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
759 O << " (" << EncStr << ')';
764 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
765 /// unsigned leb128 value.
766 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
767 if (MAI->hasLEB128()) {
771 O << MAI->getData8bitsDirective();
776 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
777 /// signed leb128 value.
778 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
779 if (MAI->hasLEB128()) {
783 O << MAI->getData8bitsDirective();
788 /// EmitInt8 - Emit a byte directive and value.
790 void AsmPrinter::EmitInt8(int Value) const {
791 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
794 /// EmitInt16 - Emit a short directive and value.
796 void AsmPrinter::EmitInt16(int Value) const {
797 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
800 /// EmitInt32 - Emit a long directive and value.
802 void AsmPrinter::EmitInt32(int Value) const {
803 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
806 /// EmitInt64 - Emit a long long directive and value.
808 void AsmPrinter::EmitInt64(uint64_t Value) const {
809 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
812 /// toOctal - Convert the low order bits of X into an octal digit.
814 static inline char toOctal(int X) {
818 /// printStringChar - Print a char, escaped if necessary.
820 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
823 } else if (C == '\\') {
825 } else if (isprint((unsigned char)C)) {
829 case '\b': O << "\\b"; break;
830 case '\f': O << "\\f"; break;
831 case '\n': O << "\\n"; break;
832 case '\r': O << "\\r"; break;
833 case '\t': O << "\\t"; break;
836 O << toOctal(C >> 6);
837 O << toOctal(C >> 3);
838 O << toOctal(C >> 0);
844 /// EmitString - Emit a string with quotes and a null terminator.
845 /// Special characters are emitted properly.
846 /// \literal (Eg. '\t') \endliteral
847 void AsmPrinter::EmitString(const StringRef String) const {
848 EmitString(String.data(), String.size());
851 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
852 const char* AscizDirective = MAI->getAscizDirective();
856 O << MAI->getAsciiDirective();
858 for (unsigned i = 0; i < Size; ++i)
859 printStringChar(O, String[i]);
867 /// EmitFile - Emit a .file directive.
868 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
869 O << "\t.file\t" << Number << " \"";
870 for (unsigned i = 0, N = Name.size(); i < N; ++i)
871 printStringChar(O, Name[i]);
876 //===----------------------------------------------------------------------===//
878 // EmitAlignment - Emit an alignment directive to the specified power of
879 // two boundary. For example, if you pass in 3 here, you will get an 8
880 // byte alignment. If a global value is specified, and if that global has
881 // an explicit alignment requested, it will unconditionally override the
882 // alignment request. However, if ForcedAlignBits is specified, this value
883 // has final say: the ultimate alignment will be the max of ForcedAlignBits
884 // and the alignment computed with NumBits and the global.
888 // if (GV && GV->hasalignment) Align = GV->getalignment();
889 // Align = std::max(Align, ForcedAlignBits);
891 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
892 unsigned ForcedAlignBits,
893 bool UseFillExpr) const {
894 if (GV && GV->getAlignment())
895 NumBits = Log2_32(GV->getAlignment());
896 NumBits = std::max(NumBits, ForcedAlignBits);
898 if (NumBits == 0) return; // No need to emit alignment.
900 unsigned FillValue = 0;
901 if (getCurrentSection()->getKind().isText())
902 FillValue = MAI->getTextAlignFillValue();
904 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
907 // Print out the specified constant, without a storage class. Only the
908 // constants valid in constant expressions can occur here.
909 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
910 if (CV->isNullValue() || isa<UndefValue>(CV)) {
915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
916 O << CI->getZExtValue();
920 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
921 // This is a constant address for a global variable or function. Use the
922 // name of the variable or function as the address value.
923 O << *GetGlobalValueSymbol(GV);
927 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
928 O << *GetBlockAddressSymbol(BA);
932 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
934 llvm_unreachable("Unknown constant value!");
939 switch (CE->getOpcode()) {
940 case Instruction::ZExt:
941 case Instruction::SExt:
942 case Instruction::FPTrunc:
943 case Instruction::FPExt:
944 case Instruction::UIToFP:
945 case Instruction::SIToFP:
946 case Instruction::FPToUI:
947 case Instruction::FPToSI:
949 llvm_unreachable("FIXME: Don't support this constant cast expr");
950 case Instruction::GetElementPtr: {
951 // generate a symbolic expression for the byte address
952 const TargetData *TD = TM.getTargetData();
953 const Constant *ptrVal = CE->getOperand(0);
954 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
955 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
958 return EmitConstantValueOnly(ptrVal);
960 // Truncate/sext the offset to the pointer size.
961 if (TD->getPointerSizeInBits() != 64) {
962 int SExtAmount = 64-TD->getPointerSizeInBits();
963 Offset = (Offset << SExtAmount) >> SExtAmount;
968 EmitConstantValueOnly(ptrVal);
970 O << ") + " << Offset;
972 O << ") - " << -Offset;
975 case Instruction::BitCast:
976 return EmitConstantValueOnly(CE->getOperand(0));
978 case Instruction::IntToPtr: {
979 // Handle casts to pointers by changing them into casts to the appropriate
980 // integer type. This promotes constant folding and simplifies this code.
981 const TargetData *TD = TM.getTargetData();
982 Constant *Op = CE->getOperand(0);
983 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
985 return EmitConstantValueOnly(Op);
988 case Instruction::PtrToInt: {
989 // Support only foldable casts to/from pointers that can be eliminated by
990 // changing the pointer to the appropriately sized integer type.
991 Constant *Op = CE->getOperand(0);
992 const Type *Ty = CE->getType();
993 const TargetData *TD = TM.getTargetData();
995 // We can emit the pointer value into this slot if the slot is an
996 // integer slot greater or equal to the size of the pointer.
997 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
998 return EmitConstantValueOnly(Op);
1001 EmitConstantValueOnly(Op);
1003 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
1006 ptrMask.toStringUnsigned(S);
1007 O << ") & " << S.str() << ')';
1011 case Instruction::Trunc:
1012 // We emit the value and depend on the assembler to truncate the generated
1013 // expression properly. This is important for differences between
1014 // blockaddress labels. Since the two labels are in the same function, it
1015 // is reasonable to treat their delta as a 32-bit value.
1016 return EmitConstantValueOnly(CE->getOperand(0));
1018 case Instruction::Add:
1019 case Instruction::Sub:
1020 case Instruction::And:
1021 case Instruction::Or:
1022 case Instruction::Xor:
1024 EmitConstantValueOnly(CE->getOperand(0));
1026 switch (CE->getOpcode()) {
1027 case Instruction::Add:
1030 case Instruction::Sub:
1033 case Instruction::And:
1036 case Instruction::Or:
1039 case Instruction::Xor:
1046 EmitConstantValueOnly(CE->getOperand(1));
1052 /// printAsCString - Print the specified array as a C compatible string, only if
1053 /// the predicate isString is true.
1055 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1057 assert(CVA->isString() && "Array is not string compatible!");
1060 for (unsigned i = 0; i != LastElt; ++i) {
1062 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1063 printStringChar(O, C);
1068 /// EmitString - Emit a zero-byte-terminated string constant.
1070 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1071 unsigned NumElts = CVA->getNumOperands();
1072 if (MAI->getAscizDirective() && NumElts &&
1073 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1074 O << MAI->getAscizDirective();
1075 printAsCString(O, CVA, NumElts-1);
1077 O << MAI->getAsciiDirective();
1078 printAsCString(O, CVA, NumElts);
1083 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1085 if (AddrSpace == 0 && CA->isString()) {
1087 } else { // Not a string. Print the values in successive locations
1088 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1089 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1093 static void EmitGlobalConstantVector(const ConstantVector *CV,
1094 unsigned AddrSpace, AsmPrinter &AP) {
1095 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1096 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1099 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1100 unsigned AddrSpace, AsmPrinter &AP) {
1101 // Print the fields in successive locations. Pad to align if needed!
1102 const TargetData *TD = AP.TM.getTargetData();
1103 unsigned Size = TD->getTypeAllocSize(CS->getType());
1104 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1105 uint64_t SizeSoFar = 0;
1106 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1107 const Constant *Field = CS->getOperand(i);
1109 // Check if padding is needed and insert one or more 0s.
1110 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1111 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1112 - Layout->getElementOffset(i)) - FieldSize;
1113 SizeSoFar += FieldSize + PadSize;
1115 // Now print the actual field value.
1116 AP.EmitGlobalConstant(Field, AddrSpace);
1118 // Insert padding - this may include padding to increase the size of the
1119 // current field up to the ABI size (if the struct is not packed) as well
1120 // as padding to ensure that the next field starts at the right offset.
1121 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1123 assert(SizeSoFar == Layout->getSizeInBytes() &&
1124 "Layout of constant struct may be incorrect!");
1127 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1129 // FP Constants are printed as integer constants to avoid losing
1131 if (CFP->getType()->isDoubleTy()) {
1132 if (AP.VerboseAsm) {
1133 double Val = CFP->getValueAPF().convertToDouble();
1134 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1137 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1138 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1142 if (CFP->getType()->isFloatTy()) {
1143 if (AP.VerboseAsm) {
1144 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1145 AP.O.PadToColumn(AP.MAI->getCommentColumn());
1146 AP.O << AP.MAI->getCommentString() << " float " << Val << '\n';
1148 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1149 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1153 if (CFP->getType()->isX86_FP80Ty()) {
1154 // all long double variants are printed as hex
1155 // api needed to prevent premature destruction
1156 APInt API = CFP->getValueAPF().bitcastToAPInt();
1157 const uint64_t *p = API.getRawData();
1158 if (AP.VerboseAsm) {
1159 // Convert to double so we can print the approximate val as a comment.
1160 APFloat DoubleVal = CFP->getValueAPF();
1162 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1164 AP.O.PadToColumn(AP.MAI->getCommentColumn());
1165 AP.O << AP.MAI->getCommentString() << " x86_fp80 ~= "
1166 << DoubleVal.convertToDouble() << '\n';
1169 if (AP.TM.getTargetData()->isBigEndian()) {
1170 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1171 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1173 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1174 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1177 // Emit the tail padding for the long double.
1178 const TargetData &TD = *AP.TM.getTargetData();
1179 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1180 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1184 assert(CFP->getType()->isPPC_FP128Ty() &&
1185 "Floating point constant type not handled");
1186 // All long double variants are printed as hex api needed to prevent
1187 // premature destruction.
1188 APInt API = CFP->getValueAPF().bitcastToAPInt();
1189 const uint64_t *p = API.getRawData();
1190 if (AP.TM.getTargetData()->isBigEndian()) {
1191 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1192 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1194 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1195 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1199 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1200 unsigned AddrSpace, AsmPrinter &AP) {
1201 const TargetData *TD = AP.TM.getTargetData();
1202 unsigned BitWidth = CI->getBitWidth();
1203 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1205 // We don't expect assemblers to support integer data directives
1206 // for more than 64 bits, so we emit the data in at most 64-bit
1207 // quantities at a time.
1208 const uint64_t *RawData = CI->getValue().getRawData();
1209 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1210 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1211 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1215 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1216 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1217 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1218 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1219 return OutStreamer.EmitZeros(Size, AddrSpace);
1222 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1223 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1230 O.PadToColumn(MAI->getCommentColumn());
1231 O << MAI->getCommentString() << " 0x";
1232 O.write_hex(CI->getZExtValue());
1235 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1238 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1243 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1244 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1246 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1247 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1249 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1250 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1252 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1253 return EmitGlobalConstantVector(V, AddrSpace, *this);
1255 if (isa<ConstantPointerNull>(CV)) {
1256 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1257 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1261 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit
1262 // the expression value.
1263 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1265 case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1266 case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1267 case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1269 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1275 llvm_unreachable("Target cannot handle given data directive width!");
1279 EmitConstantValueOnly(CV);
1283 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1284 // Target doesn't support this yet!
1285 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1288 /// PrintSpecial - Print information related to the specified machine instr
1289 /// that is independent of the operand, and may be independent of the instr
1290 /// itself. This can be useful for portably encoding the comment character
1291 /// or other bits of target-specific knowledge into the asmstrings. The
1292 /// syntax used is ${:comment}. Targets can override this to add support
1293 /// for their own strange codes.
1294 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1295 if (!strcmp(Code, "private")) {
1296 O << MAI->getPrivateGlobalPrefix();
1297 } else if (!strcmp(Code, "comment")) {
1299 O << MAI->getCommentString();
1300 } else if (!strcmp(Code, "uid")) {
1301 // Comparing the address of MI isn't sufficient, because machineinstrs may
1302 // be allocated to the same address across functions.
1303 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1305 // If this is a new LastFn instruction, bump the counter.
1306 if (LastMI != MI || LastFn != ThisF) {
1314 raw_string_ostream Msg(msg);
1315 Msg << "Unknown special formatter '" << Code
1316 << "' for machine instr: " << *MI;
1317 llvm_report_error(Msg.str());
1321 /// processDebugLoc - Processes the debug information of each machine
1322 /// instruction's DebugLoc.
1323 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1324 bool BeforePrintingInsn) {
1325 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1326 || !DW->ShouldEmitDwarfDebug())
1328 DebugLoc DL = MI->getDebugLoc();
1331 DILocation CurDLT = MF->getDILocation(DL);
1332 if (CurDLT.getScope().isNull())
1335 if (!BeforePrintingInsn) {
1336 // After printing instruction
1338 } else if (CurDLT.getNode() != PrevDLT) {
1339 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1340 CurDLT.getColumnNumber(),
1341 CurDLT.getScope().getNode());
1344 DW->BeginScope(MI, L);
1345 PrevDLT = CurDLT.getNode();
1350 /// printInlineAsm - This method formats and prints the specified machine
1351 /// instruction that is an inline asm.
1352 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1353 unsigned NumOperands = MI->getNumOperands();
1355 // Count the number of register definitions.
1356 unsigned NumDefs = 0;
1357 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1359 assert(NumDefs != NumOperands-1 && "No asm string?");
1361 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1363 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1364 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1368 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1369 // These are useful to see where empty asm's wound up.
1370 if (AsmStr[0] == 0) {
1371 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1372 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1376 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1378 // The variant of the current asmprinter.
1379 int AsmPrinterVariant = MAI->getAssemblerDialect();
1381 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1382 const char *LastEmitted = AsmStr; // One past the last character emitted.
1384 while (*LastEmitted) {
1385 switch (*LastEmitted) {
1387 // Not a special case, emit the string section literally.
1388 const char *LiteralEnd = LastEmitted+1;
1389 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1390 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1392 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1393 O.write(LastEmitted, LiteralEnd-LastEmitted);
1394 LastEmitted = LiteralEnd;
1398 ++LastEmitted; // Consume newline character.
1399 O << '\n'; // Indent code with newline.
1402 ++LastEmitted; // Consume '$' character.
1406 switch (*LastEmitted) {
1407 default: Done = false; break;
1408 case '$': // $$ -> $
1409 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1411 ++LastEmitted; // Consume second '$' character.
1413 case '(': // $( -> same as GCC's { character.
1414 ++LastEmitted; // Consume '(' character.
1415 if (CurVariant != -1) {
1416 llvm_report_error("Nested variants found in inline asm string: '"
1417 + std::string(AsmStr) + "'");
1419 CurVariant = 0; // We're in the first variant now.
1422 ++LastEmitted; // consume '|' character.
1423 if (CurVariant == -1)
1424 O << '|'; // this is gcc's behavior for | outside a variant
1426 ++CurVariant; // We're in the next variant.
1428 case ')': // $) -> same as GCC's } char.
1429 ++LastEmitted; // consume ')' character.
1430 if (CurVariant == -1)
1431 O << '}'; // this is gcc's behavior for } outside a variant
1438 bool HasCurlyBraces = false;
1439 if (*LastEmitted == '{') { // ${variable}
1440 ++LastEmitted; // Consume '{' character.
1441 HasCurlyBraces = true;
1444 // If we have ${:foo}, then this is not a real operand reference, it is a
1445 // "magic" string reference, just like in .td files. Arrange to call
1447 if (HasCurlyBraces && *LastEmitted == ':') {
1449 const char *StrStart = LastEmitted;
1450 const char *StrEnd = strchr(StrStart, '}');
1452 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1453 + std::string(AsmStr) + "'");
1456 std::string Val(StrStart, StrEnd);
1457 PrintSpecial(MI, Val.c_str());
1458 LastEmitted = StrEnd+1;
1462 const char *IDStart = LastEmitted;
1465 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1466 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1467 llvm_report_error("Bad $ operand number in inline asm string: '"
1468 + std::string(AsmStr) + "'");
1470 LastEmitted = IDEnd;
1472 char Modifier[2] = { 0, 0 };
1474 if (HasCurlyBraces) {
1475 // If we have curly braces, check for a modifier character. This
1476 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1477 if (*LastEmitted == ':') {
1478 ++LastEmitted; // Consume ':' character.
1479 if (*LastEmitted == 0) {
1480 llvm_report_error("Bad ${:} expression in inline asm string: '"
1481 + std::string(AsmStr) + "'");
1484 Modifier[0] = *LastEmitted;
1485 ++LastEmitted; // Consume modifier character.
1488 if (*LastEmitted != '}') {
1489 llvm_report_error("Bad ${} expression in inline asm string: '"
1490 + std::string(AsmStr) + "'");
1492 ++LastEmitted; // Consume '}' character.
1495 if ((unsigned)Val >= NumOperands-1) {
1496 llvm_report_error("Invalid $ operand number in inline asm string: '"
1497 + std::string(AsmStr) + "'");
1500 // Okay, we finally have a value number. Ask the target to print this
1502 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1507 // Scan to find the machine operand number for the operand.
1508 for (; Val; --Val) {
1509 if (OpNo >= MI->getNumOperands()) break;
1510 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1511 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1514 if (OpNo >= MI->getNumOperands()) {
1517 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1518 ++OpNo; // Skip over the ID number.
1520 if (Modifier[0] == 'l') // labels are target independent
1521 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1523 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1524 if ((OpFlags & 7) == 4) {
1525 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1526 Modifier[0] ? Modifier : 0);
1528 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1529 Modifier[0] ? Modifier : 0);
1535 raw_string_ostream Msg(msg);
1536 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1538 llvm_report_error(Msg.str());
1545 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1548 /// printImplicitDef - This method prints the specified machine instruction
1549 /// that is an implicit def.
1550 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1551 if (!VerboseAsm) return;
1552 O.PadToColumn(MAI->getCommentColumn());
1553 O << MAI->getCommentString() << " implicit-def: "
1554 << TRI->getName(MI->getOperand(0).getReg());
1557 void AsmPrinter::printKill(const MachineInstr *MI) const {
1558 if (!VerboseAsm) return;
1559 O.PadToColumn(MAI->getCommentColumn());
1560 O << MAI->getCommentString() << " kill:";
1561 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1562 const MachineOperand &op = MI->getOperand(n);
1563 assert(op.isReg() && "KILL instruction must have only register operands");
1564 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1568 /// printLabel - This method prints a local label used by debug and
1569 /// exception handling tables.
1570 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1571 printLabel(MI->getOperand(0).getImm());
1574 void AsmPrinter::printLabel(unsigned Id) const {
1575 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1578 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1579 /// instruction, using the specified assembler variant. Targets should
1580 /// override this to format as appropriate.
1581 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1582 unsigned AsmVariant, const char *ExtraCode) {
1583 // Target doesn't support this yet!
1587 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1588 unsigned AsmVariant,
1589 const char *ExtraCode) {
1590 // Target doesn't support this yet!
1594 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1595 const char *Suffix) const {
1596 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1599 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1600 const BasicBlock *BB,
1601 const char *Suffix) const {
1602 assert(BB->hasName() &&
1603 "Address of anonymous basic block not supported yet!");
1605 // This code must use the function name itself, and not the function number,
1606 // since it must be possible to generate the label name from within other
1608 SmallString<60> FnName;
1609 Mang->getNameWithPrefix(FnName, F, false);
1611 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1612 SmallString<60> NameResult;
1613 Mang->getNameWithPrefix(NameResult,
1614 StringRef("BA") + Twine((unsigned)FnName.size()) +
1615 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1618 return OutContext.GetOrCreateSymbol(NameResult.str());
1621 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1622 SmallString<60> Name;
1623 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1624 << getFunctionNumber() << '_' << MBBID;
1626 return OutContext.GetOrCreateSymbol(Name.str());
1629 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1631 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1632 SmallString<60> NameStr;
1633 Mang->getNameWithPrefix(NameStr, GV, false);
1634 return OutContext.GetOrCreateSymbol(NameStr.str());
1637 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1638 /// global value name as its base, with the specified suffix, and where the
1639 /// symbol is forced to have private linkage if ForcePrivate is true.
1640 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1642 bool ForcePrivate) const {
1643 SmallString<60> NameStr;
1644 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1645 NameStr.append(Suffix.begin(), Suffix.end());
1646 return OutContext.GetOrCreateSymbol(NameStr.str());
1649 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1651 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1652 SmallString<60> NameStr;
1653 Mang->getNameWithPrefix(NameStr, Sym);
1654 return OutContext.GetOrCreateSymbol(NameStr.str());
1658 /// EmitBasicBlockStart - This method prints the label for the specified
1659 /// MachineBasicBlock, an alignment (if present) and a comment describing
1660 /// it if appropriate.
1661 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1662 // Emit an alignment directive for this block, if needed.
1663 if (unsigned Align = MBB->getAlignment())
1664 EmitAlignment(Log2_32(Align));
1666 // If the block has its address taken, emit a special label to satisfy
1667 // references to the block. This is done so that we don't need to
1668 // remember the number of this label, and so that we can make
1669 // forward references to labels without knowing what their numbers
1671 if (MBB->hasAddressTaken()) {
1672 const BasicBlock *BB = MBB->getBasicBlock();
1673 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1675 O.PadToColumn(MAI->getCommentColumn());
1676 O << MAI->getCommentString() << " Address Taken" << '\n';
1680 // Print the main label for the block.
1681 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1683 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1685 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1688 // Print some comments to accompany the label.
1690 if (const BasicBlock *BB = MBB->getBasicBlock())
1691 if (BB->hasName()) {
1692 O.PadToColumn(MAI->getCommentColumn());
1693 O << MAI->getCommentString() << ' ';
1694 WriteAsOperand(O, BB, /*PrintType=*/false);
1702 /// printPICJumpTableSetLabel - This method prints a set label for the
1703 /// specified MachineBasicBlock for a jumptable entry.
1704 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1705 const MachineBasicBlock *MBB) const {
1706 if (!MAI->getSetDirective())
1709 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1710 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1711 << *GetMBBSymbol(MBB->getNumber())
1712 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1713 << '_' << uid << '\n';
1716 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1717 const MachineBasicBlock *MBB) const {
1718 if (!MAI->getSetDirective())
1721 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1722 << getFunctionNumber() << '_' << uid << '_' << uid2
1723 << "_set_" << MBB->getNumber() << ','
1724 << *GetMBBSymbol(MBB->getNumber())
1725 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1726 << '_' << uid << '_' << uid2 << '\n';
1729 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1730 unsigned Visibility) const {
1731 if (Visibility == GlobalValue::HiddenVisibility) {
1732 if (const char *Directive = MAI->getHiddenDirective())
1733 O << Directive << *Sym << '\n';
1734 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1735 if (const char *Directive = MAI->getProtectedDirective())
1736 O << Directive << *Sym << '\n';
1740 void AsmPrinter::printOffset(int64_t Offset) const {
1743 else if (Offset < 0)
1747 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1748 if (!S->usesMetadata())
1751 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1752 if (GCPI != GCMetadataPrinters.end())
1753 return GCPI->second;
1755 const char *Name = S->getName().c_str();
1757 for (GCMetadataPrinterRegistry::iterator
1758 I = GCMetadataPrinterRegistry::begin(),
1759 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1760 if (strcmp(Name, I->getName()) == 0) {
1761 GCMetadataPrinter *GMP = I->instantiate();
1763 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1767 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1768 llvm_unreachable(0);
1771 /// EmitComments - Pretty-print comments for instructions
1772 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1776 bool Newline = false;
1778 if (!MI.getDebugLoc().isUnknown()) {
1779 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1781 // Print source line info.
1782 O.PadToColumn(MAI->getCommentColumn());
1783 O << MAI->getCommentString() << ' ';
1784 DIScope Scope = DLT.getScope();
1785 // Omit the directory, because it's likely to be long and uninteresting.
1786 if (!Scope.isNull())
1787 O << Scope.getFilename();
1790 O << ':' << DLT.getLineNumber();
1791 if (DLT.getColumnNumber() != 0)
1792 O << ':' << DLT.getColumnNumber();
1796 // Check for spills and reloads
1799 const MachineFrameInfo *FrameInfo =
1800 MI.getParent()->getParent()->getFrameInfo();
1802 // We assume a single instruction only has a spill or reload, not
1804 const MachineMemOperand *MMO;
1805 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1806 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1807 MMO = *MI.memoperands_begin();
1808 if (Newline) O << '\n';
1809 O.PadToColumn(MAI->getCommentColumn());
1810 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1814 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1815 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1816 if (Newline) O << '\n';
1817 O.PadToColumn(MAI->getCommentColumn());
1818 O << MAI->getCommentString() << ' '
1819 << MMO->getSize() << "-byte Folded Reload";
1823 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1824 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1825 MMO = *MI.memoperands_begin();
1826 if (Newline) O << '\n';
1827 O.PadToColumn(MAI->getCommentColumn());
1828 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1832 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1833 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1834 if (Newline) O << '\n';
1835 O.PadToColumn(MAI->getCommentColumn());
1836 O << MAI->getCommentString() << ' '
1837 << MMO->getSize() << "-byte Folded Spill";
1842 // Check for spill-induced copies
1843 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1844 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1845 SrcSubIdx, DstSubIdx)) {
1846 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1847 if (Newline) O << '\n';
1848 O.PadToColumn(MAI->getCommentColumn());
1849 O << MAI->getCommentString() << " Reload Reuse";
1854 /// PrintChildLoopComment - Print comments about child loops within
1855 /// the loop for this basic block, with nesting.
1857 static void PrintChildLoopComment(formatted_raw_ostream &O,
1858 const MachineLoop *loop,
1859 const MCAsmInfo *MAI,
1860 int FunctionNumber) {
1861 // Add child loop information
1862 for(MachineLoop::iterator cl = loop->begin(),
1863 clend = loop->end();
1866 MachineBasicBlock *Header = (*cl)->getHeader();
1867 assert(Header && "No header for loop");
1870 O.PadToColumn(MAI->getCommentColumn());
1872 O << MAI->getCommentString();
1873 O.indent(((*cl)->getLoopDepth()-1)*2)
1874 << " Child Loop BB" << FunctionNumber << "_"
1875 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1877 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1881 /// EmitComments - Pretty-print comments for basic blocks
1882 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
1884 // Add loop depth information
1885 const MachineLoop *loop = LI->getLoopFor(&MBB);
1888 // Print a newline after bb# annotation.
1890 O.PadToColumn(MAI->getCommentColumn());
1891 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1894 O.PadToColumn(MAI->getCommentColumn());
1896 MachineBasicBlock *Header = loop->getHeader();
1897 assert(Header && "No header for loop");
1899 if (Header == &MBB) {
1900 O << MAI->getCommentString() << " Loop Header";
1901 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1904 O << MAI->getCommentString() << " Loop Header is BB"
1905 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1908 if (loop->empty()) {
1910 O.PadToColumn(MAI->getCommentColumn());
1911 O << MAI->getCommentString() << " Inner Loop";
1914 // Add parent loop information
1915 for (const MachineLoop *CurLoop = loop->getParentLoop();
1917 CurLoop = CurLoop->getParentLoop()) {
1918 MachineBasicBlock *Header = CurLoop->getHeader();
1919 assert(Header && "No header for loop");
1922 O.PadToColumn(MAI->getCommentColumn());
1923 O << MAI->getCommentString();
1924 O.indent((CurLoop->getLoopDepth()-1)*2)
1925 << " Inside Loop BB" << getFunctionNumber() << "_"
1926 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();