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/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/DwarfWriter.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/Support/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.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"
46 #include "llvm/ADT/StringExtras.h"
50 static cl::opt<cl::boolOrDefault>
51 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
54 char AsmPrinter::ID = 0;
55 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
56 const MCAsmInfo *T, bool VDef)
57 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
58 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
60 OutContext(*new MCContext()),
61 // FIXME: Pass instprinter to streamer.
62 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
64 LastMI(0), LastFn(0), Counter(~0U),
65 PrevDLT(0, 0, ~0U, ~0U) {
68 case cl::BOU_UNSET: VerboseAsm = VDef; break;
69 case cl::BOU_TRUE: VerboseAsm = true; break;
70 case cl::BOU_FALSE: VerboseAsm = false; break;
74 AsmPrinter::~AsmPrinter() {
75 for (gcp_iterator I = GCMetadataPrinters.begin(),
76 E = GCMetadataPrinters.end(); I != E; ++I)
83 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
84 return TM.getTargetLowering()->getObjFileLowering();
87 /// getCurrentSection() - Return the current section we are emitting to.
88 const MCSection *AsmPrinter::getCurrentSection() const {
89 return OutStreamer.getCurrentSection();
93 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
95 MachineFunctionPass::getAnalysisUsage(AU);
96 AU.addRequired<GCModuleInfo>();
98 AU.addRequired<MachineLoopInfo>();
101 bool AsmPrinter::doInitialization(Module &M) {
102 // Initialize TargetLoweringObjectFile.
103 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
104 .Initialize(OutContext, TM);
106 Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
107 MAI->getLinkerPrivateGlobalPrefix());
109 if (MAI->doesAllowQuotesInName())
110 Mang->setUseQuotes(true);
112 if (MAI->doesAllowNameToStartWithDigit())
113 Mang->setSymbolsCanStartWithDigit(true);
115 // Allow the target to emit any magic that it wants at the start of the file.
116 EmitStartOfAsmFile(M);
118 if (MAI->hasSingleParameterDotFile()) {
119 /* Very minimal debug info. It is ignored if we emit actual
120 debug info. If we don't, this at least helps the user find where
121 a function came from. */
122 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
125 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
126 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
127 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
128 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
129 MP->beginAssembly(O, *this, *MAI);
131 if (!M.getModuleInlineAsm().empty())
132 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
133 << M.getModuleInlineAsm()
134 << '\n' << MAI->getCommentString()
135 << " End of file scope inline assembly\n";
137 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
139 MMI->AnalyzeModule(M);
140 DW = getAnalysisIfAvailable<DwarfWriter>();
142 DW->BeginModule(&M, MMI, O, this, MAI);
147 bool AsmPrinter::doFinalization(Module &M) {
148 // Emit global variables.
149 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
151 PrintGlobalVariable(I);
153 // Emit final debug information.
154 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
157 // If the target wants to know about weak references, print them all.
158 if (MAI->getWeakRefDirective()) {
159 // FIXME: This is not lazy, it would be nice to only print weak references
160 // to stuff that is actually used. Note that doing so would require targets
161 // to notice uses in operands (due to constant exprs etc). This should
162 // happen with the MC stuff eventually.
164 // Print out module-level global variables here.
165 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
167 if (I->hasExternalWeakLinkage())
168 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
171 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
172 if (I->hasExternalWeakLinkage())
173 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
177 if (MAI->getSetDirective()) {
179 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
181 std::string Name = Mang->getMangledName(I);
183 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
184 std::string Target = Mang->getMangledName(GV);
186 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
187 O << "\t.globl\t" << Name << '\n';
188 else if (I->hasWeakLinkage())
189 O << MAI->getWeakRefDirective() << Name << '\n';
190 else if (!I->hasLocalLinkage())
191 llvm_unreachable("Invalid alias linkage");
193 printVisibility(Name, I->getVisibility());
195 O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
199 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
200 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
201 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
202 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
203 MP->finishAssembly(O, *this, *MAI);
205 // If we don't have any trampolines, then we don't require stack memory
206 // to be executable. Some targets have a directive to declare this.
207 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
208 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
209 if (MAI->getNonexecutableStackDirective())
210 O << MAI->getNonexecutableStackDirective() << '\n';
213 // Allow the target to emit any magic that it wants at the end of the file,
214 // after everything else has gone out.
217 delete Mang; Mang = 0;
220 OutStreamer.Finish();
224 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
225 // What's my mangled name?
226 CurrentFnName = Mang->getMangledName(MF.getFunction());
227 IncrementFunctionNumber();
230 LI = &getAnalysis<MachineLoopInfo>();
234 // SectionCPs - Keep track the alignment, constpool entries per Section.
238 SmallVector<unsigned, 4> CPEs;
239 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
243 /// EmitConstantPool - Print to the current output stream assembly
244 /// representations of the constants in the constant pool MCP. This is
245 /// used to print out constants which have been "spilled to memory" by
246 /// the code generator.
248 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
249 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
250 if (CP.empty()) return;
252 // Calculate sections for constant pool entries. We collect entries to go into
253 // the same section together to reduce amount of section switch statements.
254 SmallVector<SectionCPs, 4> CPSections;
255 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
256 const MachineConstantPoolEntry &CPE = CP[i];
257 unsigned Align = CPE.getAlignment();
260 switch (CPE.getRelocationInfo()) {
261 default: llvm_unreachable("Unknown section kind");
262 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
264 Kind = SectionKind::getReadOnlyWithRelLocal();
267 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
268 case 4: Kind = SectionKind::getMergeableConst4(); break;
269 case 8: Kind = SectionKind::getMergeableConst8(); break;
270 case 16: Kind = SectionKind::getMergeableConst16();break;
271 default: Kind = SectionKind::getMergeableConst(); break;
275 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
277 // The number of sections are small, just do a linear search from the
278 // last section to the first.
280 unsigned SecIdx = CPSections.size();
281 while (SecIdx != 0) {
282 if (CPSections[--SecIdx].S == S) {
288 SecIdx = CPSections.size();
289 CPSections.push_back(SectionCPs(S, Align));
292 if (Align > CPSections[SecIdx].Alignment)
293 CPSections[SecIdx].Alignment = Align;
294 CPSections[SecIdx].CPEs.push_back(i);
297 // Now print stuff into the calculated sections.
298 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
299 OutStreamer.SwitchSection(CPSections[i].S);
300 EmitAlignment(Log2_32(CPSections[i].Alignment));
303 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
304 unsigned CPI = CPSections[i].CPEs[j];
305 MachineConstantPoolEntry CPE = CP[CPI];
307 // Emit inter-object padding for alignment.
308 unsigned AlignMask = CPE.getAlignment() - 1;
309 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
310 EmitZeros(NewOffset - Offset);
312 const Type *Ty = CPE.getType();
313 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
315 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
318 O.PadToColumn(MAI->getCommentColumn());
319 O << MAI->getCommentString() << " constant ";
320 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
323 if (CPE.isMachineConstantPoolEntry())
324 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
326 EmitGlobalConstant(CPE.Val.ConstVal);
331 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
332 /// by the current function to the current output stream.
334 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
335 MachineFunction &MF) {
336 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
337 if (JT.empty()) return;
339 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
341 // Pick the directive to use to print the jump table entries, and switch to
342 // the appropriate section.
343 TargetLowering *LoweringInfo = TM.getTargetLowering();
345 const Function *F = MF.getFunction();
346 bool JTInDiffSection = false;
347 if (F->isWeakForLinker() ||
348 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
349 // In PIC mode, we need to emit the jump table to the same section as the
350 // function body itself, otherwise the label differences won't make sense.
351 // We should also do if the section name is NULL or function is declared in
352 // discardable section.
353 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
356 // Otherwise, drop it in the readonly section.
357 const MCSection *ReadOnlySection =
358 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
359 OutStreamer.SwitchSection(ReadOnlySection);
360 JTInDiffSection = true;
363 EmitAlignment(Log2_32(MJTI->getAlignment()));
365 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
366 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
368 // If this jump table was deleted, ignore it.
369 if (JTBBs.empty()) continue;
371 // For PIC codegen, if possible we want to use the SetDirective to reduce
372 // the number of relocations the assembler will generate for the jump table.
373 // Set directives are all printed before the jump table itself.
374 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
375 if (MAI->getSetDirective() && IsPic)
376 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
377 if (EmittedSets.insert(JTBBs[ii]))
378 printPICJumpTableSetLabel(i, JTBBs[ii]);
380 // On some targets (e.g. Darwin) we want to emit two consequtive labels
381 // before each jump table. The first label is never referenced, but tells
382 // the assembler and linker the extents of the jump table object. The
383 // second label is actually referenced by the code.
384 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
385 O << MAI->getLinkerPrivateGlobalPrefix()
386 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
389 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
390 << '_' << i << ":\n";
392 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
393 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
399 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
400 const MachineBasicBlock *MBB,
401 unsigned uid) const {
402 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
404 // Use JumpTableDirective otherwise honor the entry size from the jump table
406 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
407 bool HadJTEntryDirective = JTEntryDirective != NULL;
408 if (!HadJTEntryDirective) {
409 JTEntryDirective = MJTI->getEntrySize() == 4 ?
410 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
413 O << JTEntryDirective << ' ';
415 // If we have emitted set directives for the jump table entries, print
416 // them rather than the entries themselves. If we're emitting PIC, then
417 // emit the table entries as differences between two text section labels.
418 // If we're emitting non-PIC code, then emit the entries as direct
419 // references to the target basic blocks.
421 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
422 } else if (MAI->getSetDirective()) {
423 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
424 << '_' << uid << "_set_" << MBB->getNumber();
426 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
427 // If the arch uses custom Jump Table directives, don't calc relative to
429 if (!HadJTEntryDirective)
430 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
431 << getFunctionNumber() << '_' << uid;
436 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
437 /// special global used by LLVM. If so, emit it and return true, otherwise
438 /// do nothing and return false.
439 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
440 if (GV->getName() == "llvm.used") {
441 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
442 EmitLLVMUsedList(GV->getInitializer());
446 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
447 if (GV->getSection() == "llvm.metadata" ||
448 GV->hasAvailableExternallyLinkage())
451 if (!GV->hasAppendingLinkage()) return false;
453 assert(GV->hasInitializer() && "Not a special LLVM global!");
455 const TargetData *TD = TM.getTargetData();
456 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
457 if (GV->getName() == "llvm.global_ctors") {
458 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
459 EmitAlignment(Align, 0);
460 EmitXXStructorList(GV->getInitializer());
464 if (GV->getName() == "llvm.global_dtors") {
465 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
466 EmitAlignment(Align, 0);
467 EmitXXStructorList(GV->getInitializer());
474 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
475 /// global in the specified llvm.used list for which emitUsedDirectiveFor
476 /// is true, as being used with this directive.
477 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
478 const char *Directive = MAI->getUsedDirective();
480 // Should be an array of 'i8*'.
481 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
482 if (InitList == 0) return;
484 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
485 const GlobalValue *GV =
486 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
487 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
489 EmitConstantValueOnly(InitList->getOperand(i));
495 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
496 /// function pointers, ignoring the init priority.
497 void AsmPrinter::EmitXXStructorList(Constant *List) {
498 // Should be an array of '{ int, void ()* }' structs. The first value is the
499 // init priority, which we ignore.
500 if (!isa<ConstantArray>(List)) return;
501 ConstantArray *InitList = cast<ConstantArray>(List);
502 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
503 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
504 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
506 if (CS->getOperand(1)->isNullValue())
507 return; // Found a null terminator, exit printing.
508 // Emit the function pointer.
509 EmitGlobalConstant(CS->getOperand(1));
514 //===----------------------------------------------------------------------===//
515 /// LEB 128 number encoding.
517 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
518 /// representing an unsigned leb128 value.
519 void AsmPrinter::PrintULEB128(unsigned Value) const {
522 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
524 if (Value) Byte |= 0x80;
525 O << "0x" << utohex_buffer(Byte, Buffer+20);
526 if (Value) O << ", ";
530 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
531 /// representing a signed leb128 value.
532 void AsmPrinter::PrintSLEB128(int Value) const {
533 int Sign = Value >> (8 * sizeof(Value) - 1);
538 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
540 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
541 if (IsMore) Byte |= 0x80;
542 O << "0x" << utohex_buffer(Byte, Buffer+20);
543 if (IsMore) O << ", ";
547 //===--------------------------------------------------------------------===//
548 // Emission and print routines
551 /// PrintHex - Print a value as a hexadecimal value.
553 void AsmPrinter::PrintHex(int Value) const {
555 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
558 /// EOL - Print a newline character to asm stream. If a comment is present
559 /// then it will be printed first. Comments should not contain '\n'.
560 void AsmPrinter::EOL() const {
564 void AsmPrinter::EOL(const std::string &Comment) const {
565 if (VerboseAsm && !Comment.empty()) {
566 O.PadToColumn(MAI->getCommentColumn());
567 O << MAI->getCommentString()
574 void AsmPrinter::EOL(const char* Comment) const {
575 if (VerboseAsm && *Comment) {
576 O.PadToColumn(MAI->getCommentColumn());
577 O << MAI->getCommentString()
584 static const char *DecodeDWARFEncoding(unsigned Encoding) {
586 case dwarf::DW_EH_PE_absptr:
588 case dwarf::DW_EH_PE_omit:
590 case dwarf::DW_EH_PE_pcrel:
592 case dwarf::DW_EH_PE_udata4:
594 case dwarf::DW_EH_PE_udata8:
596 case dwarf::DW_EH_PE_sdata4:
598 case dwarf::DW_EH_PE_sdata8:
600 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
601 return "pcrel udata4";
602 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
603 return "pcrel sdata4";
604 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
605 return "pcrel udata8";
606 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
607 return "pcrel sdata8";
608 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
609 return "indirect pcrel udata4";
610 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
611 return "indirect pcrel sdata4";
612 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
613 return "indirect pcrel udata8";
614 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
615 return "indirect pcrel sdata8";
621 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
622 if (VerboseAsm && *Comment) {
623 O.PadToColumn(MAI->getCommentColumn());
624 O << MAI->getCommentString()
628 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
629 O << " (" << EncStr << ')';
634 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
635 /// unsigned leb128 value.
636 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
637 if (MAI->hasLEB128()) {
641 O << MAI->getData8bitsDirective();
646 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
647 /// signed leb128 value.
648 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
649 if (MAI->hasLEB128()) {
653 O << MAI->getData8bitsDirective();
658 /// EmitInt8 - Emit a byte directive and value.
660 void AsmPrinter::EmitInt8(int Value) const {
661 O << MAI->getData8bitsDirective();
662 PrintHex(Value & 0xFF);
665 /// EmitInt16 - Emit a short directive and value.
667 void AsmPrinter::EmitInt16(int Value) const {
668 O << MAI->getData16bitsDirective();
669 PrintHex(Value & 0xFFFF);
672 /// EmitInt32 - Emit a long directive and value.
674 void AsmPrinter::EmitInt32(int Value) const {
675 O << MAI->getData32bitsDirective();
679 /// EmitInt64 - Emit a long long directive and value.
681 void AsmPrinter::EmitInt64(uint64_t Value) const {
682 if (MAI->getData64bitsDirective()) {
683 O << MAI->getData64bitsDirective();
686 if (TM.getTargetData()->isBigEndian()) {
687 EmitInt32(unsigned(Value >> 32)); O << '\n';
688 EmitInt32(unsigned(Value));
690 EmitInt32(unsigned(Value)); O << '\n';
691 EmitInt32(unsigned(Value >> 32));
696 /// toOctal - Convert the low order bits of X into an octal digit.
698 static inline char toOctal(int X) {
702 /// printStringChar - Print a char, escaped if necessary.
704 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
707 } else if (C == '\\') {
709 } else if (isprint((unsigned char)C)) {
713 case '\b': O << "\\b"; break;
714 case '\f': O << "\\f"; break;
715 case '\n': O << "\\n"; break;
716 case '\r': O << "\\r"; break;
717 case '\t': O << "\\t"; break;
720 O << toOctal(C >> 6);
721 O << toOctal(C >> 3);
722 O << toOctal(C >> 0);
728 /// EmitString - Emit a string with quotes and a null terminator.
729 /// Special characters are emitted properly.
730 /// \literal (Eg. '\t') \endliteral
731 void AsmPrinter::EmitString(const StringRef String) const {
732 EmitString(String.data(), String.size());
735 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
736 const char* AscizDirective = MAI->getAscizDirective();
740 O << MAI->getAsciiDirective();
742 for (unsigned i = 0; i < Size; ++i)
743 printStringChar(O, String[i]);
751 /// EmitFile - Emit a .file directive.
752 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
753 O << "\t.file\t" << Number << " \"";
754 for (unsigned i = 0, N = Name.size(); i < N; ++i)
755 printStringChar(O, Name[i]);
760 //===----------------------------------------------------------------------===//
762 // EmitAlignment - Emit an alignment directive to the specified power of
763 // two boundary. For example, if you pass in 3 here, you will get an 8
764 // byte alignment. If a global value is specified, and if that global has
765 // an explicit alignment requested, it will unconditionally override the
766 // alignment request. However, if ForcedAlignBits is specified, this value
767 // has final say: the ultimate alignment will be the max of ForcedAlignBits
768 // and the alignment computed with NumBits and the global.
772 // if (GV && GV->hasalignment) Align = GV->getalignment();
773 // Align = std::max(Align, ForcedAlignBits);
775 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
776 unsigned ForcedAlignBits,
777 bool UseFillExpr) const {
778 if (GV && GV->getAlignment())
779 NumBits = Log2_32(GV->getAlignment());
780 NumBits = std::max(NumBits, ForcedAlignBits);
782 if (NumBits == 0) return; // No need to emit alignment.
784 unsigned FillValue = 0;
785 if (getCurrentSection()->getKind().isText())
786 FillValue = MAI->getTextAlignFillValue();
788 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
791 /// EmitZeros - Emit a block of zeros.
793 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
795 if (MAI->getZeroDirective()) {
796 O << MAI->getZeroDirective() << NumZeros;
797 if (MAI->getZeroDirectiveSuffix())
798 O << MAI->getZeroDirectiveSuffix();
801 for (; NumZeros; --NumZeros)
802 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
807 // Print out the specified constant, without a storage class. Only the
808 // constants valid in constant expressions can occur here.
809 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
810 if (CV->isNullValue() || isa<UndefValue>(CV)) {
815 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
816 O << CI->getZExtValue();
820 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
821 // This is a constant address for a global variable or function. Use the
822 // name of the variable or function as the address value.
823 O << Mang->getMangledName(GV);
827 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
828 GetBlockAddressSymbol(BA)->print(O, MAI);
832 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
834 llvm_unreachable("Unknown constant value!");
839 switch (CE->getOpcode()) {
840 case Instruction::ZExt:
841 case Instruction::SExt:
842 case Instruction::FPTrunc:
843 case Instruction::FPExt:
844 case Instruction::UIToFP:
845 case Instruction::SIToFP:
846 case Instruction::FPToUI:
847 case Instruction::FPToSI:
849 llvm_unreachable("FIXME: Don't support this constant cast expr");
850 case Instruction::GetElementPtr: {
851 // generate a symbolic expression for the byte address
852 const TargetData *TD = TM.getTargetData();
853 const Constant *ptrVal = CE->getOperand(0);
854 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
855 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
858 return EmitConstantValueOnly(ptrVal);
860 // Truncate/sext the offset to the pointer size.
861 if (TD->getPointerSizeInBits() != 64) {
862 int SExtAmount = 64-TD->getPointerSizeInBits();
863 Offset = (Offset << SExtAmount) >> SExtAmount;
868 EmitConstantValueOnly(ptrVal);
870 O << ") + " << Offset;
872 O << ") - " << -Offset;
875 case Instruction::BitCast:
876 return EmitConstantValueOnly(CE->getOperand(0));
878 case Instruction::IntToPtr: {
879 // Handle casts to pointers by changing them into casts to the appropriate
880 // integer type. This promotes constant folding and simplifies this code.
881 const TargetData *TD = TM.getTargetData();
882 Constant *Op = CE->getOperand(0);
883 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
885 return EmitConstantValueOnly(Op);
888 case Instruction::PtrToInt: {
889 // Support only foldable casts to/from pointers that can be eliminated by
890 // changing the pointer to the appropriately sized integer type.
891 Constant *Op = CE->getOperand(0);
892 const Type *Ty = CE->getType();
893 const TargetData *TD = TM.getTargetData();
895 // We can emit the pointer value into this slot if the slot is an
896 // integer slot greater or equal to the size of the pointer.
897 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
898 return EmitConstantValueOnly(Op);
901 EmitConstantValueOnly(Op);
903 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
906 ptrMask.toStringUnsigned(S);
907 O << ") & " << S.str() << ')';
911 case Instruction::Trunc:
912 // We emit the value and depend on the assembler to truncate the generated
913 // expression properly. This is important for differences between
914 // blockaddress labels. Since the two labels are in the same function, it
915 // is reasonable to treat their delta as a 32-bit value.
916 return EmitConstantValueOnly(CE->getOperand(0));
918 case Instruction::Add:
919 case Instruction::Sub:
920 case Instruction::And:
921 case Instruction::Or:
922 case Instruction::Xor:
924 EmitConstantValueOnly(CE->getOperand(0));
926 switch (CE->getOpcode()) {
927 case Instruction::Add:
930 case Instruction::Sub:
933 case Instruction::And:
936 case Instruction::Or:
939 case Instruction::Xor:
946 EmitConstantValueOnly(CE->getOperand(1));
952 /// printAsCString - Print the specified array as a C compatible string, only if
953 /// the predicate isString is true.
955 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
957 assert(CVA->isString() && "Array is not string compatible!");
960 for (unsigned i = 0; i != LastElt; ++i) {
962 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
963 printStringChar(O, C);
968 /// EmitString - Emit a zero-byte-terminated string constant.
970 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
971 unsigned NumElts = CVA->getNumOperands();
972 if (MAI->getAscizDirective() && NumElts &&
973 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
974 O << MAI->getAscizDirective();
975 printAsCString(O, CVA, NumElts-1);
977 O << MAI->getAsciiDirective();
978 printAsCString(O, CVA, NumElts);
983 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
984 unsigned AddrSpace) {
985 if (CVA->isString()) {
987 } else { // Not a string. Print the values in successive locations
988 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
989 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
993 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
994 const VectorType *PTy = CP->getType();
996 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
997 EmitGlobalConstant(CP->getOperand(I));
1000 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1001 unsigned AddrSpace) {
1002 // Print the fields in successive locations. Pad to align if needed!
1003 const TargetData *TD = TM.getTargetData();
1004 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1005 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1006 uint64_t sizeSoFar = 0;
1007 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1008 const Constant* field = CVS->getOperand(i);
1010 // Check if padding is needed and insert one or more 0s.
1011 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1012 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1013 - cvsLayout->getElementOffset(i)) - fieldSize;
1014 sizeSoFar += fieldSize + padSize;
1016 // Now print the actual field value.
1017 EmitGlobalConstant(field, AddrSpace);
1019 // Insert padding - this may include padding to increase the size of the
1020 // current field up to the ABI size (if the struct is not packed) as well
1021 // as padding to ensure that the next field starts at the right offset.
1022 EmitZeros(padSize, AddrSpace);
1024 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1025 "Layout of constant struct may be incorrect!");
1028 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1029 unsigned AddrSpace) {
1030 // FP Constants are printed as integer constants to avoid losing
1032 LLVMContext &Context = CFP->getContext();
1033 const TargetData *TD = TM.getTargetData();
1034 if (CFP->getType()->isDoubleTy()) {
1035 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1036 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1037 if (MAI->getData64bitsDirective(AddrSpace)) {
1038 O << MAI->getData64bitsDirective(AddrSpace) << i;
1040 O.PadToColumn(MAI->getCommentColumn());
1041 O << MAI->getCommentString() << " double " << Val;
1044 } else if (TD->isBigEndian()) {
1045 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1047 O.PadToColumn(MAI->getCommentColumn());
1048 O << MAI->getCommentString()
1049 << " most 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;
1060 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1062 O.PadToColumn(MAI->getCommentColumn());
1063 O << MAI->getCommentString()
1064 << " least significant word of double " << Val;
1067 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1069 O.PadToColumn(MAI->getCommentColumn());
1070 O << MAI->getCommentString()
1071 << " most significant word of double " << Val;
1078 if (CFP->getType()->isFloatTy()) {
1079 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1080 O << MAI->getData32bitsDirective(AddrSpace)
1081 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1083 O.PadToColumn(MAI->getCommentColumn());
1084 O << MAI->getCommentString() << " float " << Val;
1090 if (CFP->getType()->isX86_FP80Ty()) {
1091 // all long double variants are printed as hex
1092 // api needed to prevent premature destruction
1093 APInt api = CFP->getValueAPF().bitcastToAPInt();
1094 const uint64_t *p = api.getRawData();
1095 // Convert to double so we can print the approximate val as a comment.
1096 APFloat DoubleVal = CFP->getValueAPF();
1098 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1100 if (TD->isBigEndian()) {
1101 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1103 O.PadToColumn(MAI->getCommentColumn());
1104 O << MAI->getCommentString()
1105 << " most significant halfword of x86_fp80 ~"
1106 << DoubleVal.convertToDouble();
1109 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1111 O.PadToColumn(MAI->getCommentColumn());
1112 O << MAI->getCommentString() << " next halfword";
1115 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1117 O.PadToColumn(MAI->getCommentColumn());
1118 O << MAI->getCommentString() << " next halfword";
1121 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1123 O.PadToColumn(MAI->getCommentColumn());
1124 O << MAI->getCommentString() << " next halfword";
1127 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1129 O.PadToColumn(MAI->getCommentColumn());
1130 O << MAI->getCommentString()
1131 << " least significant halfword";
1135 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1137 O.PadToColumn(MAI->getCommentColumn());
1138 O << MAI->getCommentString()
1139 << " least significant halfword of x86_fp80 ~"
1140 << DoubleVal.convertToDouble();
1143 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1145 O.PadToColumn(MAI->getCommentColumn());
1146 O << MAI->getCommentString()
1147 << " next halfword";
1150 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1152 O.PadToColumn(MAI->getCommentColumn());
1153 O << MAI->getCommentString()
1154 << " next halfword";
1157 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1159 O.PadToColumn(MAI->getCommentColumn());
1160 O << MAI->getCommentString()
1161 << " next halfword";
1164 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1166 O.PadToColumn(MAI->getCommentColumn());
1167 O << MAI->getCommentString()
1168 << " most significant halfword";
1172 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1173 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1177 if (CFP->getType()->isPPC_FP128Ty()) {
1178 // all long double variants are printed as hex
1179 // api needed to prevent premature destruction
1180 APInt api = CFP->getValueAPF().bitcastToAPInt();
1181 const uint64_t *p = api.getRawData();
1182 if (TD->isBigEndian()) {
1183 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1185 O.PadToColumn(MAI->getCommentColumn());
1186 O << MAI->getCommentString()
1187 << " most significant word of ppc_fp128";
1190 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1192 O.PadToColumn(MAI->getCommentColumn());
1193 O << MAI->getCommentString()
1197 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1199 O.PadToColumn(MAI->getCommentColumn());
1200 O << MAI->getCommentString()
1204 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1206 O.PadToColumn(MAI->getCommentColumn());
1207 O << MAI->getCommentString()
1208 << " least significant word";
1212 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1214 O.PadToColumn(MAI->getCommentColumn());
1215 O << MAI->getCommentString()
1216 << " least significant word of ppc_fp128";
1219 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1221 O.PadToColumn(MAI->getCommentColumn());
1222 O << MAI->getCommentString()
1226 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1228 O.PadToColumn(MAI->getCommentColumn());
1229 O << MAI->getCommentString()
1233 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1235 O.PadToColumn(MAI->getCommentColumn());
1236 O << MAI->getCommentString()
1237 << " most significant word";
1242 } else llvm_unreachable("Floating point constant type not handled");
1245 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1246 unsigned AddrSpace) {
1247 const TargetData *TD = TM.getTargetData();
1248 unsigned BitWidth = CI->getBitWidth();
1249 assert(isPowerOf2_32(BitWidth) &&
1250 "Non-power-of-2-sized integers not handled!");
1252 // We don't expect assemblers to support integer data directives
1253 // for more than 64 bits, so we emit the data in at most 64-bit
1254 // quantities at a time.
1255 const uint64_t *RawData = CI->getValue().getRawData();
1256 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1258 if (TD->isBigEndian())
1259 Val = RawData[e - i - 1];
1263 if (MAI->getData64bitsDirective(AddrSpace))
1264 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1265 else if (TD->isBigEndian()) {
1266 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1268 O.PadToColumn(MAI->getCommentColumn());
1269 O << MAI->getCommentString()
1270 << " most significant half of i64 " << Val;
1273 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1275 O.PadToColumn(MAI->getCommentColumn());
1276 O << MAI->getCommentString()
1277 << " least significant half of i64 " << Val;
1281 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1283 O.PadToColumn(MAI->getCommentColumn());
1284 O << MAI->getCommentString()
1285 << " least significant half of i64 " << Val;
1288 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1290 O.PadToColumn(MAI->getCommentColumn());
1291 O << MAI->getCommentString()
1292 << " most significant half of i64 " << Val;
1299 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1300 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1301 const TargetData *TD = TM.getTargetData();
1302 const Type *type = CV->getType();
1303 unsigned Size = TD->getTypeAllocSize(type);
1305 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1306 EmitZeros(Size, AddrSpace);
1310 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1311 EmitGlobalConstantArray(CVA , AddrSpace);
1315 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1316 EmitGlobalConstantStruct(CVS, AddrSpace);
1320 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1321 EmitGlobalConstantFP(CFP, AddrSpace);
1325 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1326 // If we can directly emit an 8-byte constant, do it.
1328 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1329 O << Data64Dir << CI->getZExtValue() << '\n';
1333 // Small integers are handled below; large integers are handled here.
1335 EmitGlobalConstantLargeInt(CI, AddrSpace);
1340 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1341 EmitGlobalConstantVector(CP);
1345 printDataDirective(type, AddrSpace);
1346 EmitConstantValueOnly(CV);
1348 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1350 CI->getValue().toStringUnsigned(S, 16);
1351 O.PadToColumn(MAI->getCommentColumn());
1352 O << MAI->getCommentString() << " 0x" << S.str();
1358 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1359 // Target doesn't support this yet!
1360 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1363 /// PrintSpecial - Print information related to the specified machine instr
1364 /// that is independent of the operand, and may be independent of the instr
1365 /// itself. This can be useful for portably encoding the comment character
1366 /// or other bits of target-specific knowledge into the asmstrings. The
1367 /// syntax used is ${:comment}. Targets can override this to add support
1368 /// for their own strange codes.
1369 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1370 if (!strcmp(Code, "private")) {
1371 O << MAI->getPrivateGlobalPrefix();
1372 } else if (!strcmp(Code, "comment")) {
1374 O << MAI->getCommentString();
1375 } else if (!strcmp(Code, "uid")) {
1376 // Comparing the address of MI isn't sufficient, because machineinstrs may
1377 // be allocated to the same address across functions.
1378 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1380 // If this is a new LastFn instruction, bump the counter.
1381 if (LastMI != MI || LastFn != ThisF) {
1389 raw_string_ostream Msg(msg);
1390 Msg << "Unknown special formatter '" << Code
1391 << "' for machine instr: " << *MI;
1392 llvm_report_error(Msg.str());
1396 /// processDebugLoc - Processes the debug information of each machine
1397 /// instruction's DebugLoc.
1398 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1399 bool BeforePrintingInsn) {
1400 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1401 || !DW->ShouldEmitDwarfDebug())
1403 DebugLoc DL = MI->getDebugLoc();
1406 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1407 if (CurDLT.Scope == 0)
1410 if (BeforePrintingInsn) {
1411 if (CurDLT != PrevDLT) {
1412 unsigned L = DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1416 DW->BeginScope(MI, L);
1420 // After printing instruction
1426 /// printInlineAsm - This method formats and prints the specified machine
1427 /// instruction that is an inline asm.
1428 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1429 unsigned NumOperands = MI->getNumOperands();
1431 // Count the number of register definitions.
1432 unsigned NumDefs = 0;
1433 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1435 assert(NumDefs != NumOperands-1 && "No asm string?");
1437 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1439 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1440 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1444 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1445 // These are useful to see where empty asm's wound up.
1446 if (AsmStr[0] == 0) {
1447 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1448 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1452 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1454 // The variant of the current asmprinter.
1455 int AsmPrinterVariant = MAI->getAssemblerDialect();
1457 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1458 const char *LastEmitted = AsmStr; // One past the last character emitted.
1460 while (*LastEmitted) {
1461 switch (*LastEmitted) {
1463 // Not a special case, emit the string section literally.
1464 const char *LiteralEnd = LastEmitted+1;
1465 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1466 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1468 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1469 O.write(LastEmitted, LiteralEnd-LastEmitted);
1470 LastEmitted = LiteralEnd;
1474 ++LastEmitted; // Consume newline character.
1475 O << '\n'; // Indent code with newline.
1478 ++LastEmitted; // Consume '$' character.
1482 switch (*LastEmitted) {
1483 default: Done = false; break;
1484 case '$': // $$ -> $
1485 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1487 ++LastEmitted; // Consume second '$' character.
1489 case '(': // $( -> same as GCC's { character.
1490 ++LastEmitted; // Consume '(' character.
1491 if (CurVariant != -1) {
1492 llvm_report_error("Nested variants found in inline asm string: '"
1493 + std::string(AsmStr) + "'");
1495 CurVariant = 0; // We're in the first variant now.
1498 ++LastEmitted; // consume '|' character.
1499 if (CurVariant == -1)
1500 O << '|'; // this is gcc's behavior for | outside a variant
1502 ++CurVariant; // We're in the next variant.
1504 case ')': // $) -> same as GCC's } char.
1505 ++LastEmitted; // consume ')' character.
1506 if (CurVariant == -1)
1507 O << '}'; // this is gcc's behavior for } outside a variant
1514 bool HasCurlyBraces = false;
1515 if (*LastEmitted == '{') { // ${variable}
1516 ++LastEmitted; // Consume '{' character.
1517 HasCurlyBraces = true;
1520 // If we have ${:foo}, then this is not a real operand reference, it is a
1521 // "magic" string reference, just like in .td files. Arrange to call
1523 if (HasCurlyBraces && *LastEmitted == ':') {
1525 const char *StrStart = LastEmitted;
1526 const char *StrEnd = strchr(StrStart, '}');
1528 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1529 + std::string(AsmStr) + "'");
1532 std::string Val(StrStart, StrEnd);
1533 PrintSpecial(MI, Val.c_str());
1534 LastEmitted = StrEnd+1;
1538 const char *IDStart = LastEmitted;
1541 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1542 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1543 llvm_report_error("Bad $ operand number in inline asm string: '"
1544 + std::string(AsmStr) + "'");
1546 LastEmitted = IDEnd;
1548 char Modifier[2] = { 0, 0 };
1550 if (HasCurlyBraces) {
1551 // If we have curly braces, check for a modifier character. This
1552 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1553 if (*LastEmitted == ':') {
1554 ++LastEmitted; // Consume ':' character.
1555 if (*LastEmitted == 0) {
1556 llvm_report_error("Bad ${:} expression in inline asm string: '"
1557 + std::string(AsmStr) + "'");
1560 Modifier[0] = *LastEmitted;
1561 ++LastEmitted; // Consume modifier character.
1564 if (*LastEmitted != '}') {
1565 llvm_report_error("Bad ${} expression in inline asm string: '"
1566 + std::string(AsmStr) + "'");
1568 ++LastEmitted; // Consume '}' character.
1571 if ((unsigned)Val >= NumOperands-1) {
1572 llvm_report_error("Invalid $ operand number in inline asm string: '"
1573 + std::string(AsmStr) + "'");
1576 // Okay, we finally have a value number. Ask the target to print this
1578 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1583 // Scan to find the machine operand number for the operand.
1584 for (; Val; --Val) {
1585 if (OpNo >= MI->getNumOperands()) break;
1586 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1587 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1590 if (OpNo >= MI->getNumOperands()) {
1593 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1594 ++OpNo; // Skip over the ID number.
1596 if (Modifier[0]=='l') // labels are target independent
1597 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1598 ->getNumber())->print(O, MAI);
1600 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1601 if ((OpFlags & 7) == 4) {
1602 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1603 Modifier[0] ? Modifier : 0);
1605 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1606 Modifier[0] ? Modifier : 0);
1612 raw_string_ostream Msg(msg);
1613 Msg << "Invalid operand found in inline asm: '"
1616 llvm_report_error(Msg.str());
1623 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1626 /// printImplicitDef - This method prints the specified machine instruction
1627 /// that is an implicit def.
1628 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1629 if (!VerboseAsm) return;
1630 O.PadToColumn(MAI->getCommentColumn());
1631 O << MAI->getCommentString() << " implicit-def: "
1632 << TRI->getName(MI->getOperand(0).getReg());
1635 void AsmPrinter::printKill(const MachineInstr *MI) const {
1636 if (!VerboseAsm) return;
1637 O.PadToColumn(MAI->getCommentColumn());
1638 O << MAI->getCommentString() << " kill:";
1639 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1640 const MachineOperand &op = MI->getOperand(n);
1641 assert(op.isReg() && "KILL instruction must have only register operands");
1642 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1646 /// printLabel - This method prints a local label used by debug and
1647 /// exception handling tables.
1648 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1649 printLabel(MI->getOperand(0).getImm());
1652 void AsmPrinter::printLabel(unsigned Id) const {
1653 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1656 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1657 /// instruction, using the specified assembler variant. Targets should
1658 /// overried this to format as appropriate.
1659 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1660 unsigned AsmVariant, const char *ExtraCode) {
1661 // Target doesn't support this yet!
1665 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1666 unsigned AsmVariant,
1667 const char *ExtraCode) {
1668 // Target doesn't support this yet!
1672 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1673 const char *Suffix) const {
1674 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1677 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1678 const BasicBlock *BB,
1679 const char *Suffix) const {
1680 assert(BB->hasName() &&
1681 "Address of anonymous basic block not supported yet!");
1683 // This code must use the function name itself, and not the function number,
1684 // since it must be possible to generate the label name from within other
1686 std::string FuncName = Mang->getMangledName(F);
1688 SmallString<60> Name;
1689 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BA"
1690 << FuncName.size() << '_' << FuncName << '_'
1691 << Mang->makeNameProper(BB->getName())
1694 return OutContext.GetOrCreateSymbol(Name.str());
1697 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1698 SmallString<60> Name;
1699 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1700 << getFunctionNumber() << '_' << MBBID;
1702 return OutContext.GetOrCreateSymbol(Name.str());
1706 /// EmitBasicBlockStart - This method prints the label for the specified
1707 /// MachineBasicBlock, an alignment (if present) and a comment describing
1708 /// it if appropriate.
1709 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1710 // Emit an alignment directive for this block, if needed.
1711 if (unsigned Align = MBB->getAlignment())
1712 EmitAlignment(Log2_32(Align));
1714 // If the block has its address taken, emit a special label to satisfy
1715 // references to the block. This is done so that we don't need to
1716 // remember the number of this label, and so that we can make
1717 // forward references to labels without knowing what their numbers
1719 if (MBB->hasAddressTaken()) {
1720 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1721 MBB->getBasicBlock())->print(O, MAI);
1724 O.PadToColumn(MAI->getCommentColumn());
1725 O << MAI->getCommentString() << " Address Taken";
1730 // Print the main label for the block.
1731 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1733 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1735 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1741 // Print some comments to accompany the label.
1743 if (const BasicBlock *BB = MBB->getBasicBlock())
1744 if (BB->hasName()) {
1745 O.PadToColumn(MAI->getCommentColumn());
1746 O << MAI->getCommentString() << ' ';
1747 WriteAsOperand(O, BB, /*PrintType=*/false);
1755 /// printPICJumpTableSetLabel - This method prints a set label for the
1756 /// specified MachineBasicBlock for a jumptable entry.
1757 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1758 const MachineBasicBlock *MBB) const {
1759 if (!MAI->getSetDirective())
1762 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1763 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1764 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1765 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1766 << '_' << uid << '\n';
1769 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1770 const MachineBasicBlock *MBB) const {
1771 if (!MAI->getSetDirective())
1774 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1775 << getFunctionNumber() << '_' << uid << '_' << uid2
1776 << "_set_" << MBB->getNumber() << ',';
1777 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1778 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1779 << '_' << uid << '_' << uid2 << '\n';
1782 /// printDataDirective - This method prints the asm directive for the
1784 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1785 const TargetData *TD = TM.getTargetData();
1786 switch (type->getTypeID()) {
1787 case Type::FloatTyID: case Type::DoubleTyID:
1788 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1789 assert(0 && "Should have already output floating point constant.");
1791 assert(0 && "Can't handle printing this type of thing");
1792 case Type::IntegerTyID: {
1793 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1795 O << MAI->getData8bitsDirective(AddrSpace);
1796 else if (BitWidth <= 16)
1797 O << MAI->getData16bitsDirective(AddrSpace);
1798 else if (BitWidth <= 32)
1799 O << MAI->getData32bitsDirective(AddrSpace);
1800 else if (BitWidth <= 64) {
1801 assert(MAI->getData64bitsDirective(AddrSpace) &&
1802 "Target cannot handle 64-bit constant exprs!");
1803 O << MAI->getData64bitsDirective(AddrSpace);
1805 llvm_unreachable("Target cannot handle given data directive width!");
1809 case Type::PointerTyID:
1810 if (TD->getPointerSize() == 8) {
1811 assert(MAI->getData64bitsDirective(AddrSpace) &&
1812 "Target cannot handle 64-bit pointer exprs!");
1813 O << MAI->getData64bitsDirective(AddrSpace);
1814 } else if (TD->getPointerSize() == 2) {
1815 O << MAI->getData16bitsDirective(AddrSpace);
1816 } else if (TD->getPointerSize() == 1) {
1817 O << MAI->getData8bitsDirective(AddrSpace);
1819 O << MAI->getData32bitsDirective(AddrSpace);
1825 void AsmPrinter::printVisibility(const std::string& Name,
1826 unsigned Visibility) const {
1827 if (Visibility == GlobalValue::HiddenVisibility) {
1828 if (const char *Directive = MAI->getHiddenDirective())
1829 O << Directive << Name << '\n';
1830 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1831 if (const char *Directive = MAI->getProtectedDirective())
1832 O << Directive << Name << '\n';
1836 void AsmPrinter::printOffset(int64_t Offset) const {
1839 else if (Offset < 0)
1843 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1844 if (!S->usesMetadata())
1847 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1848 if (GCPI != GCMetadataPrinters.end())
1849 return GCPI->second;
1851 const char *Name = S->getName().c_str();
1853 for (GCMetadataPrinterRegistry::iterator
1854 I = GCMetadataPrinterRegistry::begin(),
1855 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1856 if (strcmp(Name, I->getName()) == 0) {
1857 GCMetadataPrinter *GMP = I->instantiate();
1859 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1863 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1864 llvm_unreachable(0);
1867 /// EmitComments - Pretty-print comments for instructions
1868 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1872 bool Newline = false;
1874 if (!MI.getDebugLoc().isUnknown()) {
1875 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1877 // Print source line info.
1878 O.PadToColumn(MAI->getCommentColumn());
1879 O << MAI->getCommentString() << ' ';
1880 DIScope Scope(DLT.Scope);
1881 // Omit the directory, because it's likely to be long and uninteresting.
1882 if (!Scope.isNull())
1883 O << Scope.getFilename();
1886 O << ':' << DLT.Line;
1888 O << ':' << DLT.Col;
1892 // Check for spills and reloads
1895 const MachineFrameInfo *FrameInfo =
1896 MI.getParent()->getParent()->getFrameInfo();
1898 // We assume a single instruction only has a spill or reload, not
1900 const MachineMemOperand *MMO;
1901 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1902 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1903 MMO = *MI.memoperands_begin();
1904 if (Newline) O << '\n';
1905 O.PadToColumn(MAI->getCommentColumn());
1906 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1910 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1911 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1912 if (Newline) O << '\n';
1913 O.PadToColumn(MAI->getCommentColumn());
1914 O << MAI->getCommentString() << ' '
1915 << MMO->getSize() << "-byte Folded Reload";
1919 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1920 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1921 MMO = *MI.memoperands_begin();
1922 if (Newline) O << '\n';
1923 O.PadToColumn(MAI->getCommentColumn());
1924 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1928 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1929 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1930 if (Newline) O << '\n';
1931 O.PadToColumn(MAI->getCommentColumn());
1932 O << MAI->getCommentString() << ' '
1933 << MMO->getSize() << "-byte Folded Spill";
1938 // Check for spill-induced copies
1939 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1940 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1941 SrcSubIdx, DstSubIdx)) {
1942 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1943 if (Newline) O << '\n';
1944 O.PadToColumn(MAI->getCommentColumn());
1945 O << MAI->getCommentString() << " Reload Reuse";
1950 /// PrintChildLoopComment - Print comments about child loops within
1951 /// the loop for this basic block, with nesting.
1953 static void PrintChildLoopComment(formatted_raw_ostream &O,
1954 const MachineLoop *loop,
1955 const MCAsmInfo *MAI,
1956 int FunctionNumber) {
1957 // Add child loop information
1958 for(MachineLoop::iterator cl = loop->begin(),
1959 clend = loop->end();
1962 MachineBasicBlock *Header = (*cl)->getHeader();
1963 assert(Header && "No header for loop");
1966 O.PadToColumn(MAI->getCommentColumn());
1968 O << MAI->getCommentString();
1969 O.indent(((*cl)->getLoopDepth()-1)*2)
1970 << " Child Loop BB" << FunctionNumber << "_"
1971 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1973 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1977 /// EmitComments - Pretty-print comments for basic blocks
1978 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
1980 // Add loop depth information
1981 const MachineLoop *loop = LI->getLoopFor(&MBB);
1984 // Print a newline after bb# annotation.
1986 O.PadToColumn(MAI->getCommentColumn());
1987 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1990 O.PadToColumn(MAI->getCommentColumn());
1992 MachineBasicBlock *Header = loop->getHeader();
1993 assert(Header && "No header for loop");
1995 if (Header == &MBB) {
1996 O << MAI->getCommentString() << " Loop Header";
1997 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2000 O << MAI->getCommentString() << " Loop Header is BB"
2001 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2004 if (loop->empty()) {
2006 O.PadToColumn(MAI->getCommentColumn());
2007 O << MAI->getCommentString() << " Inner Loop";
2010 // Add parent loop information
2011 for (const MachineLoop *CurLoop = loop->getParentLoop();
2013 CurLoop = CurLoop->getParentLoop()) {
2014 MachineBasicBlock *Header = CurLoop->getHeader();
2015 assert(Header && "No header for loop");
2018 O.PadToColumn(MAI->getCommentColumn());
2019 O << MAI->getCommentString();
2020 O.indent((CurLoop->getLoopDepth()-1)*2)
2021 << " Inside Loop BB" << getFunctionNumber() << "_"
2022 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();