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