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 MCSymbol *Name = GetGlobalValueSymbol(I);
183 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
184 MCSymbol *Target = GetGlobalValueSymbol(GV);
186 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) {
190 } else if (I->hasWeakLinkage()) {
191 O << MAI->getWeakRefDirective();
195 assert(!I->hasLocalLinkage() && "Invalid alias linkage");
198 printVisibility(Name, I->getVisibility());
200 O << MAI->getSetDirective() << ' ';
203 Target->print(O, MAI);
208 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
209 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
210 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
211 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
212 MP->finishAssembly(O, *this, *MAI);
214 // If we don't have any trampolines, then we don't require stack memory
215 // to be executable. Some targets have a directive to declare this.
216 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
217 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
218 if (MAI->getNonexecutableStackDirective())
219 O << MAI->getNonexecutableStackDirective() << '\n';
222 // Allow the target to emit any magic that it wants at the end of the file,
223 // after everything else has gone out.
226 delete Mang; Mang = 0;
229 OutStreamer.Finish();
233 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
234 // What's my mangled name?
235 CurrentFnName = Mang->getMangledName(MF.getFunction());
236 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
237 IncrementFunctionNumber();
240 LI = &getAnalysis<MachineLoopInfo>();
244 // SectionCPs - Keep track the alignment, constpool entries per Section.
248 SmallVector<unsigned, 4> CPEs;
249 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
253 /// EmitConstantPool - Print to the current output stream assembly
254 /// representations of the constants in the constant pool MCP. This is
255 /// used to print out constants which have been "spilled to memory" by
256 /// the code generator.
258 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
259 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
260 if (CP.empty()) return;
262 // Calculate sections for constant pool entries. We collect entries to go into
263 // the same section together to reduce amount of section switch statements.
264 SmallVector<SectionCPs, 4> CPSections;
265 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
266 const MachineConstantPoolEntry &CPE = CP[i];
267 unsigned Align = CPE.getAlignment();
270 switch (CPE.getRelocationInfo()) {
271 default: llvm_unreachable("Unknown section kind");
272 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
274 Kind = SectionKind::getReadOnlyWithRelLocal();
277 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
278 case 4: Kind = SectionKind::getMergeableConst4(); break;
279 case 8: Kind = SectionKind::getMergeableConst8(); break;
280 case 16: Kind = SectionKind::getMergeableConst16();break;
281 default: Kind = SectionKind::getMergeableConst(); break;
285 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
287 // The number of sections are small, just do a linear search from the
288 // last section to the first.
290 unsigned SecIdx = CPSections.size();
291 while (SecIdx != 0) {
292 if (CPSections[--SecIdx].S == S) {
298 SecIdx = CPSections.size();
299 CPSections.push_back(SectionCPs(S, Align));
302 if (Align > CPSections[SecIdx].Alignment)
303 CPSections[SecIdx].Alignment = Align;
304 CPSections[SecIdx].CPEs.push_back(i);
307 // Now print stuff into the calculated sections.
308 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
309 OutStreamer.SwitchSection(CPSections[i].S);
310 EmitAlignment(Log2_32(CPSections[i].Alignment));
313 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
314 unsigned CPI = CPSections[i].CPEs[j];
315 MachineConstantPoolEntry CPE = CP[CPI];
317 // Emit inter-object padding for alignment.
318 unsigned AlignMask = CPE.getAlignment() - 1;
319 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
320 EmitZeros(NewOffset - Offset);
322 const Type *Ty = CPE.getType();
323 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
325 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
328 O.PadToColumn(MAI->getCommentColumn());
329 O << MAI->getCommentString() << " constant ";
330 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
333 if (CPE.isMachineConstantPoolEntry())
334 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
336 EmitGlobalConstant(CPE.Val.ConstVal);
341 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
342 /// by the current function to the current output stream.
344 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
345 MachineFunction &MF) {
346 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
347 if (JT.empty()) return;
349 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
351 // Pick the directive to use to print the jump table entries, and switch to
352 // the appropriate section.
353 TargetLowering *LoweringInfo = TM.getTargetLowering();
355 const Function *F = MF.getFunction();
356 bool JTInDiffSection = false;
357 if (F->isWeakForLinker() ||
358 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
359 // In PIC mode, we need to emit the jump table to the same section as the
360 // function body itself, otherwise the label differences won't make sense.
361 // We should also do if the section name is NULL or function is declared in
362 // discardable section.
363 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
366 // Otherwise, drop it in the readonly section.
367 const MCSection *ReadOnlySection =
368 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
369 OutStreamer.SwitchSection(ReadOnlySection);
370 JTInDiffSection = true;
373 EmitAlignment(Log2_32(MJTI->getAlignment()));
375 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
376 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
378 // If this jump table was deleted, ignore it.
379 if (JTBBs.empty()) continue;
381 // For PIC codegen, if possible we want to use the SetDirective to reduce
382 // the number of relocations the assembler will generate for the jump table.
383 // Set directives are all printed before the jump table itself.
384 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
385 if (MAI->getSetDirective() && IsPic)
386 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
387 if (EmittedSets.insert(JTBBs[ii]))
388 printPICJumpTableSetLabel(i, JTBBs[ii]);
390 // On some targets (e.g. Darwin) we want to emit two consequtive labels
391 // before each jump table. The first label is never referenced, but tells
392 // the assembler and linker the extents of the jump table object. The
393 // second label is actually referenced by the code.
394 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
395 O << MAI->getLinkerPrivateGlobalPrefix()
396 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
399 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
400 << '_' << i << ":\n";
402 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
403 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
409 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
410 const MachineBasicBlock *MBB,
411 unsigned uid) const {
412 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
414 // Use JumpTableDirective otherwise honor the entry size from the jump table
416 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
417 bool HadJTEntryDirective = JTEntryDirective != NULL;
418 if (!HadJTEntryDirective) {
419 JTEntryDirective = MJTI->getEntrySize() == 4 ?
420 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
423 O << JTEntryDirective << ' ';
425 // If we have emitted set directives for the jump table entries, print
426 // them rather than the entries themselves. If we're emitting PIC, then
427 // emit the table entries as differences between two text section labels.
428 // If we're emitting non-PIC code, then emit the entries as direct
429 // references to the target basic blocks.
431 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
432 } else if (MAI->getSetDirective()) {
433 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
434 << '_' << uid << "_set_" << MBB->getNumber();
436 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
437 // If the arch uses custom Jump Table directives, don't calc relative to
439 if (!HadJTEntryDirective)
440 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
441 << getFunctionNumber() << '_' << uid;
446 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
447 /// special global used by LLVM. If so, emit it and return true, otherwise
448 /// do nothing and return false.
449 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
450 if (GV->getName() == "llvm.used") {
451 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
452 EmitLLVMUsedList(GV->getInitializer());
456 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
457 if (GV->getSection() == "llvm.metadata" ||
458 GV->hasAvailableExternallyLinkage())
461 if (!GV->hasAppendingLinkage()) return false;
463 assert(GV->hasInitializer() && "Not a special LLVM global!");
465 const TargetData *TD = TM.getTargetData();
466 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
467 if (GV->getName() == "llvm.global_ctors") {
468 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
469 EmitAlignment(Align, 0);
470 EmitXXStructorList(GV->getInitializer());
474 if (GV->getName() == "llvm.global_dtors") {
475 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
476 EmitAlignment(Align, 0);
477 EmitXXStructorList(GV->getInitializer());
484 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
485 /// global in the specified llvm.used list for which emitUsedDirectiveFor
486 /// is true, as being used with this directive.
487 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
488 const char *Directive = MAI->getUsedDirective();
490 // Should be an array of 'i8*'.
491 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
492 if (InitList == 0) return;
494 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
495 const GlobalValue *GV =
496 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
497 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
499 EmitConstantValueOnly(InitList->getOperand(i));
505 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
506 /// function pointers, ignoring the init priority.
507 void AsmPrinter::EmitXXStructorList(Constant *List) {
508 // Should be an array of '{ int, void ()* }' structs. The first value is the
509 // init priority, which we ignore.
510 if (!isa<ConstantArray>(List)) return;
511 ConstantArray *InitList = cast<ConstantArray>(List);
512 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
513 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
514 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
516 if (CS->getOperand(1)->isNullValue())
517 return; // Found a null terminator, exit printing.
518 // Emit the function pointer.
519 EmitGlobalConstant(CS->getOperand(1));
524 //===----------------------------------------------------------------------===//
525 /// LEB 128 number encoding.
527 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
528 /// representing an unsigned leb128 value.
529 void AsmPrinter::PrintULEB128(unsigned Value) const {
532 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
534 if (Value) Byte |= 0x80;
535 O << "0x" << utohex_buffer(Byte, Buffer+20);
536 if (Value) O << ", ";
540 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
541 /// representing a signed leb128 value.
542 void AsmPrinter::PrintSLEB128(int Value) const {
543 int Sign = Value >> (8 * sizeof(Value) - 1);
548 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
550 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
551 if (IsMore) Byte |= 0x80;
552 O << "0x" << utohex_buffer(Byte, Buffer+20);
553 if (IsMore) O << ", ";
557 //===--------------------------------------------------------------------===//
558 // Emission and print routines
561 /// PrintHex - Print a value as a hexadecimal value.
563 void AsmPrinter::PrintHex(int Value) const {
565 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
568 /// EOL - Print a newline character to asm stream. If a comment is present
569 /// then it will be printed first. Comments should not contain '\n'.
570 void AsmPrinter::EOL() const {
574 void AsmPrinter::EOL(const std::string &Comment) const {
575 if (VerboseAsm && !Comment.empty()) {
576 O.PadToColumn(MAI->getCommentColumn());
577 O << MAI->getCommentString()
584 void AsmPrinter::EOL(const char* Comment) const {
585 if (VerboseAsm && *Comment) {
586 O.PadToColumn(MAI->getCommentColumn());
587 O << MAI->getCommentString()
594 static const char *DecodeDWARFEncoding(unsigned Encoding) {
596 case dwarf::DW_EH_PE_absptr:
598 case dwarf::DW_EH_PE_omit:
600 case dwarf::DW_EH_PE_pcrel:
602 case dwarf::DW_EH_PE_udata4:
604 case dwarf::DW_EH_PE_udata8:
606 case dwarf::DW_EH_PE_sdata4:
608 case dwarf::DW_EH_PE_sdata8:
610 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
611 return "pcrel udata4";
612 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
613 return "pcrel sdata4";
614 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
615 return "pcrel udata8";
616 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
617 return "pcrel sdata8";
618 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
619 return "indirect pcrel udata4";
620 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
621 return "indirect pcrel sdata4";
622 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
623 return "indirect pcrel udata8";
624 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
625 return "indirect pcrel sdata8";
631 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
632 if (VerboseAsm && *Comment) {
633 O.PadToColumn(MAI->getCommentColumn());
634 O << MAI->getCommentString()
638 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
639 O << " (" << EncStr << ')';
644 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
645 /// unsigned leb128 value.
646 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
647 if (MAI->hasLEB128()) {
651 O << MAI->getData8bitsDirective();
656 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
657 /// signed leb128 value.
658 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
659 if (MAI->hasLEB128()) {
663 O << MAI->getData8bitsDirective();
668 /// EmitInt8 - Emit a byte directive and value.
670 void AsmPrinter::EmitInt8(int Value) const {
671 O << MAI->getData8bitsDirective();
672 PrintHex(Value & 0xFF);
675 /// EmitInt16 - Emit a short directive and value.
677 void AsmPrinter::EmitInt16(int Value) const {
678 O << MAI->getData16bitsDirective();
679 PrintHex(Value & 0xFFFF);
682 /// EmitInt32 - Emit a long directive and value.
684 void AsmPrinter::EmitInt32(int Value) const {
685 O << MAI->getData32bitsDirective();
689 /// EmitInt64 - Emit a long long directive and value.
691 void AsmPrinter::EmitInt64(uint64_t Value) const {
692 if (MAI->getData64bitsDirective()) {
693 O << MAI->getData64bitsDirective();
696 if (TM.getTargetData()->isBigEndian()) {
697 EmitInt32(unsigned(Value >> 32)); O << '\n';
698 EmitInt32(unsigned(Value));
700 EmitInt32(unsigned(Value)); O << '\n';
701 EmitInt32(unsigned(Value >> 32));
706 /// toOctal - Convert the low order bits of X into an octal digit.
708 static inline char toOctal(int X) {
712 /// printStringChar - Print a char, escaped if necessary.
714 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
717 } else if (C == '\\') {
719 } else if (isprint((unsigned char)C)) {
723 case '\b': O << "\\b"; break;
724 case '\f': O << "\\f"; break;
725 case '\n': O << "\\n"; break;
726 case '\r': O << "\\r"; break;
727 case '\t': O << "\\t"; break;
730 O << toOctal(C >> 6);
731 O << toOctal(C >> 3);
732 O << toOctal(C >> 0);
738 /// EmitString - Emit a string with quotes and a null terminator.
739 /// Special characters are emitted properly.
740 /// \literal (Eg. '\t') \endliteral
741 void AsmPrinter::EmitString(const StringRef String) const {
742 EmitString(String.data(), String.size());
745 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
746 const char* AscizDirective = MAI->getAscizDirective();
750 O << MAI->getAsciiDirective();
752 for (unsigned i = 0; i < Size; ++i)
753 printStringChar(O, String[i]);
761 /// EmitFile - Emit a .file directive.
762 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
763 O << "\t.file\t" << Number << " \"";
764 for (unsigned i = 0, N = Name.size(); i < N; ++i)
765 printStringChar(O, Name[i]);
770 //===----------------------------------------------------------------------===//
772 // EmitAlignment - Emit an alignment directive to the specified power of
773 // two boundary. For example, if you pass in 3 here, you will get an 8
774 // byte alignment. If a global value is specified, and if that global has
775 // an explicit alignment requested, it will unconditionally override the
776 // alignment request. However, if ForcedAlignBits is specified, this value
777 // has final say: the ultimate alignment will be the max of ForcedAlignBits
778 // and the alignment computed with NumBits and the global.
782 // if (GV && GV->hasalignment) Align = GV->getalignment();
783 // Align = std::max(Align, ForcedAlignBits);
785 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
786 unsigned ForcedAlignBits,
787 bool UseFillExpr) const {
788 if (GV && GV->getAlignment())
789 NumBits = Log2_32(GV->getAlignment());
790 NumBits = std::max(NumBits, ForcedAlignBits);
792 if (NumBits == 0) return; // No need to emit alignment.
794 unsigned FillValue = 0;
795 if (getCurrentSection()->getKind().isText())
796 FillValue = MAI->getTextAlignFillValue();
798 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
801 /// EmitZeros - Emit a block of zeros.
803 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
805 if (MAI->getZeroDirective()) {
806 O << MAI->getZeroDirective() << NumZeros;
807 if (MAI->getZeroDirectiveSuffix())
808 O << MAI->getZeroDirectiveSuffix();
811 for (; NumZeros; --NumZeros)
812 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
817 // Print out the specified constant, without a storage class. Only the
818 // constants valid in constant expressions can occur here.
819 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
820 if (CV->isNullValue() || isa<UndefValue>(CV)) {
825 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
826 O << CI->getZExtValue();
830 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
831 // This is a constant address for a global variable or function. Use the
832 // name of the variable or function as the address value.
833 O << Mang->getMangledName(GV);
837 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
838 GetBlockAddressSymbol(BA)->print(O, MAI);
842 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
844 llvm_unreachable("Unknown constant value!");
849 switch (CE->getOpcode()) {
850 case Instruction::ZExt:
851 case Instruction::SExt:
852 case Instruction::FPTrunc:
853 case Instruction::FPExt:
854 case Instruction::UIToFP:
855 case Instruction::SIToFP:
856 case Instruction::FPToUI:
857 case Instruction::FPToSI:
859 llvm_unreachable("FIXME: Don't support this constant cast expr");
860 case Instruction::GetElementPtr: {
861 // generate a symbolic expression for the byte address
862 const TargetData *TD = TM.getTargetData();
863 const Constant *ptrVal = CE->getOperand(0);
864 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
865 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
868 return EmitConstantValueOnly(ptrVal);
870 // Truncate/sext the offset to the pointer size.
871 if (TD->getPointerSizeInBits() != 64) {
872 int SExtAmount = 64-TD->getPointerSizeInBits();
873 Offset = (Offset << SExtAmount) >> SExtAmount;
878 EmitConstantValueOnly(ptrVal);
880 O << ") + " << Offset;
882 O << ") - " << -Offset;
885 case Instruction::BitCast:
886 return EmitConstantValueOnly(CE->getOperand(0));
888 case Instruction::IntToPtr: {
889 // Handle casts to pointers by changing them into casts to the appropriate
890 // integer type. This promotes constant folding and simplifies this code.
891 const TargetData *TD = TM.getTargetData();
892 Constant *Op = CE->getOperand(0);
893 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
895 return EmitConstantValueOnly(Op);
898 case Instruction::PtrToInt: {
899 // Support only foldable casts to/from pointers that can be eliminated by
900 // changing the pointer to the appropriately sized integer type.
901 Constant *Op = CE->getOperand(0);
902 const Type *Ty = CE->getType();
903 const TargetData *TD = TM.getTargetData();
905 // We can emit the pointer value into this slot if the slot is an
906 // integer slot greater or equal to the size of the pointer.
907 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
908 return EmitConstantValueOnly(Op);
911 EmitConstantValueOnly(Op);
913 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
916 ptrMask.toStringUnsigned(S);
917 O << ") & " << S.str() << ')';
921 case Instruction::Trunc:
922 // We emit the value and depend on the assembler to truncate the generated
923 // expression properly. This is important for differences between
924 // blockaddress labels. Since the two labels are in the same function, it
925 // is reasonable to treat their delta as a 32-bit value.
926 return EmitConstantValueOnly(CE->getOperand(0));
928 case Instruction::Add:
929 case Instruction::Sub:
930 case Instruction::And:
931 case Instruction::Or:
932 case Instruction::Xor:
934 EmitConstantValueOnly(CE->getOperand(0));
936 switch (CE->getOpcode()) {
937 case Instruction::Add:
940 case Instruction::Sub:
943 case Instruction::And:
946 case Instruction::Or:
949 case Instruction::Xor:
956 EmitConstantValueOnly(CE->getOperand(1));
962 /// printAsCString - Print the specified array as a C compatible string, only if
963 /// the predicate isString is true.
965 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
967 assert(CVA->isString() && "Array is not string compatible!");
970 for (unsigned i = 0; i != LastElt; ++i) {
972 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
973 printStringChar(O, C);
978 /// EmitString - Emit a zero-byte-terminated string constant.
980 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
981 unsigned NumElts = CVA->getNumOperands();
982 if (MAI->getAscizDirective() && NumElts &&
983 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
984 O << MAI->getAscizDirective();
985 printAsCString(O, CVA, NumElts-1);
987 O << MAI->getAsciiDirective();
988 printAsCString(O, CVA, NumElts);
993 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
994 unsigned AddrSpace) {
995 if (CVA->isString()) {
997 } else { // Not a string. Print the values in successive locations
998 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
999 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1003 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1004 const VectorType *PTy = CP->getType();
1006 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1007 EmitGlobalConstant(CP->getOperand(I));
1010 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1011 unsigned AddrSpace) {
1012 // Print the fields in successive locations. Pad to align if needed!
1013 const TargetData *TD = TM.getTargetData();
1014 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1015 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1016 uint64_t sizeSoFar = 0;
1017 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1018 const Constant* field = CVS->getOperand(i);
1020 // Check if padding is needed and insert one or more 0s.
1021 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1022 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1023 - cvsLayout->getElementOffset(i)) - fieldSize;
1024 sizeSoFar += fieldSize + padSize;
1026 // Now print the actual field value.
1027 EmitGlobalConstant(field, AddrSpace);
1029 // Insert padding - this may include padding to increase the size of the
1030 // current field up to the ABI size (if the struct is not packed) as well
1031 // as padding to ensure that the next field starts at the right offset.
1032 EmitZeros(padSize, AddrSpace);
1034 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1035 "Layout of constant struct may be incorrect!");
1038 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1039 unsigned AddrSpace) {
1040 // FP Constants are printed as integer constants to avoid losing
1042 LLVMContext &Context = CFP->getContext();
1043 const TargetData *TD = TM.getTargetData();
1044 if (CFP->getType()->isDoubleTy()) {
1045 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1046 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1047 if (MAI->getData64bitsDirective(AddrSpace)) {
1048 O << MAI->getData64bitsDirective(AddrSpace) << i;
1050 O.PadToColumn(MAI->getCommentColumn());
1051 O << MAI->getCommentString() << " double " << Val;
1054 } else if (TD->isBigEndian()) {
1055 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1057 O.PadToColumn(MAI->getCommentColumn());
1058 O << MAI->getCommentString()
1059 << " most significant word of double " << Val;
1062 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1064 O.PadToColumn(MAI->getCommentColumn());
1065 O << MAI->getCommentString()
1066 << " least significant word of double " << Val;
1070 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1072 O.PadToColumn(MAI->getCommentColumn());
1073 O << MAI->getCommentString()
1074 << " least significant word of double " << Val;
1077 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1079 O.PadToColumn(MAI->getCommentColumn());
1080 O << MAI->getCommentString()
1081 << " most significant word of double " << Val;
1088 if (CFP->getType()->isFloatTy()) {
1089 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1090 O << MAI->getData32bitsDirective(AddrSpace)
1091 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1093 O.PadToColumn(MAI->getCommentColumn());
1094 O << MAI->getCommentString() << " float " << Val;
1100 if (CFP->getType()->isX86_FP80Ty()) {
1101 // all long double variants are printed as hex
1102 // api needed to prevent premature destruction
1103 APInt api = CFP->getValueAPF().bitcastToAPInt();
1104 const uint64_t *p = api.getRawData();
1105 // Convert to double so we can print the approximate val as a comment.
1106 APFloat DoubleVal = CFP->getValueAPF();
1108 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1110 if (TD->isBigEndian()) {
1111 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1113 O.PadToColumn(MAI->getCommentColumn());
1114 O << MAI->getCommentString()
1115 << " most significant halfword of x86_fp80 ~"
1116 << DoubleVal.convertToDouble();
1119 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1121 O.PadToColumn(MAI->getCommentColumn());
1122 O << MAI->getCommentString() << " next halfword";
1125 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1127 O.PadToColumn(MAI->getCommentColumn());
1128 O << MAI->getCommentString() << " next halfword";
1131 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1133 O.PadToColumn(MAI->getCommentColumn());
1134 O << MAI->getCommentString() << " next halfword";
1137 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1139 O.PadToColumn(MAI->getCommentColumn());
1140 O << MAI->getCommentString()
1141 << " least significant halfword";
1145 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1147 O.PadToColumn(MAI->getCommentColumn());
1148 O << MAI->getCommentString()
1149 << " least significant halfword of x86_fp80 ~"
1150 << DoubleVal.convertToDouble();
1153 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1155 O.PadToColumn(MAI->getCommentColumn());
1156 O << MAI->getCommentString()
1157 << " next halfword";
1160 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1162 O.PadToColumn(MAI->getCommentColumn());
1163 O << MAI->getCommentString()
1164 << " next halfword";
1167 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1169 O.PadToColumn(MAI->getCommentColumn());
1170 O << MAI->getCommentString()
1171 << " next halfword";
1174 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1176 O.PadToColumn(MAI->getCommentColumn());
1177 O << MAI->getCommentString()
1178 << " most significant halfword";
1182 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1183 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1187 if (CFP->getType()->isPPC_FP128Ty()) {
1188 // all long double variants are printed as hex
1189 // api needed to prevent premature destruction
1190 APInt api = CFP->getValueAPF().bitcastToAPInt();
1191 const uint64_t *p = api.getRawData();
1192 if (TD->isBigEndian()) {
1193 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1195 O.PadToColumn(MAI->getCommentColumn());
1196 O << MAI->getCommentString()
1197 << " most significant word of ppc_fp128";
1200 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1202 O.PadToColumn(MAI->getCommentColumn());
1203 O << MAI->getCommentString()
1207 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1209 O.PadToColumn(MAI->getCommentColumn());
1210 O << MAI->getCommentString()
1214 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1216 O.PadToColumn(MAI->getCommentColumn());
1217 O << MAI->getCommentString()
1218 << " least significant word";
1222 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1224 O.PadToColumn(MAI->getCommentColumn());
1225 O << MAI->getCommentString()
1226 << " least significant word of ppc_fp128";
1229 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1231 O.PadToColumn(MAI->getCommentColumn());
1232 O << MAI->getCommentString()
1236 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1238 O.PadToColumn(MAI->getCommentColumn());
1239 O << MAI->getCommentString()
1243 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1245 O.PadToColumn(MAI->getCommentColumn());
1246 O << MAI->getCommentString()
1247 << " most significant word";
1252 } else llvm_unreachable("Floating point constant type not handled");
1255 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1256 unsigned AddrSpace) {
1257 const TargetData *TD = TM.getTargetData();
1258 unsigned BitWidth = CI->getBitWidth();
1259 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1261 // We don't expect assemblers to support integer data directives
1262 // for more than 64 bits, so we emit the data in at most 64-bit
1263 // quantities at a time.
1264 const uint64_t *RawData = CI->getValue().getRawData();
1265 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1267 if (TD->isBigEndian())
1268 Val = RawData[e - i - 1];
1272 if (MAI->getData64bitsDirective(AddrSpace)) {
1273 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1277 // Emit two 32-bit chunks, order depends on endianness.
1278 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1279 const char *FirstName = " least", *SecondName = " most";
1280 if (TD->isBigEndian()) {
1281 std::swap(FirstChunk, SecondChunk);
1282 std::swap(FirstName, SecondName);
1285 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1287 O.PadToColumn(MAI->getCommentColumn());
1288 O << MAI->getCommentString()
1289 << FirstName << " significant half of i64 " << Val;
1293 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1295 O.PadToColumn(MAI->getCommentColumn());
1296 O << MAI->getCommentString()
1297 << SecondName << " significant half of i64 " << Val;
1303 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1304 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1305 const TargetData *TD = TM.getTargetData();
1306 const Type *type = CV->getType();
1307 unsigned Size = TD->getTypeAllocSize(type);
1309 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1310 EmitZeros(Size, AddrSpace);
1314 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1315 EmitGlobalConstantArray(CVA , AddrSpace);
1319 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1320 EmitGlobalConstantStruct(CVS, AddrSpace);
1324 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1325 EmitGlobalConstantFP(CFP, AddrSpace);
1329 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1330 // If we can directly emit an 8-byte constant, do it.
1332 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1333 O << Data64Dir << CI->getZExtValue() << '\n';
1337 // Small integers are handled below; large integers are handled here.
1339 EmitGlobalConstantLargeInt(CI, AddrSpace);
1344 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1345 EmitGlobalConstantVector(CP);
1349 printDataDirective(type, AddrSpace);
1350 EmitConstantValueOnly(CV);
1352 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1354 CI->getValue().toStringUnsigned(S, 16);
1355 O.PadToColumn(MAI->getCommentColumn());
1356 O << MAI->getCommentString() << " 0x" << S.str();
1362 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1363 // Target doesn't support this yet!
1364 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1367 /// PrintSpecial - Print information related to the specified machine instr
1368 /// that is independent of the operand, and may be independent of the instr
1369 /// itself. This can be useful for portably encoding the comment character
1370 /// or other bits of target-specific knowledge into the asmstrings. The
1371 /// syntax used is ${:comment}. Targets can override this to add support
1372 /// for their own strange codes.
1373 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1374 if (!strcmp(Code, "private")) {
1375 O << MAI->getPrivateGlobalPrefix();
1376 } else if (!strcmp(Code, "comment")) {
1378 O << MAI->getCommentString();
1379 } else if (!strcmp(Code, "uid")) {
1380 // Comparing the address of MI isn't sufficient, because machineinstrs may
1381 // be allocated to the same address across functions.
1382 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1384 // If this is a new LastFn instruction, bump the counter.
1385 if (LastMI != MI || LastFn != ThisF) {
1393 raw_string_ostream Msg(msg);
1394 Msg << "Unknown special formatter '" << Code
1395 << "' for machine instr: " << *MI;
1396 llvm_report_error(Msg.str());
1400 /// processDebugLoc - Processes the debug information of each machine
1401 /// instruction's DebugLoc.
1402 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1403 bool BeforePrintingInsn) {
1404 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1405 || !DW->ShouldEmitDwarfDebug())
1407 DebugLoc DL = MI->getDebugLoc();
1410 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1411 if (CurDLT.Scope == 0)
1414 if (BeforePrintingInsn) {
1415 if (CurDLT != PrevDLT) {
1416 unsigned L = DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1420 DW->BeginScope(MI, L);
1424 // After printing instruction
1430 /// printInlineAsm - This method formats and prints the specified machine
1431 /// instruction that is an inline asm.
1432 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1433 unsigned NumOperands = MI->getNumOperands();
1435 // Count the number of register definitions.
1436 unsigned NumDefs = 0;
1437 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1439 assert(NumDefs != NumOperands-1 && "No asm string?");
1441 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1443 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1444 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1448 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1449 // These are useful to see where empty asm's wound up.
1450 if (AsmStr[0] == 0) {
1451 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1452 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1456 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1458 // The variant of the current asmprinter.
1459 int AsmPrinterVariant = MAI->getAssemblerDialect();
1461 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1462 const char *LastEmitted = AsmStr; // One past the last character emitted.
1464 while (*LastEmitted) {
1465 switch (*LastEmitted) {
1467 // Not a special case, emit the string section literally.
1468 const char *LiteralEnd = LastEmitted+1;
1469 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1470 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1472 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1473 O.write(LastEmitted, LiteralEnd-LastEmitted);
1474 LastEmitted = LiteralEnd;
1478 ++LastEmitted; // Consume newline character.
1479 O << '\n'; // Indent code with newline.
1482 ++LastEmitted; // Consume '$' character.
1486 switch (*LastEmitted) {
1487 default: Done = false; break;
1488 case '$': // $$ -> $
1489 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1491 ++LastEmitted; // Consume second '$' character.
1493 case '(': // $( -> same as GCC's { character.
1494 ++LastEmitted; // Consume '(' character.
1495 if (CurVariant != -1) {
1496 llvm_report_error("Nested variants found in inline asm string: '"
1497 + std::string(AsmStr) + "'");
1499 CurVariant = 0; // We're in the first variant now.
1502 ++LastEmitted; // consume '|' character.
1503 if (CurVariant == -1)
1504 O << '|'; // this is gcc's behavior for | outside a variant
1506 ++CurVariant; // We're in the next variant.
1508 case ')': // $) -> same as GCC's } char.
1509 ++LastEmitted; // consume ')' character.
1510 if (CurVariant == -1)
1511 O << '}'; // this is gcc's behavior for } outside a variant
1518 bool HasCurlyBraces = false;
1519 if (*LastEmitted == '{') { // ${variable}
1520 ++LastEmitted; // Consume '{' character.
1521 HasCurlyBraces = true;
1524 // If we have ${:foo}, then this is not a real operand reference, it is a
1525 // "magic" string reference, just like in .td files. Arrange to call
1527 if (HasCurlyBraces && *LastEmitted == ':') {
1529 const char *StrStart = LastEmitted;
1530 const char *StrEnd = strchr(StrStart, '}');
1532 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1533 + std::string(AsmStr) + "'");
1536 std::string Val(StrStart, StrEnd);
1537 PrintSpecial(MI, Val.c_str());
1538 LastEmitted = StrEnd+1;
1542 const char *IDStart = LastEmitted;
1545 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1546 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1547 llvm_report_error("Bad $ operand number in inline asm string: '"
1548 + std::string(AsmStr) + "'");
1550 LastEmitted = IDEnd;
1552 char Modifier[2] = { 0, 0 };
1554 if (HasCurlyBraces) {
1555 // If we have curly braces, check for a modifier character. This
1556 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1557 if (*LastEmitted == ':') {
1558 ++LastEmitted; // Consume ':' character.
1559 if (*LastEmitted == 0) {
1560 llvm_report_error("Bad ${:} expression in inline asm string: '"
1561 + std::string(AsmStr) + "'");
1564 Modifier[0] = *LastEmitted;
1565 ++LastEmitted; // Consume modifier character.
1568 if (*LastEmitted != '}') {
1569 llvm_report_error("Bad ${} expression in inline asm string: '"
1570 + std::string(AsmStr) + "'");
1572 ++LastEmitted; // Consume '}' character.
1575 if ((unsigned)Val >= NumOperands-1) {
1576 llvm_report_error("Invalid $ operand number in inline asm string: '"
1577 + std::string(AsmStr) + "'");
1580 // Okay, we finally have a value number. Ask the target to print this
1582 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1587 // Scan to find the machine operand number for the operand.
1588 for (; Val; --Val) {
1589 if (OpNo >= MI->getNumOperands()) break;
1590 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1591 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1594 if (OpNo >= MI->getNumOperands()) {
1597 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1598 ++OpNo; // Skip over the ID number.
1600 if (Modifier[0]=='l') // labels are target independent
1601 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1602 ->getNumber())->print(O, MAI);
1604 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1605 if ((OpFlags & 7) == 4) {
1606 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1607 Modifier[0] ? Modifier : 0);
1609 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1610 Modifier[0] ? Modifier : 0);
1616 raw_string_ostream Msg(msg);
1617 Msg << "Invalid operand found in inline asm: '"
1620 llvm_report_error(Msg.str());
1627 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1630 /// printImplicitDef - This method prints the specified machine instruction
1631 /// that is an implicit def.
1632 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1633 if (!VerboseAsm) return;
1634 O.PadToColumn(MAI->getCommentColumn());
1635 O << MAI->getCommentString() << " implicit-def: "
1636 << TRI->getName(MI->getOperand(0).getReg());
1639 void AsmPrinter::printKill(const MachineInstr *MI) const {
1640 if (!VerboseAsm) return;
1641 O.PadToColumn(MAI->getCommentColumn());
1642 O << MAI->getCommentString() << " kill:";
1643 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1644 const MachineOperand &op = MI->getOperand(n);
1645 assert(op.isReg() && "KILL instruction must have only register operands");
1646 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1650 /// printLabel - This method prints a local label used by debug and
1651 /// exception handling tables.
1652 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1653 printLabel(MI->getOperand(0).getImm());
1656 void AsmPrinter::printLabel(unsigned Id) const {
1657 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1660 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1661 /// instruction, using the specified assembler variant. Targets should
1662 /// override this to format as appropriate.
1663 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1664 unsigned AsmVariant, const char *ExtraCode) {
1665 // Target doesn't support this yet!
1669 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1670 unsigned AsmVariant,
1671 const char *ExtraCode) {
1672 // Target doesn't support this yet!
1676 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1677 const char *Suffix) const {
1678 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1681 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1682 const BasicBlock *BB,
1683 const char *Suffix) const {
1684 assert(BB->hasName() &&
1685 "Address of anonymous basic block not supported yet!");
1687 // This code must use the function name itself, and not the function number,
1688 // since it must be possible to generate the label name from within other
1690 SmallString<60> FnName;
1691 Mang->getNameWithPrefix(FnName, F, false);
1693 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1694 SmallString<60> NameResult;
1695 Mang->getNameWithPrefix(NameResult,
1696 StringRef("BA") + Twine((unsigned)FnName.size()) +
1697 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1700 return OutContext.GetOrCreateSymbol(NameResult.str());
1703 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1704 SmallString<60> Name;
1705 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1706 << getFunctionNumber() << '_' << MBBID;
1708 return OutContext.GetOrCreateSymbol(Name.str());
1711 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1713 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1714 SmallString<60> NameStr;
1715 Mang->getNameWithPrefix(NameStr, GV, false);
1716 return OutContext.GetOrCreateSymbol(NameStr.str());
1719 /// GetPrivateGlobalValueSymbolStub - Return the MCSymbol for a symbol with
1720 /// global value name as its base, with the specified suffix, and where the
1721 /// symbol is forced to have private linkage.
1722 MCSymbol *AsmPrinter::GetPrivateGlobalValueSymbolStub(const GlobalValue *GV,
1723 StringRef Suffix) const {
1724 SmallString<60> NameStr;
1725 Mang->getNameWithPrefix(NameStr, GV, true);
1726 NameStr.append(Suffix.begin(), Suffix.end());
1727 return OutContext.GetOrCreateSymbol(NameStr.str());
1730 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1732 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1733 SmallString<60> NameStr;
1734 Mang->getNameWithPrefix(NameStr, Sym);
1735 return OutContext.GetOrCreateSymbol(NameStr.str());
1739 /// EmitBasicBlockStart - This method prints the label for the specified
1740 /// MachineBasicBlock, an alignment (if present) and a comment describing
1741 /// it if appropriate.
1742 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1743 // Emit an alignment directive for this block, if needed.
1744 if (unsigned Align = MBB->getAlignment())
1745 EmitAlignment(Log2_32(Align));
1747 // If the block has its address taken, emit a special label to satisfy
1748 // references to the block. This is done so that we don't need to
1749 // remember the number of this label, and so that we can make
1750 // forward references to labels without knowing what their numbers
1752 if (MBB->hasAddressTaken()) {
1753 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1754 MBB->getBasicBlock())->print(O, MAI);
1757 O.PadToColumn(MAI->getCommentColumn());
1758 O << MAI->getCommentString() << " Address Taken";
1763 // Print the main label for the block.
1764 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1766 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1768 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1774 // Print some comments to accompany the label.
1776 if (const BasicBlock *BB = MBB->getBasicBlock())
1777 if (BB->hasName()) {
1778 O.PadToColumn(MAI->getCommentColumn());
1779 O << MAI->getCommentString() << ' ';
1780 WriteAsOperand(O, BB, /*PrintType=*/false);
1788 /// printPICJumpTableSetLabel - This method prints a set label for the
1789 /// specified MachineBasicBlock for a jumptable entry.
1790 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1791 const MachineBasicBlock *MBB) const {
1792 if (!MAI->getSetDirective())
1795 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1796 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1797 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1798 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1799 << '_' << uid << '\n';
1802 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1803 const MachineBasicBlock *MBB) const {
1804 if (!MAI->getSetDirective())
1807 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1808 << getFunctionNumber() << '_' << uid << '_' << uid2
1809 << "_set_" << MBB->getNumber() << ',';
1810 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1811 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1812 << '_' << uid << '_' << uid2 << '\n';
1815 /// printDataDirective - This method prints the asm directive for the
1817 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1818 const TargetData *TD = TM.getTargetData();
1819 switch (type->getTypeID()) {
1820 case Type::FloatTyID: case Type::DoubleTyID:
1821 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1822 assert(0 && "Should have already output floating point constant.");
1824 assert(0 && "Can't handle printing this type of thing");
1825 case Type::IntegerTyID: {
1826 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1828 O << MAI->getData8bitsDirective(AddrSpace);
1829 else if (BitWidth <= 16)
1830 O << MAI->getData16bitsDirective(AddrSpace);
1831 else if (BitWidth <= 32)
1832 O << MAI->getData32bitsDirective(AddrSpace);
1833 else if (BitWidth <= 64) {
1834 assert(MAI->getData64bitsDirective(AddrSpace) &&
1835 "Target cannot handle 64-bit constant exprs!");
1836 O << MAI->getData64bitsDirective(AddrSpace);
1838 llvm_unreachable("Target cannot handle given data directive width!");
1842 case Type::PointerTyID:
1843 if (TD->getPointerSize() == 8) {
1844 assert(MAI->getData64bitsDirective(AddrSpace) &&
1845 "Target cannot handle 64-bit pointer exprs!");
1846 O << MAI->getData64bitsDirective(AddrSpace);
1847 } else if (TD->getPointerSize() == 2) {
1848 O << MAI->getData16bitsDirective(AddrSpace);
1849 } else if (TD->getPointerSize() == 1) {
1850 O << MAI->getData8bitsDirective(AddrSpace);
1852 O << MAI->getData32bitsDirective(AddrSpace);
1858 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1859 unsigned Visibility) const {
1860 if (Visibility == GlobalValue::HiddenVisibility) {
1861 if (const char *Directive = MAI->getHiddenDirective()) {
1866 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1867 if (const char *Directive = MAI->getProtectedDirective()) {
1875 void AsmPrinter::printOffset(int64_t Offset) const {
1878 else if (Offset < 0)
1882 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1883 if (!S->usesMetadata())
1886 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1887 if (GCPI != GCMetadataPrinters.end())
1888 return GCPI->second;
1890 const char *Name = S->getName().c_str();
1892 for (GCMetadataPrinterRegistry::iterator
1893 I = GCMetadataPrinterRegistry::begin(),
1894 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1895 if (strcmp(Name, I->getName()) == 0) {
1896 GCMetadataPrinter *GMP = I->instantiate();
1898 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1902 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1903 llvm_unreachable(0);
1906 /// EmitComments - Pretty-print comments for instructions
1907 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1911 bool Newline = false;
1913 if (!MI.getDebugLoc().isUnknown()) {
1914 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1916 // Print source line info.
1917 O.PadToColumn(MAI->getCommentColumn());
1918 O << MAI->getCommentString() << ' ';
1919 DIScope Scope(DLT.Scope);
1920 // Omit the directory, because it's likely to be long and uninteresting.
1921 if (!Scope.isNull())
1922 O << Scope.getFilename();
1925 O << ':' << DLT.Line;
1927 O << ':' << DLT.Col;
1931 // Check for spills and reloads
1934 const MachineFrameInfo *FrameInfo =
1935 MI.getParent()->getParent()->getFrameInfo();
1937 // We assume a single instruction only has a spill or reload, not
1939 const MachineMemOperand *MMO;
1940 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1941 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1942 MMO = *MI.memoperands_begin();
1943 if (Newline) O << '\n';
1944 O.PadToColumn(MAI->getCommentColumn());
1945 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1949 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1950 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1951 if (Newline) O << '\n';
1952 O.PadToColumn(MAI->getCommentColumn());
1953 O << MAI->getCommentString() << ' '
1954 << MMO->getSize() << "-byte Folded Reload";
1958 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1959 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1960 MMO = *MI.memoperands_begin();
1961 if (Newline) O << '\n';
1962 O.PadToColumn(MAI->getCommentColumn());
1963 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1967 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1968 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1969 if (Newline) O << '\n';
1970 O.PadToColumn(MAI->getCommentColumn());
1971 O << MAI->getCommentString() << ' '
1972 << MMO->getSize() << "-byte Folded Spill";
1977 // Check for spill-induced copies
1978 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1979 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1980 SrcSubIdx, DstSubIdx)) {
1981 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1982 if (Newline) O << '\n';
1983 O.PadToColumn(MAI->getCommentColumn());
1984 O << MAI->getCommentString() << " Reload Reuse";
1989 /// PrintChildLoopComment - Print comments about child loops within
1990 /// the loop for this basic block, with nesting.
1992 static void PrintChildLoopComment(formatted_raw_ostream &O,
1993 const MachineLoop *loop,
1994 const MCAsmInfo *MAI,
1995 int FunctionNumber) {
1996 // Add child loop information
1997 for(MachineLoop::iterator cl = loop->begin(),
1998 clend = loop->end();
2001 MachineBasicBlock *Header = (*cl)->getHeader();
2002 assert(Header && "No header for loop");
2005 O.PadToColumn(MAI->getCommentColumn());
2007 O << MAI->getCommentString();
2008 O.indent(((*cl)->getLoopDepth()-1)*2)
2009 << " Child Loop BB" << FunctionNumber << "_"
2010 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2012 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2016 /// EmitComments - Pretty-print comments for basic blocks
2017 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2019 // Add loop depth information
2020 const MachineLoop *loop = LI->getLoopFor(&MBB);
2023 // Print a newline after bb# annotation.
2025 O.PadToColumn(MAI->getCommentColumn());
2026 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2029 O.PadToColumn(MAI->getCommentColumn());
2031 MachineBasicBlock *Header = loop->getHeader();
2032 assert(Header && "No header for loop");
2034 if (Header == &MBB) {
2035 O << MAI->getCommentString() << " Loop Header";
2036 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2039 O << MAI->getCommentString() << " Loop Header is BB"
2040 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2043 if (loop->empty()) {
2045 O.PadToColumn(MAI->getCommentColumn());
2046 O << MAI->getCommentString() << " Inner Loop";
2049 // Add parent loop information
2050 for (const MachineLoop *CurLoop = loop->getParentLoop();
2052 CurLoop = CurLoop->getParentLoop()) {
2053 MachineBasicBlock *Header = CurLoop->getHeader();
2054 assert(Header && "No header for loop");
2057 O.PadToColumn(MAI->getCommentColumn());
2058 O << MAI->getCommentString();
2059 O.indent((CurLoop->getLoopDepth()-1)*2)
2060 << " Inside Loop BB" << getFunctionNumber() << "_"
2061 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();