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