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';
212 // Allow the target to emit any magic that it wants at the end of the file,
213 // after everything else has gone out.
216 delete Mang; Mang = 0;
219 OutStreamer.Finish();
223 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
224 // What's my mangled name?
225 CurrentFnName = Mang->getMangledName(MF.getFunction());
226 IncrementFunctionNumber();
229 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));
513 //===----------------------------------------------------------------------===//
514 /// LEB 128 number encoding.
516 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
517 /// representing an unsigned leb128 value.
518 void AsmPrinter::PrintULEB128(unsigned Value) const {
521 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
523 if (Value) Byte |= 0x80;
524 O << "0x" << utohex_buffer(Byte, Buffer+20);
525 if (Value) O << ", ";
529 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
530 /// representing a signed leb128 value.
531 void AsmPrinter::PrintSLEB128(int Value) const {
532 int Sign = Value >> (8 * sizeof(Value) - 1);
537 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
539 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
540 if (IsMore) Byte |= 0x80;
541 O << "0x" << utohex_buffer(Byte, Buffer+20);
542 if (IsMore) O << ", ";
546 //===--------------------------------------------------------------------===//
547 // Emission and print routines
550 /// PrintHex - Print a value as a hexidecimal value.
552 void AsmPrinter::PrintHex(int Value) const {
554 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
557 /// EOL - Print a newline character to asm stream. If a comment is present
558 /// then it will be printed first. Comments should not contain '\n'.
559 void AsmPrinter::EOL() const {
563 void AsmPrinter::EOL(const std::string &Comment) const {
564 if (VerboseAsm && !Comment.empty()) {
565 O.PadToColumn(MAI->getCommentColumn());
566 O << MAI->getCommentString()
573 void AsmPrinter::EOL(const char* Comment) const {
574 if (VerboseAsm && *Comment) {
575 O.PadToColumn(MAI->getCommentColumn());
576 O << MAI->getCommentString()
583 static const char *DecodeDWARFEncoding(unsigned Encoding) {
585 case dwarf::DW_EH_PE_absptr:
587 case dwarf::DW_EH_PE_omit:
589 case dwarf::DW_EH_PE_pcrel:
591 case dwarf::DW_EH_PE_udata4:
593 case dwarf::DW_EH_PE_udata8:
595 case dwarf::DW_EH_PE_sdata4:
597 case dwarf::DW_EH_PE_sdata8:
599 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
600 return "pcrel udata4";
601 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
602 return "pcrel sdata4";
603 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
604 return "pcrel udata8";
605 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
606 return "pcrel sdata8";
607 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
608 return "indirect pcrel udata4";
609 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
610 return "indirect pcrel sdata4";
611 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
612 return "indirect pcrel udata8";
613 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
614 return "indirect pcrel sdata8";
620 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
621 if (VerboseAsm && *Comment) {
622 O.PadToColumn(MAI->getCommentColumn());
623 O << MAI->getCommentString()
627 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
628 O << " (" << EncStr << ')';
633 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
634 /// unsigned leb128 value.
635 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
636 if (MAI->hasLEB128()) {
640 O << MAI->getData8bitsDirective();
645 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
646 /// signed leb128 value.
647 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
648 if (MAI->hasLEB128()) {
652 O << MAI->getData8bitsDirective();
657 /// EmitInt8 - Emit a byte directive and value.
659 void AsmPrinter::EmitInt8(int Value) const {
660 O << MAI->getData8bitsDirective();
661 PrintHex(Value & 0xFF);
664 /// EmitInt16 - Emit a short directive and value.
666 void AsmPrinter::EmitInt16(int Value) const {
667 O << MAI->getData16bitsDirective();
668 PrintHex(Value & 0xFFFF);
671 /// EmitInt32 - Emit a long directive and value.
673 void AsmPrinter::EmitInt32(int Value) const {
674 O << MAI->getData32bitsDirective();
678 /// EmitInt64 - Emit a long long directive and value.
680 void AsmPrinter::EmitInt64(uint64_t Value) const {
681 if (MAI->getData64bitsDirective()) {
682 O << MAI->getData64bitsDirective();
685 if (TM.getTargetData()->isBigEndian()) {
686 EmitInt32(unsigned(Value >> 32)); O << '\n';
687 EmitInt32(unsigned(Value));
689 EmitInt32(unsigned(Value)); O << '\n';
690 EmitInt32(unsigned(Value >> 32));
695 /// toOctal - Convert the low order bits of X into an octal digit.
697 static inline char toOctal(int X) {
701 /// printStringChar - Print a char, escaped if necessary.
703 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
706 } else if (C == '\\') {
708 } else if (isprint((unsigned char)C)) {
712 case '\b': O << "\\b"; break;
713 case '\f': O << "\\f"; break;
714 case '\n': O << "\\n"; break;
715 case '\r': O << "\\r"; break;
716 case '\t': O << "\\t"; break;
719 O << toOctal(C >> 6);
720 O << toOctal(C >> 3);
721 O << toOctal(C >> 0);
727 /// EmitString - Emit a string with quotes and a null terminator.
728 /// Special characters are emitted properly.
729 /// \literal (Eg. '\t') \endliteral
730 void AsmPrinter::EmitString(const std::string &String) const {
731 EmitString(String.c_str(), String.size());
734 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
735 const char* AscizDirective = MAI->getAscizDirective();
739 O << MAI->getAsciiDirective();
741 for (unsigned i = 0; i < Size; ++i)
742 printStringChar(O, String[i]);
750 /// EmitFile - Emit a .file directive.
751 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
752 O << "\t.file\t" << Number << " \"";
753 for (unsigned i = 0, N = Name.size(); i < N; ++i)
754 printStringChar(O, Name[i]);
759 //===----------------------------------------------------------------------===//
761 // EmitAlignment - Emit an alignment directive to the specified power of
762 // two boundary. For example, if you pass in 3 here, you will get an 8
763 // byte alignment. If a global value is specified, and if that global has
764 // an explicit alignment requested, it will unconditionally override the
765 // alignment request. However, if ForcedAlignBits is specified, this value
766 // has final say: the ultimate alignment will be the max of ForcedAlignBits
767 // and the alignment computed with NumBits and the global.
771 // if (GV && GV->hasalignment) Align = GV->getalignment();
772 // Align = std::max(Align, ForcedAlignBits);
774 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
775 unsigned ForcedAlignBits,
776 bool UseFillExpr) const {
777 if (GV && GV->getAlignment())
778 NumBits = Log2_32(GV->getAlignment());
779 NumBits = std::max(NumBits, ForcedAlignBits);
781 if (NumBits == 0) return; // No need to emit alignment.
783 unsigned FillValue = 0;
784 if (getCurrentSection()->getKind().isText())
785 FillValue = MAI->getTextAlignFillValue();
787 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
790 /// EmitZeros - Emit a block of zeros.
792 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
794 if (MAI->getZeroDirective()) {
795 O << MAI->getZeroDirective() << NumZeros;
796 if (MAI->getZeroDirectiveSuffix())
797 O << MAI->getZeroDirectiveSuffix();
800 for (; NumZeros; --NumZeros)
801 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
806 // Print out the specified constant, without a storage class. Only the
807 // constants valid in constant expressions can occur here.
808 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
809 if (CV->isNullValue() || isa<UndefValue>(CV))
811 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
812 O << CI->getZExtValue();
813 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
814 // This is a constant address for a global variable or function. Use the
815 // name of the variable or function as the address value.
816 O << Mang->getMangledName(GV);
817 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
818 const TargetData *TD = TM.getTargetData();
819 unsigned Opcode = CE->getOpcode();
821 case Instruction::Trunc:
822 case Instruction::ZExt:
823 case Instruction::SExt:
824 case Instruction::FPTrunc:
825 case Instruction::FPExt:
826 case Instruction::UIToFP:
827 case Instruction::SIToFP:
828 case Instruction::FPToUI:
829 case Instruction::FPToSI:
830 llvm_unreachable("FIXME: Don't support this constant cast expr");
831 case Instruction::GetElementPtr: {
832 // generate a symbolic expression for the byte address
833 const Constant *ptrVal = CE->getOperand(0);
834 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
835 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
837 // Truncate/sext the offset to the pointer size.
838 if (TD->getPointerSizeInBits() != 64) {
839 int SExtAmount = 64-TD->getPointerSizeInBits();
840 Offset = (Offset << SExtAmount) >> SExtAmount;
845 EmitConstantValueOnly(ptrVal);
847 O << ") + " << Offset;
849 O << ") - " << -Offset;
851 EmitConstantValueOnly(ptrVal);
855 case Instruction::BitCast:
856 return EmitConstantValueOnly(CE->getOperand(0));
858 case Instruction::IntToPtr: {
859 // Handle casts to pointers by changing them into casts to the appropriate
860 // integer type. This promotes constant folding and simplifies this code.
861 Constant *Op = CE->getOperand(0);
862 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
864 return EmitConstantValueOnly(Op);
868 case Instruction::PtrToInt: {
869 // Support only foldable casts to/from pointers that can be eliminated by
870 // changing the pointer to the appropriately sized integer type.
871 Constant *Op = CE->getOperand(0);
872 const Type *Ty = CE->getType();
874 // We can emit the pointer value into this slot if the slot is an
875 // integer slot greater or equal to the size of the pointer.
876 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
877 return EmitConstantValueOnly(Op);
880 EmitConstantValueOnly(Op);
882 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
885 ptrMask.toStringUnsigned(S);
886 O << ") & " << S.str() << ')';
889 case Instruction::Add:
890 case Instruction::Sub:
891 case Instruction::And:
892 case Instruction::Or:
893 case Instruction::Xor:
895 EmitConstantValueOnly(CE->getOperand(0));
898 case Instruction::Add:
901 case Instruction::Sub:
904 case Instruction::And:
907 case Instruction::Or:
910 case Instruction::Xor:
917 EmitConstantValueOnly(CE->getOperand(1));
921 llvm_unreachable("Unsupported operator!");
924 llvm_unreachable("Unknown constant value!");
928 /// printAsCString - Print the specified array as a C compatible string, only if
929 /// the predicate isString is true.
931 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
933 assert(CVA->isString() && "Array is not string compatible!");
936 for (unsigned i = 0; i != LastElt; ++i) {
938 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
939 printStringChar(O, C);
944 /// EmitString - Emit a zero-byte-terminated string constant.
946 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
947 unsigned NumElts = CVA->getNumOperands();
948 if (MAI->getAscizDirective() && NumElts &&
949 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
950 O << MAI->getAscizDirective();
951 printAsCString(O, CVA, NumElts-1);
953 O << MAI->getAsciiDirective();
954 printAsCString(O, CVA, NumElts);
959 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
960 unsigned AddrSpace) {
961 if (CVA->isString()) {
963 } else { // Not a string. Print the values in successive locations
964 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
965 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
969 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
970 const VectorType *PTy = CP->getType();
972 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
973 EmitGlobalConstant(CP->getOperand(I));
976 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
977 unsigned AddrSpace) {
978 // Print the fields in successive locations. Pad to align if needed!
979 const TargetData *TD = TM.getTargetData();
980 unsigned Size = TD->getTypeAllocSize(CVS->getType());
981 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
982 uint64_t sizeSoFar = 0;
983 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
984 const Constant* field = CVS->getOperand(i);
986 // Check if padding is needed and insert one or more 0s.
987 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
988 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
989 - cvsLayout->getElementOffset(i)) - fieldSize;
990 sizeSoFar += fieldSize + padSize;
992 // Now print the actual field value.
993 EmitGlobalConstant(field, AddrSpace);
995 // Insert padding - this may include padding to increase the size of the
996 // current field up to the ABI size (if the struct is not packed) as well
997 // as padding to ensure that the next field starts at the right offset.
998 EmitZeros(padSize, AddrSpace);
1000 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1001 "Layout of constant struct may be incorrect!");
1004 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1005 unsigned AddrSpace) {
1006 // FP Constants are printed as integer constants to avoid losing
1008 LLVMContext &Context = CFP->getContext();
1009 const TargetData *TD = TM.getTargetData();
1010 if (CFP->getType() == Type::getDoubleTy(Context)) {
1011 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1012 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1013 if (MAI->getData64bitsDirective(AddrSpace)) {
1014 O << MAI->getData64bitsDirective(AddrSpace) << i;
1016 O.PadToColumn(MAI->getCommentColumn());
1017 O << MAI->getCommentString() << " double " << Val;
1020 } else if (TD->isBigEndian()) {
1021 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1023 O.PadToColumn(MAI->getCommentColumn());
1024 O << MAI->getCommentString()
1025 << " most significant word of double " << Val;
1028 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1030 O.PadToColumn(MAI->getCommentColumn());
1031 O << MAI->getCommentString()
1032 << " least significant word of double " << Val;
1036 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1038 O.PadToColumn(MAI->getCommentColumn());
1039 O << MAI->getCommentString()
1040 << " least significant word of double " << Val;
1043 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1045 O.PadToColumn(MAI->getCommentColumn());
1046 O << MAI->getCommentString()
1047 << " most significant word of double " << Val;
1052 } else if (CFP->getType() == Type::getFloatTy(Context)) {
1053 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1054 O << MAI->getData32bitsDirective(AddrSpace)
1055 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1057 O.PadToColumn(MAI->getCommentColumn());
1058 O << MAI->getCommentString() << " float " << Val;
1062 } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1063 // all long double variants are printed as hex
1064 // api needed to prevent premature destruction
1065 APInt api = CFP->getValueAPF().bitcastToAPInt();
1066 const uint64_t *p = api.getRawData();
1067 // Convert to double so we can print the approximate val as a comment.
1068 APFloat DoubleVal = CFP->getValueAPF();
1070 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1072 if (TD->isBigEndian()) {
1073 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1075 O.PadToColumn(MAI->getCommentColumn());
1076 O << MAI->getCommentString()
1077 << " most significant halfword of x86_fp80 ~"
1078 << DoubleVal.convertToDouble();
1081 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1083 O.PadToColumn(MAI->getCommentColumn());
1084 O << MAI->getCommentString() << " next halfword";
1087 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1089 O.PadToColumn(MAI->getCommentColumn());
1090 O << MAI->getCommentString() << " next halfword";
1093 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1095 O.PadToColumn(MAI->getCommentColumn());
1096 O << MAI->getCommentString() << " next halfword";
1099 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1101 O.PadToColumn(MAI->getCommentColumn());
1102 O << MAI->getCommentString()
1103 << " least significant halfword";
1107 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1109 O.PadToColumn(MAI->getCommentColumn());
1110 O << MAI->getCommentString()
1111 << " least significant halfword of x86_fp80 ~"
1112 << DoubleVal.convertToDouble();
1115 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1117 O.PadToColumn(MAI->getCommentColumn());
1118 O << MAI->getCommentString()
1119 << " next halfword";
1122 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1124 O.PadToColumn(MAI->getCommentColumn());
1125 O << MAI->getCommentString()
1126 << " next halfword";
1129 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1131 O.PadToColumn(MAI->getCommentColumn());
1132 O << MAI->getCommentString()
1133 << " next halfword";
1136 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1138 O.PadToColumn(MAI->getCommentColumn());
1139 O << MAI->getCommentString()
1140 << " most significant halfword";
1144 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1145 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1147 } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1148 // all long double variants are printed as hex
1149 // api needed to prevent premature destruction
1150 APInt api = CFP->getValueAPF().bitcastToAPInt();
1151 const uint64_t *p = api.getRawData();
1152 if (TD->isBigEndian()) {
1153 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1155 O.PadToColumn(MAI->getCommentColumn());
1156 O << MAI->getCommentString()
1157 << " most significant word of ppc_fp128";
1160 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1162 O.PadToColumn(MAI->getCommentColumn());
1163 O << MAI->getCommentString()
1167 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1169 O.PadToColumn(MAI->getCommentColumn());
1170 O << MAI->getCommentString()
1174 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1176 O.PadToColumn(MAI->getCommentColumn());
1177 O << MAI->getCommentString()
1178 << " least significant word";
1182 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1184 O.PadToColumn(MAI->getCommentColumn());
1185 O << MAI->getCommentString()
1186 << " least significant word of ppc_fp128";
1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1191 O.PadToColumn(MAI->getCommentColumn());
1192 O << MAI->getCommentString()
1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1198 O.PadToColumn(MAI->getCommentColumn());
1199 O << MAI->getCommentString()
1203 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1205 O.PadToColumn(MAI->getCommentColumn());
1206 O << MAI->getCommentString()
1207 << " most significant word";
1212 } else llvm_unreachable("Floating point constant type not handled");
1215 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1216 unsigned AddrSpace) {
1217 const TargetData *TD = TM.getTargetData();
1218 unsigned BitWidth = CI->getBitWidth();
1219 assert(isPowerOf2_32(BitWidth) &&
1220 "Non-power-of-2-sized integers not handled!");
1222 // We don't expect assemblers to support integer data directives
1223 // for more than 64 bits, so we emit the data in at most 64-bit
1224 // quantities at a time.
1225 const uint64_t *RawData = CI->getValue().getRawData();
1226 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1228 if (TD->isBigEndian())
1229 Val = RawData[e - i - 1];
1233 if (MAI->getData64bitsDirective(AddrSpace))
1234 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1235 else if (TD->isBigEndian()) {
1236 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1238 O.PadToColumn(MAI->getCommentColumn());
1239 O << MAI->getCommentString()
1240 << " most significant half of i64 " << Val;
1243 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1245 O.PadToColumn(MAI->getCommentColumn());
1246 O << MAI->getCommentString()
1247 << " least significant half of i64 " << Val;
1251 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1253 O.PadToColumn(MAI->getCommentColumn());
1254 O << MAI->getCommentString()
1255 << " least significant half of i64 " << Val;
1258 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1260 O.PadToColumn(MAI->getCommentColumn());
1261 O << MAI->getCommentString()
1262 << " most significant half of i64 " << Val;
1269 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1270 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1271 const TargetData *TD = TM.getTargetData();
1272 const Type *type = CV->getType();
1273 unsigned Size = TD->getTypeAllocSize(type);
1275 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1276 EmitZeros(Size, AddrSpace);
1278 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1279 EmitGlobalConstantArray(CVA , AddrSpace);
1281 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1282 EmitGlobalConstantStruct(CVS, AddrSpace);
1284 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1285 EmitGlobalConstantFP(CFP, AddrSpace);
1287 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1288 // Small integers are handled below; large integers are handled here.
1290 EmitGlobalConstantLargeInt(CI, AddrSpace);
1293 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1294 EmitGlobalConstantVector(CP);
1298 printDataDirective(type, AddrSpace);
1299 EmitConstantValueOnly(CV);
1301 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1303 CI->getValue().toStringUnsigned(S, 16);
1304 O.PadToColumn(MAI->getCommentColumn());
1305 O << MAI->getCommentString() << " 0x" << S.str();
1311 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1312 // Target doesn't support this yet!
1313 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1316 /// PrintSpecial - Print information related to the specified machine instr
1317 /// that is independent of the operand, and may be independent of the instr
1318 /// itself. This can be useful for portably encoding the comment character
1319 /// or other bits of target-specific knowledge into the asmstrings. The
1320 /// syntax used is ${:comment}. Targets can override this to add support
1321 /// for their own strange codes.
1322 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1323 if (!strcmp(Code, "private")) {
1324 O << MAI->getPrivateGlobalPrefix();
1325 } else if (!strcmp(Code, "comment")) {
1327 O << MAI->getCommentString();
1328 } else if (!strcmp(Code, "uid")) {
1329 // Comparing the address of MI isn't sufficient, because machineinstrs may
1330 // be allocated to the same address across functions.
1331 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1333 // If this is a new LastFn instruction, bump the counter.
1334 if (LastMI != MI || LastFn != ThisF) {
1342 raw_string_ostream Msg(msg);
1343 Msg << "Unknown special formatter '" << Code
1344 << "' for machine instr: " << *MI;
1345 llvm_report_error(Msg.str());
1349 /// processDebugLoc - Processes the debug information of each machine
1350 /// instruction's DebugLoc.
1351 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1355 if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1356 if (!DL.isUnknown()) {
1357 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1359 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1360 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1361 DICompileUnit(CurDLT.CompileUnit)));
1370 /// printInlineAsm - This method formats and prints the specified machine
1371 /// instruction that is an inline asm.
1372 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1373 unsigned NumOperands = MI->getNumOperands();
1375 // Count the number of register definitions.
1376 unsigned NumDefs = 0;
1377 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1379 assert(NumDefs != NumOperands-1 && "No asm string?");
1381 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1383 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1384 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1386 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1387 // These are useful to see where empty asm's wound up.
1388 if (AsmStr[0] == 0) {
1389 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1390 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1394 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1396 // The variant of the current asmprinter.
1397 int AsmPrinterVariant = MAI->getAssemblerDialect();
1399 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1400 const char *LastEmitted = AsmStr; // One past the last character emitted.
1402 while (*LastEmitted) {
1403 switch (*LastEmitted) {
1405 // Not a special case, emit the string section literally.
1406 const char *LiteralEnd = LastEmitted+1;
1407 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1408 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1410 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1411 O.write(LastEmitted, LiteralEnd-LastEmitted);
1412 LastEmitted = LiteralEnd;
1416 ++LastEmitted; // Consume newline character.
1417 O << '\n'; // Indent code with newline.
1420 ++LastEmitted; // Consume '$' character.
1424 switch (*LastEmitted) {
1425 default: Done = false; break;
1426 case '$': // $$ -> $
1427 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1429 ++LastEmitted; // Consume second '$' character.
1431 case '(': // $( -> same as GCC's { character.
1432 ++LastEmitted; // Consume '(' character.
1433 if (CurVariant != -1) {
1434 llvm_report_error("Nested variants found in inline asm string: '"
1435 + std::string(AsmStr) + "'");
1437 CurVariant = 0; // We're in the first variant now.
1440 ++LastEmitted; // consume '|' character.
1441 if (CurVariant == -1)
1442 O << '|'; // this is gcc's behavior for | outside a variant
1444 ++CurVariant; // We're in the next variant.
1446 case ')': // $) -> same as GCC's } char.
1447 ++LastEmitted; // consume ')' character.
1448 if (CurVariant == -1)
1449 O << '}'; // this is gcc's behavior for } outside a variant
1456 bool HasCurlyBraces = false;
1457 if (*LastEmitted == '{') { // ${variable}
1458 ++LastEmitted; // Consume '{' character.
1459 HasCurlyBraces = true;
1462 // If we have ${:foo}, then this is not a real operand reference, it is a
1463 // "magic" string reference, just like in .td files. Arrange to call
1465 if (HasCurlyBraces && *LastEmitted == ':') {
1467 const char *StrStart = LastEmitted;
1468 const char *StrEnd = strchr(StrStart, '}');
1470 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1471 + std::string(AsmStr) + "'");
1474 std::string Val(StrStart, StrEnd);
1475 PrintSpecial(MI, Val.c_str());
1476 LastEmitted = StrEnd+1;
1480 const char *IDStart = LastEmitted;
1483 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1484 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1485 llvm_report_error("Bad $ operand number in inline asm string: '"
1486 + std::string(AsmStr) + "'");
1488 LastEmitted = IDEnd;
1490 char Modifier[2] = { 0, 0 };
1492 if (HasCurlyBraces) {
1493 // If we have curly braces, check for a modifier character. This
1494 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1495 if (*LastEmitted == ':') {
1496 ++LastEmitted; // Consume ':' character.
1497 if (*LastEmitted == 0) {
1498 llvm_report_error("Bad ${:} expression in inline asm string: '"
1499 + std::string(AsmStr) + "'");
1502 Modifier[0] = *LastEmitted;
1503 ++LastEmitted; // Consume modifier character.
1506 if (*LastEmitted != '}') {
1507 llvm_report_error("Bad ${} expression in inline asm string: '"
1508 + std::string(AsmStr) + "'");
1510 ++LastEmitted; // Consume '}' character.
1513 if ((unsigned)Val >= NumOperands-1) {
1514 llvm_report_error("Invalid $ operand number in inline asm string: '"
1515 + std::string(AsmStr) + "'");
1518 // Okay, we finally have a value number. Ask the target to print this
1520 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1525 // Scan to find the machine operand number for the operand.
1526 for (; Val; --Val) {
1527 if (OpNo >= MI->getNumOperands()) break;
1528 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1529 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1532 if (OpNo >= MI->getNumOperands()) {
1535 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1536 ++OpNo; // Skip over the ID number.
1538 if (Modifier[0]=='l') // labels are target independent
1539 GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1540 ->getNumber())->print(O, MAI);
1542 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1543 if ((OpFlags & 7) == 4) {
1544 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1545 Modifier[0] ? Modifier : 0);
1547 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1548 Modifier[0] ? Modifier : 0);
1554 raw_string_ostream Msg(msg);
1555 Msg << "Invalid operand found in inline asm: '"
1558 llvm_report_error(Msg.str());
1565 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1568 /// printImplicitDef - This method prints the specified machine instruction
1569 /// that is an implicit def.
1570 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1571 if (!VerboseAsm) return;
1572 O.PadToColumn(MAI->getCommentColumn());
1573 O << MAI->getCommentString() << " implicit-def: "
1574 << TRI->getName(MI->getOperand(0).getReg());
1577 /// printLabel - This method prints a local label used by debug and
1578 /// exception handling tables.
1579 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1580 printLabel(MI->getOperand(0).getImm());
1583 void AsmPrinter::printLabel(unsigned Id) const {
1584 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1587 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1588 /// instruction, using the specified assembler variant. Targets should
1589 /// overried this to format as appropriate.
1590 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1591 unsigned AsmVariant, const char *ExtraCode) {
1592 // Target doesn't support this yet!
1596 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1597 unsigned AsmVariant,
1598 const char *ExtraCode) {
1599 // Target doesn't support this yet!
1603 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1604 SmallString<60> Name;
1605 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1606 << getFunctionNumber() << '_' << MBBID;
1608 return OutContext.GetOrCreateSymbol(Name.str());
1612 /// EmitBasicBlockStart - This method prints the label for the specified
1613 /// MachineBasicBlock, an alignment (if present) and a comment describing
1614 /// it if appropriate.
1615 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1616 if (unsigned Align = MBB->getAlignment())
1617 EmitAlignment(Log2_32(Align));
1619 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1623 if (const BasicBlock *BB = MBB->getBasicBlock())
1624 if (BB->hasName()) {
1625 O.PadToColumn(MAI->getCommentColumn());
1626 O << MAI->getCommentString() << ' ';
1627 WriteAsOperand(O, BB, /*PrintType=*/false);
1634 /// printPICJumpTableSetLabel - This method prints a set label for the
1635 /// specified MachineBasicBlock for a jumptable entry.
1636 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1637 const MachineBasicBlock *MBB) const {
1638 if (!MAI->getSetDirective())
1641 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1642 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1643 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1644 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1645 << '_' << uid << '\n';
1648 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1649 const MachineBasicBlock *MBB) const {
1650 if (!MAI->getSetDirective())
1653 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1654 << getFunctionNumber() << '_' << uid << '_' << uid2
1655 << "_set_" << MBB->getNumber() << ',';
1656 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1657 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1658 << '_' << uid << '_' << uid2 << '\n';
1661 /// printDataDirective - This method prints the asm directive for the
1663 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1664 const TargetData *TD = TM.getTargetData();
1665 switch (type->getTypeID()) {
1666 case Type::FloatTyID: case Type::DoubleTyID:
1667 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1668 assert(0 && "Should have already output floating point constant.");
1670 assert(0 && "Can't handle printing this type of thing");
1671 case Type::IntegerTyID: {
1672 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1674 O << MAI->getData8bitsDirective(AddrSpace);
1675 else if (BitWidth <= 16)
1676 O << MAI->getData16bitsDirective(AddrSpace);
1677 else if (BitWidth <= 32)
1678 O << MAI->getData32bitsDirective(AddrSpace);
1679 else if (BitWidth <= 64) {
1680 assert(MAI->getData64bitsDirective(AddrSpace) &&
1681 "Target cannot handle 64-bit constant exprs!");
1682 O << MAI->getData64bitsDirective(AddrSpace);
1684 llvm_unreachable("Target cannot handle given data directive width!");
1688 case Type::PointerTyID:
1689 if (TD->getPointerSize() == 8) {
1690 assert(MAI->getData64bitsDirective(AddrSpace) &&
1691 "Target cannot handle 64-bit pointer exprs!");
1692 O << MAI->getData64bitsDirective(AddrSpace);
1693 } else if (TD->getPointerSize() == 2) {
1694 O << MAI->getData16bitsDirective(AddrSpace);
1695 } else if (TD->getPointerSize() == 1) {
1696 O << MAI->getData8bitsDirective(AddrSpace);
1698 O << MAI->getData32bitsDirective(AddrSpace);
1704 void AsmPrinter::printVisibility(const std::string& Name,
1705 unsigned Visibility) const {
1706 if (Visibility == GlobalValue::HiddenVisibility) {
1707 if (const char *Directive = MAI->getHiddenDirective())
1708 O << Directive << Name << '\n';
1709 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1710 if (const char *Directive = MAI->getProtectedDirective())
1711 O << Directive << Name << '\n';
1715 void AsmPrinter::printOffset(int64_t Offset) const {
1718 else if (Offset < 0)
1722 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1723 if (!S->usesMetadata())
1726 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1727 if (GCPI != GCMetadataPrinters.end())
1728 return GCPI->second;
1730 const char *Name = S->getName().c_str();
1732 for (GCMetadataPrinterRegistry::iterator
1733 I = GCMetadataPrinterRegistry::begin(),
1734 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1735 if (strcmp(Name, I->getName()) == 0) {
1736 GCMetadataPrinter *GMP = I->instantiate();
1738 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1742 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1743 llvm_unreachable(0);
1746 /// EmitComments - Pretty-print comments for instructions
1747 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1748 assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1750 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1752 // Print source line info.
1753 O.PadToColumn(MAI->getCommentColumn());
1754 O << MAI->getCommentString() << " SrcLine ";
1755 if (DLT.CompileUnit) {
1757 DICompileUnit CU(DLT.CompileUnit);
1758 O << CU.getFilename(Str) << " ";
1762 O << ":" << DLT.Col;
1765 /// PrintChildLoopComment - Print comments about child loops within
1766 /// the loop for this basic block, with nesting.
1768 static void PrintChildLoopComment(formatted_raw_ostream &O,
1769 const MachineLoop *loop,
1770 const MCAsmInfo *MAI,
1771 int FunctionNumber) {
1772 // Add child loop information
1773 for(MachineLoop::iterator cl = loop->begin(),
1774 clend = loop->end();
1777 MachineBasicBlock *Header = (*cl)->getHeader();
1778 assert(Header && "No header for loop");
1781 O.PadToColumn(MAI->getCommentColumn());
1783 O << MAI->getCommentString();
1784 O.indent(((*cl)->getLoopDepth()-1)*2)
1785 << " Child Loop BB" << FunctionNumber << "_"
1786 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1788 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1792 /// EmitComments - Pretty-print comments for basic blocks
1793 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1796 // Add loop depth information
1797 const MachineLoop *loop = LI->getLoopFor(&MBB);
1800 // Print a newline after bb# annotation.
1802 O.PadToColumn(MAI->getCommentColumn());
1803 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1806 O.PadToColumn(MAI->getCommentColumn());
1808 MachineBasicBlock *Header = loop->getHeader();
1809 assert(Header && "No header for loop");
1811 if (Header == &MBB) {
1812 O << MAI->getCommentString() << " Loop Header";
1813 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1816 O << MAI->getCommentString() << " Loop Header is BB"
1817 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1820 if (loop->empty()) {
1822 O.PadToColumn(MAI->getCommentColumn());
1823 O << MAI->getCommentString() << " Inner Loop";
1826 // Add parent loop information
1827 for (const MachineLoop *CurLoop = loop->getParentLoop();
1829 CurLoop = CurLoop->getParentLoop()) {
1830 MachineBasicBlock *Header = CurLoop->getHeader();
1831 assert(Header && "No header for loop");
1834 O.PadToColumn(MAI->getCommentColumn());
1835 O << MAI->getCommentString();
1836 O.indent((CurLoop->getLoopDepth()-1)*2)
1837 << " Inside Loop BB" << getFunctionNumber() << "_"
1838 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();