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