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 char AsmPrinter::ID = 0;
54 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
55 const MCAsmInfo *T, bool VDef)
56 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
57 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
59 OutContext(*new MCContext()),
60 // FIXME: Pass instprinter to streamer.
61 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
63 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
66 case cl::BOU_UNSET: VerboseAsm = VDef; break;
67 case cl::BOU_TRUE: VerboseAsm = true; break;
68 case cl::BOU_FALSE: VerboseAsm = false; break;
72 AsmPrinter::~AsmPrinter() {
73 for (gcp_iterator I = GCMetadataPrinters.begin(),
74 E = GCMetadataPrinters.end(); I != E; ++I)
81 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
82 return TM.getTargetLowering()->getObjFileLowering();
85 /// getCurrentSection() - Return the current section we are emitting to.
86 const MCSection *AsmPrinter::getCurrentSection() const {
87 return OutStreamer.getCurrentSection();
91 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
93 MachineFunctionPass::getAnalysisUsage(AU);
94 AU.addRequired<GCModuleInfo>();
96 AU.addRequired<MachineLoopInfo>();
99 bool AsmPrinter::doInitialization(Module &M) {
100 // Initialize TargetLoweringObjectFile.
101 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
102 .Initialize(OutContext, TM);
104 Mang = new Mangler(*MAI);
106 // Allow the target to emit any magic that it wants at the start of the file.
107 EmitStartOfAsmFile(M);
109 if (MAI->hasSingleParameterDotFile()) {
110 /* Very minimal debug info. It is ignored if we emit actual
111 debug info. If we don't, this at least helps the user find where
112 a function came from. */
113 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
116 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
117 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
118 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
119 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
120 MP->beginAssembly(O, *this, *MAI);
122 if (!M.getModuleInlineAsm().empty())
123 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
124 << M.getModuleInlineAsm()
125 << '\n' << MAI->getCommentString()
126 << " End of file scope inline assembly\n";
128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
130 MMI->AnalyzeModule(M);
131 DW = getAnalysisIfAvailable<DwarfWriter>();
133 DW->BeginModule(&M, MMI, O, this, MAI);
138 bool AsmPrinter::doFinalization(Module &M) {
139 // Emit global variables.
140 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
142 PrintGlobalVariable(I);
144 // Emit final debug information.
145 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
148 // If the target wants to know about weak references, print them all.
149 if (MAI->getWeakRefDirective()) {
150 // FIXME: This is not lazy, it would be nice to only print weak references
151 // to stuff that is actually used. Note that doing so would require targets
152 // to notice uses in operands (due to constant exprs etc). This should
153 // happen with the MC stuff eventually.
155 // Print out module-level global variables here.
156 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
158 if (!I->hasExternalWeakLinkage()) continue;
159 O << MAI->getWeakRefDirective();
160 GetGlobalValueSymbol(I)->print(O, MAI);
164 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
165 if (!I->hasExternalWeakLinkage()) continue;
166 O << MAI->getWeakRefDirective();
167 GetGlobalValueSymbol(I)->print(O, MAI);
172 if (MAI->getSetDirective()) {
174 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
176 MCSymbol *Name = GetGlobalValueSymbol(I);
178 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
179 MCSymbol *Target = GetGlobalValueSymbol(GV);
181 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) {
185 } else if (I->hasWeakLinkage()) {
186 O << MAI->getWeakRefDirective();
190 assert(I->hasLocalLinkage() && "Invalid alias linkage");
193 printVisibility(Name, I->getVisibility());
195 O << MAI->getSetDirective() << ' ';
198 Target->print(O, MAI);
203 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
204 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
205 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
206 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
207 MP->finishAssembly(O, *this, *MAI);
209 // If we don't have any trampolines, then we don't require stack memory
210 // to be executable. Some targets have a directive to declare this.
211 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
212 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
213 if (MAI->getNonexecutableStackDirective())
214 O << MAI->getNonexecutableStackDirective() << '\n';
217 // Allow the target to emit any magic that it wants at the end of the file,
218 // after everything else has gone out.
221 delete Mang; Mang = 0;
224 OutStreamer.Finish();
228 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
229 // Get the function symbol.
230 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
231 IncrementFunctionNumber();
234 LI = &getAnalysis<MachineLoopInfo>();
238 // SectionCPs - Keep track the alignment, constpool entries per Section.
242 SmallVector<unsigned, 4> CPEs;
243 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
247 /// EmitConstantPool - Print to the current output stream assembly
248 /// representations of the constants in the constant pool MCP. This is
249 /// used to print out constants which have been "spilled to memory" by
250 /// the code generator.
252 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
253 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
254 if (CP.empty()) return;
256 // Calculate sections for constant pool entries. We collect entries to go into
257 // the same section together to reduce amount of section switch statements.
258 SmallVector<SectionCPs, 4> CPSections;
259 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
260 const MachineConstantPoolEntry &CPE = CP[i];
261 unsigned Align = CPE.getAlignment();
264 switch (CPE.getRelocationInfo()) {
265 default: llvm_unreachable("Unknown section kind");
266 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
268 Kind = SectionKind::getReadOnlyWithRelLocal();
271 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
272 case 4: Kind = SectionKind::getMergeableConst4(); break;
273 case 8: Kind = SectionKind::getMergeableConst8(); break;
274 case 16: Kind = SectionKind::getMergeableConst16();break;
275 default: Kind = SectionKind::getMergeableConst(); break;
279 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
281 // The number of sections are small, just do a linear search from the
282 // last section to the first.
284 unsigned SecIdx = CPSections.size();
285 while (SecIdx != 0) {
286 if (CPSections[--SecIdx].S == S) {
292 SecIdx = CPSections.size();
293 CPSections.push_back(SectionCPs(S, Align));
296 if (Align > CPSections[SecIdx].Alignment)
297 CPSections[SecIdx].Alignment = Align;
298 CPSections[SecIdx].CPEs.push_back(i);
301 // Now print stuff into the calculated sections.
302 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
303 OutStreamer.SwitchSection(CPSections[i].S);
304 EmitAlignment(Log2_32(CPSections[i].Alignment));
307 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
308 unsigned CPI = CPSections[i].CPEs[j];
309 MachineConstantPoolEntry CPE = CP[CPI];
311 // Emit inter-object padding for alignment.
312 unsigned AlignMask = CPE.getAlignment() - 1;
313 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
314 EmitZeros(NewOffset - Offset);
316 const Type *Ty = CPE.getType();
317 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
319 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
322 O.PadToColumn(MAI->getCommentColumn());
323 O << MAI->getCommentString() << " constant ";
324 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
327 if (CPE.isMachineConstantPoolEntry())
328 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
330 EmitGlobalConstant(CPE.Val.ConstVal);
335 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
336 /// by the current function to the current output stream.
338 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
339 MachineFunction &MF) {
340 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
341 if (JT.empty()) return;
343 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
345 // Pick the directive to use to print the jump table entries, and switch to
346 // the appropriate section.
347 TargetLowering *LoweringInfo = TM.getTargetLowering();
349 const Function *F = MF.getFunction();
350 bool JTInDiffSection = false;
351 if (F->isWeakForLinker() ||
352 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
353 // In PIC mode, we need to emit the jump table to the same section as the
354 // function body itself, otherwise the label differences won't make sense.
355 // We should also do if the section name is NULL or function is declared in
356 // discardable section.
357 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
360 // Otherwise, drop it in the readonly section.
361 const MCSection *ReadOnlySection =
362 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
363 OutStreamer.SwitchSection(ReadOnlySection);
364 JTInDiffSection = true;
367 EmitAlignment(Log2_32(MJTI->getAlignment()));
369 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
370 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
372 // If this jump table was deleted, ignore it.
373 if (JTBBs.empty()) continue;
375 // For PIC codegen, if possible we want to use the SetDirective to reduce
376 // the number of relocations the assembler will generate for the jump table.
377 // Set directives are all printed before the jump table itself.
378 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
379 if (MAI->getSetDirective() && IsPic)
380 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
381 if (EmittedSets.insert(JTBBs[ii]))
382 printPICJumpTableSetLabel(i, JTBBs[ii]);
384 // On some targets (e.g. Darwin) we want to emit two consequtive labels
385 // before each jump table. The first label is never referenced, but tells
386 // the assembler and linker the extents of the jump table object. The
387 // second label is actually referenced by the code.
388 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
389 O << MAI->getLinkerPrivateGlobalPrefix()
390 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
393 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
394 << '_' << i << ":\n";
396 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
397 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
403 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
404 const MachineBasicBlock *MBB,
405 unsigned uid) const {
406 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
408 // Use JumpTableDirective otherwise honor the entry size from the jump table
410 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
411 bool HadJTEntryDirective = JTEntryDirective != NULL;
412 if (!HadJTEntryDirective) {
413 JTEntryDirective = MJTI->getEntrySize() == 4 ?
414 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
417 O << JTEntryDirective << ' ';
419 // If we have emitted set directives for the jump table entries, print
420 // them rather than the entries themselves. If we're emitting PIC, then
421 // emit the table entries as differences between two text section labels.
422 // If we're emitting non-PIC code, then emit the entries as direct
423 // references to the target basic blocks.
425 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
426 } else if (MAI->getSetDirective()) {
427 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
428 << '_' << uid << "_set_" << MBB->getNumber();
430 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
431 // If the arch uses custom Jump Table directives, don't calc relative to
433 if (!HadJTEntryDirective)
434 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
435 << getFunctionNumber() << '_' << uid;
440 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
441 /// special global used by LLVM. If so, emit it and return true, otherwise
442 /// do nothing and return false.
443 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
444 if (GV->getName() == "llvm.used") {
445 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
446 EmitLLVMUsedList(GV->getInitializer());
450 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
451 if (GV->getSection() == "llvm.metadata" ||
452 GV->hasAvailableExternallyLinkage())
455 if (!GV->hasAppendingLinkage()) return false;
457 assert(GV->hasInitializer() && "Not a special LLVM global!");
459 const TargetData *TD = TM.getTargetData();
460 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
461 if (GV->getName() == "llvm.global_ctors") {
462 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
463 EmitAlignment(Align, 0);
464 EmitXXStructorList(GV->getInitializer());
468 if (GV->getName() == "llvm.global_dtors") {
469 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
470 EmitAlignment(Align, 0);
471 EmitXXStructorList(GV->getInitializer());
478 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
479 /// global in the specified llvm.used list for which emitUsedDirectiveFor
480 /// is true, as being used with this directive.
481 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
482 const char *Directive = MAI->getUsedDirective();
484 // Should be an array of 'i8*'.
485 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
486 if (InitList == 0) return;
488 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
489 const GlobalValue *GV =
490 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
491 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
493 EmitConstantValueOnly(InitList->getOperand(i));
499 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
500 /// function pointers, ignoring the init priority.
501 void AsmPrinter::EmitXXStructorList(Constant *List) {
502 // Should be an array of '{ int, void ()* }' structs. The first value is the
503 // init priority, which we ignore.
504 if (!isa<ConstantArray>(List)) return;
505 ConstantArray *InitList = cast<ConstantArray>(List);
506 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
507 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
508 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
510 if (CS->getOperand(1)->isNullValue())
511 return; // Found a null terminator, exit printing.
512 // Emit the function pointer.
513 EmitGlobalConstant(CS->getOperand(1));
518 //===----------------------------------------------------------------------===//
519 /// LEB 128 number encoding.
521 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
522 /// representing an unsigned leb128 value.
523 void AsmPrinter::PrintULEB128(unsigned Value) const {
525 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
527 if (Value) Byte |= 0x80;
529 if (Value) O << ", ";
533 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
534 /// representing a signed leb128 value.
535 void AsmPrinter::PrintSLEB128(int Value) const {
536 int Sign = Value >> (8 * sizeof(Value) - 1);
540 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
542 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
543 if (IsMore) Byte |= 0x80;
545 if (IsMore) O << ", ";
549 //===--------------------------------------------------------------------===//
550 // Emission and print routines
553 /// PrintHex - Print a value as a hexadecimal value.
555 void AsmPrinter::PrintHex(uint64_t Value) const {
560 /// EOL - Print a newline character to asm stream. If a comment is present
561 /// then it will be printed first. Comments should not contain '\n'.
562 void AsmPrinter::EOL() const {
566 void AsmPrinter::EOL(const Twine &Comment) const {
567 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
568 O.PadToColumn(MAI->getCommentColumn());
569 O << MAI->getCommentString()
576 static const char *DecodeDWARFEncoding(unsigned Encoding) {
578 case dwarf::DW_EH_PE_absptr:
580 case dwarf::DW_EH_PE_omit:
582 case dwarf::DW_EH_PE_pcrel:
584 case dwarf::DW_EH_PE_udata4:
586 case dwarf::DW_EH_PE_udata8:
588 case dwarf::DW_EH_PE_sdata4:
590 case dwarf::DW_EH_PE_sdata8:
592 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
593 return "pcrel udata4";
594 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
595 return "pcrel sdata4";
596 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
597 return "pcrel udata8";
598 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
599 return "pcrel sdata8";
600 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
601 return "indirect pcrel udata4";
602 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
603 return "indirect pcrel sdata4";
604 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
605 return "indirect pcrel udata8";
606 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
607 return "indirect pcrel sdata8";
613 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
614 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
615 O.PadToColumn(MAI->getCommentColumn());
616 O << MAI->getCommentString()
620 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
621 O << " (" << EncStr << ')';
626 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
627 /// unsigned leb128 value.
628 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
629 if (MAI->hasLEB128()) {
633 O << MAI->getData8bitsDirective();
638 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
639 /// signed leb128 value.
640 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
641 if (MAI->hasLEB128()) {
645 O << MAI->getData8bitsDirective();
650 /// EmitInt8 - Emit a byte directive and value.
652 void AsmPrinter::EmitInt8(int Value) const {
653 O << MAI->getData8bitsDirective();
654 PrintHex(Value & 0xFF);
657 /// EmitInt16 - Emit a short directive and value.
659 void AsmPrinter::EmitInt16(int Value) const {
660 O << MAI->getData16bitsDirective();
661 PrintHex(Value & 0xFFFF);
664 /// EmitInt32 - Emit a long directive and value.
666 void AsmPrinter::EmitInt32(int Value) const {
667 O << MAI->getData32bitsDirective();
671 /// EmitInt64 - Emit a long long directive and value.
673 void AsmPrinter::EmitInt64(uint64_t Value) const {
674 if (MAI->getData64bitsDirective()) {
675 O << MAI->getData64bitsDirective();
678 if (TM.getTargetData()->isBigEndian()) {
679 EmitInt32(unsigned(Value >> 32)); O << '\n';
680 EmitInt32(unsigned(Value));
682 EmitInt32(unsigned(Value)); O << '\n';
683 EmitInt32(unsigned(Value >> 32));
688 /// toOctal - Convert the low order bits of X into an octal digit.
690 static inline char toOctal(int X) {
694 /// printStringChar - Print a char, escaped if necessary.
696 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
699 } else if (C == '\\') {
701 } else if (isprint((unsigned char)C)) {
705 case '\b': O << "\\b"; break;
706 case '\f': O << "\\f"; break;
707 case '\n': O << "\\n"; break;
708 case '\r': O << "\\r"; break;
709 case '\t': O << "\\t"; break;
712 O << toOctal(C >> 6);
713 O << toOctal(C >> 3);
714 O << toOctal(C >> 0);
720 /// EmitString - Emit a string with quotes and a null terminator.
721 /// Special characters are emitted properly.
722 /// \literal (Eg. '\t') \endliteral
723 void AsmPrinter::EmitString(const StringRef String) const {
724 EmitString(String.data(), String.size());
727 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
728 const char* AscizDirective = MAI->getAscizDirective();
732 O << MAI->getAsciiDirective();
734 for (unsigned i = 0; i < Size; ++i)
735 printStringChar(O, String[i]);
743 /// EmitFile - Emit a .file directive.
744 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
745 O << "\t.file\t" << Number << " \"";
746 for (unsigned i = 0, N = Name.size(); i < N; ++i)
747 printStringChar(O, Name[i]);
752 //===----------------------------------------------------------------------===//
754 // EmitAlignment - Emit an alignment directive to the specified power of
755 // two boundary. For example, if you pass in 3 here, you will get an 8
756 // byte alignment. If a global value is specified, and if that global has
757 // an explicit alignment requested, it will unconditionally override the
758 // alignment request. However, if ForcedAlignBits is specified, this value
759 // has final say: the ultimate alignment will be the max of ForcedAlignBits
760 // and the alignment computed with NumBits and the global.
764 // if (GV && GV->hasalignment) Align = GV->getalignment();
765 // Align = std::max(Align, ForcedAlignBits);
767 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
768 unsigned ForcedAlignBits,
769 bool UseFillExpr) const {
770 if (GV && GV->getAlignment())
771 NumBits = Log2_32(GV->getAlignment());
772 NumBits = std::max(NumBits, ForcedAlignBits);
774 if (NumBits == 0) return; // No need to emit alignment.
776 unsigned FillValue = 0;
777 if (getCurrentSection()->getKind().isText())
778 FillValue = MAI->getTextAlignFillValue();
780 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
783 /// EmitZeros - Emit a block of zeros.
785 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
787 if (MAI->getZeroDirective()) {
788 O << MAI->getZeroDirective() << NumZeros;
789 if (MAI->getZeroDirectiveSuffix())
790 O << MAI->getZeroDirectiveSuffix();
793 for (; NumZeros; --NumZeros)
794 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
799 // Print out the specified constant, without a storage class. Only the
800 // constants valid in constant expressions can occur here.
801 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
802 if (CV->isNullValue() || isa<UndefValue>(CV)) {
807 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
808 O << CI->getZExtValue();
812 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
813 // This is a constant address for a global variable or function. Use the
814 // name of the variable or function as the address value.
815 GetGlobalValueSymbol(GV)->print(O, MAI);
819 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
820 GetBlockAddressSymbol(BA)->print(O, MAI);
824 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
826 llvm_unreachable("Unknown constant value!");
831 switch (CE->getOpcode()) {
832 case Instruction::ZExt:
833 case Instruction::SExt:
834 case Instruction::FPTrunc:
835 case Instruction::FPExt:
836 case Instruction::UIToFP:
837 case Instruction::SIToFP:
838 case Instruction::FPToUI:
839 case Instruction::FPToSI:
841 llvm_unreachable("FIXME: Don't support this constant cast expr");
842 case Instruction::GetElementPtr: {
843 // generate a symbolic expression for the byte address
844 const TargetData *TD = TM.getTargetData();
845 const Constant *ptrVal = CE->getOperand(0);
846 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
847 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
850 return EmitConstantValueOnly(ptrVal);
852 // Truncate/sext the offset to the pointer size.
853 if (TD->getPointerSizeInBits() != 64) {
854 int SExtAmount = 64-TD->getPointerSizeInBits();
855 Offset = (Offset << SExtAmount) >> SExtAmount;
860 EmitConstantValueOnly(ptrVal);
862 O << ") + " << Offset;
864 O << ") - " << -Offset;
867 case Instruction::BitCast:
868 return EmitConstantValueOnly(CE->getOperand(0));
870 case Instruction::IntToPtr: {
871 // Handle casts to pointers by changing them into casts to the appropriate
872 // integer type. This promotes constant folding and simplifies this code.
873 const TargetData *TD = TM.getTargetData();
874 Constant *Op = CE->getOperand(0);
875 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
877 return EmitConstantValueOnly(Op);
880 case Instruction::PtrToInt: {
881 // Support only foldable casts to/from pointers that can be eliminated by
882 // changing the pointer to the appropriately sized integer type.
883 Constant *Op = CE->getOperand(0);
884 const Type *Ty = CE->getType();
885 const TargetData *TD = TM.getTargetData();
887 // We can emit the pointer value into this slot if the slot is an
888 // integer slot greater or equal to the size of the pointer.
889 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
890 return EmitConstantValueOnly(Op);
893 EmitConstantValueOnly(Op);
895 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
898 ptrMask.toStringUnsigned(S);
899 O << ") & " << S.str() << ')';
903 case Instruction::Trunc:
904 // We emit the value and depend on the assembler to truncate the generated
905 // expression properly. This is important for differences between
906 // blockaddress labels. Since the two labels are in the same function, it
907 // is reasonable to treat their delta as a 32-bit value.
908 return EmitConstantValueOnly(CE->getOperand(0));
910 case Instruction::Add:
911 case Instruction::Sub:
912 case Instruction::And:
913 case Instruction::Or:
914 case Instruction::Xor:
916 EmitConstantValueOnly(CE->getOperand(0));
918 switch (CE->getOpcode()) {
919 case Instruction::Add:
922 case Instruction::Sub:
925 case Instruction::And:
928 case Instruction::Or:
931 case Instruction::Xor:
938 EmitConstantValueOnly(CE->getOperand(1));
944 /// printAsCString - Print the specified array as a C compatible string, only if
945 /// the predicate isString is true.
947 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
949 assert(CVA->isString() && "Array is not string compatible!");
952 for (unsigned i = 0; i != LastElt; ++i) {
954 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
955 printStringChar(O, C);
960 /// EmitString - Emit a zero-byte-terminated string constant.
962 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
963 unsigned NumElts = CVA->getNumOperands();
964 if (MAI->getAscizDirective() && NumElts &&
965 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
966 O << MAI->getAscizDirective();
967 printAsCString(O, CVA, NumElts-1);
969 O << MAI->getAsciiDirective();
970 printAsCString(O, CVA, NumElts);
975 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
976 unsigned AddrSpace) {
977 if (CVA->isString()) {
979 } else { // Not a string. Print the values in successive locations
980 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
981 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
985 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
986 const VectorType *PTy = CP->getType();
988 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
989 EmitGlobalConstant(CP->getOperand(I));
992 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
993 unsigned AddrSpace) {
994 // Print the fields in successive locations. Pad to align if needed!
995 const TargetData *TD = TM.getTargetData();
996 unsigned Size = TD->getTypeAllocSize(CVS->getType());
997 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
998 uint64_t sizeSoFar = 0;
999 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1000 const Constant* field = CVS->getOperand(i);
1002 // Check if padding is needed and insert one or more 0s.
1003 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1004 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1005 - cvsLayout->getElementOffset(i)) - fieldSize;
1006 sizeSoFar += fieldSize + padSize;
1008 // Now print the actual field value.
1009 EmitGlobalConstant(field, AddrSpace);
1011 // Insert padding - this may include padding to increase the size of the
1012 // current field up to the ABI size (if the struct is not packed) as well
1013 // as padding to ensure that the next field starts at the right offset.
1014 EmitZeros(padSize, AddrSpace);
1016 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1017 "Layout of constant struct may be incorrect!");
1020 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1021 unsigned AddrSpace) {
1022 // FP Constants are printed as integer constants to avoid losing
1024 LLVMContext &Context = CFP->getContext();
1025 const TargetData *TD = TM.getTargetData();
1026 if (CFP->getType()->isDoubleTy()) {
1027 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1028 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1029 if (MAI->getData64bitsDirective(AddrSpace)) {
1030 O << MAI->getData64bitsDirective(AddrSpace) << i;
1032 O.PadToColumn(MAI->getCommentColumn());
1033 O << MAI->getCommentString() << " double " << Val;
1036 } else if (TD->isBigEndian()) {
1037 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1039 O.PadToColumn(MAI->getCommentColumn());
1040 O << MAI->getCommentString()
1041 << " most significant word of double " << Val;
1044 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1046 O.PadToColumn(MAI->getCommentColumn());
1047 O << MAI->getCommentString()
1048 << " least significant word of double " << Val;
1052 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1054 O.PadToColumn(MAI->getCommentColumn());
1055 O << MAI->getCommentString()
1056 << " least significant word of double " << Val;
1059 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1061 O.PadToColumn(MAI->getCommentColumn());
1062 O << MAI->getCommentString()
1063 << " most significant word of double " << Val;
1070 if (CFP->getType()->isFloatTy()) {
1071 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1072 O << MAI->getData32bitsDirective(AddrSpace)
1073 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1075 O.PadToColumn(MAI->getCommentColumn());
1076 O << MAI->getCommentString() << " float " << Val;
1082 if (CFP->getType()->isX86_FP80Ty()) {
1083 // all long double variants are printed as hex
1084 // api needed to prevent premature destruction
1085 APInt api = CFP->getValueAPF().bitcastToAPInt();
1086 const uint64_t *p = api.getRawData();
1087 // Convert to double so we can print the approximate val as a comment.
1088 APFloat DoubleVal = CFP->getValueAPF();
1090 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1092 if (TD->isBigEndian()) {
1093 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1095 O.PadToColumn(MAI->getCommentColumn());
1096 O << MAI->getCommentString()
1097 << " most significant halfword of x86_fp80 ~"
1098 << DoubleVal.convertToDouble();
1101 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1103 O.PadToColumn(MAI->getCommentColumn());
1104 O << MAI->getCommentString() << " next halfword";
1107 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1109 O.PadToColumn(MAI->getCommentColumn());
1110 O << MAI->getCommentString() << " next halfword";
1113 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1115 O.PadToColumn(MAI->getCommentColumn());
1116 O << MAI->getCommentString() << " next halfword";
1119 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1121 O.PadToColumn(MAI->getCommentColumn());
1122 O << MAI->getCommentString()
1123 << " least significant halfword";
1127 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1129 O.PadToColumn(MAI->getCommentColumn());
1130 O << MAI->getCommentString()
1131 << " least significant halfword of x86_fp80 ~"
1132 << DoubleVal.convertToDouble();
1135 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1137 O.PadToColumn(MAI->getCommentColumn());
1138 O << MAI->getCommentString()
1139 << " next halfword";
1142 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1144 O.PadToColumn(MAI->getCommentColumn());
1145 O << MAI->getCommentString()
1146 << " next halfword";
1149 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1151 O.PadToColumn(MAI->getCommentColumn());
1152 O << MAI->getCommentString()
1153 << " next halfword";
1156 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1158 O.PadToColumn(MAI->getCommentColumn());
1159 O << MAI->getCommentString()
1160 << " most significant halfword";
1164 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1165 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1169 if (CFP->getType()->isPPC_FP128Ty()) {
1170 // all long double variants are printed as hex
1171 // api needed to prevent premature destruction
1172 APInt api = CFP->getValueAPF().bitcastToAPInt();
1173 const uint64_t *p = api.getRawData();
1174 if (TD->isBigEndian()) {
1175 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1177 O.PadToColumn(MAI->getCommentColumn());
1178 O << MAI->getCommentString()
1179 << " most significant word of ppc_fp128";
1182 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1184 O.PadToColumn(MAI->getCommentColumn());
1185 O << MAI->getCommentString()
1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1191 O.PadToColumn(MAI->getCommentColumn());
1192 O << MAI->getCommentString()
1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1198 O.PadToColumn(MAI->getCommentColumn());
1199 O << MAI->getCommentString()
1200 << " least significant word";
1204 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1206 O.PadToColumn(MAI->getCommentColumn());
1207 O << MAI->getCommentString()
1208 << " least significant word of ppc_fp128";
1211 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1213 O.PadToColumn(MAI->getCommentColumn());
1214 O << MAI->getCommentString()
1218 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1220 O.PadToColumn(MAI->getCommentColumn());
1221 O << MAI->getCommentString()
1225 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1227 O.PadToColumn(MAI->getCommentColumn());
1228 O << MAI->getCommentString()
1229 << " most significant word";
1234 } else llvm_unreachable("Floating point constant type not handled");
1237 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1238 unsigned AddrSpace) {
1239 const TargetData *TD = TM.getTargetData();
1240 unsigned BitWidth = CI->getBitWidth();
1241 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1243 // We don't expect assemblers to support integer data directives
1244 // for more than 64 bits, so we emit the data in at most 64-bit
1245 // quantities at a time.
1246 const uint64_t *RawData = CI->getValue().getRawData();
1247 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1249 if (TD->isBigEndian())
1250 Val = RawData[e - i - 1];
1254 if (MAI->getData64bitsDirective(AddrSpace)) {
1255 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1259 // Emit two 32-bit chunks, order depends on endianness.
1260 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1261 const char *FirstName = " least", *SecondName = " most";
1262 if (TD->isBigEndian()) {
1263 std::swap(FirstChunk, SecondChunk);
1264 std::swap(FirstName, SecondName);
1267 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1269 O.PadToColumn(MAI->getCommentColumn());
1270 O << MAI->getCommentString()
1271 << FirstName << " significant half of i64 " << Val;
1275 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1277 O.PadToColumn(MAI->getCommentColumn());
1278 O << MAI->getCommentString()
1279 << SecondName << " significant half of i64 " << Val;
1285 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1286 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1287 const TargetData *TD = TM.getTargetData();
1288 const Type *type = CV->getType();
1289 unsigned Size = TD->getTypeAllocSize(type);
1291 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1292 EmitZeros(Size, AddrSpace);
1296 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1297 EmitGlobalConstantArray(CVA , AddrSpace);
1301 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1302 EmitGlobalConstantStruct(CVS, AddrSpace);
1306 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1307 EmitGlobalConstantFP(CFP, AddrSpace);
1311 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1312 // If we can directly emit an 8-byte constant, do it.
1314 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1315 O << Data64Dir << CI->getZExtValue() << '\n';
1319 // Small integers are handled below; large integers are handled here.
1321 EmitGlobalConstantLargeInt(CI, AddrSpace);
1326 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1327 EmitGlobalConstantVector(CP);
1331 printDataDirective(type, AddrSpace);
1332 EmitConstantValueOnly(CV);
1334 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1336 CI->getValue().toStringUnsigned(S, 16);
1337 O.PadToColumn(MAI->getCommentColumn());
1338 O << MAI->getCommentString() << " 0x" << S.str();
1344 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1345 // Target doesn't support this yet!
1346 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1349 /// PrintSpecial - Print information related to the specified machine instr
1350 /// that is independent of the operand, and may be independent of the instr
1351 /// itself. This can be useful for portably encoding the comment character
1352 /// or other bits of target-specific knowledge into the asmstrings. The
1353 /// syntax used is ${:comment}. Targets can override this to add support
1354 /// for their own strange codes.
1355 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1356 if (!strcmp(Code, "private")) {
1357 O << MAI->getPrivateGlobalPrefix();
1358 } else if (!strcmp(Code, "comment")) {
1360 O << MAI->getCommentString();
1361 } else if (!strcmp(Code, "uid")) {
1362 // Comparing the address of MI isn't sufficient, because machineinstrs may
1363 // be allocated to the same address across functions.
1364 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1366 // If this is a new LastFn instruction, bump the counter.
1367 if (LastMI != MI || LastFn != ThisF) {
1375 raw_string_ostream Msg(msg);
1376 Msg << "Unknown special formatter '" << Code
1377 << "' for machine instr: " << *MI;
1378 llvm_report_error(Msg.str());
1382 /// processDebugLoc - Processes the debug information of each machine
1383 /// instruction's DebugLoc.
1384 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1385 bool BeforePrintingInsn) {
1386 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1387 || !DW->ShouldEmitDwarfDebug())
1389 DebugLoc DL = MI->getDebugLoc();
1392 DILocation CurDLT = MF->getDILocation(DL);
1393 if (CurDLT.getScope().isNull())
1396 if (BeforePrintingInsn) {
1397 if (CurDLT.getNode() != PrevDLT.getNode()) {
1398 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1399 CurDLT.getColumnNumber(),
1400 CurDLT.getScope().getNode());
1403 DW->BeginScope(MI, L);
1407 // After printing instruction
1413 /// printInlineAsm - This method formats and prints the specified machine
1414 /// instruction that is an inline asm.
1415 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1416 unsigned NumOperands = MI->getNumOperands();
1418 // Count the number of register definitions.
1419 unsigned NumDefs = 0;
1420 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1422 assert(NumDefs != NumOperands-1 && "No asm string?");
1424 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1426 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1427 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1431 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1432 // These are useful to see where empty asm's wound up.
1433 if (AsmStr[0] == 0) {
1434 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1435 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1439 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1441 // The variant of the current asmprinter.
1442 int AsmPrinterVariant = MAI->getAssemblerDialect();
1444 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1445 const char *LastEmitted = AsmStr; // One past the last character emitted.
1447 while (*LastEmitted) {
1448 switch (*LastEmitted) {
1450 // Not a special case, emit the string section literally.
1451 const char *LiteralEnd = LastEmitted+1;
1452 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1453 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1455 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1456 O.write(LastEmitted, LiteralEnd-LastEmitted);
1457 LastEmitted = LiteralEnd;
1461 ++LastEmitted; // Consume newline character.
1462 O << '\n'; // Indent code with newline.
1465 ++LastEmitted; // Consume '$' character.
1469 switch (*LastEmitted) {
1470 default: Done = false; break;
1471 case '$': // $$ -> $
1472 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1474 ++LastEmitted; // Consume second '$' character.
1476 case '(': // $( -> same as GCC's { character.
1477 ++LastEmitted; // Consume '(' character.
1478 if (CurVariant != -1) {
1479 llvm_report_error("Nested variants found in inline asm string: '"
1480 + std::string(AsmStr) + "'");
1482 CurVariant = 0; // We're in the first variant now.
1485 ++LastEmitted; // consume '|' character.
1486 if (CurVariant == -1)
1487 O << '|'; // this is gcc's behavior for | outside a variant
1489 ++CurVariant; // We're in the next variant.
1491 case ')': // $) -> same as GCC's } char.
1492 ++LastEmitted; // consume ')' character.
1493 if (CurVariant == -1)
1494 O << '}'; // this is gcc's behavior for } outside a variant
1501 bool HasCurlyBraces = false;
1502 if (*LastEmitted == '{') { // ${variable}
1503 ++LastEmitted; // Consume '{' character.
1504 HasCurlyBraces = true;
1507 // If we have ${:foo}, then this is not a real operand reference, it is a
1508 // "magic" string reference, just like in .td files. Arrange to call
1510 if (HasCurlyBraces && *LastEmitted == ':') {
1512 const char *StrStart = LastEmitted;
1513 const char *StrEnd = strchr(StrStart, '}');
1515 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1516 + std::string(AsmStr) + "'");
1519 std::string Val(StrStart, StrEnd);
1520 PrintSpecial(MI, Val.c_str());
1521 LastEmitted = StrEnd+1;
1525 const char *IDStart = LastEmitted;
1528 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1529 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1530 llvm_report_error("Bad $ operand number in inline asm string: '"
1531 + std::string(AsmStr) + "'");
1533 LastEmitted = IDEnd;
1535 char Modifier[2] = { 0, 0 };
1537 if (HasCurlyBraces) {
1538 // If we have curly braces, check for a modifier character. This
1539 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1540 if (*LastEmitted == ':') {
1541 ++LastEmitted; // Consume ':' character.
1542 if (*LastEmitted == 0) {
1543 llvm_report_error("Bad ${:} expression in inline asm string: '"
1544 + std::string(AsmStr) + "'");
1547 Modifier[0] = *LastEmitted;
1548 ++LastEmitted; // Consume modifier character.
1551 if (*LastEmitted != '}') {
1552 llvm_report_error("Bad ${} expression in inline asm string: '"
1553 + std::string(AsmStr) + "'");
1555 ++LastEmitted; // Consume '}' character.
1558 if ((unsigned)Val >= NumOperands-1) {
1559 llvm_report_error("Invalid $ operand number in inline asm string: '"
1560 + std::string(AsmStr) + "'");
1563 // Okay, we finally have a value number. Ask the target to print this
1565 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1570 // Scan to find the machine operand number for the operand.
1571 for (; Val; --Val) {
1572 if (OpNo >= MI->getNumOperands()) break;
1573 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1574 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1577 if (OpNo >= MI->getNumOperands()) {
1580 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1581 ++OpNo; // Skip over the ID number.
1583 if (Modifier[0]=='l') // labels are target independent
1584 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1585 ->getNumber())->print(O, MAI);
1587 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1588 if ((OpFlags & 7) == 4) {
1589 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1590 Modifier[0] ? Modifier : 0);
1592 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1593 Modifier[0] ? Modifier : 0);
1599 raw_string_ostream Msg(msg);
1600 Msg << "Invalid operand found in inline asm: '"
1603 llvm_report_error(Msg.str());
1610 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1613 /// printImplicitDef - This method prints the specified machine instruction
1614 /// that is an implicit def.
1615 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1616 if (!VerboseAsm) return;
1617 O.PadToColumn(MAI->getCommentColumn());
1618 O << MAI->getCommentString() << " implicit-def: "
1619 << TRI->getName(MI->getOperand(0).getReg());
1622 void AsmPrinter::printKill(const MachineInstr *MI) const {
1623 if (!VerboseAsm) return;
1624 O.PadToColumn(MAI->getCommentColumn());
1625 O << MAI->getCommentString() << " kill:";
1626 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1627 const MachineOperand &op = MI->getOperand(n);
1628 assert(op.isReg() && "KILL instruction must have only register operands");
1629 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1633 /// printLabel - This method prints a local label used by debug and
1634 /// exception handling tables.
1635 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1636 printLabel(MI->getOperand(0).getImm());
1639 void AsmPrinter::printLabel(unsigned Id) const {
1640 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1643 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1644 /// instruction, using the specified assembler variant. Targets should
1645 /// override this to format as appropriate.
1646 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1647 unsigned AsmVariant, const char *ExtraCode) {
1648 // Target doesn't support this yet!
1652 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1653 unsigned AsmVariant,
1654 const char *ExtraCode) {
1655 // Target doesn't support this yet!
1659 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1660 const char *Suffix) const {
1661 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1664 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1665 const BasicBlock *BB,
1666 const char *Suffix) const {
1667 assert(BB->hasName() &&
1668 "Address of anonymous basic block not supported yet!");
1670 // This code must use the function name itself, and not the function number,
1671 // since it must be possible to generate the label name from within other
1673 SmallString<60> FnName;
1674 Mang->getNameWithPrefix(FnName, F, false);
1676 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1677 SmallString<60> NameResult;
1678 Mang->getNameWithPrefix(NameResult,
1679 StringRef("BA") + Twine((unsigned)FnName.size()) +
1680 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1683 return OutContext.GetOrCreateSymbol(NameResult.str());
1686 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1687 SmallString<60> Name;
1688 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1689 << getFunctionNumber() << '_' << MBBID;
1691 return OutContext.GetOrCreateSymbol(Name.str());
1694 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1696 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1697 SmallString<60> NameStr;
1698 Mang->getNameWithPrefix(NameStr, GV, false);
1699 return OutContext.GetOrCreateSymbol(NameStr.str());
1702 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1703 /// global value name as its base, with the specified suffix, and where the
1704 /// symbol is forced to have private linkage if ForcePrivate is true.
1705 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1707 bool ForcePrivate) const {
1708 SmallString<60> NameStr;
1709 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1710 NameStr.append(Suffix.begin(), Suffix.end());
1711 return OutContext.GetOrCreateSymbol(NameStr.str());
1714 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1716 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1717 SmallString<60> NameStr;
1718 Mang->getNameWithPrefix(NameStr, Sym);
1719 return OutContext.GetOrCreateSymbol(NameStr.str());
1723 /// EmitBasicBlockStart - This method prints the label for the specified
1724 /// MachineBasicBlock, an alignment (if present) and a comment describing
1725 /// it if appropriate.
1726 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1727 // Emit an alignment directive for this block, if needed.
1728 if (unsigned Align = MBB->getAlignment())
1729 EmitAlignment(Log2_32(Align));
1731 // If the block has its address taken, emit a special label to satisfy
1732 // references to the block. This is done so that we don't need to
1733 // remember the number of this label, and so that we can make
1734 // forward references to labels without knowing what their numbers
1736 if (MBB->hasAddressTaken()) {
1737 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1738 MBB->getBasicBlock())->print(O, MAI);
1741 O.PadToColumn(MAI->getCommentColumn());
1742 O << MAI->getCommentString() << " Address Taken";
1747 // Print the main label for the block.
1748 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1750 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1752 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1758 // Print some comments to accompany the label.
1760 if (const BasicBlock *BB = MBB->getBasicBlock())
1761 if (BB->hasName()) {
1762 O.PadToColumn(MAI->getCommentColumn());
1763 O << MAI->getCommentString() << ' ';
1764 WriteAsOperand(O, BB, /*PrintType=*/false);
1772 /// printPICJumpTableSetLabel - This method prints a set label for the
1773 /// specified MachineBasicBlock for a jumptable entry.
1774 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1775 const MachineBasicBlock *MBB) const {
1776 if (!MAI->getSetDirective())
1779 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1780 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1781 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1782 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1783 << '_' << uid << '\n';
1786 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1787 const MachineBasicBlock *MBB) const {
1788 if (!MAI->getSetDirective())
1791 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1792 << getFunctionNumber() << '_' << uid << '_' << uid2
1793 << "_set_" << MBB->getNumber() << ',';
1794 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1795 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1796 << '_' << uid << '_' << uid2 << '\n';
1799 /// printDataDirective - This method prints the asm directive for the
1801 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1802 const TargetData *TD = TM.getTargetData();
1803 switch (type->getTypeID()) {
1804 case Type::FloatTyID: case Type::DoubleTyID:
1805 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1806 assert(0 && "Should have already output floating point constant.");
1808 assert(0 && "Can't handle printing this type of thing");
1809 case Type::IntegerTyID: {
1810 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1812 O << MAI->getData8bitsDirective(AddrSpace);
1813 else if (BitWidth <= 16)
1814 O << MAI->getData16bitsDirective(AddrSpace);
1815 else if (BitWidth <= 32)
1816 O << MAI->getData32bitsDirective(AddrSpace);
1817 else if (BitWidth <= 64) {
1818 assert(MAI->getData64bitsDirective(AddrSpace) &&
1819 "Target cannot handle 64-bit constant exprs!");
1820 O << MAI->getData64bitsDirective(AddrSpace);
1822 llvm_unreachable("Target cannot handle given data directive width!");
1826 case Type::PointerTyID:
1827 if (TD->getPointerSize() == 8) {
1828 assert(MAI->getData64bitsDirective(AddrSpace) &&
1829 "Target cannot handle 64-bit pointer exprs!");
1830 O << MAI->getData64bitsDirective(AddrSpace);
1831 } else if (TD->getPointerSize() == 2) {
1832 O << MAI->getData16bitsDirective(AddrSpace);
1833 } else if (TD->getPointerSize() == 1) {
1834 O << MAI->getData8bitsDirective(AddrSpace);
1836 O << MAI->getData32bitsDirective(AddrSpace);
1842 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1843 unsigned Visibility) const {
1844 if (Visibility == GlobalValue::HiddenVisibility) {
1845 if (const char *Directive = MAI->getHiddenDirective()) {
1850 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1851 if (const char *Directive = MAI->getProtectedDirective()) {
1859 void AsmPrinter::printOffset(int64_t Offset) const {
1862 else if (Offset < 0)
1866 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1867 if (!S->usesMetadata())
1870 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1871 if (GCPI != GCMetadataPrinters.end())
1872 return GCPI->second;
1874 const char *Name = S->getName().c_str();
1876 for (GCMetadataPrinterRegistry::iterator
1877 I = GCMetadataPrinterRegistry::begin(),
1878 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1879 if (strcmp(Name, I->getName()) == 0) {
1880 GCMetadataPrinter *GMP = I->instantiate();
1882 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1886 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1887 llvm_unreachable(0);
1890 /// EmitComments - Pretty-print comments for instructions
1891 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1895 bool Newline = false;
1897 if (!MI.getDebugLoc().isUnknown()) {
1898 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1900 // Print source line info.
1901 O.PadToColumn(MAI->getCommentColumn());
1902 O << MAI->getCommentString() << ' ';
1903 DIScope Scope = DLT.getScope();
1904 // Omit the directory, because it's likely to be long and uninteresting.
1905 if (!Scope.isNull())
1906 O << Scope.getFilename();
1909 O << ':' << DLT.getLineNumber();
1910 if (DLT.getColumnNumber() != 0)
1911 O << ':' << DLT.getColumnNumber();
1915 // Check for spills and reloads
1918 const MachineFrameInfo *FrameInfo =
1919 MI.getParent()->getParent()->getFrameInfo();
1921 // We assume a single instruction only has a spill or reload, not
1923 const MachineMemOperand *MMO;
1924 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1925 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1926 MMO = *MI.memoperands_begin();
1927 if (Newline) O << '\n';
1928 O.PadToColumn(MAI->getCommentColumn());
1929 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1933 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1934 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1935 if (Newline) O << '\n';
1936 O.PadToColumn(MAI->getCommentColumn());
1937 O << MAI->getCommentString() << ' '
1938 << MMO->getSize() << "-byte Folded Reload";
1942 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1943 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1944 MMO = *MI.memoperands_begin();
1945 if (Newline) O << '\n';
1946 O.PadToColumn(MAI->getCommentColumn());
1947 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1951 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1952 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1953 if (Newline) O << '\n';
1954 O.PadToColumn(MAI->getCommentColumn());
1955 O << MAI->getCommentString() << ' '
1956 << MMO->getSize() << "-byte Folded Spill";
1961 // Check for spill-induced copies
1962 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1963 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1964 SrcSubIdx, DstSubIdx)) {
1965 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1966 if (Newline) O << '\n';
1967 O.PadToColumn(MAI->getCommentColumn());
1968 O << MAI->getCommentString() << " Reload Reuse";
1973 /// PrintChildLoopComment - Print comments about child loops within
1974 /// the loop for this basic block, with nesting.
1976 static void PrintChildLoopComment(formatted_raw_ostream &O,
1977 const MachineLoop *loop,
1978 const MCAsmInfo *MAI,
1979 int FunctionNumber) {
1980 // Add child loop information
1981 for(MachineLoop::iterator cl = loop->begin(),
1982 clend = loop->end();
1985 MachineBasicBlock *Header = (*cl)->getHeader();
1986 assert(Header && "No header for loop");
1989 O.PadToColumn(MAI->getCommentColumn());
1991 O << MAI->getCommentString();
1992 O.indent(((*cl)->getLoopDepth()-1)*2)
1993 << " Child Loop BB" << FunctionNumber << "_"
1994 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1996 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2000 /// EmitComments - Pretty-print comments for basic blocks
2001 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2003 // Add loop depth information
2004 const MachineLoop *loop = LI->getLoopFor(&MBB);
2007 // Print a newline after bb# annotation.
2009 O.PadToColumn(MAI->getCommentColumn());
2010 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2013 O.PadToColumn(MAI->getCommentColumn());
2015 MachineBasicBlock *Header = loop->getHeader();
2016 assert(Header && "No header for loop");
2018 if (Header == &MBB) {
2019 O << MAI->getCommentString() << " Loop Header";
2020 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2023 O << MAI->getCommentString() << " Loop Header is BB"
2024 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2027 if (loop->empty()) {
2029 O.PadToColumn(MAI->getCommentColumn());
2030 O << MAI->getCommentString() << " Inner Loop";
2033 // Add parent loop information
2034 for (const MachineLoop *CurLoop = loop->getParentLoop();
2036 CurLoop = CurLoop->getParentLoop()) {
2037 MachineBasicBlock *Header = CurLoop->getHeader();
2038 assert(Header && "No header for loop");
2041 O.PadToColumn(MAI->getCommentColumn());
2042 O << MAI->getCommentString();
2043 O.indent((CurLoop->getLoopDepth()-1)*2)
2044 << " Inside Loop BB" << getFunctionNumber() << "_"
2045 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();