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