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