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/MachineFunction.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/StringExtras.h"
48 static cl::opt<cl::boolOrDefault>
49 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
50 cl::init(cl::BOU_UNSET));
52 char AsmPrinter::ID = 0;
53 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
54 const MCAsmInfo *T, bool VDef)
55 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
56 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
58 OutContext(*new MCContext()),
59 // FIXME: Pass instprinter to streamer.
60 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
62 LastMI(0), LastFn(0), Counter(~0U),
63 PrevDLT(0, ~0U, ~0U) {
66 case cl::BOU_UNSET: VerboseAsm = VDef; break;
67 case cl::BOU_TRUE: VerboseAsm = true; break;
68 case cl::BOU_FALSE: VerboseAsm = false; break;
72 AsmPrinter::~AsmPrinter() {
73 for (gcp_iterator I = GCMetadataPrinters.begin(),
74 E = GCMetadataPrinters.end(); I != E; ++I)
81 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
82 return TM.getTargetLowering()->getObjFileLowering();
85 /// getCurrentSection() - Return the current section we are emitting to.
86 const MCSection *AsmPrinter::getCurrentSection() const {
87 return OutStreamer.getCurrentSection();
91 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
93 MachineFunctionPass::getAnalysisUsage(AU);
94 AU.addRequired<GCModuleInfo>();
96 AU.addRequired<MachineLoopInfo>();
99 bool AsmPrinter::doInitialization(Module &M) {
100 // Initialize TargetLoweringObjectFile.
101 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
102 .Initialize(OutContext, TM);
104 Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
105 MAI->getLinkerPrivateGlobalPrefix());
107 if (MAI->doesAllowQuotesInName())
108 Mang->setUseQuotes(true);
110 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
111 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
113 if (MAI->hasSingleParameterDotFile()) {
114 /* Very minimal debug info. It is ignored if we emit actual
115 debug info. If we don't, this at helps the user find where
116 a function came from. */
117 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
120 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
121 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
122 MP->beginAssembly(O, *this, *MAI);
124 if (!M.getModuleInlineAsm().empty())
125 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
126 << M.getModuleInlineAsm()
127 << '\n' << MAI->getCommentString()
128 << " End of file scope inline assembly\n";
130 if (MAI->doesSupportDebugInformation() ||
131 MAI->doesSupportExceptionHandling()) {
132 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
134 MMI->AnalyzeModule(M);
135 DW = getAnalysisIfAvailable<DwarfWriter>();
137 DW->BeginModule(&M, MMI, O, this, MAI);
143 bool AsmPrinter::doFinalization(Module &M) {
144 // Emit global variables.
145 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
147 PrintGlobalVariable(I);
149 // Emit final debug information.
150 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
153 // If the target wants to know about weak references, print them all.
154 if (MAI->getWeakRefDirective()) {
155 // FIXME: This is not lazy, it would be nice to only print weak references
156 // to stuff that is actually used. Note that doing so would require targets
157 // to notice uses in operands (due to constant exprs etc). This should
158 // happen with the MC stuff eventually.
160 // Print out module-level global variables here.
161 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
163 if (I->hasExternalWeakLinkage())
164 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
167 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
168 if (I->hasExternalWeakLinkage())
169 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
173 if (MAI->getSetDirective()) {
175 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
177 std::string Name = Mang->getMangledName(I);
179 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
180 std::string Target = Mang->getMangledName(GV);
182 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
183 O << "\t.globl\t" << Name << '\n';
184 else if (I->hasWeakLinkage())
185 O << MAI->getWeakRefDirective() << Name << '\n';
186 else if (!I->hasLocalLinkage())
187 llvm_unreachable("Invalid alias linkage");
189 printVisibility(Name, I->getVisibility());
191 O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
195 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
196 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
197 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
198 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
199 MP->finishAssembly(O, *this, *MAI);
201 // If we don't have any trampolines, then we don't require stack memory
202 // to be executable. Some targets have a directive to declare this.
203 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
204 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
205 if (MAI->getNonexecutableStackDirective())
206 O << MAI->getNonexecutableStackDirective() << '\n';
208 delete Mang; Mang = 0;
211 OutStreamer.Finish();
216 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
217 assert(MF && "No machine function?");
218 return Mang->getMangledName(MF->getFunction(), ".eh",
219 MAI->is_EHSymbolPrivate());
222 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
223 // What's my mangled name?
224 CurrentFnName = Mang->getMangledName(MF.getFunction());
225 IncrementFunctionNumber();
228 LI = &getAnalysis<MachineLoopInfo>();
233 // SectionCPs - Keep track the alignment, constpool entries per Section.
237 SmallVector<unsigned, 4> CPEs;
238 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
242 /// EmitConstantPool - Print to the current output stream assembly
243 /// representations of the constants in the constant pool MCP. This is
244 /// used to print out constants which have been "spilled to memory" by
245 /// the code generator.
247 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
248 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
249 if (CP.empty()) return;
251 // Calculate sections for constant pool entries. We collect entries to go into
252 // the same section together to reduce amount of section switch statements.
253 SmallVector<SectionCPs, 4> CPSections;
254 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
255 const MachineConstantPoolEntry &CPE = CP[i];
256 unsigned Align = CPE.getAlignment();
259 switch (CPE.getRelocationInfo()) {
260 default: llvm_unreachable("Unknown section kind");
261 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
263 Kind = SectionKind::getReadOnlyWithRelLocal();
266 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
267 case 4: Kind = SectionKind::getMergeableConst4(); break;
268 case 8: Kind = SectionKind::getMergeableConst8(); break;
269 case 16: Kind = SectionKind::getMergeableConst16();break;
270 default: Kind = SectionKind::getMergeableConst(); break;
274 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
276 // The number of sections are small, just do a linear search from the
277 // last section to the first.
279 unsigned SecIdx = CPSections.size();
280 while (SecIdx != 0) {
281 if (CPSections[--SecIdx].S == S) {
287 SecIdx = CPSections.size();
288 CPSections.push_back(SectionCPs(S, Align));
291 if (Align > CPSections[SecIdx].Alignment)
292 CPSections[SecIdx].Alignment = Align;
293 CPSections[SecIdx].CPEs.push_back(i);
296 // Now print stuff into the calculated sections.
297 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
298 OutStreamer.SwitchSection(CPSections[i].S);
299 EmitAlignment(Log2_32(CPSections[i].Alignment));
302 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
303 unsigned CPI = CPSections[i].CPEs[j];
304 MachineConstantPoolEntry CPE = CP[CPI];
306 // Emit inter-object padding for alignment.
307 unsigned AlignMask = CPE.getAlignment() - 1;
308 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
309 EmitZeros(NewOffset - Offset);
311 const Type *Ty = CPE.getType();
312 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
314 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
317 O.PadToColumn(MAI->getCommentColumn());
318 O << MAI->getCommentString() << " constant ";
319 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
322 if (CPE.isMachineConstantPoolEntry())
323 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
325 EmitGlobalConstant(CPE.Val.ConstVal);
330 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
331 /// by the current function to the current output stream.
333 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
334 MachineFunction &MF) {
335 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
336 if (JT.empty()) return;
338 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
340 // Pick the directive to use to print the jump table entries, and switch to
341 // the appropriate section.
342 TargetLowering *LoweringInfo = TM.getTargetLowering();
344 const Function *F = MF.getFunction();
345 bool JTInDiffSection = false;
346 if (F->isWeakForLinker() ||
347 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
348 // In PIC mode, we need to emit the jump table to the same section as the
349 // function body itself, otherwise the label differences won't make sense.
350 // We should also do if the section name is NULL or function is declared in
351 // discardable section.
352 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
355 // Otherwise, drop it in the readonly section.
356 const MCSection *ReadOnlySection =
357 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
358 OutStreamer.SwitchSection(ReadOnlySection);
359 JTInDiffSection = true;
362 EmitAlignment(Log2_32(MJTI->getAlignment()));
364 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
365 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
367 // If this jump table was deleted, ignore it.
368 if (JTBBs.empty()) continue;
370 // For PIC codegen, if possible we want to use the SetDirective to reduce
371 // the number of relocations the assembler will generate for the jump table.
372 // Set directives are all printed before the jump table itself.
373 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
374 if (MAI->getSetDirective() && IsPic)
375 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
376 if (EmittedSets.insert(JTBBs[ii]))
377 printPICJumpTableSetLabel(i, JTBBs[ii]);
379 // On some targets (e.g. Darwin) we want to emit two consequtive labels
380 // before each jump table. The first label is never referenced, but tells
381 // the assembler and linker the extents of the jump table object. The
382 // second label is actually referenced by the code.
383 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
384 O << MAI->getLinkerPrivateGlobalPrefix()
385 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
388 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
389 << '_' << i << ":\n";
391 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
392 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
398 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
399 const MachineBasicBlock *MBB,
400 unsigned uid) const {
401 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
403 // Use JumpTableDirective otherwise honor the entry size from the jump table
405 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
406 bool HadJTEntryDirective = JTEntryDirective != NULL;
407 if (!HadJTEntryDirective) {
408 JTEntryDirective = MJTI->getEntrySize() == 4 ?
409 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
412 O << JTEntryDirective << ' ';
414 // If we have emitted set directives for the jump table entries, print
415 // them rather than the entries themselves. If we're emitting PIC, then
416 // emit the table entries as differences between two text section labels.
417 // If we're emitting non-PIC code, then emit the entries as direct
418 // references to the target basic blocks.
420 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
421 } else if (MAI->getSetDirective()) {
422 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
423 << '_' << uid << "_set_" << MBB->getNumber();
425 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
426 // If the arch uses custom Jump Table directives, don't calc relative to
428 if (!HadJTEntryDirective)
429 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
430 << getFunctionNumber() << '_' << uid;
435 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
436 /// special global used by LLVM. If so, emit it and return true, otherwise
437 /// do nothing and return false.
438 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
439 if (GV->getName() == "llvm.used") {
440 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
441 EmitLLVMUsedList(GV->getInitializer());
445 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
446 if (GV->getSection() == "llvm.metadata" ||
447 GV->hasAvailableExternallyLinkage())
450 if (!GV->hasAppendingLinkage()) return false;
452 assert(GV->hasInitializer() && "Not a special LLVM global!");
454 const TargetData *TD = TM.getTargetData();
455 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
456 if (GV->getName() == "llvm.global_ctors") {
457 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
458 EmitAlignment(Align, 0);
459 EmitXXStructorList(GV->getInitializer());
463 if (GV->getName() == "llvm.global_dtors") {
464 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
465 EmitAlignment(Align, 0);
466 EmitXXStructorList(GV->getInitializer());
473 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
474 /// global in the specified llvm.used list for which emitUsedDirectiveFor
475 /// is true, as being used with this directive.
476 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
477 const char *Directive = MAI->getUsedDirective();
479 // Should be an array of 'i8*'.
480 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
481 if (InitList == 0) return;
483 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
484 const GlobalValue *GV =
485 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
486 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
488 EmitConstantValueOnly(InitList->getOperand(i));
494 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
495 /// function pointers, ignoring the init priority.
496 void AsmPrinter::EmitXXStructorList(Constant *List) {
497 // Should be an array of '{ int, void ()* }' structs. The first value is the
498 // init priority, which we ignore.
499 if (!isa<ConstantArray>(List)) return;
500 ConstantArray *InitList = cast<ConstantArray>(List);
501 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
502 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
503 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
505 if (CS->getOperand(1)->isNullValue())
506 return; // Found a null terminator, exit printing.
507 // Emit the function pointer.
508 EmitGlobalConstant(CS->getOperand(1));
512 /// getGlobalLinkName - Returns the asm/link name of of the specified
513 /// global variable. Should be overridden by each target asm printer to
514 /// generate the appropriate value.
515 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
516 std::string &LinkName) const {
517 if (isa<Function>(GV)) {
518 LinkName += MAI->getFunctionAddrPrefix();
519 LinkName += Mang->getMangledName(GV);
520 LinkName += MAI->getFunctionAddrSuffix();
522 LinkName += MAI->getGlobalVarAddrPrefix();
523 LinkName += Mang->getMangledName(GV);
524 LinkName += MAI->getGlobalVarAddrSuffix();
530 /// EmitExternalGlobal - Emit the external reference to a global variable.
531 /// Should be overridden if an indirect reference should be used.
532 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
534 O << getGlobalLinkName(GV, GLN);
539 //===----------------------------------------------------------------------===//
540 /// LEB 128 number encoding.
542 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
543 /// representing an unsigned leb128 value.
544 void AsmPrinter::PrintULEB128(unsigned Value) const {
547 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
549 if (Value) Byte |= 0x80;
550 O << "0x" << utohex_buffer(Byte, Buffer+20);
551 if (Value) O << ", ";
555 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
556 /// representing a signed leb128 value.
557 void AsmPrinter::PrintSLEB128(int Value) const {
558 int Sign = Value >> (8 * sizeof(Value) - 1);
563 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
565 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
566 if (IsMore) Byte |= 0x80;
567 O << "0x" << utohex_buffer(Byte, Buffer+20);
568 if (IsMore) O << ", ";
572 //===--------------------------------------------------------------------===//
573 // Emission and print routines
576 /// PrintHex - Print a value as a hexidecimal value.
578 void AsmPrinter::PrintHex(int Value) const {
580 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
583 /// EOL - Print a newline character to asm stream. If a comment is present
584 /// then it will be printed first. Comments should not contain '\n'.
585 void AsmPrinter::EOL() const {
589 void AsmPrinter::EOL(const std::string &Comment) const {
590 if (VerboseAsm && !Comment.empty()) {
591 O.PadToColumn(MAI->getCommentColumn());
592 O << MAI->getCommentString()
599 void AsmPrinter::EOL(const char* Comment) const {
600 if (VerboseAsm && *Comment) {
601 O.PadToColumn(MAI->getCommentColumn());
602 O << MAI->getCommentString()
609 static const char *DecodeDWARFEncoding(unsigned Encoding) {
611 case dwarf::DW_EH_PE_absptr:
613 case dwarf::DW_EH_PE_omit:
615 case dwarf::DW_EH_PE_pcrel:
617 case dwarf::DW_EH_PE_udata4:
619 case dwarf::DW_EH_PE_udata8:
621 case dwarf::DW_EH_PE_sdata4:
623 case dwarf::DW_EH_PE_sdata8:
625 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
626 return "pcrel udata4";
627 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
628 return "pcrel sdata4";
629 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
630 return "pcrel udata8";
631 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
632 return "pcrel sdata8";
633 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
634 return "indirect pcrel udata4";
635 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
636 return "indirect pcrel sdata4";
637 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
638 return "indirect pcrel udata8";
639 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
640 return "indirect pcrel sdata8";
646 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
647 if (VerboseAsm && *Comment) {
648 O.PadToColumn(MAI->getCommentColumn());
649 O << MAI->getCommentString()
653 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
654 O << " (" << EncStr << ')';
659 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
660 /// unsigned leb128 value.
661 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
662 if (MAI->hasLEB128()) {
666 O << MAI->getData8bitsDirective();
671 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
672 /// signed leb128 value.
673 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
674 if (MAI->hasLEB128()) {
678 O << MAI->getData8bitsDirective();
683 /// EmitInt8 - Emit a byte directive and value.
685 void AsmPrinter::EmitInt8(int Value) const {
686 O << MAI->getData8bitsDirective();
687 PrintHex(Value & 0xFF);
690 /// EmitInt16 - Emit a short directive and value.
692 void AsmPrinter::EmitInt16(int Value) const {
693 O << MAI->getData16bitsDirective();
694 PrintHex(Value & 0xFFFF);
697 /// EmitInt32 - Emit a long directive and value.
699 void AsmPrinter::EmitInt32(int Value) const {
700 O << MAI->getData32bitsDirective();
704 /// EmitInt64 - Emit a long long directive and value.
706 void AsmPrinter::EmitInt64(uint64_t Value) const {
707 if (MAI->getData64bitsDirective()) {
708 O << MAI->getData64bitsDirective();
711 if (TM.getTargetData()->isBigEndian()) {
712 EmitInt32(unsigned(Value >> 32)); O << '\n';
713 EmitInt32(unsigned(Value));
715 EmitInt32(unsigned(Value)); O << '\n';
716 EmitInt32(unsigned(Value >> 32));
721 /// toOctal - Convert the low order bits of X into an octal digit.
723 static inline char toOctal(int X) {
727 /// printStringChar - Print a char, escaped if necessary.
729 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
732 } else if (C == '\\') {
734 } else if (isprint((unsigned char)C)) {
738 case '\b': O << "\\b"; break;
739 case '\f': O << "\\f"; break;
740 case '\n': O << "\\n"; break;
741 case '\r': O << "\\r"; break;
742 case '\t': O << "\\t"; break;
745 O << toOctal(C >> 6);
746 O << toOctal(C >> 3);
747 O << toOctal(C >> 0);
753 /// EmitString - Emit a string with quotes and a null terminator.
754 /// Special characters are emitted properly.
755 /// \literal (Eg. '\t') \endliteral
756 void AsmPrinter::EmitString(const std::string &String) const {
757 EmitString(String.c_str(), String.size());
760 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
761 const char* AscizDirective = MAI->getAscizDirective();
765 O << MAI->getAsciiDirective();
767 for (unsigned i = 0; i < Size; ++i)
768 printStringChar(O, String[i]);
776 /// EmitFile - Emit a .file directive.
777 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
778 O << "\t.file\t" << Number << " \"";
779 for (unsigned i = 0, N = Name.size(); i < N; ++i)
780 printStringChar(O, Name[i]);
785 //===----------------------------------------------------------------------===//
787 // EmitAlignment - Emit an alignment directive to the specified power of
788 // two boundary. For example, if you pass in 3 here, you will get an 8
789 // byte alignment. If a global value is specified, and if that global has
790 // an explicit alignment requested, it will unconditionally override the
791 // alignment request. However, if ForcedAlignBits is specified, this value
792 // has final say: the ultimate alignment will be the max of ForcedAlignBits
793 // and the alignment computed with NumBits and the global.
797 // if (GV && GV->hasalignment) Align = GV->getalignment();
798 // Align = std::max(Align, ForcedAlignBits);
800 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
801 unsigned ForcedAlignBits,
802 bool UseFillExpr) const {
803 if (GV && GV->getAlignment())
804 NumBits = Log2_32(GV->getAlignment());
805 NumBits = std::max(NumBits, ForcedAlignBits);
807 if (NumBits == 0) return; // No need to emit alignment.
809 unsigned FillValue = 0;
810 if (getCurrentSection()->getKind().isText())
811 FillValue = MAI->getTextAlignFillValue();
813 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
816 /// EmitZeros - Emit a block of zeros.
818 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
820 if (MAI->getZeroDirective()) {
821 O << MAI->getZeroDirective() << NumZeros;
822 if (MAI->getZeroDirectiveSuffix())
823 O << MAI->getZeroDirectiveSuffix();
826 for (; NumZeros; --NumZeros)
827 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
832 // Print out the specified constant, without a storage class. Only the
833 // constants valid in constant expressions can occur here.
834 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
835 if (CV->isNullValue() || isa<UndefValue>(CV))
837 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
838 O << CI->getZExtValue();
839 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
840 // This is a constant address for a global variable or function. Use the
841 // name of the variable or function as the address value, possibly
842 // decorating it with GlobalVarAddrPrefix/Suffix or
843 // FunctionAddrPrefix/Suffix (these all default to "" )
844 if (isa<Function>(GV)) {
845 O << MAI->getFunctionAddrPrefix()
846 << Mang->getMangledName(GV)
847 << MAI->getFunctionAddrSuffix();
849 O << MAI->getGlobalVarAddrPrefix()
850 << Mang->getMangledName(GV)
851 << MAI->getGlobalVarAddrSuffix();
853 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
854 const TargetData *TD = TM.getTargetData();
855 unsigned Opcode = CE->getOpcode();
857 case Instruction::Trunc:
858 case Instruction::ZExt:
859 case Instruction::SExt:
860 case Instruction::FPTrunc:
861 case Instruction::FPExt:
862 case Instruction::UIToFP:
863 case Instruction::SIToFP:
864 case Instruction::FPToUI:
865 case Instruction::FPToSI:
866 llvm_unreachable("FIXME: Don't support this constant cast expr");
867 case Instruction::GetElementPtr: {
868 // generate a symbolic expression for the byte address
869 const Constant *ptrVal = CE->getOperand(0);
870 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
871 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
873 // Truncate/sext the offset to the pointer size.
874 if (TD->getPointerSizeInBits() != 64) {
875 int SExtAmount = 64-TD->getPointerSizeInBits();
876 Offset = (Offset << SExtAmount) >> SExtAmount;
881 EmitConstantValueOnly(ptrVal);
883 O << ") + " << Offset;
885 O << ") - " << -Offset;
887 EmitConstantValueOnly(ptrVal);
891 case Instruction::BitCast:
892 return EmitConstantValueOnly(CE->getOperand(0));
894 case Instruction::IntToPtr: {
895 // Handle casts to pointers by changing them into casts to the appropriate
896 // integer type. This promotes constant folding and simplifies this code.
897 Constant *Op = CE->getOperand(0);
898 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
900 return EmitConstantValueOnly(Op);
904 case Instruction::PtrToInt: {
905 // Support only foldable casts to/from pointers that can be eliminated by
906 // changing the pointer to the appropriately sized integer type.
907 Constant *Op = CE->getOperand(0);
908 const Type *Ty = CE->getType();
910 // We can emit the pointer value into this slot if the slot is an
911 // integer slot greater or equal to the size of the pointer.
912 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
913 return EmitConstantValueOnly(Op);
916 EmitConstantValueOnly(Op);
918 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
921 ptrMask.toStringUnsigned(S);
922 O << ") & " << S.str() << ')';
925 case Instruction::Add:
926 case Instruction::Sub:
927 case Instruction::And:
928 case Instruction::Or:
929 case Instruction::Xor:
931 EmitConstantValueOnly(CE->getOperand(0));
934 case Instruction::Add:
937 case Instruction::Sub:
940 case Instruction::And:
943 case Instruction::Or:
946 case Instruction::Xor:
953 EmitConstantValueOnly(CE->getOperand(1));
957 llvm_unreachable("Unsupported operator!");
960 llvm_unreachable("Unknown constant value!");
964 /// printAsCString - Print the specified array as a C compatible string, only if
965 /// the predicate isString is true.
967 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
969 assert(CVA->isString() && "Array is not string compatible!");
972 for (unsigned i = 0; i != LastElt; ++i) {
974 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
975 printStringChar(O, C);
980 /// EmitString - Emit a zero-byte-terminated string constant.
982 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
983 unsigned NumElts = CVA->getNumOperands();
984 if (MAI->getAscizDirective() && NumElts &&
985 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
986 O << MAI->getAscizDirective();
987 printAsCString(O, CVA, NumElts-1);
989 O << MAI->getAsciiDirective();
990 printAsCString(O, CVA, NumElts);
995 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
996 unsigned AddrSpace) {
997 if (CVA->isString()) {
999 } else { // Not a string. Print the values in successive locations
1000 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1001 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1005 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1006 const VectorType *PTy = CP->getType();
1008 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1009 EmitGlobalConstant(CP->getOperand(I));
1012 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1013 unsigned AddrSpace) {
1014 // Print the fields in successive locations. Pad to align if needed!
1015 const TargetData *TD = TM.getTargetData();
1016 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1017 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1018 uint64_t sizeSoFar = 0;
1019 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1020 const Constant* field = CVS->getOperand(i);
1022 // Check if padding is needed and insert one or more 0s.
1023 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1024 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1025 - cvsLayout->getElementOffset(i)) - fieldSize;
1026 sizeSoFar += fieldSize + padSize;
1028 // Now print the actual field value.
1029 EmitGlobalConstant(field, AddrSpace);
1031 // Insert padding - this may include padding to increase the size of the
1032 // current field up to the ABI size (if the struct is not packed) as well
1033 // as padding to ensure that the next field starts at the right offset.
1034 EmitZeros(padSize, AddrSpace);
1036 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1037 "Layout of constant struct may be incorrect!");
1040 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1041 unsigned AddrSpace) {
1042 // FP Constants are printed as integer constants to avoid losing
1044 LLVMContext &Context = CFP->getContext();
1045 const TargetData *TD = TM.getTargetData();
1046 if (CFP->getType() == Type::getDoubleTy(Context)) {
1047 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1048 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1049 if (MAI->getData64bitsDirective(AddrSpace)) {
1050 O << MAI->getData64bitsDirective(AddrSpace) << i;
1052 O.PadToColumn(MAI->getCommentColumn());
1053 O << MAI->getCommentString() << " double " << Val;
1056 } else if (TD->isBigEndian()) {
1057 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1059 O.PadToColumn(MAI->getCommentColumn());
1060 O << MAI->getCommentString()
1061 << " most significant word of double " << Val;
1064 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1066 O.PadToColumn(MAI->getCommentColumn());
1067 O << MAI->getCommentString()
1068 << " least significant word of double " << Val;
1072 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1074 O.PadToColumn(MAI->getCommentColumn());
1075 O << MAI->getCommentString()
1076 << " least significant word of double " << Val;
1079 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1081 O.PadToColumn(MAI->getCommentColumn());
1082 O << MAI->getCommentString()
1083 << " most significant word of double " << Val;
1088 } else if (CFP->getType() == Type::getFloatTy(Context)) {
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;
1098 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1099 // all long double variants are printed as hex
1100 // api needed to prevent premature destruction
1101 APInt api = CFP->getValueAPF().bitcastToAPInt();
1102 const uint64_t *p = api.getRawData();
1103 // Convert to double so we can print the approximate val as a comment.
1104 APFloat DoubleVal = CFP->getValueAPF();
1106 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1108 if (TD->isBigEndian()) {
1109 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1111 O.PadToColumn(MAI->getCommentColumn());
1112 O << MAI->getCommentString()
1113 << " most significant halfword of x86_fp80 ~"
1114 << DoubleVal.convertToDouble();
1117 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1119 O.PadToColumn(MAI->getCommentColumn());
1120 O << MAI->getCommentString() << " next halfword";
1123 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1125 O.PadToColumn(MAI->getCommentColumn());
1126 O << MAI->getCommentString() << " next halfword";
1129 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1131 O.PadToColumn(MAI->getCommentColumn());
1132 O << MAI->getCommentString() << " next halfword";
1135 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1137 O.PadToColumn(MAI->getCommentColumn());
1138 O << MAI->getCommentString()
1139 << " least significant halfword";
1143 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1145 O.PadToColumn(MAI->getCommentColumn());
1146 O << MAI->getCommentString()
1147 << " least significant halfword of x86_fp80 ~"
1148 << DoubleVal.convertToDouble();
1151 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1153 O.PadToColumn(MAI->getCommentColumn());
1154 O << MAI->getCommentString()
1155 << " next halfword";
1158 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1160 O.PadToColumn(MAI->getCommentColumn());
1161 O << MAI->getCommentString()
1162 << " next halfword";
1165 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1167 O.PadToColumn(MAI->getCommentColumn());
1168 O << MAI->getCommentString()
1169 << " next halfword";
1172 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1174 O.PadToColumn(MAI->getCommentColumn());
1175 O << MAI->getCommentString()
1176 << " most significant halfword";
1180 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1181 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1183 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1184 // all long double variants are printed as hex
1185 // api needed to prevent premature destruction
1186 APInt api = CFP->getValueAPF().bitcastToAPInt();
1187 const uint64_t *p = api.getRawData();
1188 if (TD->isBigEndian()) {
1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1191 O.PadToColumn(MAI->getCommentColumn());
1192 O << MAI->getCommentString()
1193 << " most significant word of ppc_fp128";
1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1198 O.PadToColumn(MAI->getCommentColumn());
1199 O << MAI->getCommentString()
1203 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1205 O.PadToColumn(MAI->getCommentColumn());
1206 O << MAI->getCommentString()
1210 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1212 O.PadToColumn(MAI->getCommentColumn());
1213 O << MAI->getCommentString()
1214 << " least significant word";
1218 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1220 O.PadToColumn(MAI->getCommentColumn());
1221 O << MAI->getCommentString()
1222 << " least significant word of ppc_fp128";
1225 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1227 O.PadToColumn(MAI->getCommentColumn());
1228 O << MAI->getCommentString()
1232 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1234 O.PadToColumn(MAI->getCommentColumn());
1235 O << MAI->getCommentString()
1239 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1241 O.PadToColumn(MAI->getCommentColumn());
1242 O << MAI->getCommentString()
1243 << " most significant word";
1248 } else llvm_unreachable("Floating point constant type not handled");
1251 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1252 unsigned AddrSpace) {
1253 const TargetData *TD = TM.getTargetData();
1254 unsigned BitWidth = CI->getBitWidth();
1255 assert(isPowerOf2_32(BitWidth) &&
1256 "Non-power-of-2-sized integers not handled!");
1258 // We don't expect assemblers to support integer data directives
1259 // for more than 64 bits, so we emit the data in at most 64-bit
1260 // quantities at a time.
1261 const uint64_t *RawData = CI->getValue().getRawData();
1262 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1264 if (TD->isBigEndian())
1265 Val = RawData[e - i - 1];
1269 if (MAI->getData64bitsDirective(AddrSpace))
1270 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1271 else if (TD->isBigEndian()) {
1272 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1274 O.PadToColumn(MAI->getCommentColumn());
1275 O << MAI->getCommentString()
1276 << " most significant half of i64 " << Val;
1279 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1281 O.PadToColumn(MAI->getCommentColumn());
1282 O << MAI->getCommentString()
1283 << " least significant half of i64 " << Val;
1287 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1289 O.PadToColumn(MAI->getCommentColumn());
1290 O << MAI->getCommentString()
1291 << " least significant half of i64 " << Val;
1294 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1296 O.PadToColumn(MAI->getCommentColumn());
1297 O << MAI->getCommentString()
1298 << " most significant half of i64 " << Val;
1305 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1306 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1307 const TargetData *TD = TM.getTargetData();
1308 const Type *type = CV->getType();
1309 unsigned Size = TD->getTypeAllocSize(type);
1311 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1312 EmitZeros(Size, AddrSpace);
1314 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1315 EmitGlobalConstantArray(CVA , AddrSpace);
1317 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1318 EmitGlobalConstantStruct(CVS, AddrSpace);
1320 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1321 EmitGlobalConstantFP(CFP, AddrSpace);
1323 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1324 // Small integers are handled below; large integers are handled here.
1326 EmitGlobalConstantLargeInt(CI, AddrSpace);
1329 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1330 EmitGlobalConstantVector(CP);
1334 printDataDirective(type, AddrSpace);
1335 EmitConstantValueOnly(CV);
1337 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1339 CI->getValue().toStringUnsigned(S, 16);
1340 O.PadToColumn(MAI->getCommentColumn());
1341 O << MAI->getCommentString() << " 0x" << S.str();
1347 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1348 // Target doesn't support this yet!
1349 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1352 /// PrintSpecial - Print information related to the specified machine instr
1353 /// that is independent of the operand, and may be independent of the instr
1354 /// itself. This can be useful for portably encoding the comment character
1355 /// or other bits of target-specific knowledge into the asmstrings. The
1356 /// syntax used is ${:comment}. Targets can override this to add support
1357 /// for their own strange codes.
1358 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1359 if (!strcmp(Code, "private")) {
1360 O << MAI->getPrivateGlobalPrefix();
1361 } else if (!strcmp(Code, "comment")) {
1363 O << MAI->getCommentString();
1364 } else if (!strcmp(Code, "uid")) {
1365 // Comparing the address of MI isn't sufficient, because machineinstrs may
1366 // be allocated to the same address across functions.
1367 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1369 // If this is a new LastFn instruction, bump the counter.
1370 if (LastMI != MI || LastFn != ThisF) {
1378 raw_string_ostream Msg(msg);
1379 Msg << "Unknown special formatter '" << Code
1380 << "' for machine instr: " << *MI;
1381 llvm_report_error(Msg.str());
1385 /// processDebugLoc - Processes the debug information of each machine
1386 /// instruction's DebugLoc.
1387 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1391 if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1392 if (!DL.isUnknown()) {
1393 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1395 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1396 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1397 DICompileUnit(CurDLT.CompileUnit)));
1406 /// printInlineAsm - This method formats and prints the specified machine
1407 /// instruction that is an inline asm.
1408 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1409 unsigned NumOperands = MI->getNumOperands();
1411 // Count the number of register definitions.
1412 unsigned NumDefs = 0;
1413 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1415 assert(NumDefs != NumOperands-1 && "No asm string?");
1417 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1419 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1420 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1422 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1423 // These are useful to see where empty asm's wound up.
1424 if (AsmStr[0] == 0) {
1425 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1426 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1430 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1432 // The variant of the current asmprinter.
1433 int AsmPrinterVariant = MAI->getAssemblerDialect();
1435 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1436 const char *LastEmitted = AsmStr; // One past the last character emitted.
1438 while (*LastEmitted) {
1439 switch (*LastEmitted) {
1441 // Not a special case, emit the string section literally.
1442 const char *LiteralEnd = LastEmitted+1;
1443 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1444 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1446 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1447 O.write(LastEmitted, LiteralEnd-LastEmitted);
1448 LastEmitted = LiteralEnd;
1452 ++LastEmitted; // Consume newline character.
1453 O << '\n'; // Indent code with newline.
1456 ++LastEmitted; // Consume '$' character.
1460 switch (*LastEmitted) {
1461 default: Done = false; break;
1462 case '$': // $$ -> $
1463 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1465 ++LastEmitted; // Consume second '$' character.
1467 case '(': // $( -> same as GCC's { character.
1468 ++LastEmitted; // Consume '(' character.
1469 if (CurVariant != -1) {
1470 llvm_report_error("Nested variants found in inline asm string: '"
1471 + std::string(AsmStr) + "'");
1473 CurVariant = 0; // We're in the first variant now.
1476 ++LastEmitted; // consume '|' character.
1477 if (CurVariant == -1)
1478 O << '|'; // this is gcc's behavior for | outside a variant
1480 ++CurVariant; // We're in the next variant.
1482 case ')': // $) -> same as GCC's } char.
1483 ++LastEmitted; // consume ')' character.
1484 if (CurVariant == -1)
1485 O << '}'; // this is gcc's behavior for } outside a variant
1492 bool HasCurlyBraces = false;
1493 if (*LastEmitted == '{') { // ${variable}
1494 ++LastEmitted; // Consume '{' character.
1495 HasCurlyBraces = true;
1498 // If we have ${:foo}, then this is not a real operand reference, it is a
1499 // "magic" string reference, just like in .td files. Arrange to call
1501 if (HasCurlyBraces && *LastEmitted == ':') {
1503 const char *StrStart = LastEmitted;
1504 const char *StrEnd = strchr(StrStart, '}');
1506 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1507 + std::string(AsmStr) + "'");
1510 std::string Val(StrStart, StrEnd);
1511 PrintSpecial(MI, Val.c_str());
1512 LastEmitted = StrEnd+1;
1516 const char *IDStart = LastEmitted;
1519 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1520 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1521 llvm_report_error("Bad $ operand number in inline asm string: '"
1522 + std::string(AsmStr) + "'");
1524 LastEmitted = IDEnd;
1526 char Modifier[2] = { 0, 0 };
1528 if (HasCurlyBraces) {
1529 // If we have curly braces, check for a modifier character. This
1530 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1531 if (*LastEmitted == ':') {
1532 ++LastEmitted; // Consume ':' character.
1533 if (*LastEmitted == 0) {
1534 llvm_report_error("Bad ${:} expression in inline asm string: '"
1535 + std::string(AsmStr) + "'");
1538 Modifier[0] = *LastEmitted;
1539 ++LastEmitted; // Consume modifier character.
1542 if (*LastEmitted != '}') {
1543 llvm_report_error("Bad ${} expression in inline asm string: '"
1544 + std::string(AsmStr) + "'");
1546 ++LastEmitted; // Consume '}' character.
1549 if ((unsigned)Val >= NumOperands-1) {
1550 llvm_report_error("Invalid $ operand number in inline asm string: '"
1551 + std::string(AsmStr) + "'");
1554 // Okay, we finally have a value number. Ask the target to print this
1556 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1561 // Scan to find the machine operand number for the operand.
1562 for (; Val; --Val) {
1563 if (OpNo >= MI->getNumOperands()) break;
1564 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1565 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1568 if (OpNo >= MI->getNumOperands()) {
1571 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1572 ++OpNo; // Skip over the ID number.
1574 if (Modifier[0]=='l') // labels are target independent
1575 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1576 ->getNumber())->print(O, MAI);
1578 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1579 if ((OpFlags & 7) == 4) {
1580 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1581 Modifier[0] ? Modifier : 0);
1583 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1584 Modifier[0] ? Modifier : 0);
1590 raw_string_ostream Msg(msg);
1591 Msg << "Invalid operand found in inline asm: '"
1594 llvm_report_error(Msg.str());
1601 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1604 /// printImplicitDef - This method prints the specified machine instruction
1605 /// that is an implicit def.
1606 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1607 if (!VerboseAsm) return;
1608 O.PadToColumn(MAI->getCommentColumn());
1609 O << MAI->getCommentString() << " implicit-def: "
1610 << TRI->getName(MI->getOperand(0).getReg());
1613 /// printLabel - This method prints a local label used by debug and
1614 /// exception handling tables.
1615 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1616 printLabel(MI->getOperand(0).getImm());
1619 void AsmPrinter::printLabel(unsigned Id) const {
1620 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1623 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1624 /// instruction, using the specified assembler variant. Targets should
1625 /// overried this to format as appropriate.
1626 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1627 unsigned AsmVariant, const char *ExtraCode) {
1628 // Target doesn't support this yet!
1632 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1633 unsigned AsmVariant,
1634 const char *ExtraCode) {
1635 // Target doesn't support this yet!
1639 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1640 SmallString<60> Name;
1641 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1642 << getFunctionNumber() << '_' << MBBID;
1644 return OutContext.GetOrCreateSymbol(Name.str());
1648 /// EmitBasicBlockStart - This method prints the label for the specified
1649 /// MachineBasicBlock, an alignment (if present) and a comment describing
1650 /// it if appropriate.
1651 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1652 if (unsigned Align = MBB->getAlignment())
1653 EmitAlignment(Log2_32(Align));
1655 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1659 if (const BasicBlock *BB = MBB->getBasicBlock())
1660 if (BB->hasName()) {
1661 O.PadToColumn(MAI->getCommentColumn());
1662 O << MAI->getCommentString() << ' ';
1663 WriteAsOperand(O, BB, /*PrintType=*/false);
1670 /// printPICJumpTableSetLabel - This method prints a set label for the
1671 /// specified MachineBasicBlock for a jumptable entry.
1672 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1673 const MachineBasicBlock *MBB) const {
1674 if (!MAI->getSetDirective())
1677 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1678 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1679 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1680 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1681 << '_' << uid << '\n';
1684 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1685 const MachineBasicBlock *MBB) const {
1686 if (!MAI->getSetDirective())
1689 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1690 << getFunctionNumber() << '_' << uid << '_' << uid2
1691 << "_set_" << MBB->getNumber() << ',';
1692 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1693 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1694 << '_' << uid << '_' << uid2 << '\n';
1697 /// printDataDirective - This method prints the asm directive for the
1699 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1700 const TargetData *TD = TM.getTargetData();
1701 switch (type->getTypeID()) {
1702 case Type::FloatTyID: case Type::DoubleTyID:
1703 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1704 assert(0 && "Should have already output floating point constant.");
1706 assert(0 && "Can't handle printing this type of thing");
1707 case Type::IntegerTyID: {
1708 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1710 O << MAI->getData8bitsDirective(AddrSpace);
1711 else if (BitWidth <= 16)
1712 O << MAI->getData16bitsDirective(AddrSpace);
1713 else if (BitWidth <= 32)
1714 O << MAI->getData32bitsDirective(AddrSpace);
1715 else if (BitWidth <= 64) {
1716 assert(MAI->getData64bitsDirective(AddrSpace) &&
1717 "Target cannot handle 64-bit constant exprs!");
1718 O << MAI->getData64bitsDirective(AddrSpace);
1720 llvm_unreachable("Target cannot handle given data directive width!");
1724 case Type::PointerTyID:
1725 if (TD->getPointerSize() == 8) {
1726 assert(MAI->getData64bitsDirective(AddrSpace) &&
1727 "Target cannot handle 64-bit pointer exprs!");
1728 O << MAI->getData64bitsDirective(AddrSpace);
1729 } else if (TD->getPointerSize() == 2) {
1730 O << MAI->getData16bitsDirective(AddrSpace);
1731 } else if (TD->getPointerSize() == 1) {
1732 O << MAI->getData8bitsDirective(AddrSpace);
1734 O << MAI->getData32bitsDirective(AddrSpace);
1740 void AsmPrinter::printVisibility(const std::string& Name,
1741 unsigned Visibility) const {
1742 if (Visibility == GlobalValue::HiddenVisibility) {
1743 if (const char *Directive = MAI->getHiddenDirective())
1744 O << Directive << Name << '\n';
1745 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1746 if (const char *Directive = MAI->getProtectedDirective())
1747 O << Directive << Name << '\n';
1751 void AsmPrinter::printOffset(int64_t Offset) const {
1754 else if (Offset < 0)
1758 void AsmPrinter::printMCInst(const MCInst *MI) {
1759 llvm_unreachable("MCInst printing unavailable on this target!");
1762 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1763 if (!S->usesMetadata())
1766 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1767 if (GCPI != GCMetadataPrinters.end())
1768 return GCPI->second;
1770 const char *Name = S->getName().c_str();
1772 for (GCMetadataPrinterRegistry::iterator
1773 I = GCMetadataPrinterRegistry::begin(),
1774 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1775 if (strcmp(Name, I->getName()) == 0) {
1776 GCMetadataPrinter *GMP = I->instantiate();
1778 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1782 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1783 llvm_unreachable(0);
1786 /// EmitComments - Pretty-print comments for instructions
1787 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1788 assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1790 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1792 // Print source line info.
1793 O.PadToColumn(MAI->getCommentColumn());
1794 O << MAI->getCommentString() << " SrcLine ";
1795 if (DLT.CompileUnit) {
1797 DICompileUnit CU(DLT.CompileUnit);
1798 O << CU.getFilename(Str) << " ";
1802 O << ":" << DLT.Col;
1805 /// PrintChildLoopComment - Print comments about child loops within
1806 /// the loop for this basic block, with nesting.
1808 static void PrintChildLoopComment(formatted_raw_ostream &O,
1809 const MachineLoop *loop,
1810 const MCAsmInfo *MAI,
1811 int FunctionNumber) {
1812 // Add child loop information
1813 for(MachineLoop::iterator cl = loop->begin(),
1814 clend = loop->end();
1817 MachineBasicBlock *Header = (*cl)->getHeader();
1818 assert(Header && "No header for loop");
1821 O.PadToColumn(MAI->getCommentColumn());
1823 O << MAI->getCommentString();
1824 O.indent(((*cl)->getLoopDepth()-1)*2)
1825 << " Child Loop BB" << FunctionNumber << "_"
1826 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1828 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1832 /// EmitComments - Pretty-print comments for basic blocks
1833 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1836 // Add loop depth information
1837 const MachineLoop *loop = LI->getLoopFor(&MBB);
1840 // Print a newline after bb# annotation.
1842 O.PadToColumn(MAI->getCommentColumn());
1843 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1846 O.PadToColumn(MAI->getCommentColumn());
1848 MachineBasicBlock *Header = loop->getHeader();
1849 assert(Header && "No header for loop");
1851 if (Header == &MBB) {
1852 O << MAI->getCommentString() << " Loop Header";
1853 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1856 O << MAI->getCommentString() << " Loop Header is BB"
1857 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1860 if (loop->empty()) {
1862 O.PadToColumn(MAI->getCommentColumn());
1863 O << MAI->getCommentString() << " Inner Loop";
1866 // Add parent loop information
1867 for (const MachineLoop *CurLoop = loop->getParentLoop();
1869 CurLoop = CurLoop->getParentLoop()) {
1870 MachineBasicBlock *Header = CurLoop->getHeader();
1871 assert(Header && "No header for loop");
1874 O.PadToColumn(MAI->getCommentColumn());
1875 O << MAI->getCommentString();
1876 O.indent((CurLoop->getLoopDepth()-1)*2)
1877 << " Inside Loop BB" << getFunctionNumber() << "_"
1878 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();