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