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