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/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
49 static cl::opt<cl::boolOrDefault>
50 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
51 cl::init(cl::BOU_UNSET));
53 char AsmPrinter::ID = 0;
54 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
55 const MCAsmInfo *T, bool VDef)
56 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
57 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
59 OutContext(*new MCContext()),
60 // FIXME: Pass instprinter to streamer.
61 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
63 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
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(*MAI);
106 // Allow the target to emit any magic that it wants at the start of the file.
107 EmitStartOfAsmFile(M);
109 if (MAI->hasSingleParameterDotFile()) {
110 /* Very minimal debug info. It is ignored if we emit actual
111 debug info. If we don't, this at least helps the user find where
112 a function came from. */
113 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
116 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
117 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
118 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
119 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
120 MP->beginAssembly(O, *this, *MAI);
122 if (!M.getModuleInlineAsm().empty())
123 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
124 << M.getModuleInlineAsm()
125 << '\n' << MAI->getCommentString()
126 << " End of file scope inline assembly\n";
128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
130 MMI->AnalyzeModule(M);
131 DW = getAnalysisIfAvailable<DwarfWriter>();
133 DW->BeginModule(&M, MMI, O, this, MAI);
138 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
139 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
140 if (!GV->hasInitializer()) // External globals require no code.
143 // Check to see if this is a special global used by LLVM, if so, emit it.
144 if (EmitSpecialLLVMGlobal(GV))
147 // Let the target emit it.
148 PrintGlobalVariable(GV);
152 bool AsmPrinter::doFinalization(Module &M) {
153 // Emit global variables.
154 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
156 EmitGlobalVariable(I);
158 // Emit final debug information.
159 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
162 // If the target wants to know about weak references, print them all.
163 if (MAI->getWeakRefDirective()) {
164 // FIXME: This is not lazy, it would be nice to only print weak references
165 // to stuff that is actually used. Note that doing so would require targets
166 // to notice uses in operands (due to constant exprs etc). This should
167 // happen with the MC stuff eventually.
169 // Print out module-level global variables here.
170 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
172 if (!I->hasExternalWeakLinkage()) continue;
173 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
176 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
177 if (!I->hasExternalWeakLinkage()) continue;
178 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
182 if (MAI->getSetDirective()) {
184 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
186 MCSymbol *Name = GetGlobalValueSymbol(I);
188 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
189 MCSymbol *Target = GetGlobalValueSymbol(GV);
191 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
192 O << "\t.globl\t" << *Name << '\n';
193 else if (I->hasWeakLinkage())
194 O << MAI->getWeakRefDirective() << *Name << '\n';
196 assert(I->hasLocalLinkage() && "Invalid alias linkage");
198 printVisibility(Name, I->getVisibility());
200 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
204 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
205 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
206 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
207 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
208 MP->finishAssembly(O, *this, *MAI);
210 // If we don't have any trampolines, then we don't require stack memory
211 // to be executable. Some targets have a directive to declare this.
212 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
213 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
214 if (MAI->getNonexecutableStackDirective())
215 O << MAI->getNonexecutableStackDirective() << '\n';
218 // Allow the target to emit any magic that it wants at the end of the file,
219 // after everything else has gone out.
222 delete Mang; Mang = 0;
225 OutStreamer.Finish();
229 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
230 // Get the function symbol.
231 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
232 IncrementFunctionNumber();
235 LI = &getAnalysis<MachineLoopInfo>();
239 // SectionCPs - Keep track the alignment, constpool entries per Section.
243 SmallVector<unsigned, 4> CPEs;
244 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
248 /// EmitConstantPool - Print to the current output stream assembly
249 /// representations of the constants in the constant pool MCP. This is
250 /// used to print out constants which have been "spilled to memory" by
251 /// the code generator.
253 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
254 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
255 if (CP.empty()) return;
257 // Calculate sections for constant pool entries. We collect entries to go into
258 // the same section together to reduce amount of section switch statements.
259 SmallVector<SectionCPs, 4> CPSections;
260 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
261 const MachineConstantPoolEntry &CPE = CP[i];
262 unsigned Align = CPE.getAlignment();
265 switch (CPE.getRelocationInfo()) {
266 default: llvm_unreachable("Unknown section kind");
267 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
269 Kind = SectionKind::getReadOnlyWithRelLocal();
272 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
273 case 4: Kind = SectionKind::getMergeableConst4(); break;
274 case 8: Kind = SectionKind::getMergeableConst8(); break;
275 case 16: Kind = SectionKind::getMergeableConst16();break;
276 default: Kind = SectionKind::getMergeableConst(); break;
280 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
282 // The number of sections are small, just do a linear search from the
283 // last section to the first.
285 unsigned SecIdx = CPSections.size();
286 while (SecIdx != 0) {
287 if (CPSections[--SecIdx].S == S) {
293 SecIdx = CPSections.size();
294 CPSections.push_back(SectionCPs(S, Align));
297 if (Align > CPSections[SecIdx].Alignment)
298 CPSections[SecIdx].Alignment = Align;
299 CPSections[SecIdx].CPEs.push_back(i);
302 // Now print stuff into the calculated sections.
303 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
304 OutStreamer.SwitchSection(CPSections[i].S);
305 EmitAlignment(Log2_32(CPSections[i].Alignment));
308 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
309 unsigned CPI = CPSections[i].CPEs[j];
310 MachineConstantPoolEntry CPE = CP[CPI];
312 // Emit inter-object padding for alignment.
313 unsigned AlignMask = CPE.getAlignment() - 1;
314 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
315 EmitZeros(NewOffset - Offset);
317 const Type *Ty = CPE.getType();
318 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
320 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
323 O.PadToColumn(MAI->getCommentColumn());
324 O << MAI->getCommentString() << " constant ";
325 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
328 if (CPE.isMachineConstantPoolEntry())
329 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
331 EmitGlobalConstant(CPE.Val.ConstVal);
336 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
337 /// by the current function to the current output stream.
339 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
340 MachineFunction &MF) {
341 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
342 if (JT.empty()) return;
344 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
346 // Pick the directive to use to print the jump table entries, and switch to
347 // the appropriate section.
348 TargetLowering *LoweringInfo = TM.getTargetLowering();
350 const Function *F = MF.getFunction();
351 bool JTInDiffSection = false;
352 if (F->isWeakForLinker() ||
353 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
354 // In PIC mode, we need to emit the jump table to the same section as the
355 // function body itself, otherwise the label differences won't make sense.
356 // We should also do if the section name is NULL or function is declared in
357 // discardable section.
358 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
361 // Otherwise, drop it in the readonly section.
362 const MCSection *ReadOnlySection =
363 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
364 OutStreamer.SwitchSection(ReadOnlySection);
365 JTInDiffSection = true;
368 EmitAlignment(Log2_32(MJTI->getAlignment()));
370 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
371 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
373 // If this jump table was deleted, ignore it.
374 if (JTBBs.empty()) continue;
376 // For PIC codegen, if possible we want to use the SetDirective to reduce
377 // the number of relocations the assembler will generate for the jump table.
378 // Set directives are all printed before the jump table itself.
379 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
380 if (MAI->getSetDirective() && IsPic)
381 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
382 if (EmittedSets.insert(JTBBs[ii]))
383 printPICJumpTableSetLabel(i, JTBBs[ii]);
385 // On some targets (e.g. Darwin) we want to emit two consequtive labels
386 // before each jump table. The first label is never referenced, but tells
387 // the assembler and linker the extents of the jump table object. The
388 // second label is actually referenced by the code.
389 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
390 O << MAI->getLinkerPrivateGlobalPrefix()
391 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
394 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
395 << '_' << i << ":\n";
397 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
398 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
404 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
405 const MachineBasicBlock *MBB,
406 unsigned uid) const {
407 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
409 // Use JumpTableDirective otherwise honor the entry size from the jump table
411 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
412 bool HadJTEntryDirective = JTEntryDirective != NULL;
413 if (!HadJTEntryDirective) {
414 JTEntryDirective = MJTI->getEntrySize() == 4 ?
415 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
418 O << JTEntryDirective << ' ';
420 // If we have emitted set directives for the jump table entries, print
421 // them rather than the entries themselves. If we're emitting PIC, then
422 // emit the table entries as differences between two text section labels.
423 // If we're emitting non-PIC code, then emit the entries as direct
424 // references to the target basic blocks.
426 O << *GetMBBSymbol(MBB->getNumber());
427 } else if (MAI->getSetDirective()) {
428 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
429 << '_' << uid << "_set_" << MBB->getNumber();
431 O << *GetMBBSymbol(MBB->getNumber());
432 // If the arch uses custom Jump Table directives, don't calc relative to
434 if (!HadJTEntryDirective)
435 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
436 << getFunctionNumber() << '_' << uid;
441 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
442 /// special global used by LLVM. If so, emit it and return true, otherwise
443 /// do nothing and return false.
444 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
445 if (GV->getName() == "llvm.used") {
446 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
447 EmitLLVMUsedList(GV->getInitializer());
451 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
452 if (GV->getSection() == "llvm.metadata" ||
453 GV->hasAvailableExternallyLinkage())
456 if (!GV->hasAppendingLinkage()) return false;
458 assert(GV->hasInitializer() && "Not a special LLVM global!");
460 const TargetData *TD = TM.getTargetData();
461 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
462 if (GV->getName() == "llvm.global_ctors") {
463 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
464 EmitAlignment(Align, 0);
465 EmitXXStructorList(GV->getInitializer());
467 if (TM.getRelocationModel() == Reloc::Static &&
468 MAI->hasStaticCtorDtorReferenceInStaticMode())
469 O << ".reference .constructors_used\n";
473 if (GV->getName() == "llvm.global_dtors") {
474 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
475 EmitAlignment(Align, 0);
476 EmitXXStructorList(GV->getInitializer());
478 if (TM.getRelocationModel() == Reloc::Static &&
479 MAI->hasStaticCtorDtorReferenceInStaticMode())
480 O << ".reference .destructors_used\n";
487 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
488 /// global in the specified llvm.used list for which emitUsedDirectiveFor
489 /// is true, as being used with this directive.
490 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
491 const char *Directive = MAI->getUsedDirective();
493 // Should be an array of 'i8*'.
494 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
495 if (InitList == 0) return;
497 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
498 const GlobalValue *GV =
499 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
500 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
502 EmitConstantValueOnly(InitList->getOperand(i));
508 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
509 /// function pointers, ignoring the init priority.
510 void AsmPrinter::EmitXXStructorList(Constant *List) {
511 // Should be an array of '{ int, void ()* }' structs. The first value is the
512 // init priority, which we ignore.
513 if (!isa<ConstantArray>(List)) return;
514 ConstantArray *InitList = cast<ConstantArray>(List);
515 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
516 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
517 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
519 if (CS->getOperand(1)->isNullValue())
520 return; // Found a null terminator, exit printing.
521 // Emit the function pointer.
522 EmitGlobalConstant(CS->getOperand(1));
527 //===----------------------------------------------------------------------===//
528 /// LEB 128 number encoding.
530 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
531 /// representing an unsigned leb128 value.
532 void AsmPrinter::PrintULEB128(unsigned Value) const {
534 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
536 if (Value) Byte |= 0x80;
538 if (Value) O << ", ";
542 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
543 /// representing a signed leb128 value.
544 void AsmPrinter::PrintSLEB128(int Value) const {
545 int Sign = Value >> (8 * sizeof(Value) - 1);
549 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
551 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
552 if (IsMore) Byte |= 0x80;
554 if (IsMore) O << ", ";
558 //===--------------------------------------------------------------------===//
559 // Emission and print routines
562 /// PrintHex - Print a value as a hexadecimal value.
564 void AsmPrinter::PrintHex(uint64_t Value) const {
569 /// EOL - Print a newline character to asm stream. If a comment is present
570 /// then it will be printed first. Comments should not contain '\n'.
571 void AsmPrinter::EOL() const {
575 void AsmPrinter::EOL(const Twine &Comment) const {
576 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
577 O.PadToColumn(MAI->getCommentColumn());
578 O << MAI->getCommentString()
585 static const char *DecodeDWARFEncoding(unsigned Encoding) {
587 case dwarf::DW_EH_PE_absptr:
589 case dwarf::DW_EH_PE_omit:
591 case dwarf::DW_EH_PE_pcrel:
593 case dwarf::DW_EH_PE_udata4:
595 case dwarf::DW_EH_PE_udata8:
597 case dwarf::DW_EH_PE_sdata4:
599 case dwarf::DW_EH_PE_sdata8:
601 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
602 return "pcrel udata4";
603 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
604 return "pcrel sdata4";
605 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
606 return "pcrel udata8";
607 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
608 return "pcrel sdata8";
609 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
610 return "indirect pcrel udata4";
611 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
612 return "indirect pcrel sdata4";
613 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
614 return "indirect pcrel udata8";
615 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
616 return "indirect pcrel sdata8";
622 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
623 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
624 O.PadToColumn(MAI->getCommentColumn());
625 O << MAI->getCommentString()
629 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
630 O << " (" << EncStr << ')';
635 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
636 /// unsigned leb128 value.
637 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
638 if (MAI->hasLEB128()) {
642 O << MAI->getData8bitsDirective();
647 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
648 /// signed leb128 value.
649 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
650 if (MAI->hasLEB128()) {
654 O << MAI->getData8bitsDirective();
659 /// EmitInt8 - Emit a byte directive and value.
661 void AsmPrinter::EmitInt8(int Value) const {
662 O << MAI->getData8bitsDirective();
663 PrintHex(Value & 0xFF);
666 /// EmitInt16 - Emit a short directive and value.
668 void AsmPrinter::EmitInt16(int Value) const {
669 O << MAI->getData16bitsDirective();
670 PrintHex(Value & 0xFFFF);
673 /// EmitInt32 - Emit a long directive and value.
675 void AsmPrinter::EmitInt32(int Value) const {
676 O << MAI->getData32bitsDirective();
680 /// EmitInt64 - Emit a long long directive and value.
682 void AsmPrinter::EmitInt64(uint64_t Value) const {
683 if (MAI->getData64bitsDirective()) {
684 O << MAI->getData64bitsDirective();
687 if (TM.getTargetData()->isBigEndian()) {
688 EmitInt32(unsigned(Value >> 32)); O << '\n';
689 EmitInt32(unsigned(Value));
691 EmitInt32(unsigned(Value)); O << '\n';
692 EmitInt32(unsigned(Value >> 32));
697 /// toOctal - Convert the low order bits of X into an octal digit.
699 static inline char toOctal(int X) {
703 /// printStringChar - Print a char, escaped if necessary.
705 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
708 } else if (C == '\\') {
710 } else if (isprint((unsigned char)C)) {
714 case '\b': O << "\\b"; break;
715 case '\f': O << "\\f"; break;
716 case '\n': O << "\\n"; break;
717 case '\r': O << "\\r"; break;
718 case '\t': O << "\\t"; break;
721 O << toOctal(C >> 6);
722 O << toOctal(C >> 3);
723 O << toOctal(C >> 0);
729 /// EmitString - Emit a string with quotes and a null terminator.
730 /// Special characters are emitted properly.
731 /// \literal (Eg. '\t') \endliteral
732 void AsmPrinter::EmitString(const StringRef String) const {
733 EmitString(String.data(), String.size());
736 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
737 const char* AscizDirective = MAI->getAscizDirective();
741 O << MAI->getAsciiDirective();
743 for (unsigned i = 0; i < Size; ++i)
744 printStringChar(O, String[i]);
752 /// EmitFile - Emit a .file directive.
753 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
754 O << "\t.file\t" << Number << " \"";
755 for (unsigned i = 0, N = Name.size(); i < N; ++i)
756 printStringChar(O, Name[i]);
761 //===----------------------------------------------------------------------===//
763 // EmitAlignment - Emit an alignment directive to the specified power of
764 // two boundary. For example, if you pass in 3 here, you will get an 8
765 // byte alignment. If a global value is specified, and if that global has
766 // an explicit alignment requested, it will unconditionally override the
767 // alignment request. However, if ForcedAlignBits is specified, this value
768 // has final say: the ultimate alignment will be the max of ForcedAlignBits
769 // and the alignment computed with NumBits and the global.
773 // if (GV && GV->hasalignment) Align = GV->getalignment();
774 // Align = std::max(Align, ForcedAlignBits);
776 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
777 unsigned ForcedAlignBits,
778 bool UseFillExpr) const {
779 if (GV && GV->getAlignment())
780 NumBits = Log2_32(GV->getAlignment());
781 NumBits = std::max(NumBits, ForcedAlignBits);
783 if (NumBits == 0) return; // No need to emit alignment.
785 unsigned FillValue = 0;
786 if (getCurrentSection()->getKind().isText())
787 FillValue = MAI->getTextAlignFillValue();
789 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
792 /// EmitZeros - Emit a block of zeros.
794 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
796 if (MAI->getZeroDirective()) {
797 O << MAI->getZeroDirective() << NumZeros;
798 if (MAI->getZeroDirectiveSuffix())
799 O << MAI->getZeroDirectiveSuffix();
802 for (; NumZeros; --NumZeros)
803 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
808 // Print out the specified constant, without a storage class. Only the
809 // constants valid in constant expressions can occur here.
810 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
811 if (CV->isNullValue() || isa<UndefValue>(CV)) {
816 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
817 O << CI->getZExtValue();
821 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
822 // This is a constant address for a global variable or function. Use the
823 // name of the variable or function as the address value.
824 O << *GetGlobalValueSymbol(GV);
828 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
829 O << *GetBlockAddressSymbol(BA);
833 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
835 llvm_unreachable("Unknown constant value!");
840 switch (CE->getOpcode()) {
841 case Instruction::ZExt:
842 case Instruction::SExt:
843 case Instruction::FPTrunc:
844 case Instruction::FPExt:
845 case Instruction::UIToFP:
846 case Instruction::SIToFP:
847 case Instruction::FPToUI:
848 case Instruction::FPToSI:
850 llvm_unreachable("FIXME: Don't support this constant cast expr");
851 case Instruction::GetElementPtr: {
852 // generate a symbolic expression for the byte address
853 const TargetData *TD = TM.getTargetData();
854 const Constant *ptrVal = CE->getOperand(0);
855 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
856 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
859 return EmitConstantValueOnly(ptrVal);
861 // Truncate/sext the offset to the pointer size.
862 if (TD->getPointerSizeInBits() != 64) {
863 int SExtAmount = 64-TD->getPointerSizeInBits();
864 Offset = (Offset << SExtAmount) >> SExtAmount;
869 EmitConstantValueOnly(ptrVal);
871 O << ") + " << Offset;
873 O << ") - " << -Offset;
876 case Instruction::BitCast:
877 return EmitConstantValueOnly(CE->getOperand(0));
879 case Instruction::IntToPtr: {
880 // Handle casts to pointers by changing them into casts to the appropriate
881 // integer type. This promotes constant folding and simplifies this code.
882 const TargetData *TD = TM.getTargetData();
883 Constant *Op = CE->getOperand(0);
884 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
886 return EmitConstantValueOnly(Op);
889 case Instruction::PtrToInt: {
890 // Support only foldable casts to/from pointers that can be eliminated by
891 // changing the pointer to the appropriately sized integer type.
892 Constant *Op = CE->getOperand(0);
893 const Type *Ty = CE->getType();
894 const TargetData *TD = TM.getTargetData();
896 // We can emit the pointer value into this slot if the slot is an
897 // integer slot greater or equal to the size of the pointer.
898 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
899 return EmitConstantValueOnly(Op);
902 EmitConstantValueOnly(Op);
904 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
907 ptrMask.toStringUnsigned(S);
908 O << ") & " << S.str() << ')';
912 case Instruction::Trunc:
913 // We emit the value and depend on the assembler to truncate the generated
914 // expression properly. This is important for differences between
915 // blockaddress labels. Since the two labels are in the same function, it
916 // is reasonable to treat their delta as a 32-bit value.
917 return EmitConstantValueOnly(CE->getOperand(0));
919 case Instruction::Add:
920 case Instruction::Sub:
921 case Instruction::And:
922 case Instruction::Or:
923 case Instruction::Xor:
925 EmitConstantValueOnly(CE->getOperand(0));
927 switch (CE->getOpcode()) {
928 case Instruction::Add:
931 case Instruction::Sub:
934 case Instruction::And:
937 case Instruction::Or:
940 case Instruction::Xor:
947 EmitConstantValueOnly(CE->getOperand(1));
953 /// printAsCString - Print the specified array as a C compatible string, only if
954 /// the predicate isString is true.
956 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
958 assert(CVA->isString() && "Array is not string compatible!");
961 for (unsigned i = 0; i != LastElt; ++i) {
963 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
964 printStringChar(O, C);
969 /// EmitString - Emit a zero-byte-terminated string constant.
971 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
972 unsigned NumElts = CVA->getNumOperands();
973 if (MAI->getAscizDirective() && NumElts &&
974 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
975 O << MAI->getAscizDirective();
976 printAsCString(O, CVA, NumElts-1);
978 O << MAI->getAsciiDirective();
979 printAsCString(O, CVA, NumElts);
984 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
985 unsigned AddrSpace) {
986 if (CVA->isString()) {
988 } else { // Not a string. Print the values in successive locations
989 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
990 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
994 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
995 const VectorType *PTy = CP->getType();
997 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
998 EmitGlobalConstant(CP->getOperand(I));
1001 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1002 unsigned AddrSpace) {
1003 // Print the fields in successive locations. Pad to align if needed!
1004 const TargetData *TD = TM.getTargetData();
1005 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1006 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1007 uint64_t sizeSoFar = 0;
1008 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1009 const Constant* field = CVS->getOperand(i);
1011 // Check if padding is needed and insert one or more 0s.
1012 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1013 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1014 - cvsLayout->getElementOffset(i)) - fieldSize;
1015 sizeSoFar += fieldSize + padSize;
1017 // Now print the actual field value.
1018 EmitGlobalConstant(field, AddrSpace);
1020 // Insert padding - this may include padding to increase the size of the
1021 // current field up to the ABI size (if the struct is not packed) as well
1022 // as padding to ensure that the next field starts at the right offset.
1023 EmitZeros(padSize, AddrSpace);
1025 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1026 "Layout of constant struct may be incorrect!");
1029 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1030 unsigned AddrSpace) {
1031 // FP Constants are printed as integer constants to avoid losing
1033 LLVMContext &Context = CFP->getContext();
1034 const TargetData *TD = TM.getTargetData();
1035 if (CFP->getType()->isDoubleTy()) {
1036 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1037 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1038 if (MAI->getData64bitsDirective(AddrSpace)) {
1039 O << MAI->getData64bitsDirective(AddrSpace) << i;
1041 O.PadToColumn(MAI->getCommentColumn());
1042 O << MAI->getCommentString() << " double " << Val;
1045 } else if (TD->isBigEndian()) {
1046 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1048 O.PadToColumn(MAI->getCommentColumn());
1049 O << MAI->getCommentString()
1050 << " most significant word of double " << Val;
1053 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1055 O.PadToColumn(MAI->getCommentColumn());
1056 O << MAI->getCommentString()
1057 << " least significant word of double " << Val;
1061 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1063 O.PadToColumn(MAI->getCommentColumn());
1064 O << MAI->getCommentString()
1065 << " least significant word of double " << Val;
1068 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1070 O.PadToColumn(MAI->getCommentColumn());
1071 O << MAI->getCommentString()
1072 << " most significant word of double " << Val;
1079 if (CFP->getType()->isFloatTy()) {
1080 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1081 O << MAI->getData32bitsDirective(AddrSpace)
1082 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1084 O.PadToColumn(MAI->getCommentColumn());
1085 O << MAI->getCommentString() << " float " << Val;
1091 if (CFP->getType()->isX86_FP80Ty()) {
1092 // all long double variants are printed as hex
1093 // api needed to prevent premature destruction
1094 APInt api = CFP->getValueAPF().bitcastToAPInt();
1095 const uint64_t *p = api.getRawData();
1096 // Convert to double so we can print the approximate val as a comment.
1097 APFloat DoubleVal = CFP->getValueAPF();
1099 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1101 if (TD->isBigEndian()) {
1102 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1104 O.PadToColumn(MAI->getCommentColumn());
1105 O << MAI->getCommentString()
1106 << " most significant halfword of x86_fp80 ~"
1107 << DoubleVal.convertToDouble();
1110 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1112 O.PadToColumn(MAI->getCommentColumn());
1113 O << MAI->getCommentString() << " next halfword";
1116 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1118 O.PadToColumn(MAI->getCommentColumn());
1119 O << MAI->getCommentString() << " next halfword";
1122 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1124 O.PadToColumn(MAI->getCommentColumn());
1125 O << MAI->getCommentString() << " next halfword";
1128 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1130 O.PadToColumn(MAI->getCommentColumn());
1131 O << MAI->getCommentString()
1132 << " least significant halfword";
1136 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1138 O.PadToColumn(MAI->getCommentColumn());
1139 O << MAI->getCommentString()
1140 << " least significant halfword of x86_fp80 ~"
1141 << DoubleVal.convertToDouble();
1144 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1146 O.PadToColumn(MAI->getCommentColumn());
1147 O << MAI->getCommentString()
1148 << " next halfword";
1151 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1153 O.PadToColumn(MAI->getCommentColumn());
1154 O << MAI->getCommentString()
1155 << " next halfword";
1158 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1160 O.PadToColumn(MAI->getCommentColumn());
1161 O << MAI->getCommentString()
1162 << " next halfword";
1165 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1167 O.PadToColumn(MAI->getCommentColumn());
1168 O << MAI->getCommentString()
1169 << " most significant halfword";
1173 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1174 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1178 if (CFP->getType()->isPPC_FP128Ty()) {
1179 // all long double variants are printed as hex
1180 // api needed to prevent premature destruction
1181 APInt api = CFP->getValueAPF().bitcastToAPInt();
1182 const uint64_t *p = api.getRawData();
1183 if (TD->isBigEndian()) {
1184 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1186 O.PadToColumn(MAI->getCommentColumn());
1187 O << MAI->getCommentString()
1188 << " most significant word of ppc_fp128";
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[1] >> 32);
1200 O.PadToColumn(MAI->getCommentColumn());
1201 O << MAI->getCommentString()
1205 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1207 O.PadToColumn(MAI->getCommentColumn());
1208 O << MAI->getCommentString()
1209 << " least significant word";
1213 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1215 O.PadToColumn(MAI->getCommentColumn());
1216 O << MAI->getCommentString()
1217 << " least significant word of ppc_fp128";
1220 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1222 O.PadToColumn(MAI->getCommentColumn());
1223 O << MAI->getCommentString()
1227 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1229 O.PadToColumn(MAI->getCommentColumn());
1230 O << MAI->getCommentString()
1234 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1236 O.PadToColumn(MAI->getCommentColumn());
1237 O << MAI->getCommentString()
1238 << " most significant word";
1243 } else llvm_unreachable("Floating point constant type not handled");
1246 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1247 unsigned AddrSpace) {
1248 const TargetData *TD = TM.getTargetData();
1249 unsigned BitWidth = CI->getBitWidth();
1250 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1252 // We don't expect assemblers to support integer data directives
1253 // for more than 64 bits, so we emit the data in at most 64-bit
1254 // quantities at a time.
1255 const uint64_t *RawData = CI->getValue().getRawData();
1256 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1258 if (TD->isBigEndian())
1259 Val = RawData[e - i - 1];
1263 if (MAI->getData64bitsDirective(AddrSpace)) {
1264 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1268 // Emit two 32-bit chunks, order depends on endianness.
1269 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1270 const char *FirstName = " least", *SecondName = " most";
1271 if (TD->isBigEndian()) {
1272 std::swap(FirstChunk, SecondChunk);
1273 std::swap(FirstName, SecondName);
1276 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1278 O.PadToColumn(MAI->getCommentColumn());
1279 O << MAI->getCommentString()
1280 << FirstName << " significant half of i64 " << Val;
1284 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1286 O.PadToColumn(MAI->getCommentColumn());
1287 O << MAI->getCommentString()
1288 << SecondName << " significant half of i64 " << Val;
1294 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1295 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1296 const TargetData *TD = TM.getTargetData();
1297 const Type *type = CV->getType();
1298 unsigned Size = TD->getTypeAllocSize(type);
1300 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1301 EmitZeros(Size, AddrSpace);
1305 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1306 EmitGlobalConstantArray(CVA , AddrSpace);
1310 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1311 EmitGlobalConstantStruct(CVS, AddrSpace);
1315 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1316 EmitGlobalConstantFP(CFP, AddrSpace);
1320 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1321 // If we can directly emit an 8-byte constant, do it.
1323 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1324 O << Data64Dir << CI->getZExtValue() << '\n';
1328 // Small integers are handled below; large integers are handled here.
1330 EmitGlobalConstantLargeInt(CI, AddrSpace);
1335 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1336 EmitGlobalConstantVector(CP);
1340 printDataDirective(type, AddrSpace);
1341 EmitConstantValueOnly(CV);
1343 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1345 CI->getValue().toStringUnsigned(S, 16);
1346 O.PadToColumn(MAI->getCommentColumn());
1347 O << MAI->getCommentString() << " 0x" << S.str();
1353 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1354 // Target doesn't support this yet!
1355 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1358 /// PrintSpecial - Print information related to the specified machine instr
1359 /// that is independent of the operand, and may be independent of the instr
1360 /// itself. This can be useful for portably encoding the comment character
1361 /// or other bits of target-specific knowledge into the asmstrings. The
1362 /// syntax used is ${:comment}. Targets can override this to add support
1363 /// for their own strange codes.
1364 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1365 if (!strcmp(Code, "private")) {
1366 O << MAI->getPrivateGlobalPrefix();
1367 } else if (!strcmp(Code, "comment")) {
1369 O << MAI->getCommentString();
1370 } else if (!strcmp(Code, "uid")) {
1371 // Comparing the address of MI isn't sufficient, because machineinstrs may
1372 // be allocated to the same address across functions.
1373 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1375 // If this is a new LastFn instruction, bump the counter.
1376 if (LastMI != MI || LastFn != ThisF) {
1384 raw_string_ostream Msg(msg);
1385 Msg << "Unknown special formatter '" << Code
1386 << "' for machine instr: " << *MI;
1387 llvm_report_error(Msg.str());
1391 /// processDebugLoc - Processes the debug information of each machine
1392 /// instruction's DebugLoc.
1393 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1394 bool BeforePrintingInsn) {
1395 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1396 || !DW->ShouldEmitDwarfDebug())
1398 DebugLoc DL = MI->getDebugLoc();
1401 DILocation CurDLT = MF->getDILocation(DL);
1402 if (CurDLT.getScope().isNull())
1405 if (BeforePrintingInsn) {
1406 if (CurDLT.getNode() != PrevDLT.getNode()) {
1407 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1408 CurDLT.getColumnNumber(),
1409 CurDLT.getScope().getNode());
1412 DW->BeginScope(MI, L);
1416 // After printing instruction
1422 /// printInlineAsm - This method formats and prints the specified machine
1423 /// instruction that is an inline asm.
1424 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1425 unsigned NumOperands = MI->getNumOperands();
1427 // Count the number of register definitions.
1428 unsigned NumDefs = 0;
1429 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1431 assert(NumDefs != NumOperands-1 && "No asm string?");
1433 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1435 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1436 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1440 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1441 // These are useful to see where empty asm's wound up.
1442 if (AsmStr[0] == 0) {
1443 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1444 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1448 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1450 // The variant of the current asmprinter.
1451 int AsmPrinterVariant = MAI->getAssemblerDialect();
1453 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1454 const char *LastEmitted = AsmStr; // One past the last character emitted.
1456 while (*LastEmitted) {
1457 switch (*LastEmitted) {
1459 // Not a special case, emit the string section literally.
1460 const char *LiteralEnd = LastEmitted+1;
1461 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1462 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1464 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1465 O.write(LastEmitted, LiteralEnd-LastEmitted);
1466 LastEmitted = LiteralEnd;
1470 ++LastEmitted; // Consume newline character.
1471 O << '\n'; // Indent code with newline.
1474 ++LastEmitted; // Consume '$' character.
1478 switch (*LastEmitted) {
1479 default: Done = false; break;
1480 case '$': // $$ -> $
1481 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1483 ++LastEmitted; // Consume second '$' character.
1485 case '(': // $( -> same as GCC's { character.
1486 ++LastEmitted; // Consume '(' character.
1487 if (CurVariant != -1) {
1488 llvm_report_error("Nested variants found in inline asm string: '"
1489 + std::string(AsmStr) + "'");
1491 CurVariant = 0; // We're in the first variant now.
1494 ++LastEmitted; // consume '|' character.
1495 if (CurVariant == -1)
1496 O << '|'; // this is gcc's behavior for | outside a variant
1498 ++CurVariant; // We're in the next variant.
1500 case ')': // $) -> same as GCC's } char.
1501 ++LastEmitted; // consume ')' character.
1502 if (CurVariant == -1)
1503 O << '}'; // this is gcc's behavior for } outside a variant
1510 bool HasCurlyBraces = false;
1511 if (*LastEmitted == '{') { // ${variable}
1512 ++LastEmitted; // Consume '{' character.
1513 HasCurlyBraces = true;
1516 // If we have ${:foo}, then this is not a real operand reference, it is a
1517 // "magic" string reference, just like in .td files. Arrange to call
1519 if (HasCurlyBraces && *LastEmitted == ':') {
1521 const char *StrStart = LastEmitted;
1522 const char *StrEnd = strchr(StrStart, '}');
1524 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1525 + std::string(AsmStr) + "'");
1528 std::string Val(StrStart, StrEnd);
1529 PrintSpecial(MI, Val.c_str());
1530 LastEmitted = StrEnd+1;
1534 const char *IDStart = LastEmitted;
1537 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1538 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1539 llvm_report_error("Bad $ operand number in inline asm string: '"
1540 + std::string(AsmStr) + "'");
1542 LastEmitted = IDEnd;
1544 char Modifier[2] = { 0, 0 };
1546 if (HasCurlyBraces) {
1547 // If we have curly braces, check for a modifier character. This
1548 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1549 if (*LastEmitted == ':') {
1550 ++LastEmitted; // Consume ':' character.
1551 if (*LastEmitted == 0) {
1552 llvm_report_error("Bad ${:} expression in inline asm string: '"
1553 + std::string(AsmStr) + "'");
1556 Modifier[0] = *LastEmitted;
1557 ++LastEmitted; // Consume modifier character.
1560 if (*LastEmitted != '}') {
1561 llvm_report_error("Bad ${} expression in inline asm string: '"
1562 + std::string(AsmStr) + "'");
1564 ++LastEmitted; // Consume '}' character.
1567 if ((unsigned)Val >= NumOperands-1) {
1568 llvm_report_error("Invalid $ operand number in inline asm string: '"
1569 + std::string(AsmStr) + "'");
1572 // Okay, we finally have a value number. Ask the target to print this
1574 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1579 // Scan to find the machine operand number for the operand.
1580 for (; Val; --Val) {
1581 if (OpNo >= MI->getNumOperands()) break;
1582 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1583 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1586 if (OpNo >= MI->getNumOperands()) {
1589 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1590 ++OpNo; // Skip over the ID number.
1592 if (Modifier[0] == 'l') // labels are target independent
1593 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1595 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1596 if ((OpFlags & 7) == 4) {
1597 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1598 Modifier[0] ? Modifier : 0);
1600 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1601 Modifier[0] ? Modifier : 0);
1607 raw_string_ostream Msg(msg);
1608 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1610 llvm_report_error(Msg.str());
1617 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1620 /// printImplicitDef - This method prints the specified machine instruction
1621 /// that is an implicit def.
1622 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1623 if (!VerboseAsm) return;
1624 O.PadToColumn(MAI->getCommentColumn());
1625 O << MAI->getCommentString() << " implicit-def: "
1626 << TRI->getName(MI->getOperand(0).getReg());
1629 void AsmPrinter::printKill(const MachineInstr *MI) const {
1630 if (!VerboseAsm) return;
1631 O.PadToColumn(MAI->getCommentColumn());
1632 O << MAI->getCommentString() << " kill:";
1633 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1634 const MachineOperand &op = MI->getOperand(n);
1635 assert(op.isReg() && "KILL instruction must have only register operands");
1636 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1640 /// printLabel - This method prints a local label used by debug and
1641 /// exception handling tables.
1642 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1643 printLabel(MI->getOperand(0).getImm());
1646 void AsmPrinter::printLabel(unsigned Id) const {
1647 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1650 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1651 /// instruction, using the specified assembler variant. Targets should
1652 /// override this to format as appropriate.
1653 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1654 unsigned AsmVariant, const char *ExtraCode) {
1655 // Target doesn't support this yet!
1659 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1660 unsigned AsmVariant,
1661 const char *ExtraCode) {
1662 // Target doesn't support this yet!
1666 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1667 const char *Suffix) const {
1668 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1671 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1672 const BasicBlock *BB,
1673 const char *Suffix) const {
1674 assert(BB->hasName() &&
1675 "Address of anonymous basic block not supported yet!");
1677 // This code must use the function name itself, and not the function number,
1678 // since it must be possible to generate the label name from within other
1680 SmallString<60> FnName;
1681 Mang->getNameWithPrefix(FnName, F, false);
1683 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1684 SmallString<60> NameResult;
1685 Mang->getNameWithPrefix(NameResult,
1686 StringRef("BA") + Twine((unsigned)FnName.size()) +
1687 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1690 return OutContext.GetOrCreateSymbol(NameResult.str());
1693 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1694 SmallString<60> Name;
1695 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1696 << getFunctionNumber() << '_' << MBBID;
1698 return OutContext.GetOrCreateSymbol(Name.str());
1701 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1703 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1704 SmallString<60> NameStr;
1705 Mang->getNameWithPrefix(NameStr, GV, false);
1706 return OutContext.GetOrCreateSymbol(NameStr.str());
1709 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1710 /// global value name as its base, with the specified suffix, and where the
1711 /// symbol is forced to have private linkage if ForcePrivate is true.
1712 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1714 bool ForcePrivate) const {
1715 SmallString<60> NameStr;
1716 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1717 NameStr.append(Suffix.begin(), Suffix.end());
1718 return OutContext.GetOrCreateSymbol(NameStr.str());
1721 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1723 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1724 SmallString<60> NameStr;
1725 Mang->getNameWithPrefix(NameStr, Sym);
1726 return OutContext.GetOrCreateSymbol(NameStr.str());
1730 /// EmitBasicBlockStart - This method prints the label for the specified
1731 /// MachineBasicBlock, an alignment (if present) and a comment describing
1732 /// it if appropriate.
1733 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1734 // Emit an alignment directive for this block, if needed.
1735 if (unsigned Align = MBB->getAlignment())
1736 EmitAlignment(Log2_32(Align));
1738 // If the block has its address taken, emit a special label to satisfy
1739 // references to the block. This is done so that we don't need to
1740 // remember the number of this label, and so that we can make
1741 // forward references to labels without knowing what their numbers
1743 if (MBB->hasAddressTaken()) {
1744 O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1745 MBB->getBasicBlock());
1748 O.PadToColumn(MAI->getCommentColumn());
1749 O << MAI->getCommentString() << " Address Taken";
1754 // Print the main label for the block.
1755 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1757 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1759 O << *GetMBBSymbol(MBB->getNumber()) << ':';
1764 // Print some comments to accompany the label.
1766 if (const BasicBlock *BB = MBB->getBasicBlock())
1767 if (BB->hasName()) {
1768 O.PadToColumn(MAI->getCommentColumn());
1769 O << MAI->getCommentString() << ' ';
1770 WriteAsOperand(O, BB, /*PrintType=*/false);
1778 /// printPICJumpTableSetLabel - This method prints a set label for the
1779 /// specified MachineBasicBlock for a jumptable entry.
1780 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1781 const MachineBasicBlock *MBB) const {
1782 if (!MAI->getSetDirective())
1785 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1786 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1787 << *GetMBBSymbol(MBB->getNumber())
1788 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1789 << '_' << uid << '\n';
1792 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1793 const MachineBasicBlock *MBB) const {
1794 if (!MAI->getSetDirective())
1797 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1798 << getFunctionNumber() << '_' << uid << '_' << uid2
1799 << "_set_" << MBB->getNumber() << ','
1800 << *GetMBBSymbol(MBB->getNumber())
1801 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1802 << '_' << uid << '_' << uid2 << '\n';
1805 /// printDataDirective - This method prints the asm directive for the
1807 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1808 const TargetData *TD = TM.getTargetData();
1809 switch (type->getTypeID()) {
1810 case Type::FloatTyID: case Type::DoubleTyID:
1811 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1812 assert(0 && "Should have already output floating point constant.");
1814 assert(0 && "Can't handle printing this type of thing");
1815 case Type::IntegerTyID: {
1816 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1818 O << MAI->getData8bitsDirective(AddrSpace);
1819 else if (BitWidth <= 16)
1820 O << MAI->getData16bitsDirective(AddrSpace);
1821 else if (BitWidth <= 32)
1822 O << MAI->getData32bitsDirective(AddrSpace);
1823 else if (BitWidth <= 64) {
1824 assert(MAI->getData64bitsDirective(AddrSpace) &&
1825 "Target cannot handle 64-bit constant exprs!");
1826 O << MAI->getData64bitsDirective(AddrSpace);
1828 llvm_unreachable("Target cannot handle given data directive width!");
1832 case Type::PointerTyID:
1833 if (TD->getPointerSize() == 8) {
1834 assert(MAI->getData64bitsDirective(AddrSpace) &&
1835 "Target cannot handle 64-bit pointer exprs!");
1836 O << MAI->getData64bitsDirective(AddrSpace);
1837 } else if (TD->getPointerSize() == 2) {
1838 O << MAI->getData16bitsDirective(AddrSpace);
1839 } else if (TD->getPointerSize() == 1) {
1840 O << MAI->getData8bitsDirective(AddrSpace);
1842 O << MAI->getData32bitsDirective(AddrSpace);
1848 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1849 unsigned Visibility) const {
1850 if (Visibility == GlobalValue::HiddenVisibility) {
1851 if (const char *Directive = MAI->getHiddenDirective())
1852 O << Directive << *Sym << '\n';
1853 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1854 if (const char *Directive = MAI->getProtectedDirective())
1855 O << Directive << *Sym << '\n';
1859 void AsmPrinter::printOffset(int64_t Offset) const {
1862 else if (Offset < 0)
1866 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1867 if (!S->usesMetadata())
1870 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1871 if (GCPI != GCMetadataPrinters.end())
1872 return GCPI->second;
1874 const char *Name = S->getName().c_str();
1876 for (GCMetadataPrinterRegistry::iterator
1877 I = GCMetadataPrinterRegistry::begin(),
1878 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1879 if (strcmp(Name, I->getName()) == 0) {
1880 GCMetadataPrinter *GMP = I->instantiate();
1882 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1886 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1887 llvm_unreachable(0);
1890 /// EmitComments - Pretty-print comments for instructions
1891 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1895 bool Newline = false;
1897 if (!MI.getDebugLoc().isUnknown()) {
1898 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1900 // Print source line info.
1901 O.PadToColumn(MAI->getCommentColumn());
1902 O << MAI->getCommentString() << ' ';
1903 DIScope Scope = DLT.getScope();
1904 // Omit the directory, because it's likely to be long and uninteresting.
1905 if (!Scope.isNull())
1906 O << Scope.getFilename();
1909 O << ':' << DLT.getLineNumber();
1910 if (DLT.getColumnNumber() != 0)
1911 O << ':' << DLT.getColumnNumber();
1915 // Check for spills and reloads
1918 const MachineFrameInfo *FrameInfo =
1919 MI.getParent()->getParent()->getFrameInfo();
1921 // We assume a single instruction only has a spill or reload, not
1923 const MachineMemOperand *MMO;
1924 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1925 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1926 MMO = *MI.memoperands_begin();
1927 if (Newline) O << '\n';
1928 O.PadToColumn(MAI->getCommentColumn());
1929 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1933 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1934 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1935 if (Newline) O << '\n';
1936 O.PadToColumn(MAI->getCommentColumn());
1937 O << MAI->getCommentString() << ' '
1938 << MMO->getSize() << "-byte Folded Reload";
1942 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1943 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1944 MMO = *MI.memoperands_begin();
1945 if (Newline) O << '\n';
1946 O.PadToColumn(MAI->getCommentColumn());
1947 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1951 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1952 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1953 if (Newline) O << '\n';
1954 O.PadToColumn(MAI->getCommentColumn());
1955 O << MAI->getCommentString() << ' '
1956 << MMO->getSize() << "-byte Folded Spill";
1961 // Check for spill-induced copies
1962 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1963 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1964 SrcSubIdx, DstSubIdx)) {
1965 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1966 if (Newline) O << '\n';
1967 O.PadToColumn(MAI->getCommentColumn());
1968 O << MAI->getCommentString() << " Reload Reuse";
1973 /// PrintChildLoopComment - Print comments about child loops within
1974 /// the loop for this basic block, with nesting.
1976 static void PrintChildLoopComment(formatted_raw_ostream &O,
1977 const MachineLoop *loop,
1978 const MCAsmInfo *MAI,
1979 int FunctionNumber) {
1980 // Add child loop information
1981 for(MachineLoop::iterator cl = loop->begin(),
1982 clend = loop->end();
1985 MachineBasicBlock *Header = (*cl)->getHeader();
1986 assert(Header && "No header for loop");
1989 O.PadToColumn(MAI->getCommentColumn());
1991 O << MAI->getCommentString();
1992 O.indent(((*cl)->getLoopDepth()-1)*2)
1993 << " Child Loop BB" << FunctionNumber << "_"
1994 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1996 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2000 /// EmitComments - Pretty-print comments for basic blocks
2001 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2003 // Add loop depth information
2004 const MachineLoop *loop = LI->getLoopFor(&MBB);
2007 // Print a newline after bb# annotation.
2009 O.PadToColumn(MAI->getCommentColumn());
2010 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2013 O.PadToColumn(MAI->getCommentColumn());
2015 MachineBasicBlock *Header = loop->getHeader();
2016 assert(Header && "No header for loop");
2018 if (Header == &MBB) {
2019 O << MAI->getCommentString() << " Loop Header";
2020 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2023 O << MAI->getCommentString() << " Loop Header is BB"
2024 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2027 if (loop->empty()) {
2029 O.PadToColumn(MAI->getCommentColumn());
2030 O << MAI->getCommentString() << " Inner Loop";
2033 // Add parent loop information
2034 for (const MachineLoop *CurLoop = loop->getParentLoop();
2036 CurLoop = CurLoop->getParentLoop()) {
2037 MachineBasicBlock *Header = CurLoop->getHeader();
2038 assert(Header && "No header for loop");
2041 O.PadToColumn(MAI->getCommentColumn());
2042 O << MAI->getCommentString();
2043 O.indent((CurLoop->getLoopDepth()-1)*2)
2044 << " Inside Loop BB" << getFunctionNumber() << "_"
2045 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();