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