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