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