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