Oh yeah, there are two of these now, unify both.
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Support/Mangler.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include <iostream>
25 #include <cerrno>
26 using namespace llvm;
27
28 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
29 : FunctionNumber(0), O(o), TM(tm),
30   CommentString("#"),
31   GlobalPrefix(""),
32   PrivateGlobalPrefix("."),
33   GlobalVarAddrPrefix(""),
34   GlobalVarAddrSuffix(""),
35   FunctionAddrPrefix(""),
36   FunctionAddrSuffix(""),
37   InlineAsmStart("#APP"),
38   InlineAsmEnd("#NO_APP"),
39   ZeroDirective("\t.zero\t"),
40   ZeroDirectiveSuffix(0),
41   AsciiDirective("\t.ascii\t"),
42   AscizDirective("\t.asciz\t"),
43   Data8bitsDirective("\t.byte\t"),
44   Data16bitsDirective("\t.short\t"),
45   Data32bitsDirective("\t.long\t"),
46   Data64bitsDirective("\t.quad\t"),
47   AlignDirective("\t.align\t"),
48   AlignmentIsInBytes(true),
49   SwitchToSectionDirective("\t.section\t"),
50   MLSections(false),
51   ConstantPoolSection("\t.section .rodata\n"),
52   JumpTableSection("\t.section .rodata\n"),
53   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
54   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
55   LCOMMDirective(0),
56   COMMDirective("\t.comm\t"),
57   COMMDirectiveTakesAlignment(true),
58   HasDotTypeDotSizeDirective(true) {
59 }
60
61
62 /// SwitchToTextSection - Switch to the specified text section of the executable
63 /// if we are not already in it!
64 ///
65 void AsmPrinter::SwitchToTextSection(const char *NewSection,
66                                      const GlobalValue *GV) {
67   std::string NS;
68   if (GV && GV->hasSection())
69     NS = GV->getSection();
70   else
71     NS = NewSection;
72   
73   // If we're already in this section, we're done.
74   if (CurrentSection == NS) return;
75
76   // Microsoft ML/MASM has a fundamentally different approach to handling
77   // sections.
78
79   if (MLSections) {
80     if (!CurrentSection.empty())
81       O << CurrentSection << "\tends\n\n";
82     CurrentSection = NS;
83     if (!CurrentSection.empty())
84       O << CurrentSection << "\tsegment 'CODE'\n";
85   } else {
86     CurrentSection = NS;
87     if (!CurrentSection.empty())
88       O << CurrentSection << '\n';
89   }
90 }
91
92 /// SwitchToTextSection - Switch to the specified text section of the executable
93 /// if we are not already in it!
94 ///
95 void AsmPrinter::SwitchToDataSection(const char *NewSection,
96                                      const GlobalValue *GV) {
97   std::string NS;
98   if (GV && GV->hasSection())
99     NS = SwitchToSectionDirective + GV->getSection();
100   else
101     NS = NewSection;
102   
103   // If we're already in this section, we're done.
104   if (CurrentSection == NS) return;
105
106   // Microsoft ML/MASM has a fundamentally different approach to handling
107   // sections.
108   
109   if (MLSections) {
110     if (!CurrentSection.empty())
111       O << CurrentSection << "\tends\n\n";
112     CurrentSection = NS;
113     if (!CurrentSection.empty())
114       O << CurrentSection << "\tsegment 'DATA'\n";
115   } else {
116     CurrentSection = NS;
117     if (!CurrentSection.empty())
118       O << CurrentSection << '\n';
119   }
120 }
121
122
123 bool AsmPrinter::doInitialization(Module &M) {
124   Mang = new Mangler(M, GlobalPrefix);
125   
126   if (!M.getModuleInlineAsm().empty())
127     O << CommentString << " Start of file scope inline assembly\n"
128       << M.getModuleInlineAsm()
129       << "\n" << CommentString << " End of file scope inline assembly\n";
130
131   SwitchToDataSection("", 0);   // Reset back to no section.
132   
133   if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
134     DebugInfo->AnalyzeModule(M);
135   }
136   
137   return false;
138 }
139
140 bool AsmPrinter::doFinalization(Module &M) {
141   delete Mang; Mang = 0;
142   return false;
143 }
144
145 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
146   // What's my mangled name?
147   CurrentFnName = Mang->getValueName(MF.getFunction());
148   IncrementFunctionNumber();
149 }
150
151 /// EmitConstantPool - Print to the current output stream assembly
152 /// representations of the constants in the constant pool MCP. This is
153 /// used to print out constants which have been "spilled to memory" by
154 /// the code generator.
155 ///
156 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
157   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
158   if (CP.empty()) return;
159   const TargetData *TD = TM.getTargetData();
160   
161   SwitchToDataSection(ConstantPoolSection, 0);
162   EmitAlignment(MCP->getConstantPoolAlignment());
163   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
164     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
165       << ":\t\t\t\t\t" << CommentString << " ";
166     WriteTypeSymbolic(O, CP[i].Val->getType(), 0) << '\n';
167     EmitGlobalConstant(CP[i].Val);
168     if (i != e-1) {
169       unsigned EntSize = TM.getTargetData()->getTypeSize(CP[i].Val->getType());
170       unsigned ValEnd = CP[i].Offset + EntSize;
171       // Emit inter-object padding for alignment.
172       EmitZeros(CP[i+1].Offset-ValEnd);
173     }
174   }
175 }
176
177 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
178 /// by the current function to the current output stream.  
179 ///
180 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI) {
181   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
182   if (JT.empty()) return;
183   const TargetData *TD = TM.getTargetData();
184   
185   // FIXME: someday we need to handle PIC jump tables
186   assert((TM.getRelocationModel() == Reloc::Static ||
187           TM.getRelocationModel() == Reloc::DynamicNoPIC) &&
188          "Unhandled relocation model emitting jump table information!");
189   
190   SwitchToDataSection(JumpTableSection, 0);
191   EmitAlignment(Log2_32(TD->getPointerAlignment()));
192   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
193     O << PrivateGlobalPrefix << "JTI" << getFunctionNumber() << '_' << i 
194       << ":\n";
195     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
196     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
197       O << Data32bitsDirective << ' ';
198       printBasicBlockLabel(JTBBs[ii]);
199       O << '\n';
200     }
201   }
202 }
203
204 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
205 /// special global used by LLVM.  If so, emit it and return true, otherwise
206 /// do nothing and return false.
207 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
208   // Ignore debug and non-emitted data.
209   if (GV->getSection() == "llvm.metadata") return true;
210   
211   if (!GV->hasAppendingLinkage()) return false;
212
213   assert(GV->hasInitializer() && "Not a special LLVM global!");
214   
215   if (GV->getName() == "llvm.used")
216     return true;  // No need to emit this at all.
217
218   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
219     SwitchToDataSection(StaticCtorsSection, 0);
220     EmitAlignment(2, 0);
221     EmitXXStructorList(GV->getInitializer());
222     return true;
223   } 
224   
225   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
226     SwitchToDataSection(StaticDtorsSection, 0);
227     EmitAlignment(2, 0);
228     EmitXXStructorList(GV->getInitializer());
229     return true;
230   }
231   
232   return false;
233 }
234
235 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
236 /// function pointers, ignoring the init priority.
237 void AsmPrinter::EmitXXStructorList(Constant *List) {
238   // Should be an array of '{ int, void ()* }' structs.  The first value is the
239   // init priority, which we ignore.
240   if (!isa<ConstantArray>(List)) return;
241   ConstantArray *InitList = cast<ConstantArray>(List);
242   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
243     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
244       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
245
246       if (CS->getOperand(1)->isNullValue())
247         return;  // Found a null terminator, exit printing.
248       // Emit the function pointer.
249       EmitGlobalConstant(CS->getOperand(1));
250     }
251 }
252
253 /// getPreferredAlignmentLog - Return the preferred alignment of the
254 /// specified global, returned in log form.  This includes an explicitly
255 /// requested alignment (if the global has one).
256 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
257   unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(GV->getType());
258   if (GV->getAlignment() > (1U << Alignment))
259     Alignment = Log2_32(GV->getAlignment());
260   
261   if (GV->hasInitializer()) {
262     // Always round up alignment of global doubles to 8 bytes.
263     if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
264       Alignment = 3;
265     if (Alignment < 4) {
266       // If the global is not external, see if it is large.  If so, give it a
267       // larger alignment.
268       if (TM.getTargetData()->getTypeSize(GV->getType()->getElementType()) > 128)
269         Alignment = 4;    // 16-byte alignment.
270     }
271   }
272   return Alignment;
273 }
274
275 // EmitAlignment - Emit an alignment directive to the specified power of two.
276 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
277   if (GV && GV->getAlignment())
278     NumBits = Log2_32(GV->getAlignment());
279   if (NumBits == 0) return;   // No need to emit alignment.
280   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
281   O << AlignDirective << NumBits << "\n";
282 }
283
284 /// EmitZeros - Emit a block of zeros.
285 ///
286 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
287   if (NumZeros) {
288     if (ZeroDirective) {
289       O << ZeroDirective << NumZeros;
290       if (ZeroDirectiveSuffix)
291         O << ZeroDirectiveSuffix;
292       O << "\n";
293     } else {
294       for (; NumZeros; --NumZeros)
295         O << Data8bitsDirective << "0\n";
296     }
297   }
298 }
299
300 // Print out the specified constant, without a storage class.  Only the
301 // constants valid in constant expressions can occur here.
302 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
303   if (CV->isNullValue() || isa<UndefValue>(CV))
304     O << "0";
305   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
306     assert(CB == ConstantBool::True);
307     O << "1";
308   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
309     if (((CI->getValue() << 32) >> 32) == CI->getValue())
310       O << CI->getValue();
311     else
312       O << (uint64_t)CI->getValue();
313   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
314     O << CI->getValue();
315   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
316     // This is a constant address for a global variable or function. Use the
317     // name of the variable or function as the address value, possibly
318     // decorating it with GlobalVarAddrPrefix/Suffix or
319     // FunctionAddrPrefix/Suffix (these all default to "" )
320     if (isa<Function>(GV))
321       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
322     else
323       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
324   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
325     const TargetData *TD = TM.getTargetData();
326     switch(CE->getOpcode()) {
327     case Instruction::GetElementPtr: {
328       // generate a symbolic expression for the byte address
329       const Constant *ptrVal = CE->getOperand(0);
330       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
331       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
332         if (Offset)
333           O << "(";
334         EmitConstantValueOnly(ptrVal);
335         if (Offset > 0)
336           O << ") + " << Offset;
337         else if (Offset < 0)
338           O << ") - " << -Offset;
339       } else {
340         EmitConstantValueOnly(ptrVal);
341       }
342       break;
343     }
344     case Instruction::Cast: {
345       // Support only non-converting or widening casts for now, that is, ones
346       // that do not involve a change in value.  This assertion is really gross,
347       // and may not even be a complete check.
348       Constant *Op = CE->getOperand(0);
349       const Type *OpTy = Op->getType(), *Ty = CE->getType();
350
351       // Remember, kids, pointers can be losslessly converted back and forth
352       // into 32-bit or wider integers, regardless of signedness. :-P
353       assert(((isa<PointerType>(OpTy)
354                && (Ty == Type::LongTy || Ty == Type::ULongTy
355                    || Ty == Type::IntTy || Ty == Type::UIntTy))
356               || (isa<PointerType>(Ty)
357                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
358                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
359               || (((TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
360                    && OpTy->isLosslesslyConvertibleTo(Ty))))
361              && "FIXME: Don't yet support this kind of constant cast expr");
362       EmitConstantValueOnly(Op);
363       break;
364     }
365     case Instruction::Add:
366       O << "(";
367       EmitConstantValueOnly(CE->getOperand(0));
368       O << ") + (";
369       EmitConstantValueOnly(CE->getOperand(1));
370       O << ")";
371       break;
372     default:
373       assert(0 && "Unsupported operator!");
374     }
375   } else {
376     assert(0 && "Unknown constant value!");
377   }
378 }
379
380 /// toOctal - Convert the low order bits of X into an octal digit.
381 ///
382 static inline char toOctal(int X) {
383   return (X&7)+'0';
384 }
385
386 /// printAsCString - Print the specified array as a C compatible string, only if
387 /// the predicate isString is true.
388 ///
389 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
390                            unsigned LastElt) {
391   assert(CVA->isString() && "Array is not string compatible!");
392
393   O << "\"";
394   for (unsigned i = 0; i != LastElt; ++i) {
395     unsigned char C =
396         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
397
398     if (C == '"') {
399       O << "\\\"";
400     } else if (C == '\\') {
401       O << "\\\\";
402     } else if (isprint(C)) {
403       O << C;
404     } else {
405       switch(C) {
406       case '\b': O << "\\b"; break;
407       case '\f': O << "\\f"; break;
408       case '\n': O << "\\n"; break;
409       case '\r': O << "\\r"; break;
410       case '\t': O << "\\t"; break;
411       default:
412         O << '\\';
413         O << toOctal(C >> 6);
414         O << toOctal(C >> 3);
415         O << toOctal(C >> 0);
416         break;
417       }
418     }
419   }
420   O << "\"";
421 }
422
423 /// EmitString - Emit a zero-byte-terminated string constant.
424 ///
425 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
426   unsigned NumElts = CVA->getNumOperands();
427   if (AscizDirective && NumElts && 
428       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
429     O << AscizDirective;
430     printAsCString(O, CVA, NumElts-1);
431   } else {
432     O << AsciiDirective;
433     printAsCString(O, CVA, NumElts);
434   }
435   O << "\n";
436 }
437
438 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
439 ///
440 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
441   const TargetData *TD = TM.getTargetData();
442
443   if (CV->isNullValue() || isa<UndefValue>(CV)) {
444     EmitZeros(TD->getTypeSize(CV->getType()));
445     return;
446   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
447     if (CVA->isString()) {
448       EmitString(CVA);
449     } else { // Not a string.  Print the values in successive locations
450       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
451         EmitGlobalConstant(CVA->getOperand(i));
452     }
453     return;
454   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
455     // Print the fields in successive locations. Pad to align if needed!
456     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
457     uint64_t sizeSoFar = 0;
458     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
459       const Constant* field = CVS->getOperand(i);
460
461       // Check if padding is needed and insert one or more 0s.
462       uint64_t fieldSize = TD->getTypeSize(field->getType());
463       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
464                            : cvsLayout->MemberOffsets[i+1])
465                           - cvsLayout->MemberOffsets[i]) - fieldSize;
466       sizeSoFar += fieldSize + padSize;
467
468       // Now print the actual field value
469       EmitGlobalConstant(field);
470
471       // Insert the field padding unless it's zero bytes...
472       EmitZeros(padSize);
473     }
474     assert(sizeSoFar == cvsLayout->StructSize &&
475            "Layout of constant struct may be incorrect!");
476     return;
477   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
478     // FP Constants are printed as integer constants to avoid losing
479     // precision...
480     double Val = CFP->getValue();
481     if (CFP->getType() == Type::DoubleTy) {
482       if (Data64bitsDirective)
483         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
484           << " double value: " << Val << "\n";
485       else if (TD->isBigEndian()) {
486         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
487           << "\t" << CommentString << " double most significant word "
488           << Val << "\n";
489         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
490           << "\t" << CommentString << " double least significant word "
491           << Val << "\n";
492       } else {
493         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
494           << "\t" << CommentString << " double least significant word " << Val
495           << "\n";
496         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
497           << "\t" << CommentString << " double most significant word " << Val
498           << "\n";
499       }
500       return;
501     } else {
502       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
503         << " float " << Val << "\n";
504       return;
505     }
506   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
507     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
508       uint64_t Val = CI->getRawValue();
509
510       if (Data64bitsDirective)
511         O << Data64bitsDirective << Val << "\n";
512       else if (TD->isBigEndian()) {
513         O << Data32bitsDirective << unsigned(Val >> 32)
514           << "\t" << CommentString << " Double-word most significant word "
515           << Val << "\n";
516         O << Data32bitsDirective << unsigned(Val)
517           << "\t" << CommentString << " Double-word least significant word "
518           << Val << "\n";
519       } else {
520         O << Data32bitsDirective << unsigned(Val)
521           << "\t" << CommentString << " Double-word least significant word "
522           << Val << "\n";
523         O << Data32bitsDirective << unsigned(Val >> 32)
524           << "\t" << CommentString << " Double-word most significant word "
525           << Val << "\n";
526       }
527       return;
528     }
529   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
530     const PackedType *PTy = CP->getType();
531     
532     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
533       EmitGlobalConstant(CP->getOperand(I));
534     
535     return;
536   }
537
538   const Type *type = CV->getType();
539   switch (type->getTypeID()) {
540   case Type::BoolTyID:
541   case Type::UByteTyID: case Type::SByteTyID:
542     O << Data8bitsDirective;
543     break;
544   case Type::UShortTyID: case Type::ShortTyID:
545     O << Data16bitsDirective;
546     break;
547   case Type::PointerTyID:
548     if (TD->getPointerSize() == 8) {
549       O << Data64bitsDirective;
550       break;
551     }
552     //Fall through for pointer size == int size
553   case Type::UIntTyID: case Type::IntTyID:
554     O << Data32bitsDirective;
555     break;
556   case Type::ULongTyID: case Type::LongTyID:
557     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
558     O << Data64bitsDirective;
559     break;
560   case Type::FloatTyID: case Type::DoubleTyID:
561     assert (0 && "Should have already output floating point constant.");
562   default:
563     assert (0 && "Can't handle printing this type of thing");
564     break;
565   }
566   EmitConstantValueOnly(CV);
567   O << "\n";
568 }
569
570 /// printInlineAsm - This method formats and prints the specified machine
571 /// instruction that is an inline asm.
572 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
573   O << InlineAsmStart << "\n\t";
574   unsigned NumOperands = MI->getNumOperands();
575   
576   // Count the number of register definitions.
577   unsigned NumDefs = 0;
578   for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
579     assert(NumDefs != NumOperands-1 && "No asm string?");
580   
581   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
582
583   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
584   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
585
586   // The variant of the current asmprinter: FIXME: change.
587   int AsmPrinterVariant = 0;
588   
589   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
590   const char *LastEmitted = AsmStr; // One past the last character emitted.
591   
592   while (*LastEmitted) {
593     switch (*LastEmitted) {
594     default: {
595       // Not a special case, emit the string section literally.
596       const char *LiteralEnd = LastEmitted+1;
597       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
598              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
599         ++LiteralEnd;
600       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
601         O.write(LastEmitted, LiteralEnd-LastEmitted);
602       LastEmitted = LiteralEnd;
603       break;
604     }
605     case '\n':
606       ++LastEmitted;   // Consume newline character.
607       O << "\n\t";     // Indent code with newline.
608       break;
609     case '$': {
610       ++LastEmitted;   // Consume '$' character.
611       if (*LastEmitted == '$') { // $$ -> $
612         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
613           O << '$';
614         ++LastEmitted;  // Consume second '$' character.
615         break;
616       }
617       
618       bool HasCurlyBraces = false;
619       if (*LastEmitted == '{') {     // ${variable}
620         ++LastEmitted;               // Consume '{' character.
621         HasCurlyBraces = true;
622       }
623       
624       const char *IDStart = LastEmitted;
625       char *IDEnd;
626       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
627       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
628         std::cerr << "Bad $ operand number in inline asm string: '" 
629                   << AsmStr << "'\n";
630         exit(1);
631       }
632       LastEmitted = IDEnd;
633       
634       char Modifier[2] = { 0, 0 };
635       
636       if (HasCurlyBraces) {
637         // If we have curly braces, check for a modifier character.  This
638         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
639         if (*LastEmitted == ':') {
640           ++LastEmitted;    // Consume ':' character.
641           if (*LastEmitted == 0) {
642             std::cerr << "Bad ${:} expression in inline asm string: '" 
643                       << AsmStr << "'\n";
644             exit(1);
645           }
646           
647           Modifier[0] = *LastEmitted;
648           ++LastEmitted;    // Consume modifier character.
649         }
650         
651         if (*LastEmitted != '}') {
652           std::cerr << "Bad ${} expression in inline asm string: '" 
653                     << AsmStr << "'\n";
654           exit(1);
655         }
656         ++LastEmitted;    // Consume '}' character.
657       }
658       
659       if ((unsigned)Val >= NumOperands-1) {
660         std::cerr << "Invalid $ operand number in inline asm string: '" 
661                   << AsmStr << "'\n";
662         exit(1);
663       }
664       
665       // Okay, we finally have a value number.  Ask the target to print this
666       // operand!
667       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
668         unsigned OpNo = 1;
669         
670         // Scan to find the machine operand number for the operand.
671         for (; Val; --Val) {
672           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
673           OpNo += (OpFlags >> 3) + 1;
674         }
675         
676         unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
677         ++OpNo;  // Skip over the ID number.
678
679         bool Error;
680         AsmPrinter *AP = const_cast<AsmPrinter*>(this);
681         if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
682           Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
683                                             Modifier[0] ? Modifier : 0);
684         } else {
685           Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
686                                       Modifier[0] ? Modifier : 0);
687         }
688         if (Error) {
689           std::cerr << "Invalid operand found in inline asm: '"
690                     << AsmStr << "'\n";
691           MI->dump();
692           exit(1);
693         }
694       }
695       break;
696     }
697     case '{':
698       ++LastEmitted;      // Consume '{' character.
699       if (CurVariant != -1) {
700         std::cerr << "Nested variants found in inline asm string: '"
701                   << AsmStr << "'\n";
702         exit(1);
703       }
704       CurVariant = 0;     // We're in the first variant now.
705       break;
706     case '|':
707       ++LastEmitted;  // consume '|' character.
708       if (CurVariant == -1) {
709         std::cerr << "Found '|' character outside of variant in inline asm "
710                   << "string: '" << AsmStr << "'\n";
711         exit(1);
712       }
713       ++CurVariant;   // We're in the next variant.
714       break;
715     case '}':
716       ++LastEmitted;  // consume '}' character.
717       if (CurVariant == -1) {
718         std::cerr << "Found '}' character outside of variant in inline asm "
719                   << "string: '" << AsmStr << "'\n";
720         exit(1);
721       }
722       CurVariant = -1;
723       break;
724     }
725   }
726   O << "\n\t" << InlineAsmEnd << "\n";
727 }
728
729 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
730 /// instruction, using the specified assembler variant.  Targets should
731 /// overried this to format as appropriate.
732 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
733                                  unsigned AsmVariant, const char *ExtraCode) {
734   // Target doesn't support this yet!
735   return true;
736 }
737
738 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
739                                        unsigned AsmVariant,
740                                        const char *ExtraCode) {
741   // Target doesn't support this yet!
742   return true;
743 }
744
745 /// printBasicBlockLabel - This method prints the label for the specified
746 /// MachineBasicBlock
747 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
748                                       bool printColon,
749                                       bool printComment) const {
750   O << PrivateGlobalPrefix << "BB" << FunctionNumber << "_"
751     << MBB->getNumber();
752   if (printColon)
753     O << ':';
754   if (printComment)
755     O << '\t' << CommentString << MBB->getBasicBlock()->getName();
756 }