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 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
148 printVisibility(GVSym, GV->getVisibility());
150 if (MAI->hasDotTypeDotSizeDirective()) {
151 O << "\t.type\t" << *GVSym;
152 if (MAI->getCommentString()[0] != '@')
158 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
160 const TargetData *TD = TM.getTargetData();
161 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
162 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
164 // Handle common and BSS local symbols (.lcomm).
165 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
166 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
169 O.PadToColumn(MAI->getCommentColumn());
170 O << MAI->getCommentString() << ' ';
171 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
175 // Handle common symbols.
176 if (GVKind.isCommon()) {
178 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
182 // Handle local BSS symbols.
183 if (MAI->hasMachoZeroFillDirective()) {
184 const MCSection *TheSection =
185 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
186 // .zerofill __DATA, __bss, _foo, 400, 5
187 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
191 if (const char *LComm = MAI->getLCOMMDirective()) {
193 O << LComm << *GVSym << ',' << Size;
199 O << "\t.local\t" << *GVSym << '\n';
201 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
205 const MCSection *TheSection =
206 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
208 // Handle the zerofill directive on darwin, which is a special form of BSS
210 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
212 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
213 // .zerofill __DATA, __common, _foo, 400, 5
214 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
218 OutStreamer.SwitchSection(TheSection);
220 // TODO: Factor into an 'emit linkage' thing that is shared with function
222 switch (GV->getLinkage()) {
223 case GlobalValue::CommonLinkage:
224 case GlobalValue::LinkOnceAnyLinkage:
225 case GlobalValue::LinkOnceODRLinkage:
226 case GlobalValue::WeakAnyLinkage:
227 case GlobalValue::WeakODRLinkage:
228 case GlobalValue::LinkerPrivateLinkage:
229 if (MAI->getWeakDefDirective() != 0) {
231 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
232 // .weak_definition _foo
233 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
234 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
236 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
237 // .linkonce same_size
241 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
244 case GlobalValue::DLLExportLinkage:
245 case GlobalValue::AppendingLinkage:
246 // FIXME: appending linkage variables should go into a section of
247 // their name or something. For now, just emit them as external.
248 case GlobalValue::ExternalLinkage:
249 // If external or appending, declare as a global symbol.
251 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
253 case GlobalValue::PrivateLinkage:
254 case GlobalValue::InternalLinkage:
257 llvm_unreachable("Unknown linkage type!");
260 EmitAlignment(AlignLog, GV);
262 O.PadToColumn(MAI->getCommentColumn());
263 O << MAI->getCommentString() << ' ';
264 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
267 OutStreamer.EmitLabel(GVSym);
269 EmitGlobalConstant(GV->getInitializer());
271 if (MAI->hasDotTypeDotSizeDirective())
272 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
276 bool AsmPrinter::doFinalization(Module &M) {
277 // Emit global variables.
278 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
280 EmitGlobalVariable(I);
282 // Emit final debug information.
283 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
286 // If the target wants to know about weak references, print them all.
287 if (MAI->getWeakRefDirective()) {
288 // FIXME: This is not lazy, it would be nice to only print weak references
289 // to stuff that is actually used. Note that doing so would require targets
290 // to notice uses in operands (due to constant exprs etc). This should
291 // happen with the MC stuff eventually.
293 // Print out module-level global variables here.
294 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
296 if (!I->hasExternalWeakLinkage()) continue;
297 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
300 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
301 if (!I->hasExternalWeakLinkage()) continue;
302 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
306 if (MAI->getSetDirective()) {
308 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
310 MCSymbol *Name = GetGlobalValueSymbol(I);
312 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
313 MCSymbol *Target = GetGlobalValueSymbol(GV);
315 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
316 O << "\t.globl\t" << *Name << '\n';
317 else if (I->hasWeakLinkage())
318 O << MAI->getWeakRefDirective() << *Name << '\n';
320 assert(I->hasLocalLinkage() && "Invalid alias linkage");
322 printVisibility(Name, I->getVisibility());
324 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
328 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
329 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
330 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
331 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
332 MP->finishAssembly(O, *this, *MAI);
334 // If we don't have any trampolines, then we don't require stack memory
335 // to be executable. Some targets have a directive to declare this.
336 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
337 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
338 if (MAI->getNonexecutableStackDirective())
339 O << MAI->getNonexecutableStackDirective() << '\n';
342 // Allow the target to emit any magic that it wants at the end of the file,
343 // after everything else has gone out.
346 delete Mang; Mang = 0;
349 OutStreamer.Finish();
353 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
354 // Get the function symbol.
355 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
356 IncrementFunctionNumber();
359 LI = &getAnalysis<MachineLoopInfo>();
363 // SectionCPs - Keep track the alignment, constpool entries per Section.
367 SmallVector<unsigned, 4> CPEs;
368 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
372 /// EmitConstantPool - Print to the current output stream assembly
373 /// representations of the constants in the constant pool MCP. This is
374 /// used to print out constants which have been "spilled to memory" by
375 /// the code generator.
377 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
378 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
379 if (CP.empty()) return;
381 // Calculate sections for constant pool entries. We collect entries to go into
382 // the same section together to reduce amount of section switch statements.
383 SmallVector<SectionCPs, 4> CPSections;
384 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385 const MachineConstantPoolEntry &CPE = CP[i];
386 unsigned Align = CPE.getAlignment();
389 switch (CPE.getRelocationInfo()) {
390 default: llvm_unreachable("Unknown section kind");
391 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
393 Kind = SectionKind::getReadOnlyWithRelLocal();
396 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
397 case 4: Kind = SectionKind::getMergeableConst4(); break;
398 case 8: Kind = SectionKind::getMergeableConst8(); break;
399 case 16: Kind = SectionKind::getMergeableConst16();break;
400 default: Kind = SectionKind::getMergeableConst(); break;
404 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
406 // The number of sections are small, just do a linear search from the
407 // last section to the first.
409 unsigned SecIdx = CPSections.size();
410 while (SecIdx != 0) {
411 if (CPSections[--SecIdx].S == S) {
417 SecIdx = CPSections.size();
418 CPSections.push_back(SectionCPs(S, Align));
421 if (Align > CPSections[SecIdx].Alignment)
422 CPSections[SecIdx].Alignment = Align;
423 CPSections[SecIdx].CPEs.push_back(i);
426 // Now print stuff into the calculated sections.
427 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
428 OutStreamer.SwitchSection(CPSections[i].S);
429 EmitAlignment(Log2_32(CPSections[i].Alignment));
432 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
433 unsigned CPI = CPSections[i].CPEs[j];
434 MachineConstantPoolEntry CPE = CP[CPI];
436 // Emit inter-object padding for alignment.
437 unsigned AlignMask = CPE.getAlignment() - 1;
438 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
439 OutStreamer.EmitFill(NewOffset - Offset);
441 const Type *Ty = CPE.getType();
442 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
444 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
447 O.PadToColumn(MAI->getCommentColumn());
448 O << MAI->getCommentString() << " constant ";
449 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
452 if (CPE.isMachineConstantPoolEntry())
453 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
455 EmitGlobalConstant(CPE.Val.ConstVal);
460 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
461 /// by the current function to the current output stream.
463 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
464 MachineFunction &MF) {
465 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
466 if (JT.empty()) return;
468 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
470 // Pick the directive to use to print the jump table entries, and switch to
471 // the appropriate section.
472 TargetLowering *LoweringInfo = TM.getTargetLowering();
474 const Function *F = MF.getFunction();
475 bool JTInDiffSection = false;
476 if (F->isWeakForLinker() ||
477 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
478 // In PIC mode, we need to emit the jump table to the same section as the
479 // function body itself, otherwise the label differences won't make sense.
480 // We should also do if the section name is NULL or function is declared in
481 // discardable section.
482 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
485 // Otherwise, drop it in the readonly section.
486 const MCSection *ReadOnlySection =
487 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
488 OutStreamer.SwitchSection(ReadOnlySection);
489 JTInDiffSection = true;
492 EmitAlignment(Log2_32(MJTI->getAlignment()));
494 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
495 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
497 // If this jump table was deleted, ignore it.
498 if (JTBBs.empty()) continue;
500 // For PIC codegen, if possible we want to use the SetDirective to reduce
501 // the number of relocations the assembler will generate for the jump table.
502 // Set directives are all printed before the jump table itself.
503 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
504 if (MAI->getSetDirective() && IsPic)
505 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
506 if (EmittedSets.insert(JTBBs[ii]))
507 printPICJumpTableSetLabel(i, JTBBs[ii]);
509 // On some targets (e.g. Darwin) we want to emit two consequtive labels
510 // before each jump table. The first label is never referenced, but tells
511 // the assembler and linker the extents of the jump table object. The
512 // second label is actually referenced by the code.
513 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
514 O << MAI->getLinkerPrivateGlobalPrefix()
515 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
518 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
519 << '_' << i << ":\n";
521 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
522 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
528 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
529 const MachineBasicBlock *MBB,
530 unsigned uid) const {
531 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
533 // Use JumpTableDirective otherwise honor the entry size from the jump table
535 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
536 bool HadJTEntryDirective = JTEntryDirective != NULL;
537 if (!HadJTEntryDirective) {
538 JTEntryDirective = MJTI->getEntrySize() == 4 ?
539 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
542 O << JTEntryDirective << ' ';
544 // If we have emitted set directives for the jump table entries, print
545 // them rather than the entries themselves. If we're emitting PIC, then
546 // emit the table entries as differences between two text section labels.
547 // If we're emitting non-PIC code, then emit the entries as direct
548 // references to the target basic blocks.
550 O << *GetMBBSymbol(MBB->getNumber());
551 } else if (MAI->getSetDirective()) {
552 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
553 << '_' << uid << "_set_" << MBB->getNumber();
555 O << *GetMBBSymbol(MBB->getNumber());
556 // If the arch uses custom Jump Table directives, don't calc relative to
558 if (!HadJTEntryDirective)
559 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
560 << getFunctionNumber() << '_' << uid;
565 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
566 /// special global used by LLVM. If so, emit it and return true, otherwise
567 /// do nothing and return false.
568 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
569 if (GV->getName() == "llvm.used") {
570 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
571 EmitLLVMUsedList(GV->getInitializer());
575 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
576 if (GV->getSection() == "llvm.metadata" ||
577 GV->hasAvailableExternallyLinkage())
580 if (!GV->hasAppendingLinkage()) return false;
582 assert(GV->hasInitializer() && "Not a special LLVM global!");
584 const TargetData *TD = TM.getTargetData();
585 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
586 if (GV->getName() == "llvm.global_ctors") {
587 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
588 EmitAlignment(Align, 0);
589 EmitXXStructorList(GV->getInitializer());
591 if (TM.getRelocationModel() == Reloc::Static &&
592 MAI->hasStaticCtorDtorReferenceInStaticMode())
593 O << ".reference .constructors_used\n";
597 if (GV->getName() == "llvm.global_dtors") {
598 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
599 EmitAlignment(Align, 0);
600 EmitXXStructorList(GV->getInitializer());
602 if (TM.getRelocationModel() == Reloc::Static &&
603 MAI->hasStaticCtorDtorReferenceInStaticMode())
604 O << ".reference .destructors_used\n";
611 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
612 /// global in the specified llvm.used list for which emitUsedDirectiveFor
613 /// is true, as being used with this directive.
614 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
615 const char *Directive = MAI->getUsedDirective();
617 // Should be an array of 'i8*'.
618 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
619 if (InitList == 0) return;
621 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
622 const GlobalValue *GV =
623 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
624 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
626 EmitConstantValueOnly(InitList->getOperand(i));
632 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
633 /// function pointers, ignoring the init priority.
634 void AsmPrinter::EmitXXStructorList(Constant *List) {
635 // Should be an array of '{ int, void ()* }' structs. The first value is the
636 // init priority, which we ignore.
637 if (!isa<ConstantArray>(List)) return;
638 ConstantArray *InitList = cast<ConstantArray>(List);
639 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
640 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
641 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
643 if (CS->getOperand(1)->isNullValue())
644 return; // Found a null terminator, exit printing.
645 // Emit the function pointer.
646 EmitGlobalConstant(CS->getOperand(1));
651 //===----------------------------------------------------------------------===//
652 /// LEB 128 number encoding.
654 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
655 /// representing an unsigned leb128 value.
656 void AsmPrinter::PrintULEB128(unsigned Value) const {
658 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
660 if (Value) Byte |= 0x80;
662 if (Value) O << ", ";
666 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
667 /// representing a signed leb128 value.
668 void AsmPrinter::PrintSLEB128(int Value) const {
669 int Sign = Value >> (8 * sizeof(Value) - 1);
673 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
675 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
676 if (IsMore) Byte |= 0x80;
678 if (IsMore) O << ", ";
682 //===--------------------------------------------------------------------===//
683 // Emission and print routines
686 /// PrintHex - Print a value as a hexadecimal value.
688 void AsmPrinter::PrintHex(uint64_t Value) const {
693 /// EOL - Print a newline character to asm stream. If a comment is present
694 /// then it will be printed first. Comments should not contain '\n'.
695 void AsmPrinter::EOL() const {
699 void AsmPrinter::EOL(const Twine &Comment) const {
700 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
701 O.PadToColumn(MAI->getCommentColumn());
702 O << MAI->getCommentString()
709 static const char *DecodeDWARFEncoding(unsigned Encoding) {
711 case dwarf::DW_EH_PE_absptr:
713 case dwarf::DW_EH_PE_omit:
715 case dwarf::DW_EH_PE_pcrel:
717 case dwarf::DW_EH_PE_udata4:
719 case dwarf::DW_EH_PE_udata8:
721 case dwarf::DW_EH_PE_sdata4:
723 case dwarf::DW_EH_PE_sdata8:
725 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
726 return "pcrel udata4";
727 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
728 return "pcrel sdata4";
729 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
730 return "pcrel udata8";
731 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
732 return "pcrel sdata8";
733 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
734 return "indirect pcrel udata4";
735 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
736 return "indirect pcrel sdata4";
737 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
738 return "indirect pcrel udata8";
739 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
740 return "indirect pcrel sdata8";
746 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
747 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
748 O.PadToColumn(MAI->getCommentColumn());
749 O << MAI->getCommentString()
753 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
754 O << " (" << EncStr << ')';
759 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
760 /// unsigned leb128 value.
761 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
762 if (MAI->hasLEB128()) {
766 O << MAI->getData8bitsDirective();
771 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
772 /// signed leb128 value.
773 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
774 if (MAI->hasLEB128()) {
778 O << MAI->getData8bitsDirective();
783 /// EmitInt8 - Emit a byte directive and value.
785 void AsmPrinter::EmitInt8(int Value) const {
786 O << MAI->getData8bitsDirective();
787 PrintHex(Value & 0xFF);
790 /// EmitInt16 - Emit a short directive and value.
792 void AsmPrinter::EmitInt16(int Value) const {
793 O << MAI->getData16bitsDirective();
794 PrintHex(Value & 0xFFFF);
797 /// EmitInt32 - Emit a long directive and value.
799 void AsmPrinter::EmitInt32(int Value) const {
800 O << MAI->getData32bitsDirective();
804 /// EmitInt64 - Emit a long long directive and value.
806 void AsmPrinter::EmitInt64(uint64_t Value) const {
807 if (MAI->getData64bitsDirective()) {
808 O << MAI->getData64bitsDirective();
811 if (TM.getTargetData()->isBigEndian()) {
812 EmitInt32(unsigned(Value >> 32)); O << '\n';
813 EmitInt32(unsigned(Value));
815 EmitInt32(unsigned(Value)); O << '\n';
816 EmitInt32(unsigned(Value >> 32));
821 /// toOctal - Convert the low order bits of X into an octal digit.
823 static inline char toOctal(int X) {
827 /// printStringChar - Print a char, escaped if necessary.
829 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
832 } else if (C == '\\') {
834 } else if (isprint((unsigned char)C)) {
838 case '\b': O << "\\b"; break;
839 case '\f': O << "\\f"; break;
840 case '\n': O << "\\n"; break;
841 case '\r': O << "\\r"; break;
842 case '\t': O << "\\t"; break;
845 O << toOctal(C >> 6);
846 O << toOctal(C >> 3);
847 O << toOctal(C >> 0);
853 /// EmitString - Emit a string with quotes and a null terminator.
854 /// Special characters are emitted properly.
855 /// \literal (Eg. '\t') \endliteral
856 void AsmPrinter::EmitString(const StringRef String) const {
857 EmitString(String.data(), String.size());
860 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
861 const char* AscizDirective = MAI->getAscizDirective();
865 O << MAI->getAsciiDirective();
867 for (unsigned i = 0; i < Size; ++i)
868 printStringChar(O, String[i]);
876 /// EmitFile - Emit a .file directive.
877 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
878 O << "\t.file\t" << Number << " \"";
879 for (unsigned i = 0, N = Name.size(); i < N; ++i)
880 printStringChar(O, Name[i]);
885 //===----------------------------------------------------------------------===//
887 // EmitAlignment - Emit an alignment directive to the specified power of
888 // two boundary. For example, if you pass in 3 here, you will get an 8
889 // byte alignment. If a global value is specified, and if that global has
890 // an explicit alignment requested, it will unconditionally override the
891 // alignment request. However, if ForcedAlignBits is specified, this value
892 // has final say: the ultimate alignment will be the max of ForcedAlignBits
893 // and the alignment computed with NumBits and the global.
897 // if (GV && GV->hasalignment) Align = GV->getalignment();
898 // Align = std::max(Align, ForcedAlignBits);
900 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
901 unsigned ForcedAlignBits,
902 bool UseFillExpr) const {
903 if (GV && GV->getAlignment())
904 NumBits = Log2_32(GV->getAlignment());
905 NumBits = std::max(NumBits, ForcedAlignBits);
907 if (NumBits == 0) return; // No need to emit alignment.
909 unsigned FillValue = 0;
910 if (getCurrentSection()->getKind().isText())
911 FillValue = MAI->getTextAlignFillValue();
913 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
916 /// EmitZeros - Emit a block of zeros.
918 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
919 if (NumZeros == 0) return;
920 if (MAI->getZeroDirective() || AddrSpace == 0) {
921 OutStreamer.EmitFill(NumZeros);
923 for (; NumZeros; --NumZeros)
924 O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
928 // Print out the specified constant, without a storage class. Only the
929 // constants valid in constant expressions can occur here.
930 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
931 if (CV->isNullValue() || isa<UndefValue>(CV)) {
936 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
937 O << CI->getZExtValue();
941 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
942 // This is a constant address for a global variable or function. Use the
943 // name of the variable or function as the address value.
944 O << *GetGlobalValueSymbol(GV);
948 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
949 O << *GetBlockAddressSymbol(BA);
953 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
955 llvm_unreachable("Unknown constant value!");
960 switch (CE->getOpcode()) {
961 case Instruction::ZExt:
962 case Instruction::SExt:
963 case Instruction::FPTrunc:
964 case Instruction::FPExt:
965 case Instruction::UIToFP:
966 case Instruction::SIToFP:
967 case Instruction::FPToUI:
968 case Instruction::FPToSI:
970 llvm_unreachable("FIXME: Don't support this constant cast expr");
971 case Instruction::GetElementPtr: {
972 // generate a symbolic expression for the byte address
973 const TargetData *TD = TM.getTargetData();
974 const Constant *ptrVal = CE->getOperand(0);
975 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
976 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
979 return EmitConstantValueOnly(ptrVal);
981 // Truncate/sext the offset to the pointer size.
982 if (TD->getPointerSizeInBits() != 64) {
983 int SExtAmount = 64-TD->getPointerSizeInBits();
984 Offset = (Offset << SExtAmount) >> SExtAmount;
989 EmitConstantValueOnly(ptrVal);
991 O << ") + " << Offset;
993 O << ") - " << -Offset;
996 case Instruction::BitCast:
997 return EmitConstantValueOnly(CE->getOperand(0));
999 case Instruction::IntToPtr: {
1000 // Handle casts to pointers by changing them into casts to the appropriate
1001 // integer type. This promotes constant folding and simplifies this code.
1002 const TargetData *TD = TM.getTargetData();
1003 Constant *Op = CE->getOperand(0);
1004 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
1006 return EmitConstantValueOnly(Op);
1009 case Instruction::PtrToInt: {
1010 // Support only foldable casts to/from pointers that can be eliminated by
1011 // changing the pointer to the appropriately sized integer type.
1012 Constant *Op = CE->getOperand(0);
1013 const Type *Ty = CE->getType();
1014 const TargetData *TD = TM.getTargetData();
1016 // We can emit the pointer value into this slot if the slot is an
1017 // integer slot greater or equal to the size of the pointer.
1018 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
1019 return EmitConstantValueOnly(Op);
1022 EmitConstantValueOnly(Op);
1024 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
1027 ptrMask.toStringUnsigned(S);
1028 O << ") & " << S.str() << ')';
1032 case Instruction::Trunc:
1033 // We emit the value and depend on the assembler to truncate the generated
1034 // expression properly. This is important for differences between
1035 // blockaddress labels. Since the two labels are in the same function, it
1036 // is reasonable to treat their delta as a 32-bit value.
1037 return EmitConstantValueOnly(CE->getOperand(0));
1039 case Instruction::Add:
1040 case Instruction::Sub:
1041 case Instruction::And:
1042 case Instruction::Or:
1043 case Instruction::Xor:
1045 EmitConstantValueOnly(CE->getOperand(0));
1047 switch (CE->getOpcode()) {
1048 case Instruction::Add:
1051 case Instruction::Sub:
1054 case Instruction::And:
1057 case Instruction::Or:
1060 case Instruction::Xor:
1067 EmitConstantValueOnly(CE->getOperand(1));
1073 /// printAsCString - Print the specified array as a C compatible string, only if
1074 /// the predicate isString is true.
1076 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1078 assert(CVA->isString() && "Array is not string compatible!");
1081 for (unsigned i = 0; i != LastElt; ++i) {
1083 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1084 printStringChar(O, C);
1089 /// EmitString - Emit a zero-byte-terminated string constant.
1091 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1092 unsigned NumElts = CVA->getNumOperands();
1093 if (MAI->getAscizDirective() && NumElts &&
1094 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1095 O << MAI->getAscizDirective();
1096 printAsCString(O, CVA, NumElts-1);
1098 O << MAI->getAsciiDirective();
1099 printAsCString(O, CVA, NumElts);
1104 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1106 if (AddrSpace == 0 && CA->isString()) {
1108 } else { // Not a string. Print the values in successive locations
1109 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1110 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1114 static void EmitGlobalConstantVector(const ConstantVector *CV,
1115 unsigned AddrSpace, AsmPrinter &AP) {
1116 const VectorType *VTy = CV->getType();
1117 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
1118 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1121 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1122 unsigned AddrSpace, AsmPrinter &AP) {
1123 // Print the fields in successive locations. Pad to align if needed!
1124 const TargetData *TD = AP.TM.getTargetData();
1125 unsigned Size = TD->getTypeAllocSize(CS->getType());
1126 const StructLayout *cvsLayout = TD->getStructLayout(CS->getType());
1127 uint64_t SizeSoFar = 0;
1128 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1129 const Constant *field = CS->getOperand(i);
1131 // Check if padding is needed and insert one or more 0s.
1132 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1133 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1134 - cvsLayout->getElementOffset(i)) - fieldSize;
1135 SizeSoFar += fieldSize + padSize;
1137 // Now print the actual field value.
1138 AP.EmitGlobalConstant(field, AddrSpace);
1140 // Insert padding - this may include padding to increase the size of the
1141 // current field up to the ABI size (if the struct is not packed) as well
1142 // as padding to ensure that the next field starts at the right offset.
1143 AP.EmitZeros(padSize, AddrSpace);
1145 assert(SizeSoFar == cvsLayout->getSizeInBytes() &&
1146 "Layout of constant struct may be incorrect!");
1149 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1150 unsigned AddrSpace) {
1151 // FP Constants are printed as integer constants to avoid losing
1153 const TargetData &TD = *TM.getTargetData();
1154 if (CFP->getType()->isDoubleTy()) {
1155 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1156 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1157 if (MAI->getData64bitsDirective(AddrSpace)) {
1158 O << MAI->getData64bitsDirective(AddrSpace) << i;
1160 O.PadToColumn(MAI->getCommentColumn());
1161 O << MAI->getCommentString() << " double " << Val;
1164 } else if (TD.isBigEndian()) {
1165 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1167 O.PadToColumn(MAI->getCommentColumn());
1168 O << MAI->getCommentString()
1169 << " most significant word of double " << Val;
1172 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1174 O.PadToColumn(MAI->getCommentColumn());
1175 O << MAI->getCommentString()
1176 << " least significant word of double " << Val;
1180 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1182 O.PadToColumn(MAI->getCommentColumn());
1183 O << MAI->getCommentString()
1184 << " least significant word of double " << Val;
1187 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1189 O.PadToColumn(MAI->getCommentColumn());
1190 O << MAI->getCommentString()
1191 << " most significant word of double " << Val;
1198 if (CFP->getType()->isFloatTy()) {
1199 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1200 O << MAI->getData32bitsDirective(AddrSpace)
1201 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1203 O.PadToColumn(MAI->getCommentColumn());
1204 O << MAI->getCommentString() << " float " << Val;
1210 if (CFP->getType()->isX86_FP80Ty()) {
1211 // all long double variants are printed as hex
1212 // api needed to prevent premature destruction
1213 APInt api = CFP->getValueAPF().bitcastToAPInt();
1214 const uint64_t *p = api.getRawData();
1215 // Convert to double so we can print the approximate val as a comment.
1216 APFloat DoubleVal = CFP->getValueAPF();
1218 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1220 if (TD.isBigEndian()) {
1221 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1223 O.PadToColumn(MAI->getCommentColumn());
1224 O << MAI->getCommentString()
1225 << " most significant halfword of x86_fp80 ~"
1226 << DoubleVal.convertToDouble();
1229 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1231 O.PadToColumn(MAI->getCommentColumn());
1232 O << MAI->getCommentString() << " next halfword";
1235 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1237 O.PadToColumn(MAI->getCommentColumn());
1238 O << MAI->getCommentString() << " next halfword";
1241 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1243 O.PadToColumn(MAI->getCommentColumn());
1244 O << MAI->getCommentString() << " next halfword";
1247 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1249 O.PadToColumn(MAI->getCommentColumn());
1250 O << MAI->getCommentString()
1251 << " least significant halfword";
1255 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1257 O.PadToColumn(MAI->getCommentColumn());
1258 O << MAI->getCommentString()
1259 << " least significant halfword of x86_fp80 ~"
1260 << DoubleVal.convertToDouble();
1263 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1265 O.PadToColumn(MAI->getCommentColumn());
1266 O << MAI->getCommentString()
1267 << " next halfword";
1270 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1272 O.PadToColumn(MAI->getCommentColumn());
1273 O << MAI->getCommentString()
1274 << " next halfword";
1277 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1279 O.PadToColumn(MAI->getCommentColumn());
1280 O << MAI->getCommentString()
1281 << " next halfword";
1284 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1286 O.PadToColumn(MAI->getCommentColumn());
1287 O << MAI->getCommentString()
1288 << " most significant halfword";
1292 LLVMContext &Context = CFP->getContext();
1293 EmitZeros(TD.getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1294 TD.getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1298 if (CFP->getType()->isPPC_FP128Ty()) {
1299 // all long double variants are printed as hex
1300 // api needed to prevent premature destruction
1301 APInt api = CFP->getValueAPF().bitcastToAPInt();
1302 const uint64_t *p = api.getRawData();
1303 if (TD.isBigEndian()) {
1304 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1306 O.PadToColumn(MAI->getCommentColumn());
1307 O << MAI->getCommentString()
1308 << " most significant word of ppc_fp128";
1311 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1313 O.PadToColumn(MAI->getCommentColumn());
1314 O << MAI->getCommentString()
1318 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1320 O.PadToColumn(MAI->getCommentColumn());
1321 O << MAI->getCommentString()
1325 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1327 O.PadToColumn(MAI->getCommentColumn());
1328 O << MAI->getCommentString()
1329 << " least significant word";
1333 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1335 O.PadToColumn(MAI->getCommentColumn());
1336 O << MAI->getCommentString()
1337 << " least significant word of ppc_fp128";
1340 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1342 O.PadToColumn(MAI->getCommentColumn());
1343 O << MAI->getCommentString()
1347 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1349 O.PadToColumn(MAI->getCommentColumn());
1350 O << MAI->getCommentString()
1354 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1356 O.PadToColumn(MAI->getCommentColumn());
1357 O << MAI->getCommentString()
1358 << " most significant word";
1363 } else llvm_unreachable("Floating point constant type not handled");
1366 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1367 unsigned AddrSpace) {
1368 const TargetData *TD = TM.getTargetData();
1369 unsigned BitWidth = CI->getBitWidth();
1370 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1372 // We don't expect assemblers to support integer data directives
1373 // for more than 64 bits, so we emit the data in at most 64-bit
1374 // quantities at a time.
1375 const uint64_t *RawData = CI->getValue().getRawData();
1376 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1378 if (TD->isBigEndian())
1379 Val = RawData[e - i - 1];
1383 if (MAI->getData64bitsDirective(AddrSpace)) {
1384 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1388 // Emit two 32-bit chunks, order depends on endianness.
1389 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
1390 const char *FirstName = " least", *SecondName = " most";
1391 if (TD->isBigEndian()) {
1392 std::swap(FirstChunk, SecondChunk);
1393 std::swap(FirstName, SecondName);
1396 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
1398 O.PadToColumn(MAI->getCommentColumn());
1399 O << MAI->getCommentString()
1400 << FirstName << " significant half of i64 " << Val;
1404 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
1406 O.PadToColumn(MAI->getCommentColumn());
1407 O << MAI->getCommentString()
1408 << SecondName << " significant half of i64 " << Val;
1414 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1415 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1416 const TargetData *TD = TM.getTargetData();
1417 const Type *type = CV->getType();
1418 unsigned Size = TD->getTypeAllocSize(type);
1420 if (CV->isNullValue() || isa<UndefValue>(CV))
1421 return EmitZeros(Size, AddrSpace);
1423 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1424 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1426 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1427 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1429 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1430 return EmitGlobalConstantFP(CFP, AddrSpace);
1432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1433 // If we can directly emit an 8-byte constant, do it.
1435 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
1436 O << Data64Dir << CI->getZExtValue() << '\n';
1440 // Small integers are handled below; large integers are handled here.
1442 EmitGlobalConstantLargeInt(CI, AddrSpace);
1447 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1448 return EmitGlobalConstantVector(V, AddrSpace, *this);
1450 printDataDirective(type, AddrSpace);
1451 EmitConstantValueOnly(CV);
1453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1455 CI->getValue().toStringUnsigned(S, 16);
1456 O.PadToColumn(MAI->getCommentColumn());
1457 O << MAI->getCommentString() << " 0x" << S.str();
1463 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1464 // Target doesn't support this yet!
1465 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1468 /// PrintSpecial - Print information related to the specified machine instr
1469 /// that is independent of the operand, and may be independent of the instr
1470 /// itself. This can be useful for portably encoding the comment character
1471 /// or other bits of target-specific knowledge into the asmstrings. The
1472 /// syntax used is ${:comment}. Targets can override this to add support
1473 /// for their own strange codes.
1474 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1475 if (!strcmp(Code, "private")) {
1476 O << MAI->getPrivateGlobalPrefix();
1477 } else if (!strcmp(Code, "comment")) {
1479 O << MAI->getCommentString();
1480 } else if (!strcmp(Code, "uid")) {
1481 // Comparing the address of MI isn't sufficient, because machineinstrs may
1482 // be allocated to the same address across functions.
1483 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1485 // If this is a new LastFn instruction, bump the counter.
1486 if (LastMI != MI || LastFn != ThisF) {
1494 raw_string_ostream Msg(msg);
1495 Msg << "Unknown special formatter '" << Code
1496 << "' for machine instr: " << *MI;
1497 llvm_report_error(Msg.str());
1501 /// processDebugLoc - Processes the debug information of each machine
1502 /// instruction's DebugLoc.
1503 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1504 bool BeforePrintingInsn) {
1505 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1506 || !DW->ShouldEmitDwarfDebug())
1508 DebugLoc DL = MI->getDebugLoc();
1511 DILocation CurDLT = MF->getDILocation(DL);
1512 if (CurDLT.getScope().isNull())
1515 if (BeforePrintingInsn) {
1516 if (CurDLT.getNode() != PrevDLT) {
1517 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1518 CurDLT.getColumnNumber(),
1519 CurDLT.getScope().getNode());
1522 DW->BeginScope(MI, L);
1523 PrevDLT = CurDLT.getNode();
1526 // After printing instruction
1532 /// printInlineAsm - This method formats and prints the specified machine
1533 /// instruction that is an inline asm.
1534 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1535 unsigned NumOperands = MI->getNumOperands();
1537 // Count the number of register definitions.
1538 unsigned NumDefs = 0;
1539 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1541 assert(NumDefs != NumOperands-1 && "No asm string?");
1543 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1545 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1546 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1550 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1551 // These are useful to see where empty asm's wound up.
1552 if (AsmStr[0] == 0) {
1553 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1554 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1558 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1560 // The variant of the current asmprinter.
1561 int AsmPrinterVariant = MAI->getAssemblerDialect();
1563 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1564 const char *LastEmitted = AsmStr; // One past the last character emitted.
1566 while (*LastEmitted) {
1567 switch (*LastEmitted) {
1569 // Not a special case, emit the string section literally.
1570 const char *LiteralEnd = LastEmitted+1;
1571 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1572 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1574 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1575 O.write(LastEmitted, LiteralEnd-LastEmitted);
1576 LastEmitted = LiteralEnd;
1580 ++LastEmitted; // Consume newline character.
1581 O << '\n'; // Indent code with newline.
1584 ++LastEmitted; // Consume '$' character.
1588 switch (*LastEmitted) {
1589 default: Done = false; break;
1590 case '$': // $$ -> $
1591 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1593 ++LastEmitted; // Consume second '$' character.
1595 case '(': // $( -> same as GCC's { character.
1596 ++LastEmitted; // Consume '(' character.
1597 if (CurVariant != -1) {
1598 llvm_report_error("Nested variants found in inline asm string: '"
1599 + std::string(AsmStr) + "'");
1601 CurVariant = 0; // We're in the first variant now.
1604 ++LastEmitted; // consume '|' character.
1605 if (CurVariant == -1)
1606 O << '|'; // this is gcc's behavior for | outside a variant
1608 ++CurVariant; // We're in the next variant.
1610 case ')': // $) -> same as GCC's } char.
1611 ++LastEmitted; // consume ')' character.
1612 if (CurVariant == -1)
1613 O << '}'; // this is gcc's behavior for } outside a variant
1620 bool HasCurlyBraces = false;
1621 if (*LastEmitted == '{') { // ${variable}
1622 ++LastEmitted; // Consume '{' character.
1623 HasCurlyBraces = true;
1626 // If we have ${:foo}, then this is not a real operand reference, it is a
1627 // "magic" string reference, just like in .td files. Arrange to call
1629 if (HasCurlyBraces && *LastEmitted == ':') {
1631 const char *StrStart = LastEmitted;
1632 const char *StrEnd = strchr(StrStart, '}');
1634 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1635 + std::string(AsmStr) + "'");
1638 std::string Val(StrStart, StrEnd);
1639 PrintSpecial(MI, Val.c_str());
1640 LastEmitted = StrEnd+1;
1644 const char *IDStart = LastEmitted;
1647 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1648 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1649 llvm_report_error("Bad $ operand number in inline asm string: '"
1650 + std::string(AsmStr) + "'");
1652 LastEmitted = IDEnd;
1654 char Modifier[2] = { 0, 0 };
1656 if (HasCurlyBraces) {
1657 // If we have curly braces, check for a modifier character. This
1658 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1659 if (*LastEmitted == ':') {
1660 ++LastEmitted; // Consume ':' character.
1661 if (*LastEmitted == 0) {
1662 llvm_report_error("Bad ${:} expression in inline asm string: '"
1663 + std::string(AsmStr) + "'");
1666 Modifier[0] = *LastEmitted;
1667 ++LastEmitted; // Consume modifier character.
1670 if (*LastEmitted != '}') {
1671 llvm_report_error("Bad ${} expression in inline asm string: '"
1672 + std::string(AsmStr) + "'");
1674 ++LastEmitted; // Consume '}' character.
1677 if ((unsigned)Val >= NumOperands-1) {
1678 llvm_report_error("Invalid $ operand number in inline asm string: '"
1679 + std::string(AsmStr) + "'");
1682 // Okay, we finally have a value number. Ask the target to print this
1684 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1689 // Scan to find the machine operand number for the operand.
1690 for (; Val; --Val) {
1691 if (OpNo >= MI->getNumOperands()) break;
1692 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1693 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1696 if (OpNo >= MI->getNumOperands()) {
1699 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1700 ++OpNo; // Skip over the ID number.
1702 if (Modifier[0] == 'l') // labels are target independent
1703 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1705 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1706 if ((OpFlags & 7) == 4) {
1707 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1708 Modifier[0] ? Modifier : 0);
1710 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1711 Modifier[0] ? Modifier : 0);
1717 raw_string_ostream Msg(msg);
1718 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1720 llvm_report_error(Msg.str());
1727 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1730 /// printImplicitDef - This method prints the specified machine instruction
1731 /// that is an implicit def.
1732 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1733 if (!VerboseAsm) return;
1734 O.PadToColumn(MAI->getCommentColumn());
1735 O << MAI->getCommentString() << " implicit-def: "
1736 << TRI->getName(MI->getOperand(0).getReg());
1739 void AsmPrinter::printKill(const MachineInstr *MI) const {
1740 if (!VerboseAsm) return;
1741 O.PadToColumn(MAI->getCommentColumn());
1742 O << MAI->getCommentString() << " kill:";
1743 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1744 const MachineOperand &op = MI->getOperand(n);
1745 assert(op.isReg() && "KILL instruction must have only register operands");
1746 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1750 /// printLabel - This method prints a local label used by debug and
1751 /// exception handling tables.
1752 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1753 printLabel(MI->getOperand(0).getImm());
1756 void AsmPrinter::printLabel(unsigned Id) const {
1757 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1760 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1761 /// instruction, using the specified assembler variant. Targets should
1762 /// override this to format as appropriate.
1763 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1764 unsigned AsmVariant, const char *ExtraCode) {
1765 // Target doesn't support this yet!
1769 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1770 unsigned AsmVariant,
1771 const char *ExtraCode) {
1772 // Target doesn't support this yet!
1776 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1777 const char *Suffix) const {
1778 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1781 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1782 const BasicBlock *BB,
1783 const char *Suffix) const {
1784 assert(BB->hasName() &&
1785 "Address of anonymous basic block not supported yet!");
1787 // This code must use the function name itself, and not the function number,
1788 // since it must be possible to generate the label name from within other
1790 SmallString<60> FnName;
1791 Mang->getNameWithPrefix(FnName, F, false);
1793 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1794 SmallString<60> NameResult;
1795 Mang->getNameWithPrefix(NameResult,
1796 StringRef("BA") + Twine((unsigned)FnName.size()) +
1797 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1800 return OutContext.GetOrCreateSymbol(NameResult.str());
1803 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1804 SmallString<60> Name;
1805 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1806 << getFunctionNumber() << '_' << MBBID;
1808 return OutContext.GetOrCreateSymbol(Name.str());
1811 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1813 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1814 SmallString<60> NameStr;
1815 Mang->getNameWithPrefix(NameStr, GV, false);
1816 return OutContext.GetOrCreateSymbol(NameStr.str());
1819 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1820 /// global value name as its base, with the specified suffix, and where the
1821 /// symbol is forced to have private linkage if ForcePrivate is true.
1822 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1824 bool ForcePrivate) const {
1825 SmallString<60> NameStr;
1826 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1827 NameStr.append(Suffix.begin(), Suffix.end());
1828 return OutContext.GetOrCreateSymbol(NameStr.str());
1831 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1833 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1834 SmallString<60> NameStr;
1835 Mang->getNameWithPrefix(NameStr, Sym);
1836 return OutContext.GetOrCreateSymbol(NameStr.str());
1840 /// EmitBasicBlockStart - This method prints the label for the specified
1841 /// MachineBasicBlock, an alignment (if present) and a comment describing
1842 /// it if appropriate.
1843 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1844 // Emit an alignment directive for this block, if needed.
1845 if (unsigned Align = MBB->getAlignment())
1846 EmitAlignment(Log2_32(Align));
1848 // If the block has its address taken, emit a special label to satisfy
1849 // references to the block. This is done so that we don't need to
1850 // remember the number of this label, and so that we can make
1851 // forward references to labels without knowing what their numbers
1853 if (MBB->hasAddressTaken()) {
1854 O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1855 MBB->getBasicBlock());
1858 O.PadToColumn(MAI->getCommentColumn());
1859 O << MAI->getCommentString() << " Address Taken";
1864 // Print the main label for the block.
1865 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1867 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1869 O << *GetMBBSymbol(MBB->getNumber()) << ':';
1874 // Print some comments to accompany the label.
1876 if (const BasicBlock *BB = MBB->getBasicBlock())
1877 if (BB->hasName()) {
1878 O.PadToColumn(MAI->getCommentColumn());
1879 O << MAI->getCommentString() << ' ';
1880 WriteAsOperand(O, BB, /*PrintType=*/false);
1888 /// printPICJumpTableSetLabel - This method prints a set label for the
1889 /// specified MachineBasicBlock for a jumptable entry.
1890 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1891 const MachineBasicBlock *MBB) const {
1892 if (!MAI->getSetDirective())
1895 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1896 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1897 << *GetMBBSymbol(MBB->getNumber())
1898 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1899 << '_' << uid << '\n';
1902 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1903 const MachineBasicBlock *MBB) const {
1904 if (!MAI->getSetDirective())
1907 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1908 << getFunctionNumber() << '_' << uid << '_' << uid2
1909 << "_set_" << MBB->getNumber() << ','
1910 << *GetMBBSymbol(MBB->getNumber())
1911 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1912 << '_' << uid << '_' << uid2 << '\n';
1915 /// printDataDirective - This method prints the asm directive for the
1917 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1918 const TargetData *TD = TM.getTargetData();
1919 switch (type->getTypeID()) {
1920 case Type::FloatTyID: case Type::DoubleTyID:
1921 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1922 assert(0 && "Should have already output floating point constant.");
1924 assert(0 && "Can't handle printing this type of thing");
1925 case Type::IntegerTyID: {
1926 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1928 O << MAI->getData8bitsDirective(AddrSpace);
1929 else if (BitWidth <= 16)
1930 O << MAI->getData16bitsDirective(AddrSpace);
1931 else if (BitWidth <= 32)
1932 O << MAI->getData32bitsDirective(AddrSpace);
1933 else if (BitWidth <= 64) {
1934 assert(MAI->getData64bitsDirective(AddrSpace) &&
1935 "Target cannot handle 64-bit constant exprs!");
1936 O << MAI->getData64bitsDirective(AddrSpace);
1938 llvm_unreachable("Target cannot handle given data directive width!");
1942 case Type::PointerTyID:
1943 if (TD->getPointerSize() == 8) {
1944 assert(MAI->getData64bitsDirective(AddrSpace) &&
1945 "Target cannot handle 64-bit pointer exprs!");
1946 O << MAI->getData64bitsDirective(AddrSpace);
1947 } else if (TD->getPointerSize() == 2) {
1948 O << MAI->getData16bitsDirective(AddrSpace);
1949 } else if (TD->getPointerSize() == 1) {
1950 O << MAI->getData8bitsDirective(AddrSpace);
1952 O << MAI->getData32bitsDirective(AddrSpace);
1958 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1959 unsigned Visibility) const {
1960 if (Visibility == GlobalValue::HiddenVisibility) {
1961 if (const char *Directive = MAI->getHiddenDirective())
1962 O << Directive << *Sym << '\n';
1963 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1964 if (const char *Directive = MAI->getProtectedDirective())
1965 O << Directive << *Sym << '\n';
1969 void AsmPrinter::printOffset(int64_t Offset) const {
1972 else if (Offset < 0)
1976 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1977 if (!S->usesMetadata())
1980 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1981 if (GCPI != GCMetadataPrinters.end())
1982 return GCPI->second;
1984 const char *Name = S->getName().c_str();
1986 for (GCMetadataPrinterRegistry::iterator
1987 I = GCMetadataPrinterRegistry::begin(),
1988 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1989 if (strcmp(Name, I->getName()) == 0) {
1990 GCMetadataPrinter *GMP = I->instantiate();
1992 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1996 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1997 llvm_unreachable(0);
2000 /// EmitComments - Pretty-print comments for instructions
2001 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
2005 bool Newline = false;
2007 if (!MI.getDebugLoc().isUnknown()) {
2008 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
2010 // Print source line info.
2011 O.PadToColumn(MAI->getCommentColumn());
2012 O << MAI->getCommentString() << ' ';
2013 DIScope Scope = DLT.getScope();
2014 // Omit the directory, because it's likely to be long and uninteresting.
2015 if (!Scope.isNull())
2016 O << Scope.getFilename();
2019 O << ':' << DLT.getLineNumber();
2020 if (DLT.getColumnNumber() != 0)
2021 O << ':' << DLT.getColumnNumber();
2025 // Check for spills and reloads
2028 const MachineFrameInfo *FrameInfo =
2029 MI.getParent()->getParent()->getFrameInfo();
2031 // We assume a single instruction only has a spill or reload, not
2033 const MachineMemOperand *MMO;
2034 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
2035 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2036 MMO = *MI.memoperands_begin();
2037 if (Newline) O << '\n';
2038 O.PadToColumn(MAI->getCommentColumn());
2039 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
2043 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
2044 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2045 if (Newline) O << '\n';
2046 O.PadToColumn(MAI->getCommentColumn());
2047 O << MAI->getCommentString() << ' '
2048 << MMO->getSize() << "-byte Folded Reload";
2052 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
2053 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2054 MMO = *MI.memoperands_begin();
2055 if (Newline) O << '\n';
2056 O.PadToColumn(MAI->getCommentColumn());
2057 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
2061 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
2062 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
2063 if (Newline) O << '\n';
2064 O.PadToColumn(MAI->getCommentColumn());
2065 O << MAI->getCommentString() << ' '
2066 << MMO->getSize() << "-byte Folded Spill";
2071 // Check for spill-induced copies
2072 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2073 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
2074 SrcSubIdx, DstSubIdx)) {
2075 if (MI.getAsmPrinterFlag(ReloadReuse)) {
2076 if (Newline) O << '\n';
2077 O.PadToColumn(MAI->getCommentColumn());
2078 O << MAI->getCommentString() << " Reload Reuse";
2083 /// PrintChildLoopComment - Print comments about child loops within
2084 /// the loop for this basic block, with nesting.
2086 static void PrintChildLoopComment(formatted_raw_ostream &O,
2087 const MachineLoop *loop,
2088 const MCAsmInfo *MAI,
2089 int FunctionNumber) {
2090 // Add child loop information
2091 for(MachineLoop::iterator cl = loop->begin(),
2092 clend = loop->end();
2095 MachineBasicBlock *Header = (*cl)->getHeader();
2096 assert(Header && "No header for loop");
2099 O.PadToColumn(MAI->getCommentColumn());
2101 O << MAI->getCommentString();
2102 O.indent(((*cl)->getLoopDepth()-1)*2)
2103 << " Child Loop BB" << FunctionNumber << "_"
2104 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
2106 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
2110 /// EmitComments - Pretty-print comments for basic blocks
2111 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
2113 // Add loop depth information
2114 const MachineLoop *loop = LI->getLoopFor(&MBB);
2117 // Print a newline after bb# annotation.
2119 O.PadToColumn(MAI->getCommentColumn());
2120 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
2123 O.PadToColumn(MAI->getCommentColumn());
2125 MachineBasicBlock *Header = loop->getHeader();
2126 assert(Header && "No header for loop");
2128 if (Header == &MBB) {
2129 O << MAI->getCommentString() << " Loop Header";
2130 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
2133 O << MAI->getCommentString() << " Loop Header is BB"
2134 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
2137 if (loop->empty()) {
2139 O.PadToColumn(MAI->getCommentColumn());
2140 O << MAI->getCommentString() << " Inner Loop";
2143 // Add parent loop information
2144 for (const MachineLoop *CurLoop = loop->getParentLoop();
2146 CurLoop = CurLoop->getParentLoop()) {
2147 MachineBasicBlock *Header = CurLoop->getHeader();
2148 assert(Header && "No header for loop");
2151 O.PadToColumn(MAI->getCommentColumn());
2152 O << MAI->getCommentString();
2153 O.indent((CurLoop->getLoopDepth()-1)*2)
2154 << " Inside Loop BB" << getFunctionNumber() << "_"
2155 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();