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 if (MAI->doesAllowNameToStartWithDigit())
111 Mang->setSymbolsCanStartWithDigit(true);
113 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
114 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
116 if (MAI->hasSingleParameterDotFile()) {
117 /* Very minimal debug info. It is ignored if we emit actual
118 debug info. If we don't, this at helps the user find where
119 a function came from. */
120 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
123 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
124 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
125 MP->beginAssembly(O, *this, *MAI);
127 if (!M.getModuleInlineAsm().empty())
128 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
129 << M.getModuleInlineAsm()
130 << '\n' << MAI->getCommentString()
131 << " End of file scope inline assembly\n";
133 if (MAI->doesSupportDebugInformation() ||
134 MAI->doesSupportExceptionHandling()) {
135 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137 MMI->AnalyzeModule(M);
138 DW = getAnalysisIfAvailable<DwarfWriter>();
140 DW->BeginModule(&M, MMI, O, this, MAI);
146 bool AsmPrinter::doFinalization(Module &M) {
147 // Emit global variables.
148 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
150 PrintGlobalVariable(I);
152 // Emit final debug information.
153 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
156 // If the target wants to know about weak references, print them all.
157 if (MAI->getWeakRefDirective()) {
158 // FIXME: This is not lazy, it would be nice to only print weak references
159 // to stuff that is actually used. Note that doing so would require targets
160 // to notice uses in operands (due to constant exprs etc). This should
161 // happen with the MC stuff eventually.
163 // Print out module-level global variables here.
164 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
166 if (I->hasExternalWeakLinkage())
167 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
170 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
171 if (I->hasExternalWeakLinkage())
172 O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
176 if (MAI->getSetDirective()) {
178 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
180 std::string Name = Mang->getMangledName(I);
182 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
183 std::string Target = Mang->getMangledName(GV);
185 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
186 O << "\t.globl\t" << Name << '\n';
187 else if (I->hasWeakLinkage())
188 O << MAI->getWeakRefDirective() << Name << '\n';
189 else if (!I->hasLocalLinkage())
190 llvm_unreachable("Invalid alias linkage");
192 printVisibility(Name, I->getVisibility());
194 O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
198 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
199 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
200 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
201 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
202 MP->finishAssembly(O, *this, *MAI);
204 // If we don't have any trampolines, then we don't require stack memory
205 // to be executable. Some targets have a directive to declare this.
206 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
207 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
208 if (MAI->getNonexecutableStackDirective())
209 O << MAI->getNonexecutableStackDirective() << '\n';
211 delete Mang; Mang = 0;
214 OutStreamer.Finish();
218 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
219 // What's my mangled name?
220 CurrentFnName = Mang->getMangledName(MF.getFunction());
221 IncrementFunctionNumber();
224 LI = &getAnalysis<MachineLoopInfo>();
228 // SectionCPs - Keep track the alignment, constpool entries per Section.
232 SmallVector<unsigned, 4> CPEs;
233 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
237 /// EmitConstantPool - Print to the current output stream assembly
238 /// representations of the constants in the constant pool MCP. This is
239 /// used to print out constants which have been "spilled to memory" by
240 /// the code generator.
242 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
243 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
244 if (CP.empty()) return;
246 // Calculate sections for constant pool entries. We collect entries to go into
247 // the same section together to reduce amount of section switch statements.
248 SmallVector<SectionCPs, 4> CPSections;
249 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
250 const MachineConstantPoolEntry &CPE = CP[i];
251 unsigned Align = CPE.getAlignment();
254 switch (CPE.getRelocationInfo()) {
255 default: llvm_unreachable("Unknown section kind");
256 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
258 Kind = SectionKind::getReadOnlyWithRelLocal();
261 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
262 case 4: Kind = SectionKind::getMergeableConst4(); break;
263 case 8: Kind = SectionKind::getMergeableConst8(); break;
264 case 16: Kind = SectionKind::getMergeableConst16();break;
265 default: Kind = SectionKind::getMergeableConst(); break;
269 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
271 // The number of sections are small, just do a linear search from the
272 // last section to the first.
274 unsigned SecIdx = CPSections.size();
275 while (SecIdx != 0) {
276 if (CPSections[--SecIdx].S == S) {
282 SecIdx = CPSections.size();
283 CPSections.push_back(SectionCPs(S, Align));
286 if (Align > CPSections[SecIdx].Alignment)
287 CPSections[SecIdx].Alignment = Align;
288 CPSections[SecIdx].CPEs.push_back(i);
291 // Now print stuff into the calculated sections.
292 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
293 OutStreamer.SwitchSection(CPSections[i].S);
294 EmitAlignment(Log2_32(CPSections[i].Alignment));
297 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
298 unsigned CPI = CPSections[i].CPEs[j];
299 MachineConstantPoolEntry CPE = CP[CPI];
301 // Emit inter-object padding for alignment.
302 unsigned AlignMask = CPE.getAlignment() - 1;
303 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
304 EmitZeros(NewOffset - Offset);
306 const Type *Ty = CPE.getType();
307 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
309 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
312 O.PadToColumn(MAI->getCommentColumn());
313 O << MAI->getCommentString() << " constant ";
314 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
317 if (CPE.isMachineConstantPoolEntry())
318 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
320 EmitGlobalConstant(CPE.Val.ConstVal);
325 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
326 /// by the current function to the current output stream.
328 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
329 MachineFunction &MF) {
330 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
331 if (JT.empty()) return;
333 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
335 // Pick the directive to use to print the jump table entries, and switch to
336 // the appropriate section.
337 TargetLowering *LoweringInfo = TM.getTargetLowering();
339 const Function *F = MF.getFunction();
340 bool JTInDiffSection = false;
341 if (F->isWeakForLinker() ||
342 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
343 // In PIC mode, we need to emit the jump table to the same section as the
344 // function body itself, otherwise the label differences won't make sense.
345 // We should also do if the section name is NULL or function is declared in
346 // discardable section.
347 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
350 // Otherwise, drop it in the readonly section.
351 const MCSection *ReadOnlySection =
352 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
353 OutStreamer.SwitchSection(ReadOnlySection);
354 JTInDiffSection = true;
357 EmitAlignment(Log2_32(MJTI->getAlignment()));
359 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
360 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
362 // If this jump table was deleted, ignore it.
363 if (JTBBs.empty()) continue;
365 // For PIC codegen, if possible we want to use the SetDirective to reduce
366 // the number of relocations the assembler will generate for the jump table.
367 // Set directives are all printed before the jump table itself.
368 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
369 if (MAI->getSetDirective() && IsPic)
370 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
371 if (EmittedSets.insert(JTBBs[ii]))
372 printPICJumpTableSetLabel(i, JTBBs[ii]);
374 // On some targets (e.g. Darwin) we want to emit two consequtive labels
375 // before each jump table. The first label is never referenced, but tells
376 // the assembler and linker the extents of the jump table object. The
377 // second label is actually referenced by the code.
378 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
379 O << MAI->getLinkerPrivateGlobalPrefix()
380 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
383 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
384 << '_' << i << ":\n";
386 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
387 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
393 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
394 const MachineBasicBlock *MBB,
395 unsigned uid) const {
396 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
398 // Use JumpTableDirective otherwise honor the entry size from the jump table
400 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
401 bool HadJTEntryDirective = JTEntryDirective != NULL;
402 if (!HadJTEntryDirective) {
403 JTEntryDirective = MJTI->getEntrySize() == 4 ?
404 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
407 O << JTEntryDirective << ' ';
409 // If we have emitted set directives for the jump table entries, print
410 // them rather than the entries themselves. If we're emitting PIC, then
411 // emit the table entries as differences between two text section labels.
412 // If we're emitting non-PIC code, then emit the entries as direct
413 // references to the target basic blocks.
415 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
416 } else if (MAI->getSetDirective()) {
417 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
418 << '_' << uid << "_set_" << MBB->getNumber();
420 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
421 // If the arch uses custom Jump Table directives, don't calc relative to
423 if (!HadJTEntryDirective)
424 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
425 << getFunctionNumber() << '_' << uid;
430 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
431 /// special global used by LLVM. If so, emit it and return true, otherwise
432 /// do nothing and return false.
433 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
434 if (GV->getName() == "llvm.used") {
435 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
436 EmitLLVMUsedList(GV->getInitializer());
440 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
441 if (GV->getSection() == "llvm.metadata" ||
442 GV->hasAvailableExternallyLinkage())
445 if (!GV->hasAppendingLinkage()) return false;
447 assert(GV->hasInitializer() && "Not a special LLVM global!");
449 const TargetData *TD = TM.getTargetData();
450 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
451 if (GV->getName() == "llvm.global_ctors") {
452 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
453 EmitAlignment(Align, 0);
454 EmitXXStructorList(GV->getInitializer());
458 if (GV->getName() == "llvm.global_dtors") {
459 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
460 EmitAlignment(Align, 0);
461 EmitXXStructorList(GV->getInitializer());
468 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
469 /// global in the specified llvm.used list for which emitUsedDirectiveFor
470 /// is true, as being used with this directive.
471 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
472 const char *Directive = MAI->getUsedDirective();
474 // Should be an array of 'i8*'.
475 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
476 if (InitList == 0) return;
478 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
479 const GlobalValue *GV =
480 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
481 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
483 EmitConstantValueOnly(InitList->getOperand(i));
489 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
490 /// function pointers, ignoring the init priority.
491 void AsmPrinter::EmitXXStructorList(Constant *List) {
492 // Should be an array of '{ int, void ()* }' structs. The first value is the
493 // init priority, which we ignore.
494 if (!isa<ConstantArray>(List)) return;
495 ConstantArray *InitList = cast<ConstantArray>(List);
496 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
497 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
498 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
500 if (CS->getOperand(1)->isNullValue())
501 return; // Found a null terminator, exit printing.
502 // Emit the function pointer.
503 EmitGlobalConstant(CS->getOperand(1));
508 //===----------------------------------------------------------------------===//
509 /// LEB 128 number encoding.
511 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
512 /// representing an unsigned leb128 value.
513 void AsmPrinter::PrintULEB128(unsigned Value) const {
516 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
518 if (Value) Byte |= 0x80;
519 O << "0x" << utohex_buffer(Byte, Buffer+20);
520 if (Value) O << ", ";
524 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
525 /// representing a signed leb128 value.
526 void AsmPrinter::PrintSLEB128(int Value) const {
527 int Sign = Value >> (8 * sizeof(Value) - 1);
532 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
534 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
535 if (IsMore) Byte |= 0x80;
536 O << "0x" << utohex_buffer(Byte, Buffer+20);
537 if (IsMore) O << ", ";
541 //===--------------------------------------------------------------------===//
542 // Emission and print routines
545 /// PrintHex - Print a value as a hexidecimal value.
547 void AsmPrinter::PrintHex(int Value) const {
549 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
552 /// EOL - Print a newline character to asm stream. If a comment is present
553 /// then it will be printed first. Comments should not contain '\n'.
554 void AsmPrinter::EOL() const {
558 void AsmPrinter::EOL(const std::string &Comment) const {
559 if (VerboseAsm && !Comment.empty()) {
560 O.PadToColumn(MAI->getCommentColumn());
561 O << MAI->getCommentString()
568 void AsmPrinter::EOL(const char* Comment) const {
569 if (VerboseAsm && *Comment) {
570 O.PadToColumn(MAI->getCommentColumn());
571 O << MAI->getCommentString()
578 static const char *DecodeDWARFEncoding(unsigned Encoding) {
580 case dwarf::DW_EH_PE_absptr:
582 case dwarf::DW_EH_PE_omit:
584 case dwarf::DW_EH_PE_pcrel:
586 case dwarf::DW_EH_PE_udata4:
588 case dwarf::DW_EH_PE_udata8:
590 case dwarf::DW_EH_PE_sdata4:
592 case dwarf::DW_EH_PE_sdata8:
594 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
595 return "pcrel udata4";
596 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
597 return "pcrel sdata4";
598 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
599 return "pcrel udata8";
600 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
601 return "pcrel sdata8";
602 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
603 return "indirect pcrel udata4";
604 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
605 return "indirect pcrel sdata4";
606 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
607 return "indirect pcrel udata8";
608 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
609 return "indirect pcrel sdata8";
615 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
616 if (VerboseAsm && *Comment) {
617 O.PadToColumn(MAI->getCommentColumn());
618 O << MAI->getCommentString()
622 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
623 O << " (" << EncStr << ')';
628 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
629 /// unsigned leb128 value.
630 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
631 if (MAI->hasLEB128()) {
635 O << MAI->getData8bitsDirective();
640 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
641 /// signed leb128 value.
642 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
643 if (MAI->hasLEB128()) {
647 O << MAI->getData8bitsDirective();
652 /// EmitInt8 - Emit a byte directive and value.
654 void AsmPrinter::EmitInt8(int Value) const {
655 O << MAI->getData8bitsDirective();
656 PrintHex(Value & 0xFF);
659 /// EmitInt16 - Emit a short directive and value.
661 void AsmPrinter::EmitInt16(int Value) const {
662 O << MAI->getData16bitsDirective();
663 PrintHex(Value & 0xFFFF);
666 /// EmitInt32 - Emit a long directive and value.
668 void AsmPrinter::EmitInt32(int Value) const {
669 O << MAI->getData32bitsDirective();
673 /// EmitInt64 - Emit a long long directive and value.
675 void AsmPrinter::EmitInt64(uint64_t Value) const {
676 if (MAI->getData64bitsDirective()) {
677 O << MAI->getData64bitsDirective();
680 if (TM.getTargetData()->isBigEndian()) {
681 EmitInt32(unsigned(Value >> 32)); O << '\n';
682 EmitInt32(unsigned(Value));
684 EmitInt32(unsigned(Value)); O << '\n';
685 EmitInt32(unsigned(Value >> 32));
690 /// toOctal - Convert the low order bits of X into an octal digit.
692 static inline char toOctal(int X) {
696 /// printStringChar - Print a char, escaped if necessary.
698 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
701 } else if (C == '\\') {
703 } else if (isprint((unsigned char)C)) {
707 case '\b': O << "\\b"; break;
708 case '\f': O << "\\f"; break;
709 case '\n': O << "\\n"; break;
710 case '\r': O << "\\r"; break;
711 case '\t': O << "\\t"; break;
714 O << toOctal(C >> 6);
715 O << toOctal(C >> 3);
716 O << toOctal(C >> 0);
722 /// EmitString - Emit a string with quotes and a null terminator.
723 /// Special characters are emitted properly.
724 /// \literal (Eg. '\t') \endliteral
725 void AsmPrinter::EmitString(const std::string &String) const {
726 EmitString(String.c_str(), String.size());
729 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
730 const char* AscizDirective = MAI->getAscizDirective();
734 O << MAI->getAsciiDirective();
736 for (unsigned i = 0; i < Size; ++i)
737 printStringChar(O, String[i]);
745 /// EmitFile - Emit a .file directive.
746 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
747 O << "\t.file\t" << Number << " \"";
748 for (unsigned i = 0, N = Name.size(); i < N; ++i)
749 printStringChar(O, Name[i]);
754 //===----------------------------------------------------------------------===//
756 // EmitAlignment - Emit an alignment directive to the specified power of
757 // two boundary. For example, if you pass in 3 here, you will get an 8
758 // byte alignment. If a global value is specified, and if that global has
759 // an explicit alignment requested, it will unconditionally override the
760 // alignment request. However, if ForcedAlignBits is specified, this value
761 // has final say: the ultimate alignment will be the max of ForcedAlignBits
762 // and the alignment computed with NumBits and the global.
766 // if (GV && GV->hasalignment) Align = GV->getalignment();
767 // Align = std::max(Align, ForcedAlignBits);
769 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
770 unsigned ForcedAlignBits,
771 bool UseFillExpr) const {
772 if (GV && GV->getAlignment())
773 NumBits = Log2_32(GV->getAlignment());
774 NumBits = std::max(NumBits, ForcedAlignBits);
776 if (NumBits == 0) return; // No need to emit alignment.
778 unsigned FillValue = 0;
779 if (getCurrentSection()->getKind().isText())
780 FillValue = MAI->getTextAlignFillValue();
782 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
785 /// EmitZeros - Emit a block of zeros.
787 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
789 if (MAI->getZeroDirective()) {
790 O << MAI->getZeroDirective() << NumZeros;
791 if (MAI->getZeroDirectiveSuffix())
792 O << MAI->getZeroDirectiveSuffix();
795 for (; NumZeros; --NumZeros)
796 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
801 // Print out the specified constant, without a storage class. Only the
802 // constants valid in constant expressions can occur here.
803 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
804 if (CV->isNullValue() || isa<UndefValue>(CV))
806 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
807 O << CI->getZExtValue();
808 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
809 // This is a constant address for a global variable or function. Use the
810 // name of the variable or function as the address value.
811 O << Mang->getMangledName(GV);
812 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
813 const TargetData *TD = TM.getTargetData();
814 unsigned Opcode = CE->getOpcode();
816 case Instruction::Trunc:
817 case Instruction::ZExt:
818 case Instruction::SExt:
819 case Instruction::FPTrunc:
820 case Instruction::FPExt:
821 case Instruction::UIToFP:
822 case Instruction::SIToFP:
823 case Instruction::FPToUI:
824 case Instruction::FPToSI:
825 llvm_unreachable("FIXME: Don't support this constant cast expr");
826 case Instruction::GetElementPtr: {
827 // generate a symbolic expression for the byte address
828 const Constant *ptrVal = CE->getOperand(0);
829 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
830 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
832 // Truncate/sext the offset to the pointer size.
833 if (TD->getPointerSizeInBits() != 64) {
834 int SExtAmount = 64-TD->getPointerSizeInBits();
835 Offset = (Offset << SExtAmount) >> SExtAmount;
840 EmitConstantValueOnly(ptrVal);
842 O << ") + " << Offset;
844 O << ") - " << -Offset;
846 EmitConstantValueOnly(ptrVal);
850 case Instruction::BitCast:
851 return EmitConstantValueOnly(CE->getOperand(0));
853 case Instruction::IntToPtr: {
854 // Handle casts to pointers by changing them into casts to the appropriate
855 // integer type. This promotes constant folding and simplifies this code.
856 Constant *Op = CE->getOperand(0);
857 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
859 return EmitConstantValueOnly(Op);
863 case Instruction::PtrToInt: {
864 // Support only foldable casts to/from pointers that can be eliminated by
865 // changing the pointer to the appropriately sized integer type.
866 Constant *Op = CE->getOperand(0);
867 const Type *Ty = CE->getType();
869 // We can emit the pointer value into this slot if the slot is an
870 // integer slot greater or equal to the size of the pointer.
871 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
872 return EmitConstantValueOnly(Op);
875 EmitConstantValueOnly(Op);
877 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
880 ptrMask.toStringUnsigned(S);
881 O << ") & " << S.str() << ')';
884 case Instruction::Add:
885 case Instruction::Sub:
886 case Instruction::And:
887 case Instruction::Or:
888 case Instruction::Xor:
890 EmitConstantValueOnly(CE->getOperand(0));
893 case Instruction::Add:
896 case Instruction::Sub:
899 case Instruction::And:
902 case Instruction::Or:
905 case Instruction::Xor:
912 EmitConstantValueOnly(CE->getOperand(1));
916 llvm_unreachable("Unsupported operator!");
919 llvm_unreachable("Unknown constant value!");
923 /// printAsCString - Print the specified array as a C compatible string, only if
924 /// the predicate isString is true.
926 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
928 assert(CVA->isString() && "Array is not string compatible!");
931 for (unsigned i = 0; i != LastElt; ++i) {
933 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
934 printStringChar(O, C);
939 /// EmitString - Emit a zero-byte-terminated string constant.
941 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
942 unsigned NumElts = CVA->getNumOperands();
943 if (MAI->getAscizDirective() && NumElts &&
944 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
945 O << MAI->getAscizDirective();
946 printAsCString(O, CVA, NumElts-1);
948 O << MAI->getAsciiDirective();
949 printAsCString(O, CVA, NumElts);
954 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
955 unsigned AddrSpace) {
956 if (CVA->isString()) {
958 } else { // Not a string. Print the values in successive locations
959 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
960 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
964 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
965 const VectorType *PTy = CP->getType();
967 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
968 EmitGlobalConstant(CP->getOperand(I));
971 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
972 unsigned AddrSpace) {
973 // Print the fields in successive locations. Pad to align if needed!
974 const TargetData *TD = TM.getTargetData();
975 unsigned Size = TD->getTypeAllocSize(CVS->getType());
976 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
977 uint64_t sizeSoFar = 0;
978 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
979 const Constant* field = CVS->getOperand(i);
981 // Check if padding is needed and insert one or more 0s.
982 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
983 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
984 - cvsLayout->getElementOffset(i)) - fieldSize;
985 sizeSoFar += fieldSize + padSize;
987 // Now print the actual field value.
988 EmitGlobalConstant(field, AddrSpace);
990 // Insert padding - this may include padding to increase the size of the
991 // current field up to the ABI size (if the struct is not packed) as well
992 // as padding to ensure that the next field starts at the right offset.
993 EmitZeros(padSize, AddrSpace);
995 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
996 "Layout of constant struct may be incorrect!");
999 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1000 unsigned AddrSpace) {
1001 // FP Constants are printed as integer constants to avoid losing
1003 LLVMContext &Context = CFP->getContext();
1004 const TargetData *TD = TM.getTargetData();
1005 if (CFP->getType() == Type::getDoubleTy(Context)) {
1006 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1007 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1008 if (MAI->getData64bitsDirective(AddrSpace)) {
1009 O << MAI->getData64bitsDirective(AddrSpace) << i;
1011 O.PadToColumn(MAI->getCommentColumn());
1012 O << MAI->getCommentString() << " double " << Val;
1015 } else if (TD->isBigEndian()) {
1016 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1018 O.PadToColumn(MAI->getCommentColumn());
1019 O << MAI->getCommentString()
1020 << " most significant word of double " << Val;
1023 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1025 O.PadToColumn(MAI->getCommentColumn());
1026 O << MAI->getCommentString()
1027 << " least significant word of double " << Val;
1031 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1033 O.PadToColumn(MAI->getCommentColumn());
1034 O << MAI->getCommentString()
1035 << " least significant word of double " << Val;
1038 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1040 O.PadToColumn(MAI->getCommentColumn());
1041 O << MAI->getCommentString()
1042 << " most significant word of double " << Val;
1047 } else if (CFP->getType() == Type::getFloatTy(Context)) {
1048 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1049 O << MAI->getData32bitsDirective(AddrSpace)
1050 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1052 O.PadToColumn(MAI->getCommentColumn());
1053 O << MAI->getCommentString() << " float " << Val;
1057 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1058 // all long double variants are printed as hex
1059 // api needed to prevent premature destruction
1060 APInt api = CFP->getValueAPF().bitcastToAPInt();
1061 const uint64_t *p = api.getRawData();
1062 // Convert to double so we can print the approximate val as a comment.
1063 APFloat DoubleVal = CFP->getValueAPF();
1065 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1067 if (TD->isBigEndian()) {
1068 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1070 O.PadToColumn(MAI->getCommentColumn());
1071 O << MAI->getCommentString()
1072 << " most significant halfword of x86_fp80 ~"
1073 << DoubleVal.convertToDouble();
1076 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1078 O.PadToColumn(MAI->getCommentColumn());
1079 O << MAI->getCommentString() << " next halfword";
1082 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1084 O.PadToColumn(MAI->getCommentColumn());
1085 O << MAI->getCommentString() << " next halfword";
1088 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1090 O.PadToColumn(MAI->getCommentColumn());
1091 O << MAI->getCommentString() << " next halfword";
1094 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1096 O.PadToColumn(MAI->getCommentColumn());
1097 O << MAI->getCommentString()
1098 << " least significant halfword";
1102 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1104 O.PadToColumn(MAI->getCommentColumn());
1105 O << MAI->getCommentString()
1106 << " least significant halfword of x86_fp80 ~"
1107 << DoubleVal.convertToDouble();
1110 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1112 O.PadToColumn(MAI->getCommentColumn());
1113 O << MAI->getCommentString()
1114 << " next halfword";
1117 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1119 O.PadToColumn(MAI->getCommentColumn());
1120 O << MAI->getCommentString()
1121 << " next halfword";
1124 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1126 O.PadToColumn(MAI->getCommentColumn());
1127 O << MAI->getCommentString()
1128 << " next halfword";
1131 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1133 O.PadToColumn(MAI->getCommentColumn());
1134 O << MAI->getCommentString()
1135 << " most significant halfword";
1139 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1140 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1142 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1143 // all long double variants are printed as hex
1144 // api needed to prevent premature destruction
1145 APInt api = CFP->getValueAPF().bitcastToAPInt();
1146 const uint64_t *p = api.getRawData();
1147 if (TD->isBigEndian()) {
1148 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1150 O.PadToColumn(MAI->getCommentColumn());
1151 O << MAI->getCommentString()
1152 << " most significant word of ppc_fp128";
1155 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1157 O.PadToColumn(MAI->getCommentColumn());
1158 O << MAI->getCommentString()
1162 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1164 O.PadToColumn(MAI->getCommentColumn());
1165 O << MAI->getCommentString()
1169 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1171 O.PadToColumn(MAI->getCommentColumn());
1172 O << MAI->getCommentString()
1173 << " least significant word";
1177 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1179 O.PadToColumn(MAI->getCommentColumn());
1180 O << MAI->getCommentString()
1181 << " least significant word of ppc_fp128";
1184 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1186 O.PadToColumn(MAI->getCommentColumn());
1187 O << MAI->getCommentString()
1191 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1193 O.PadToColumn(MAI->getCommentColumn());
1194 O << MAI->getCommentString()
1198 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1200 O.PadToColumn(MAI->getCommentColumn());
1201 O << MAI->getCommentString()
1202 << " most significant word";
1207 } else llvm_unreachable("Floating point constant type not handled");
1210 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1211 unsigned AddrSpace) {
1212 const TargetData *TD = TM.getTargetData();
1213 unsigned BitWidth = CI->getBitWidth();
1214 assert(isPowerOf2_32(BitWidth) &&
1215 "Non-power-of-2-sized integers not handled!");
1217 // We don't expect assemblers to support integer data directives
1218 // for more than 64 bits, so we emit the data in at most 64-bit
1219 // quantities at a time.
1220 const uint64_t *RawData = CI->getValue().getRawData();
1221 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1223 if (TD->isBigEndian())
1224 Val = RawData[e - i - 1];
1228 if (MAI->getData64bitsDirective(AddrSpace))
1229 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1230 else if (TD->isBigEndian()) {
1231 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1233 O.PadToColumn(MAI->getCommentColumn());
1234 O << MAI->getCommentString()
1235 << " most significant half of i64 " << Val;
1238 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1240 O.PadToColumn(MAI->getCommentColumn());
1241 O << MAI->getCommentString()
1242 << " least significant half of i64 " << Val;
1246 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1248 O.PadToColumn(MAI->getCommentColumn());
1249 O << MAI->getCommentString()
1250 << " least significant half of i64 " << Val;
1253 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1255 O.PadToColumn(MAI->getCommentColumn());
1256 O << MAI->getCommentString()
1257 << " most significant half of i64 " << Val;
1264 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1265 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1266 const TargetData *TD = TM.getTargetData();
1267 const Type *type = CV->getType();
1268 unsigned Size = TD->getTypeAllocSize(type);
1270 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1271 EmitZeros(Size, AddrSpace);
1273 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1274 EmitGlobalConstantArray(CVA , AddrSpace);
1276 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1277 EmitGlobalConstantStruct(CVS, AddrSpace);
1279 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1280 EmitGlobalConstantFP(CFP, AddrSpace);
1282 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1283 // Small integers are handled below; large integers are handled here.
1285 EmitGlobalConstantLargeInt(CI, AddrSpace);
1288 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1289 EmitGlobalConstantVector(CP);
1293 printDataDirective(type, AddrSpace);
1294 EmitConstantValueOnly(CV);
1296 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1298 CI->getValue().toStringUnsigned(S, 16);
1299 O.PadToColumn(MAI->getCommentColumn());
1300 O << MAI->getCommentString() << " 0x" << S.str();
1306 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1307 // Target doesn't support this yet!
1308 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1311 /// PrintSpecial - Print information related to the specified machine instr
1312 /// that is independent of the operand, and may be independent of the instr
1313 /// itself. This can be useful for portably encoding the comment character
1314 /// or other bits of target-specific knowledge into the asmstrings. The
1315 /// syntax used is ${:comment}. Targets can override this to add support
1316 /// for their own strange codes.
1317 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1318 if (!strcmp(Code, "private")) {
1319 O << MAI->getPrivateGlobalPrefix();
1320 } else if (!strcmp(Code, "comment")) {
1322 O << MAI->getCommentString();
1323 } else if (!strcmp(Code, "uid")) {
1324 // Comparing the address of MI isn't sufficient, because machineinstrs may
1325 // be allocated to the same address across functions.
1326 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1328 // If this is a new LastFn instruction, bump the counter.
1329 if (LastMI != MI || LastFn != ThisF) {
1337 raw_string_ostream Msg(msg);
1338 Msg << "Unknown special formatter '" << Code
1339 << "' for machine instr: " << *MI;
1340 llvm_report_error(Msg.str());
1344 /// processDebugLoc - Processes the debug information of each machine
1345 /// instruction's DebugLoc.
1346 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1350 if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1351 if (!DL.isUnknown()) {
1352 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1354 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1355 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1356 DICompileUnit(CurDLT.CompileUnit)));
1365 /// printInlineAsm - This method formats and prints the specified machine
1366 /// instruction that is an inline asm.
1367 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1368 unsigned NumOperands = MI->getNumOperands();
1370 // Count the number of register definitions.
1371 unsigned NumDefs = 0;
1372 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1374 assert(NumDefs != NumOperands-1 && "No asm string?");
1376 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1378 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1379 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1381 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1382 // These are useful to see where empty asm's wound up.
1383 if (AsmStr[0] == 0) {
1384 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1385 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1389 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1391 // The variant of the current asmprinter.
1392 int AsmPrinterVariant = MAI->getAssemblerDialect();
1394 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1395 const char *LastEmitted = AsmStr; // One past the last character emitted.
1397 while (*LastEmitted) {
1398 switch (*LastEmitted) {
1400 // Not a special case, emit the string section literally.
1401 const char *LiteralEnd = LastEmitted+1;
1402 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1403 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1405 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1406 O.write(LastEmitted, LiteralEnd-LastEmitted);
1407 LastEmitted = LiteralEnd;
1411 ++LastEmitted; // Consume newline character.
1412 O << '\n'; // Indent code with newline.
1415 ++LastEmitted; // Consume '$' character.
1419 switch (*LastEmitted) {
1420 default: Done = false; break;
1421 case '$': // $$ -> $
1422 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1424 ++LastEmitted; // Consume second '$' character.
1426 case '(': // $( -> same as GCC's { character.
1427 ++LastEmitted; // Consume '(' character.
1428 if (CurVariant != -1) {
1429 llvm_report_error("Nested variants found in inline asm string: '"
1430 + std::string(AsmStr) + "'");
1432 CurVariant = 0; // We're in the first variant now.
1435 ++LastEmitted; // consume '|' character.
1436 if (CurVariant == -1)
1437 O << '|'; // this is gcc's behavior for | outside a variant
1439 ++CurVariant; // We're in the next variant.
1441 case ')': // $) -> same as GCC's } char.
1442 ++LastEmitted; // consume ')' character.
1443 if (CurVariant == -1)
1444 O << '}'; // this is gcc's behavior for } outside a variant
1451 bool HasCurlyBraces = false;
1452 if (*LastEmitted == '{') { // ${variable}
1453 ++LastEmitted; // Consume '{' character.
1454 HasCurlyBraces = true;
1457 // If we have ${:foo}, then this is not a real operand reference, it is a
1458 // "magic" string reference, just like in .td files. Arrange to call
1460 if (HasCurlyBraces && *LastEmitted == ':') {
1462 const char *StrStart = LastEmitted;
1463 const char *StrEnd = strchr(StrStart, '}');
1465 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1466 + std::string(AsmStr) + "'");
1469 std::string Val(StrStart, StrEnd);
1470 PrintSpecial(MI, Val.c_str());
1471 LastEmitted = StrEnd+1;
1475 const char *IDStart = LastEmitted;
1478 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1479 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1480 llvm_report_error("Bad $ operand number in inline asm string: '"
1481 + std::string(AsmStr) + "'");
1483 LastEmitted = IDEnd;
1485 char Modifier[2] = { 0, 0 };
1487 if (HasCurlyBraces) {
1488 // If we have curly braces, check for a modifier character. This
1489 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1490 if (*LastEmitted == ':') {
1491 ++LastEmitted; // Consume ':' character.
1492 if (*LastEmitted == 0) {
1493 llvm_report_error("Bad ${:} expression in inline asm string: '"
1494 + std::string(AsmStr) + "'");
1497 Modifier[0] = *LastEmitted;
1498 ++LastEmitted; // Consume modifier character.
1501 if (*LastEmitted != '}') {
1502 llvm_report_error("Bad ${} expression in inline asm string: '"
1503 + std::string(AsmStr) + "'");
1505 ++LastEmitted; // Consume '}' character.
1508 if ((unsigned)Val >= NumOperands-1) {
1509 llvm_report_error("Invalid $ operand number in inline asm string: '"
1510 + std::string(AsmStr) + "'");
1513 // Okay, we finally have a value number. Ask the target to print this
1515 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1520 // Scan to find the machine operand number for the operand.
1521 for (; Val; --Val) {
1522 if (OpNo >= MI->getNumOperands()) break;
1523 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1524 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1527 if (OpNo >= MI->getNumOperands()) {
1530 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1531 ++OpNo; // Skip over the ID number.
1533 if (Modifier[0]=='l') // labels are target independent
1534 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1535 ->getNumber())->print(O, MAI);
1537 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1538 if ((OpFlags & 7) == 4) {
1539 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1540 Modifier[0] ? Modifier : 0);
1542 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1543 Modifier[0] ? Modifier : 0);
1549 raw_string_ostream Msg(msg);
1550 Msg << "Invalid operand found in inline asm: '"
1553 llvm_report_error(Msg.str());
1560 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1563 /// printImplicitDef - This method prints the specified machine instruction
1564 /// that is an implicit def.
1565 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1566 if (!VerboseAsm) return;
1567 O.PadToColumn(MAI->getCommentColumn());
1568 O << MAI->getCommentString() << " implicit-def: "
1569 << TRI->getName(MI->getOperand(0).getReg());
1572 /// printLabel - This method prints a local label used by debug and
1573 /// exception handling tables.
1574 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1575 printLabel(MI->getOperand(0).getImm());
1578 void AsmPrinter::printLabel(unsigned Id) const {
1579 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1582 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1583 /// instruction, using the specified assembler variant. Targets should
1584 /// overried this to format as appropriate.
1585 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1586 unsigned AsmVariant, const char *ExtraCode) {
1587 // Target doesn't support this yet!
1591 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1592 unsigned AsmVariant,
1593 const char *ExtraCode) {
1594 // Target doesn't support this yet!
1598 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1599 SmallString<60> Name;
1600 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1601 << getFunctionNumber() << '_' << MBBID;
1603 return OutContext.GetOrCreateSymbol(Name.str());
1607 /// EmitBasicBlockStart - This method prints the label for the specified
1608 /// MachineBasicBlock, an alignment (if present) and a comment describing
1609 /// it if appropriate.
1610 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1611 if (unsigned Align = MBB->getAlignment())
1612 EmitAlignment(Log2_32(Align));
1614 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1618 if (const BasicBlock *BB = MBB->getBasicBlock())
1619 if (BB->hasName()) {
1620 O.PadToColumn(MAI->getCommentColumn());
1621 O << MAI->getCommentString() << ' ';
1622 WriteAsOperand(O, BB, /*PrintType=*/false);
1629 /// printPICJumpTableSetLabel - This method prints a set label for the
1630 /// specified MachineBasicBlock for a jumptable entry.
1631 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1632 const MachineBasicBlock *MBB) const {
1633 if (!MAI->getSetDirective())
1636 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1637 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1638 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1639 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1640 << '_' << uid << '\n';
1643 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1644 const MachineBasicBlock *MBB) const {
1645 if (!MAI->getSetDirective())
1648 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1649 << getFunctionNumber() << '_' << uid << '_' << uid2
1650 << "_set_" << MBB->getNumber() << ',';
1651 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1652 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1653 << '_' << uid << '_' << uid2 << '\n';
1656 /// printDataDirective - This method prints the asm directive for the
1658 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1659 const TargetData *TD = TM.getTargetData();
1660 switch (type->getTypeID()) {
1661 case Type::FloatTyID: case Type::DoubleTyID:
1662 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1663 assert(0 && "Should have already output floating point constant.");
1665 assert(0 && "Can't handle printing this type of thing");
1666 case Type::IntegerTyID: {
1667 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1669 O << MAI->getData8bitsDirective(AddrSpace);
1670 else if (BitWidth <= 16)
1671 O << MAI->getData16bitsDirective(AddrSpace);
1672 else if (BitWidth <= 32)
1673 O << MAI->getData32bitsDirective(AddrSpace);
1674 else if (BitWidth <= 64) {
1675 assert(MAI->getData64bitsDirective(AddrSpace) &&
1676 "Target cannot handle 64-bit constant exprs!");
1677 O << MAI->getData64bitsDirective(AddrSpace);
1679 llvm_unreachable("Target cannot handle given data directive width!");
1683 case Type::PointerTyID:
1684 if (TD->getPointerSize() == 8) {
1685 assert(MAI->getData64bitsDirective(AddrSpace) &&
1686 "Target cannot handle 64-bit pointer exprs!");
1687 O << MAI->getData64bitsDirective(AddrSpace);
1688 } else if (TD->getPointerSize() == 2) {
1689 O << MAI->getData16bitsDirective(AddrSpace);
1690 } else if (TD->getPointerSize() == 1) {
1691 O << MAI->getData8bitsDirective(AddrSpace);
1693 O << MAI->getData32bitsDirective(AddrSpace);
1699 void AsmPrinter::printVisibility(const std::string& Name,
1700 unsigned Visibility) const {
1701 if (Visibility == GlobalValue::HiddenVisibility) {
1702 if (const char *Directive = MAI->getHiddenDirective())
1703 O << Directive << Name << '\n';
1704 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1705 if (const char *Directive = MAI->getProtectedDirective())
1706 O << Directive << Name << '\n';
1710 void AsmPrinter::printOffset(int64_t Offset) const {
1713 else if (Offset < 0)
1717 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1718 if (!S->usesMetadata())
1721 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1722 if (GCPI != GCMetadataPrinters.end())
1723 return GCPI->second;
1725 const char *Name = S->getName().c_str();
1727 for (GCMetadataPrinterRegistry::iterator
1728 I = GCMetadataPrinterRegistry::begin(),
1729 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1730 if (strcmp(Name, I->getName()) == 0) {
1731 GCMetadataPrinter *GMP = I->instantiate();
1733 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1737 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1738 llvm_unreachable(0);
1741 /// EmitComments - Pretty-print comments for instructions
1742 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1743 assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1745 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1747 // Print source line info.
1748 O.PadToColumn(MAI->getCommentColumn());
1749 O << MAI->getCommentString() << " SrcLine ";
1750 if (DLT.CompileUnit) {
1752 DICompileUnit CU(DLT.CompileUnit);
1753 O << CU.getFilename(Str) << " ";
1757 O << ":" << DLT.Col;
1760 /// PrintChildLoopComment - Print comments about child loops within
1761 /// the loop for this basic block, with nesting.
1763 static void PrintChildLoopComment(formatted_raw_ostream &O,
1764 const MachineLoop *loop,
1765 const MCAsmInfo *MAI,
1766 int FunctionNumber) {
1767 // Add child loop information
1768 for(MachineLoop::iterator cl = loop->begin(),
1769 clend = loop->end();
1772 MachineBasicBlock *Header = (*cl)->getHeader();
1773 assert(Header && "No header for loop");
1776 O.PadToColumn(MAI->getCommentColumn());
1778 O << MAI->getCommentString();
1779 O.indent(((*cl)->getLoopDepth()-1)*2)
1780 << " Child Loop BB" << FunctionNumber << "_"
1781 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1783 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1787 /// EmitComments - Pretty-print comments for basic blocks
1788 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1791 // Add loop depth information
1792 const MachineLoop *loop = LI->getLoopFor(&MBB);
1795 // Print a newline after bb# annotation.
1797 O.PadToColumn(MAI->getCommentColumn());
1798 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1801 O.PadToColumn(MAI->getCommentColumn());
1803 MachineBasicBlock *Header = loop->getHeader();
1804 assert(Header && "No header for loop");
1806 if (Header == &MBB) {
1807 O << MAI->getCommentString() << " Loop Header";
1808 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1811 O << MAI->getCommentString() << " Loop Header is BB"
1812 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1815 if (loop->empty()) {
1817 O.PadToColumn(MAI->getCommentColumn());
1818 O << MAI->getCommentString() << " Inner Loop";
1821 // Add parent loop information
1822 for (const MachineLoop *CurLoop = loop->getParentLoop();
1824 CurLoop = CurLoop->getParentLoop()) {
1825 MachineBasicBlock *Header = CurLoop->getHeader();
1826 assert(Header && "No header for loop");
1829 O.PadToColumn(MAI->getCommentColumn());
1830 O << MAI->getCommentString();
1831 O.indent((CurLoop->getLoopDepth()-1)*2)
1832 << " Inside Loop BB" << getFunctionNumber() << "_"
1833 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();