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