mcstreamerize .no_dead_strip and .reference for static ctors/dtors.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
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/Format.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/Mangler.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallString.h"
47 #include <cerrno>
48 using namespace llvm;
49
50 static cl::opt<cl::boolOrDefault>
51 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52            cl::init(cl::BOU_UNSET));
53
54 static bool getVerboseAsm(bool VDef) {
55   switch (AsmVerbose) {
56   default:
57   case cl::BOU_UNSET: return VDef;
58   case cl::BOU_TRUE:  return true;
59   case cl::BOU_FALSE: return false;
60   }      
61 }
62
63 char AsmPrinter::ID = 0;
64 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
65                        const MCAsmInfo *T, bool VDef)
66   : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
67     TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
68
69     OutContext(*new MCContext()),
70     // FIXME: Pass instprinter to streamer.
71     OutStreamer(*createAsmStreamer(OutContext, O, *T,
72                                    TM.getTargetData()->isLittleEndian(),
73                                    getVerboseAsm(VDef), 0)),
74
75     LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
76   DW = 0; MMI = 0;
77   VerboseAsm = getVerboseAsm(VDef);
78 }
79
80 AsmPrinter::~AsmPrinter() {
81   for (gcp_iterator I = GCMetadataPrinters.begin(),
82                     E = GCMetadataPrinters.end(); I != E; ++I)
83     delete I->second;
84   
85   delete &OutStreamer;
86   delete &OutContext;
87 }
88
89 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
90   return TM.getTargetLowering()->getObjFileLowering();
91 }
92
93 /// getCurrentSection() - Return the current section we are emitting to.
94 const MCSection *AsmPrinter::getCurrentSection() const {
95   return OutStreamer.getCurrentSection();
96 }
97
98
99 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100   AU.setPreservesAll();
101   MachineFunctionPass::getAnalysisUsage(AU);
102   AU.addRequired<GCModuleInfo>();
103   if (VerboseAsm)
104     AU.addRequired<MachineLoopInfo>();
105 }
106
107 bool AsmPrinter::doInitialization(Module &M) {
108   // Initialize TargetLoweringObjectFile.
109   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
110     .Initialize(OutContext, TM);
111   
112   Mang = new Mangler(*MAI);
113   
114   // Allow the target to emit any magic that it wants at the start of the file.
115   EmitStartOfAsmFile(M);
116
117   if (MAI->hasSingleParameterDotFile()) {
118     // Very minimal debug info. It is ignored if we emit actual
119     // debug info. If we don't, this at least helps the user find where
120     // a function came from.
121     O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
122   }
123
124   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
126   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
128       MP->beginAssembly(O, *this, *MAI);
129   
130   if (!M.getModuleInlineAsm().empty())
131     O << MAI->getCommentString() << " Start of file scope inline assembly\n"
132       << M.getModuleInlineAsm()
133       << '\n' << MAI->getCommentString()
134       << " End of file scope inline assembly\n";
135
136   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137   if (MMI)
138     MMI->AnalyzeModule(M);
139   DW = getAnalysisIfAvailable<DwarfWriter>();
140   if (DW)
141     DW->BeginModule(&M, MMI, O, this, MAI);
142
143   return false;
144 }
145
146 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
147 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
148   if (!GV->hasInitializer())   // External globals require no code.
149     return;
150   
151   // Check to see if this is a special global used by LLVM, if so, emit it.
152   if (EmitSpecialLLVMGlobal(GV))
153     return;
154
155   MCSymbol *GVSym = GetGlobalValueSymbol(GV);
156   printVisibility(GVSym, GV->getVisibility());
157
158   if (MAI->hasDotTypeDotSizeDirective()) {
159     O << "\t.type\t" << *GVSym;
160     if (MAI->getCommentString()[0] != '@')
161       O << ",@object\n";
162     else
163       O << ",%object\n";
164   }
165   
166   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
167
168   const TargetData *TD = TM.getTargetData();
169   unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
170   unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
171   
172   // Handle common and BSS local symbols (.lcomm).
173   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
174     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
175     
176     if (VerboseAsm) {
177       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
178                      /*PrintType=*/false, GV->getParent());
179       OutStreamer.GetCommentOS() << '\n';
180     }
181     
182     // Handle common symbols.
183     if (GVKind.isCommon()) {
184       // .comm _foo, 42, 4
185       OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
186       return;
187     }
188     
189     // Handle local BSS symbols.
190     if (MAI->hasMachoZeroFillDirective()) {
191       const MCSection *TheSection =
192         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193       // .zerofill __DATA, __bss, _foo, 400, 5
194       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
195       return;
196     }
197     
198     if (const char *LComm = MAI->getLCOMMDirective()) {
199       // .lcomm _foo, 42
200       O << LComm << *GVSym << ',' << Size << '\n';
201       return;
202     }
203     
204     // .local _foo
205     OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Local);
206     // .comm _foo, 42, 4
207     OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
208     return;
209   }
210   
211   const MCSection *TheSection =
212     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
213
214   // Handle the zerofill directive on darwin, which is a special form of BSS
215   // emission.
216   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
217     // .globl _foo
218     OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
219     // .zerofill __DATA, __common, _foo, 400, 5
220     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
221     return;
222   }
223
224   OutStreamer.SwitchSection(TheSection);
225
226   // TODO: Factor into an 'emit linkage' thing that is shared with function
227   // bodies.
228   switch (GV->getLinkage()) {
229   case GlobalValue::CommonLinkage:
230   case GlobalValue::LinkOnceAnyLinkage:
231   case GlobalValue::LinkOnceODRLinkage:
232   case GlobalValue::WeakAnyLinkage:
233   case GlobalValue::WeakODRLinkage:
234   case GlobalValue::LinkerPrivateLinkage:
235     if (MAI->getWeakDefDirective() != 0) {
236       // .globl _foo
237       OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
238       // .weak_definition _foo
239       OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
240     } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
241       // .globl _foo
242       OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
243       // .linkonce same_size
244       O << LinkOnce;
245     } else {
246       // .weak _foo
247       OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
248     }
249     break;
250   case GlobalValue::DLLExportLinkage:
251   case GlobalValue::AppendingLinkage:
252     // FIXME: appending linkage variables should go into a section of
253     // their name or something.  For now, just emit them as external.
254   case GlobalValue::ExternalLinkage:
255     // If external or appending, declare as a global symbol.
256     // .globl _foo
257     OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
258     break;
259   case GlobalValue::PrivateLinkage:
260   case GlobalValue::InternalLinkage:
261      break;
262   default:
263     llvm_unreachable("Unknown linkage type!");
264   }
265
266   EmitAlignment(AlignLog, GV);
267   if (VerboseAsm) {
268     WriteAsOperand(OutStreamer.GetCommentOS(), GV,
269                    /*PrintType=*/false, GV->getParent());
270     OutStreamer.GetCommentOS() << '\n';
271   }
272   OutStreamer.EmitLabel(GVSym);
273
274   EmitGlobalConstant(GV->getInitializer());
275
276   if (MAI->hasDotTypeDotSizeDirective())
277     O << "\t.size\t" << *GVSym << ", " << Size << '\n';
278   
279   OutStreamer.AddBlankLine();
280 }
281
282
283 bool AsmPrinter::doFinalization(Module &M) {
284   // Emit global variables.
285   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
286        I != E; ++I)
287     EmitGlobalVariable(I);
288   
289   // Emit final debug information.
290   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
291     DW->EndModule();
292   
293   // If the target wants to know about weak references, print them all.
294   if (MAI->getWeakRefDirective()) {
295     // FIXME: This is not lazy, it would be nice to only print weak references
296     // to stuff that is actually used.  Note that doing so would require targets
297     // to notice uses in operands (due to constant exprs etc).  This should
298     // happen with the MC stuff eventually.
299
300     // Print out module-level global variables here.
301     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
302          I != E; ++I) {
303       if (!I->hasExternalWeakLinkage()) continue;
304       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
305                                       MCStreamer::WeakReference);
306     }
307     
308     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
309       if (!I->hasExternalWeakLinkage()) continue;
310       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
311                                       MCStreamer::WeakReference);
312     }
313   }
314
315   if (MAI->getSetDirective()) {
316     OutStreamer.AddBlankLine();
317     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
318          I != E; ++I) {
319       MCSymbol *Name = GetGlobalValueSymbol(I);
320
321       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
322       MCSymbol *Target = GetGlobalValueSymbol(GV);
323
324       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
325         OutStreamer.EmitSymbolAttribute(Name, MCStreamer::Global);
326       else if (I->hasWeakLinkage())
327         OutStreamer.EmitSymbolAttribute(Name, MCStreamer::WeakReference);
328       else
329         assert(I->hasLocalLinkage() && "Invalid alias linkage");
330
331       printVisibility(Name, I->getVisibility());
332
333       O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
334     }
335   }
336
337   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
338   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
339   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
340     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
341       MP->finishAssembly(O, *this, *MAI);
342
343   // If we don't have any trampolines, then we don't require stack memory
344   // to be executable. Some targets have a directive to declare this.
345   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
346   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
347     // FIXME: This is actually a section switch on linux/x86 and systemz, use
348     // switch section.
349     if (MAI->getNonexecutableStackDirective())
350       O << MAI->getNonexecutableStackDirective() << '\n';
351
352   
353   // Allow the target to emit any magic that it wants at the end of the file,
354   // after everything else has gone out.
355   EmitEndOfAsmFile(M);
356   
357   delete Mang; Mang = 0;
358   DW = 0; MMI = 0;
359   
360   OutStreamer.Finish();
361   return false;
362 }
363
364 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
365   // Get the function symbol.
366   CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
367   IncrementFunctionNumber();
368
369   if (VerboseAsm)
370     LI = &getAnalysis<MachineLoopInfo>();
371 }
372
373 namespace {
374   // SectionCPs - Keep track the alignment, constpool entries per Section.
375   struct SectionCPs {
376     const MCSection *S;
377     unsigned Alignment;
378     SmallVector<unsigned, 4> CPEs;
379     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
380   };
381 }
382
383 /// EmitConstantPool - Print to the current output stream assembly
384 /// representations of the constants in the constant pool MCP. This is
385 /// used to print out constants which have been "spilled to memory" by
386 /// the code generator.
387 ///
388 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
389   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
390   if (CP.empty()) return;
391
392   // Calculate sections for constant pool entries. We collect entries to go into
393   // the same section together to reduce amount of section switch statements.
394   SmallVector<SectionCPs, 4> CPSections;
395   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
396     const MachineConstantPoolEntry &CPE = CP[i];
397     unsigned Align = CPE.getAlignment();
398     
399     SectionKind Kind;
400     switch (CPE.getRelocationInfo()) {
401     default: llvm_unreachable("Unknown section kind");
402     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
403     case 1:
404       Kind = SectionKind::getReadOnlyWithRelLocal();
405       break;
406     case 0:
407     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
408     case 4:  Kind = SectionKind::getMergeableConst4(); break;
409     case 8:  Kind = SectionKind::getMergeableConst8(); break;
410     case 16: Kind = SectionKind::getMergeableConst16();break;
411     default: Kind = SectionKind::getMergeableConst(); break;
412     }
413     }
414
415     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
416     
417     // The number of sections are small, just do a linear search from the
418     // last section to the first.
419     bool Found = false;
420     unsigned SecIdx = CPSections.size();
421     while (SecIdx != 0) {
422       if (CPSections[--SecIdx].S == S) {
423         Found = true;
424         break;
425       }
426     }
427     if (!Found) {
428       SecIdx = CPSections.size();
429       CPSections.push_back(SectionCPs(S, Align));
430     }
431
432     if (Align > CPSections[SecIdx].Alignment)
433       CPSections[SecIdx].Alignment = Align;
434     CPSections[SecIdx].CPEs.push_back(i);
435   }
436
437   // Now print stuff into the calculated sections.
438   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
439     OutStreamer.SwitchSection(CPSections[i].S);
440     EmitAlignment(Log2_32(CPSections[i].Alignment));
441
442     unsigned Offset = 0;
443     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
444       unsigned CPI = CPSections[i].CPEs[j];
445       MachineConstantPoolEntry CPE = CP[CPI];
446
447       // Emit inter-object padding for alignment.
448       unsigned AlignMask = CPE.getAlignment() - 1;
449       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
450       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
451
452       const Type *Ty = CPE.getType();
453       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
454
455       // Emit the label with a comment on it.
456       if (VerboseAsm) {
457         OutStreamer.GetCommentOS() << "constant pool ";
458         WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
459                           MF->getFunction()->getParent());
460         OutStreamer.GetCommentOS() << '\n';
461       }
462       OutStreamer.EmitLabel(GetCPISymbol(CPI));
463
464       if (CPE.isMachineConstantPoolEntry())
465         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
466       else
467         EmitGlobalConstant(CPE.Val.ConstVal);
468     }
469   }
470 }
471
472 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
473 /// by the current function to the current output stream.  
474 ///
475 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
476                                    MachineFunction &MF) {
477   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
478   if (JT.empty()) return;
479
480   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
481   
482   // Pick the directive to use to print the jump table entries, and switch to 
483   // the appropriate section.
484   TargetLowering *LoweringInfo = TM.getTargetLowering();
485
486   const Function *F = MF.getFunction();
487   bool JTInDiffSection = false;
488   if (F->isWeakForLinker() ||
489       (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
490     // In PIC mode, we need to emit the jump table to the same section as the
491     // function body itself, otherwise the label differences won't make sense.
492     // We should also do if the section name is NULL or function is declared in
493     // discardable section.
494     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
495                                                                     TM));
496   } else {
497     // Otherwise, drop it in the readonly section.
498     const MCSection *ReadOnlySection = 
499       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
500     OutStreamer.SwitchSection(ReadOnlySection);
501     JTInDiffSection = true;
502   }
503   
504   EmitAlignment(Log2_32(MJTI->getAlignment()));
505   
506   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
507     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
508     
509     // If this jump table was deleted, ignore it. 
510     if (JTBBs.empty()) continue;
511
512     // For PIC codegen, if possible we want to use the SetDirective to reduce
513     // the number of relocations the assembler will generate for the jump table.
514     // Set directives are all printed before the jump table itself.
515     SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
516     if (MAI->getSetDirective() && IsPic)
517       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
518         if (EmittedSets.insert(JTBBs[ii]))
519           printPICJumpTableSetLabel(i, JTBBs[ii]);
520     
521     // On some targets (e.g. Darwin) we want to emit two consequtive labels
522     // before each jump table.  The first label is never referenced, but tells
523     // the assembler and linker the extents of the jump table object.  The
524     // second label is actually referenced by the code.
525     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
526       OutStreamer.EmitLabel(GetJTISymbol(i, true));
527
528     OutStreamer.EmitLabel(GetJTISymbol(i));
529
530     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
531       printPICJumpTableEntry(MJTI, JTBBs[ii], i);
532       O << '\n';
533     }
534   }
535 }
536
537 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
538                                         const MachineBasicBlock *MBB,
539                                         unsigned uid)  const {
540   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
541   
542   // Use JumpTableDirective otherwise honor the entry size from the jump table
543   // info.
544   const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
545   bool HadJTEntryDirective = JTEntryDirective != NULL;
546   if (!HadJTEntryDirective) {
547     JTEntryDirective = MJTI->getEntrySize() == 4 ?
548       MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
549   }
550
551   O << JTEntryDirective << ' ';
552
553   // If we have emitted set directives for the jump table entries, print 
554   // them rather than the entries themselves.  If we're emitting PIC, then
555   // emit the table entries as differences between two text section labels.
556   // If we're emitting non-PIC code, then emit the entries as direct
557   // references to the target basic blocks.
558   if (!isPIC) {
559     O << *GetMBBSymbol(MBB->getNumber());
560   } else if (MAI->getSetDirective()) {
561     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
562       << '_' << uid << "_set_" << MBB->getNumber();
563   } else {
564     O << *GetMBBSymbol(MBB->getNumber());
565     // If the arch uses custom Jump Table directives, don't calc relative to
566     // JT.
567     if (!HadJTEntryDirective) 
568       O << '-' << *GetJTISymbol(uid);
569   }
570 }
571
572
573 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
574 /// special global used by LLVM.  If so, emit it and return true, otherwise
575 /// do nothing and return false.
576 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
577   if (GV->getName() == "llvm.used") {
578     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
579       EmitLLVMUsedList(GV->getInitializer());
580     return true;
581   }
582
583   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
584   if (GV->getSection() == "llvm.metadata" ||
585       GV->hasAvailableExternallyLinkage())
586     return true;
587   
588   if (!GV->hasAppendingLinkage()) return false;
589
590   assert(GV->hasInitializer() && "Not a special LLVM global!");
591   
592   const TargetData *TD = TM.getTargetData();
593   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
594   if (GV->getName() == "llvm.global_ctors") {
595     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
596     EmitAlignment(Align, 0);
597     EmitXXStructorList(GV->getInitializer());
598     
599     if (TM.getRelocationModel() == Reloc::Static &&
600         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
601       StringRef Sym(".constructors_used");
602       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
603                                       MCStreamer::Reference);
604     }
605     return true;
606   } 
607   
608   if (GV->getName() == "llvm.global_dtors") {
609     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
610     EmitAlignment(Align, 0);
611     EmitXXStructorList(GV->getInitializer());
612
613     if (TM.getRelocationModel() == Reloc::Static &&
614         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
615       StringRef Sym(".destructors_used");
616       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
617                                       MCStreamer::Reference);
618     }
619     return true;
620   }
621   
622   return false;
623 }
624
625 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
626 /// global in the specified llvm.used list for which emitUsedDirectiveFor
627 /// is true, as being used with this directive.
628 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
629   // Should be an array of 'i8*'.
630   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
631   if (InitList == 0) return;
632   
633   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
634     const GlobalValue *GV =
635       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
636     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
637       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
638                                       MCStreamer::NoDeadStrip);
639   }
640 }
641
642 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
643 /// function pointers, ignoring the init priority.
644 void AsmPrinter::EmitXXStructorList(Constant *List) {
645   // Should be an array of '{ int, void ()* }' structs.  The first value is the
646   // init priority, which we ignore.
647   if (!isa<ConstantArray>(List)) return;
648   ConstantArray *InitList = cast<ConstantArray>(List);
649   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
650     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
651       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
652
653       if (CS->getOperand(1)->isNullValue())
654         return;  // Found a null terminator, exit printing.
655       // Emit the function pointer.
656       EmitGlobalConstant(CS->getOperand(1));
657     }
658 }
659
660 //===--------------------------------------------------------------------===//
661 // Emission and print routines
662 //
663
664 /// EmitInt8 - Emit a byte directive and value.
665 ///
666 void AsmPrinter::EmitInt8(int Value) const {
667   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
668 }
669
670 /// EmitInt16 - Emit a short directive and value.
671 ///
672 void AsmPrinter::EmitInt16(int Value) const {
673   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
674 }
675
676 /// EmitInt32 - Emit a long directive and value.
677 ///
678 void AsmPrinter::EmitInt32(int Value) const {
679   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
680 }
681
682 /// EmitInt64 - Emit a long long directive and value.
683 ///
684 void AsmPrinter::EmitInt64(uint64_t Value) const {
685   OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
686 }
687
688
689 /// toOctal - Convert the low order bits of X into an octal digit.
690 ///
691 static inline char toOctal(int X) {
692   return (X&7)+'0';
693 }
694
695 /// printStringChar - Print a char, escaped if necessary.
696 ///
697 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
698   if (C == '"') {
699     O << "\\\"";
700   } else if (C == '\\') {
701     O << "\\\\";
702   } else if (isprint((unsigned char)C)) {
703     O << C;
704   } else {
705     switch(C) {
706     case '\b': O << "\\b"; break;
707     case '\f': O << "\\f"; break;
708     case '\n': O << "\\n"; break;
709     case '\r': O << "\\r"; break;
710     case '\t': O << "\\t"; break;
711     default:
712       O << '\\';
713       O << toOctal(C >> 6);
714       O << toOctal(C >> 3);
715       O << toOctal(C >> 0);
716       break;
717     }
718   }
719 }
720
721 /// EmitFile - Emit a .file directive.
722 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
723   O << "\t.file\t" << Number << " \"";
724   for (unsigned i = 0, N = Name.size(); i < N; ++i)
725     printStringChar(O, Name[i]);
726   O << '\"';
727 }
728
729
730 //===----------------------------------------------------------------------===//
731
732 // EmitAlignment - Emit an alignment directive to the specified power of
733 // two boundary.  For example, if you pass in 3 here, you will get an 8
734 // byte alignment.  If a global value is specified, and if that global has
735 // an explicit alignment requested, it will unconditionally override the
736 // alignment request.  However, if ForcedAlignBits is specified, this value
737 // has final say: the ultimate alignment will be the max of ForcedAlignBits
738 // and the alignment computed with NumBits and the global.
739 //
740 // The algorithm is:
741 //     Align = NumBits;
742 //     if (GV && GV->hasalignment) Align = GV->getalignment();
743 //     Align = std::max(Align, ForcedAlignBits);
744 //
745 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
746                                unsigned ForcedAlignBits,
747                                bool UseFillExpr) const {
748   if (GV && GV->getAlignment())
749     NumBits = Log2_32(GV->getAlignment());
750   NumBits = std::max(NumBits, ForcedAlignBits);
751   
752   if (NumBits == 0) return;   // No need to emit alignment.
753   
754   unsigned FillValue = 0;
755   if (getCurrentSection()->getKind().isText())
756     FillValue = MAI->getTextAlignFillValue();
757   
758   OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
759 }
760
761 // Print out the specified constant, without a storage class.  Only the
762 // constants valid in constant expressions can occur here.
763 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
764   if (CV->isNullValue() || isa<UndefValue>(CV)) {
765     O << '0';
766     return;
767   }
768
769   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
770     O << CI->getZExtValue();
771     return;
772   }
773   
774   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
775     // This is a constant address for a global variable or function. Use the
776     // name of the variable or function as the address value.
777     O << *GetGlobalValueSymbol(GV);
778     return;
779   }
780   
781   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
782     O << *GetBlockAddressSymbol(BA);
783     return;
784   }
785   
786   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
787   if (CE == 0) {
788     llvm_unreachable("Unknown constant value!");
789     O << '0';
790     return;
791   }
792   
793   switch (CE->getOpcode()) {
794   case Instruction::ZExt:
795   case Instruction::SExt:
796   case Instruction::FPTrunc:
797   case Instruction::FPExt:
798   case Instruction::UIToFP:
799   case Instruction::SIToFP:
800   case Instruction::FPToUI:
801   case Instruction::FPToSI:
802   default:
803     llvm_unreachable("FIXME: Don't support this constant cast expr");
804   case Instruction::GetElementPtr: {
805     // generate a symbolic expression for the byte address
806     const TargetData *TD = TM.getTargetData();
807     const Constant *ptrVal = CE->getOperand(0);
808     SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
809     int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
810                                           idxVec.size());
811     if (Offset == 0)
812       return EmitConstantValueOnly(ptrVal);
813     
814     // Truncate/sext the offset to the pointer size.
815     if (TD->getPointerSizeInBits() != 64) {
816       int SExtAmount = 64-TD->getPointerSizeInBits();
817       Offset = (Offset << SExtAmount) >> SExtAmount;
818     }
819     
820     if (Offset)
821       O << '(';
822     EmitConstantValueOnly(ptrVal);
823     if (Offset > 0)
824       O << ") + " << Offset;
825     else
826       O << ") - " << -Offset;
827     return;
828   }
829   case Instruction::BitCast:
830     return EmitConstantValueOnly(CE->getOperand(0));
831
832   case Instruction::IntToPtr: {
833     // Handle casts to pointers by changing them into casts to the appropriate
834     // integer type.  This promotes constant folding and simplifies this code.
835     const TargetData *TD = TM.getTargetData();
836     Constant *Op = CE->getOperand(0);
837     Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
838                                       false/*ZExt*/);
839     return EmitConstantValueOnly(Op);
840   }
841     
842   case Instruction::PtrToInt: {
843     // Support only foldable casts to/from pointers that can be eliminated by
844     // changing the pointer to the appropriately sized integer type.
845     Constant *Op = CE->getOperand(0);
846     const Type *Ty = CE->getType();
847     const TargetData *TD = TM.getTargetData();
848
849     // We can emit the pointer value into this slot if the slot is an
850     // integer slot greater or equal to the size of the pointer.
851     if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
852       return EmitConstantValueOnly(Op);
853
854     O << "((";
855     EmitConstantValueOnly(Op);
856     APInt ptrMask =
857       APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
858     
859     SmallString<40> S;
860     ptrMask.toStringUnsigned(S);
861     O << ") & " << S.str() << ')';
862     return;
863   }
864       
865   case Instruction::Trunc:
866     // We emit the value and depend on the assembler to truncate the generated
867     // expression properly.  This is important for differences between
868     // blockaddress labels.  Since the two labels are in the same function, it
869     // is reasonable to treat their delta as a 32-bit value.
870     return EmitConstantValueOnly(CE->getOperand(0));
871       
872   case Instruction::Add:
873   case Instruction::Sub:
874   case Instruction::And:
875   case Instruction::Or:
876   case Instruction::Xor:
877     O << '(';
878     EmitConstantValueOnly(CE->getOperand(0));
879     O << ')';
880     switch (CE->getOpcode()) {
881     case Instruction::Add:
882      O << " + ";
883      break;
884     case Instruction::Sub:
885      O << " - ";
886      break;
887     case Instruction::And:
888      O << " & ";
889      break;
890     case Instruction::Or:
891      O << " | ";
892      break;
893     case Instruction::Xor:
894      O << " ^ ";
895      break;
896     default:
897      break;
898     }
899     O << '(';
900     EmitConstantValueOnly(CE->getOperand(1));
901     O << ')';
902     break;
903   }
904 }
905
906 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
907                                     AsmPrinter &AP) {
908   if (AddrSpace != 0 || !CA->isString()) {
909     // Not a string.  Print the values in successive locations
910     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
911       AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
912     return;
913   }
914   
915   // Otherwise, it can be emitted as .ascii.
916   SmallVector<char, 128> TmpVec;
917   TmpVec.reserve(CA->getNumOperands());
918   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
919     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
920
921   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
922 }
923
924 static void EmitGlobalConstantVector(const ConstantVector *CV,
925                                      unsigned AddrSpace, AsmPrinter &AP) {
926   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
927     AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
928 }
929
930 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
931                                      unsigned AddrSpace, AsmPrinter &AP) {
932   // Print the fields in successive locations. Pad to align if needed!
933   const TargetData *TD = AP.TM.getTargetData();
934   unsigned Size = TD->getTypeAllocSize(CS->getType());
935   const StructLayout *Layout = TD->getStructLayout(CS->getType());
936   uint64_t SizeSoFar = 0;
937   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
938     const Constant *Field = CS->getOperand(i);
939
940     // Check if padding is needed and insert one or more 0s.
941     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
942     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
943                         - Layout->getElementOffset(i)) - FieldSize;
944     SizeSoFar += FieldSize + PadSize;
945
946     // Now print the actual field value.
947     AP.EmitGlobalConstant(Field, AddrSpace);
948
949     // Insert padding - this may include padding to increase the size of the
950     // current field up to the ABI size (if the struct is not packed) as well
951     // as padding to ensure that the next field starts at the right offset.
952     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
953   }
954   assert(SizeSoFar == Layout->getSizeInBytes() &&
955          "Layout of constant struct may be incorrect!");
956 }
957
958 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
959                                  AsmPrinter &AP) {
960   // FP Constants are printed as integer constants to avoid losing
961   // precision.
962   if (CFP->getType()->isDoubleTy()) {
963     if (AP.VerboseAsm) {
964       double Val = CFP->getValueAPF().convertToDouble();
965       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
966     }
967
968     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
969     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
970     return;
971   }
972   
973   if (CFP->getType()->isFloatTy()) {
974     if (AP.VerboseAsm) {
975       float Val = CFP->getValueAPF().convertToFloat();
976       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
977     }
978     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
979     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
980     return;
981   }
982   
983   if (CFP->getType()->isX86_FP80Ty()) {
984     // all long double variants are printed as hex
985     // api needed to prevent premature destruction
986     APInt API = CFP->getValueAPF().bitcastToAPInt();
987     const uint64_t *p = API.getRawData();
988     if (AP.VerboseAsm) {
989       // Convert to double so we can print the approximate val as a comment.
990       APFloat DoubleVal = CFP->getValueAPF();
991       bool ignored;
992       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
993                         &ignored);
994       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
995         << DoubleVal.convertToDouble() << '\n';
996     }
997     
998     if (AP.TM.getTargetData()->isBigEndian()) {
999       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1000       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1001     } else {
1002       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1003       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1004     }
1005     
1006     // Emit the tail padding for the long double.
1007     const TargetData &TD = *AP.TM.getTargetData();
1008     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1009                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1010     return;
1011   }
1012   
1013   assert(CFP->getType()->isPPC_FP128Ty() &&
1014          "Floating point constant type not handled");
1015   // All long double variants are printed as hex api needed to prevent
1016   // premature destruction.
1017   APInt API = CFP->getValueAPF().bitcastToAPInt();
1018   const uint64_t *p = API.getRawData();
1019   if (AP.TM.getTargetData()->isBigEndian()) {
1020     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1021     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1022   } else {
1023     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1024     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1025   }
1026 }
1027
1028 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1029                                        unsigned AddrSpace, AsmPrinter &AP) {
1030   const TargetData *TD = AP.TM.getTargetData();
1031   unsigned BitWidth = CI->getBitWidth();
1032   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1033
1034   // We don't expect assemblers to support integer data directives
1035   // for more than 64 bits, so we emit the data in at most 64-bit
1036   // quantities at a time.
1037   const uint64_t *RawData = CI->getValue().getRawData();
1038   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1039     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1040     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1041   }
1042 }
1043
1044 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1045 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1046   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1047     uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1048     return OutStreamer.EmitZeros(Size, AddrSpace);
1049   }
1050
1051   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1052     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1053     switch (Size) {
1054     case 1:
1055     case 2:
1056     case 4:
1057     case 8:
1058       if (VerboseAsm)
1059         OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1060       OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1061       return;
1062     default:
1063       EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1064       return;
1065     }
1066   }
1067   
1068   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1069     return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1070   
1071   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1072     return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1073
1074   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1075     return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1076   
1077   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1078     return EmitGlobalConstantVector(V, AddrSpace, *this);
1079
1080   if (isa<ConstantPointerNull>(CV)) {
1081     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1082     OutStreamer.EmitIntValue(0, Size, AddrSpace);
1083     return;
1084   }
1085   
1086   // Otherwise, it must be a ConstantExpr.  Emit the data directive, then emit
1087   // the expression value.
1088   switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1089   case 0: return;
1090   case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1091   case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1092   case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1093   case 8:
1094     if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1095       O << Dir;
1096       break;
1097     }
1098     // FALL THROUGH.
1099   default:
1100     llvm_unreachable("Target cannot handle given data directive width!");
1101     return;
1102   }
1103   
1104   EmitConstantValueOnly(CV);
1105   O << '\n';
1106 }
1107
1108 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1109   // Target doesn't support this yet!
1110   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1111 }
1112
1113 /// PrintSpecial - Print information related to the specified machine instr
1114 /// that is independent of the operand, and may be independent of the instr
1115 /// itself.  This can be useful for portably encoding the comment character
1116 /// or other bits of target-specific knowledge into the asmstrings.  The
1117 /// syntax used is ${:comment}.  Targets can override this to add support
1118 /// for their own strange codes.
1119 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1120   if (!strcmp(Code, "private")) {
1121     O << MAI->getPrivateGlobalPrefix();
1122   } else if (!strcmp(Code, "comment")) {
1123     if (VerboseAsm)
1124       O << MAI->getCommentString();
1125   } else if (!strcmp(Code, "uid")) {
1126     // Comparing the address of MI isn't sufficient, because machineinstrs may
1127     // be allocated to the same address across functions.
1128     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1129     
1130     // If this is a new LastFn instruction, bump the counter.
1131     if (LastMI != MI || LastFn != ThisF) {
1132       ++Counter;
1133       LastMI = MI;
1134       LastFn = ThisF;
1135     }
1136     O << Counter;
1137   } else {
1138     std::string msg;
1139     raw_string_ostream Msg(msg);
1140     Msg << "Unknown special formatter '" << Code
1141          << "' for machine instr: " << *MI;
1142     llvm_report_error(Msg.str());
1143   }    
1144 }
1145
1146 /// processDebugLoc - Processes the debug information of each machine
1147 /// instruction's DebugLoc.
1148 void AsmPrinter::processDebugLoc(const MachineInstr *MI, 
1149                                  bool BeforePrintingInsn) {
1150   if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1151       || !DW->ShouldEmitDwarfDebug())
1152     return;
1153   DebugLoc DL = MI->getDebugLoc();
1154   if (DL.isUnknown())
1155     return;
1156   DILocation CurDLT = MF->getDILocation(DL);
1157   if (CurDLT.getScope().isNull())
1158     return;
1159
1160   if (!BeforePrintingInsn) {
1161     // After printing instruction
1162     DW->EndScope(MI);
1163   } else if (CurDLT.getNode() != PrevDLT) {
1164     unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 
1165                                       CurDLT.getColumnNumber(),
1166                                       CurDLT.getScope().getNode());
1167     printLabel(L);
1168     O << '\n';
1169     DW->BeginScope(MI, L);
1170     PrevDLT = CurDLT.getNode();
1171   }
1172 }
1173
1174
1175 /// printInlineAsm - This method formats and prints the specified machine
1176 /// instruction that is an inline asm.
1177 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1178   unsigned NumOperands = MI->getNumOperands();
1179   
1180   // Count the number of register definitions.
1181   unsigned NumDefs = 0;
1182   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1183        ++NumDefs)
1184     assert(NumDefs != NumOperands-1 && "No asm string?");
1185   
1186   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1187
1188   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1189   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1190
1191   O << '\t';
1192
1193   // If this asmstr is empty, just print the #APP/#NOAPP markers.
1194   // These are useful to see where empty asm's wound up.
1195   if (AsmStr[0] == 0) {
1196     O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1197     O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1198     return;
1199   }
1200   
1201   O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1202
1203   // The variant of the current asmprinter.
1204   int AsmPrinterVariant = MAI->getAssemblerDialect();
1205
1206   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1207   const char *LastEmitted = AsmStr; // One past the last character emitted.
1208   
1209   while (*LastEmitted) {
1210     switch (*LastEmitted) {
1211     default: {
1212       // Not a special case, emit the string section literally.
1213       const char *LiteralEnd = LastEmitted+1;
1214       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1215              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1216         ++LiteralEnd;
1217       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1218         O.write(LastEmitted, LiteralEnd-LastEmitted);
1219       LastEmitted = LiteralEnd;
1220       break;
1221     }
1222     case '\n':
1223       ++LastEmitted;   // Consume newline character.
1224       O << '\n';       // Indent code with newline.
1225       break;
1226     case '$': {
1227       ++LastEmitted;   // Consume '$' character.
1228       bool Done = true;
1229
1230       // Handle escapes.
1231       switch (*LastEmitted) {
1232       default: Done = false; break;
1233       case '$':     // $$ -> $
1234         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1235           O << '$';
1236         ++LastEmitted;  // Consume second '$' character.
1237         break;
1238       case '(':             // $( -> same as GCC's { character.
1239         ++LastEmitted;      // Consume '(' character.
1240         if (CurVariant != -1) {
1241           llvm_report_error("Nested variants found in inline asm string: '"
1242                             + std::string(AsmStr) + "'");
1243         }
1244         CurVariant = 0;     // We're in the first variant now.
1245         break;
1246       case '|':
1247         ++LastEmitted;  // consume '|' character.
1248         if (CurVariant == -1)
1249           O << '|';       // this is gcc's behavior for | outside a variant
1250         else
1251           ++CurVariant;   // We're in the next variant.
1252         break;
1253       case ')':         // $) -> same as GCC's } char.
1254         ++LastEmitted;  // consume ')' character.
1255         if (CurVariant == -1)
1256           O << '}';     // this is gcc's behavior for } outside a variant
1257         else 
1258           CurVariant = -1;
1259         break;
1260       }
1261       if (Done) break;
1262       
1263       bool HasCurlyBraces = false;
1264       if (*LastEmitted == '{') {     // ${variable}
1265         ++LastEmitted;               // Consume '{' character.
1266         HasCurlyBraces = true;
1267       }
1268       
1269       // If we have ${:foo}, then this is not a real operand reference, it is a
1270       // "magic" string reference, just like in .td files.  Arrange to call
1271       // PrintSpecial.
1272       if (HasCurlyBraces && *LastEmitted == ':') {
1273         ++LastEmitted;
1274         const char *StrStart = LastEmitted;
1275         const char *StrEnd = strchr(StrStart, '}');
1276         if (StrEnd == 0) {
1277           llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
1278                             + std::string(AsmStr) + "'");
1279         }
1280         
1281         std::string Val(StrStart, StrEnd);
1282         PrintSpecial(MI, Val.c_str());
1283         LastEmitted = StrEnd+1;
1284         break;
1285       }
1286             
1287       const char *IDStart = LastEmitted;
1288       char *IDEnd;
1289       errno = 0;
1290       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1291       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1292         llvm_report_error("Bad $ operand number in inline asm string: '" 
1293                           + std::string(AsmStr) + "'");
1294       }
1295       LastEmitted = IDEnd;
1296       
1297       char Modifier[2] = { 0, 0 };
1298       
1299       if (HasCurlyBraces) {
1300         // If we have curly braces, check for a modifier character.  This
1301         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1302         if (*LastEmitted == ':') {
1303           ++LastEmitted;    // Consume ':' character.
1304           if (*LastEmitted == 0) {
1305             llvm_report_error("Bad ${:} expression in inline asm string: '" 
1306                               + std::string(AsmStr) + "'");
1307           }
1308           
1309           Modifier[0] = *LastEmitted;
1310           ++LastEmitted;    // Consume modifier character.
1311         }
1312         
1313         if (*LastEmitted != '}') {
1314           llvm_report_error("Bad ${} expression in inline asm string: '" 
1315                             + std::string(AsmStr) + "'");
1316         }
1317         ++LastEmitted;    // Consume '}' character.
1318       }
1319       
1320       if ((unsigned)Val >= NumOperands-1) {
1321         llvm_report_error("Invalid $ operand number in inline asm string: '" 
1322                           + std::string(AsmStr) + "'");
1323       }
1324       
1325       // Okay, we finally have a value number.  Ask the target to print this
1326       // operand!
1327       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1328         unsigned OpNo = 1;
1329
1330         bool Error = false;
1331
1332         // Scan to find the machine operand number for the operand.
1333         for (; Val; --Val) {
1334           if (OpNo >= MI->getNumOperands()) break;
1335           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1336           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1337         }
1338
1339         if (OpNo >= MI->getNumOperands()) {
1340           Error = true;
1341         } else {
1342           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1343           ++OpNo;  // Skip over the ID number.
1344
1345           if (Modifier[0] == 'l')  // labels are target independent
1346             O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1347           else {
1348             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1349             if ((OpFlags & 7) == 4) {
1350               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1351                                                 Modifier[0] ? Modifier : 0);
1352             } else {
1353               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1354                                           Modifier[0] ? Modifier : 0);
1355             }
1356           }
1357         }
1358         if (Error) {
1359           std::string msg;
1360           raw_string_ostream Msg(msg);
1361           Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1362           MI->print(Msg);
1363           llvm_report_error(Msg.str());
1364         }
1365       }
1366       break;
1367     }
1368     }
1369   }
1370   O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1371 }
1372
1373 /// printImplicitDef - This method prints the specified machine instruction
1374 /// that is an implicit def.
1375 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1376   if (!VerboseAsm) return;
1377   O.PadToColumn(MAI->getCommentColumn());
1378   O << MAI->getCommentString() << " implicit-def: "
1379     << TRI->getName(MI->getOperand(0).getReg());
1380 }
1381
1382 void AsmPrinter::printKill(const MachineInstr *MI) const {
1383   if (!VerboseAsm) return;
1384   O.PadToColumn(MAI->getCommentColumn());
1385   O << MAI->getCommentString() << " kill:";
1386   for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1387     const MachineOperand &op = MI->getOperand(n);
1388     assert(op.isReg() && "KILL instruction must have only register operands");
1389     O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1390   }
1391 }
1392
1393 /// printLabel - This method prints a local label used by debug and
1394 /// exception handling tables.
1395 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1396   printLabel(MI->getOperand(0).getImm());
1397 }
1398
1399 void AsmPrinter::printLabel(unsigned Id) const {
1400   O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1401 }
1402
1403 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1404 /// instruction, using the specified assembler variant.  Targets should
1405 /// override this to format as appropriate.
1406 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1407                                  unsigned AsmVariant, const char *ExtraCode) {
1408   // Target doesn't support this yet!
1409   return true;
1410 }
1411
1412 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1413                                        unsigned AsmVariant,
1414                                        const char *ExtraCode) {
1415   // Target doesn't support this yet!
1416   return true;
1417 }
1418
1419 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1420                                             const char *Suffix) const {
1421   return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1422 }
1423
1424 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1425                                             const BasicBlock *BB,
1426                                             const char *Suffix) const {
1427   assert(BB->hasName() &&
1428          "Address of anonymous basic block not supported yet!");
1429
1430   // This code must use the function name itself, and not the function number,
1431   // since it must be possible to generate the label name from within other
1432   // functions.
1433   SmallString<60> FnName;
1434   Mang->getNameWithPrefix(FnName, F, false);
1435
1436   // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1437   SmallString<60> NameResult;
1438   Mang->getNameWithPrefix(NameResult,
1439                           StringRef("BA") + Twine((unsigned)FnName.size()) + 
1440                           "_" + FnName.str() + "_" + BB->getName() + Suffix, 
1441                           Mangler::Private);
1442
1443   return OutContext.GetOrCreateSymbol(NameResult.str());
1444 }
1445
1446 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1447   SmallString<60> Name;
1448   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1449     << getFunctionNumber() << '_' << MBBID;
1450   return OutContext.GetOrCreateSymbol(Name.str());
1451 }
1452
1453 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1454 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1455   SmallString<60> Name;
1456   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1457     << getFunctionNumber() << '_' << CPID;
1458   return OutContext.GetOrCreateSymbol(Name.str());
1459 }
1460
1461 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1462 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1463   const char *Prefix = isLinkerPrivate ? MAI->getLinkerPrivateGlobalPrefix() :
1464                                          MAI->getPrivateGlobalPrefix();
1465   SmallString<60> Name;
1466   raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_'
1467     << JTID;
1468   return OutContext.GetOrCreateSymbol(Name.str());
1469 }
1470
1471 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1472 /// value.
1473 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1474   SmallString<60> NameStr;
1475   Mang->getNameWithPrefix(NameStr, GV, false);
1476   return OutContext.GetOrCreateSymbol(NameStr.str());
1477 }
1478
1479 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1480 /// global value name as its base, with the specified suffix, and where the
1481 /// symbol is forced to have private linkage if ForcePrivate is true.
1482 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1483                                                    StringRef Suffix,
1484                                                    bool ForcePrivate) const {
1485   SmallString<60> NameStr;
1486   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1487   NameStr.append(Suffix.begin(), Suffix.end());
1488   return OutContext.GetOrCreateSymbol(NameStr.str());
1489 }
1490
1491 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1492 /// ExternalSymbol.
1493 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1494   SmallString<60> NameStr;
1495   Mang->getNameWithPrefix(NameStr, Sym);
1496   return OutContext.GetOrCreateSymbol(NameStr.str());
1497 }  
1498
1499
1500
1501 /// PrintParentLoopComment - Print comments about parent loops of this one.
1502 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1503                                    unsigned FunctionNumber) {
1504   if (Loop == 0) return;
1505   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1506   OS.indent(Loop->getLoopDepth()*2)
1507     << "Parent Loop BB" << FunctionNumber << "_"
1508     << Loop->getHeader()->getNumber()
1509     << " Depth=" << Loop->getLoopDepth() << '\n';
1510 }
1511
1512
1513 /// PrintChildLoopComment - Print comments about child loops within
1514 /// the loop for this basic block, with nesting.
1515 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1516                                   unsigned FunctionNumber) {
1517   // Add child loop information
1518   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1519     OS.indent((*CL)->getLoopDepth()*2)
1520       << "Child Loop BB" << FunctionNumber << "_"
1521       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1522       << '\n';
1523     PrintChildLoopComment(OS, *CL, FunctionNumber);
1524   }
1525 }
1526
1527 /// EmitComments - Pretty-print comments for basic blocks.
1528 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1529                                         const MachineLoopInfo *LI,
1530                                         const AsmPrinter &AP) {
1531   // Add loop depth information
1532   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1533   if (Loop == 0) return;
1534   
1535   MachineBasicBlock *Header = Loop->getHeader();
1536   assert(Header && "No header for loop");
1537   
1538   // If this block is not a loop header, just print out what is the loop header
1539   // and return.
1540   if (Header != &MBB) {
1541     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1542                               Twine(AP.getFunctionNumber())+"_" +
1543                               Twine(Loop->getHeader()->getNumber())+
1544                               " Depth="+Twine(Loop->getLoopDepth()));
1545     return;
1546   }
1547   
1548   // Otherwise, it is a loop header.  Print out information about child and
1549   // parent loops.
1550   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1551   
1552   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 
1553   
1554   OS << "=>";
1555   OS.indent(Loop->getLoopDepth()*2-2);
1556   
1557   OS << "This ";
1558   if (Loop->empty())
1559     OS << "Inner ";
1560   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1561   
1562   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1563 }
1564
1565
1566 /// EmitBasicBlockStart - This method prints the label for the specified
1567 /// MachineBasicBlock, an alignment (if present) and a comment describing
1568 /// it if appropriate.
1569 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1570   // Emit an alignment directive for this block, if needed.
1571   if (unsigned Align = MBB->getAlignment())
1572     EmitAlignment(Log2_32(Align));
1573
1574   // If the block has its address taken, emit a special label to satisfy
1575   // references to the block. This is done so that we don't need to
1576   // remember the number of this label, and so that we can make
1577   // forward references to labels without knowing what their numbers
1578   // will be.
1579   if (MBB->hasAddressTaken()) {
1580     const BasicBlock *BB = MBB->getBasicBlock();
1581     if (VerboseAsm)
1582       OutStreamer.AddComment("Address Taken");
1583     OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1584   }
1585
1586   // Print the main label for the block.
1587   if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1588     if (VerboseAsm) {
1589       // NOTE: Want this comment at start of line.
1590       O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1591       if (const BasicBlock *BB = MBB->getBasicBlock())
1592         if (BB->hasName())
1593           OutStreamer.AddComment("%" + BB->getName());
1594       
1595       PrintBasicBlockLoopComments(*MBB, LI, *this);
1596       OutStreamer.AddBlankLine();
1597     }
1598   } else {
1599     if (VerboseAsm) {
1600       if (const BasicBlock *BB = MBB->getBasicBlock())
1601         if (BB->hasName())
1602           OutStreamer.AddComment("%" + BB->getName());
1603       PrintBasicBlockLoopComments(*MBB, LI, *this);
1604     }
1605
1606     OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1607   }
1608 }
1609
1610 /// printPICJumpTableSetLabel - This method prints a set label for the
1611 /// specified MachineBasicBlock for a jumptable entry.
1612 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 
1613                                            const MachineBasicBlock *MBB) const {
1614   if (!MAI->getSetDirective())
1615     return;
1616   
1617   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1618     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1619     << *GetMBBSymbol(MBB->getNumber())
1620     << '-' << *GetJTISymbol(uid) << '\n';
1621 }
1622
1623 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1624                                            const MachineBasicBlock *MBB) const {
1625   if (!MAI->getSetDirective())
1626     return;
1627   
1628   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1629     << getFunctionNumber() << '_' << uid << '_' << uid2
1630     << "_set_" << MBB->getNumber() << ','
1631     << *GetMBBSymbol(MBB->getNumber())
1632     << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1633     << '_' << uid << '_' << uid2 << '\n';
1634 }
1635
1636 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1637                                  unsigned Visibility) const {
1638   if (Visibility == GlobalValue::HiddenVisibility) {
1639     if (const char *Directive = MAI->getHiddenDirective())
1640       O << Directive << *Sym << '\n';
1641   } else if (Visibility == GlobalValue::ProtectedVisibility) {
1642     if (const char *Directive = MAI->getProtectedDirective())
1643       O << Directive << *Sym << '\n';
1644   }
1645 }
1646
1647 void AsmPrinter::printOffset(int64_t Offset) const {
1648   if (Offset > 0)
1649     O << '+' << Offset;
1650   else if (Offset < 0)
1651     O << Offset;
1652 }
1653
1654 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1655   if (!S->usesMetadata())
1656     return 0;
1657   
1658   gcp_iterator GCPI = GCMetadataPrinters.find(S);
1659   if (GCPI != GCMetadataPrinters.end())
1660     return GCPI->second;
1661   
1662   const char *Name = S->getName().c_str();
1663   
1664   for (GCMetadataPrinterRegistry::iterator
1665          I = GCMetadataPrinterRegistry::begin(),
1666          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1667     if (strcmp(Name, I->getName()) == 0) {
1668       GCMetadataPrinter *GMP = I->instantiate();
1669       GMP->S = S;
1670       GCMetadataPrinters.insert(std::make_pair(S, GMP));
1671       return GMP;
1672     }
1673   
1674   errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1675   llvm_unreachable(0);
1676 }
1677
1678 /// EmitComments - Pretty-print comments for instructions
1679 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1680   if (!VerboseAsm)
1681     return;
1682
1683   bool Newline = false;
1684
1685   if (!MI.getDebugLoc().isUnknown()) {
1686     DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1687
1688     // Print source line info.
1689     O.PadToColumn(MAI->getCommentColumn());
1690     O << MAI->getCommentString() << ' ';
1691     DIScope Scope = DLT.getScope();
1692     // Omit the directory, because it's likely to be long and uninteresting.
1693     if (!Scope.isNull())
1694       O << Scope.getFilename();
1695     else
1696       O << "<unknown>";
1697     O << ':' << DLT.getLineNumber();
1698     if (DLT.getColumnNumber() != 0)
1699       O << ':' << DLT.getColumnNumber();
1700     Newline = true;
1701   }
1702
1703   // Check for spills and reloads
1704   int FI;
1705
1706   const MachineFrameInfo *FrameInfo =
1707     MI.getParent()->getParent()->getFrameInfo();
1708
1709   // We assume a single instruction only has a spill or reload, not
1710   // both.
1711   const MachineMemOperand *MMO;
1712   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1713     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1714       MMO = *MI.memoperands_begin();
1715       if (Newline) O << '\n';
1716       O.PadToColumn(MAI->getCommentColumn());
1717       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1718       Newline = true;
1719     }
1720   }
1721   else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1722     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1723       if (Newline) O << '\n';
1724       O.PadToColumn(MAI->getCommentColumn());
1725       O << MAI->getCommentString() << ' '
1726         << MMO->getSize() << "-byte Folded Reload";
1727       Newline = true;
1728     }
1729   }
1730   else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1731     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1732       MMO = *MI.memoperands_begin();
1733       if (Newline) O << '\n';
1734       O.PadToColumn(MAI->getCommentColumn());
1735       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1736       Newline = true;
1737     }
1738   }
1739   else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1740     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1741       if (Newline) O << '\n';
1742       O.PadToColumn(MAI->getCommentColumn());
1743       O << MAI->getCommentString() << ' '
1744         << MMO->getSize() << "-byte Folded Spill";
1745       Newline = true;
1746     }
1747   }
1748
1749   // Check for spill-induced copies
1750   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1751   if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1752                                       SrcSubIdx, DstSubIdx)) {
1753     if (MI.getAsmPrinterFlag(ReloadReuse)) {
1754       if (Newline) O << '\n';
1755       O.PadToColumn(MAI->getCommentColumn());
1756       O << MAI->getCommentString() << " Reload Reuse";
1757     }
1758   }
1759 }
1760