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