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