Add support for ${:comment}, which expands to the current target's comment
[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/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include <iostream>
27 #include <cerrno>
28 using namespace llvm;
29
30 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
31                        const TargetAsmInfo *T)
32 : FunctionNumber(0), O(o), TM(tm), TAI(T)
33 {}
34
35
36 /// SwitchToTextSection - Switch to the specified text section of the executable
37 /// if we are not already in it!
38 ///
39 void AsmPrinter::SwitchToTextSection(const char *NewSection,
40                                      const GlobalValue *GV) {
41   std::string NS;
42   if (GV && GV->hasSection())
43     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
44   else
45     NS = NewSection;
46   
47   // If we're already in this section, we're done.
48   if (CurrentSection == NS) return;
49
50   // Close the current section, if applicable.
51   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
52     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
53
54   CurrentSection = NS;
55
56   if (!CurrentSection.empty())
57     O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
58 }
59
60 /// SwitchToDataSection - Switch to the specified data section of the executable
61 /// if we are not already in it!
62 ///
63 void AsmPrinter::SwitchToDataSection(const char *NewSection,
64                                      const GlobalValue *GV) {
65   std::string NS;
66   if (GV && GV->hasSection())
67     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
68   else
69     NS = NewSection;
70   
71   // If we're already in this section, we're done.
72   if (CurrentSection == NS) return;
73
74   // Close the current section, if applicable.
75   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
76     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
77
78   CurrentSection = NS;
79   
80   if (!CurrentSection.empty())
81     O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
82 }
83
84
85 bool AsmPrinter::doInitialization(Module &M) {
86   Mang = new Mangler(M, TAI->getGlobalPrefix());
87   
88   if (!M.getModuleInlineAsm().empty())
89     O << TAI->getCommentString() << " Start of file scope inline assembly\n"
90       << M.getModuleInlineAsm()
91       << "\n" << TAI->getCommentString()
92       << " End of file scope inline assembly\n";
93
94   SwitchToDataSection("", 0);   // Reset back to no section.
95   
96   if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
97     DebugInfo->AnalyzeModule(M);
98   }
99   
100   return false;
101 }
102
103 bool AsmPrinter::doFinalization(Module &M) {
104   delete Mang; Mang = 0;
105   return false;
106 }
107
108 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
109   // What's my mangled name?
110   CurrentFnName = Mang->getValueName(MF.getFunction());
111   IncrementFunctionNumber();
112 }
113
114 /// EmitConstantPool - Print to the current output stream assembly
115 /// representations of the constants in the constant pool MCP. This is
116 /// used to print out constants which have been "spilled to memory" by
117 /// the code generator.
118 ///
119 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
120   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
121   if (CP.empty()) return;
122
123   // Some targets require 4-, 8-, and 16- byte constant literals to be placed
124   // in special sections.
125   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
126   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
127   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
128   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
129   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
130   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
131     MachineConstantPoolEntry CPE = CP[i];
132     const Type *Ty = CPE.getType();
133     if (TAI->getFourByteConstantSection() &&
134         TM.getTargetData()->getTypeSize(Ty) == 4)
135       FourByteCPs.push_back(std::make_pair(CPE, i));
136     else if (TAI->getEightByteConstantSection() &&
137              TM.getTargetData()->getTypeSize(Ty) == 8)
138       EightByteCPs.push_back(std::make_pair(CPE, i));
139     else if (TAI->getSixteenByteConstantSection() &&
140              TM.getTargetData()->getTypeSize(Ty) == 16)
141       SixteenByteCPs.push_back(std::make_pair(CPE, i));
142     else
143       OtherCPs.push_back(std::make_pair(CPE, i));
144   }
145
146   unsigned Alignment = MCP->getConstantPoolAlignment();
147   EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
148   EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
149   EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
150                    SixteenByteCPs);
151   EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
152 }
153
154 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
155                std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
156   if (CP.empty()) return;
157
158   SwitchToDataSection(Section, 0);
159   EmitAlignment(Alignment);
160   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
161     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
162       << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
163     WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
164     if (CP[i].first.isMachineConstantPoolEntry())
165       EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
166      else
167       EmitGlobalConstant(CP[i].first.Val.ConstVal);
168     if (i != e-1) {
169       const Type *Ty = CP[i].first.getType();
170       unsigned EntSize =
171         TM.getTargetData()->getTypeSize(Ty);
172       unsigned ValEnd = CP[i].first.getOffset() + EntSize;
173       // Emit inter-object padding for alignment.
174       EmitZeros(CP[i+1].first.getOffset()-ValEnd);
175     }
176   }
177 }
178
179 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
180 /// by the current function to the current output stream.  
181 ///
182 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI) {
183   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
184   if (JT.empty()) return;
185   const TargetData *TD = TM.getTargetData();
186   
187   // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
188   // and 32 bits for PIC since PIC jump table entries are differences, not
189   // pointers to blocks.
190   // Use the architecture specific relocation directive, if it is set
191   const char *JTEntryDirective = TAI->getJumpTableDirective();
192   if (!JTEntryDirective)
193     JTEntryDirective = TAI->getData32bitsDirective();
194   
195   // Pick the directive to use to print the jump table entries, and switch to 
196   // the appropriate section.
197   if (TM.getRelocationModel() == Reloc::PIC_) {
198     SwitchToTextSection(TAI->getJumpTableTextSection(), 0);
199   } else {
200     SwitchToDataSection(TAI->getJumpTableDataSection(), 0);
201     if (TD->getPointerSize() == 8)
202       JTEntryDirective = TAI->getData64bitsDirective();
203   }
204   EmitAlignment(Log2_32(TD->getPointerAlignment()));
205   
206   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
207     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
208
209     // For PIC codegen, if possible we want to use the SetDirective to reduce
210     // the number of relocations the assembler will generate for the jump table.
211     // Set directives are all printed before the jump table itself.
212     std::set<MachineBasicBlock*> EmittedSets;
213     if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
214       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
215         if (EmittedSets.insert(JTBBs[ii]).second)
216           printSetLabel(i, JTBBs[ii]);
217     
218     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
219       << '_' << i << ":\n";
220     
221     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
222       O << JTEntryDirective << ' ';
223       // If we have emitted set directives for the jump table entries, print 
224       // them rather than the entries themselves.  If we're emitting PIC, then
225       // emit the table entries as differences between two text section labels.
226       // If we're emitting non-PIC code, then emit the entries as direct
227       // references to the target basic blocks.
228       if (!EmittedSets.empty()) {
229         O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
230           << '_' << i << "_set_" << JTBBs[ii]->getNumber();
231       } else if (TM.getRelocationModel() == Reloc::PIC_) {
232         printBasicBlockLabel(JTBBs[ii], false, false);
233         //If the arch uses custom Jump Table directives, don't calc relative to JT
234         if (!TAI->getJumpTableDirective()) 
235           O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
236             << getFunctionNumber() << '_' << i;
237       } else {
238         printBasicBlockLabel(JTBBs[ii], false, false);
239       }
240       O << '\n';
241     }
242   }
243 }
244
245 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
246 /// special global used by LLVM.  If so, emit it and return true, otherwise
247 /// do nothing and return false.
248 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
249   // Ignore debug and non-emitted data.
250   if (GV->getSection() == "llvm.metadata") return true;
251   
252   if (!GV->hasAppendingLinkage()) return false;
253
254   assert(GV->hasInitializer() && "Not a special LLVM global!");
255   
256   if (GV->getName() == "llvm.used") {
257     if (TAI->getUsedDirective() != 0)    // No need to emit this at all.
258       EmitLLVMUsedList(GV->getInitializer());
259     return true;
260   }
261
262   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
263     SwitchToDataSection(TAI->getStaticCtorsSection(), 0);
264     EmitAlignment(2, 0);
265     EmitXXStructorList(GV->getInitializer());
266     return true;
267   } 
268   
269   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
270     SwitchToDataSection(TAI->getStaticDtorsSection(), 0);
271     EmitAlignment(2, 0);
272     EmitXXStructorList(GV->getInitializer());
273     return true;
274   }
275   
276   return false;
277 }
278
279 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
280 /// global in the specified llvm.used list as being used with this directive.
281 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
282   const char *Directive = TAI->getUsedDirective();
283
284   // Should be an array of 'sbyte*'.
285   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
286   if (InitList == 0) return;
287   
288   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
289     O << Directive;
290     EmitConstantValueOnly(InitList->getOperand(i));
291     O << "\n";
292   }
293 }
294
295 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
296 /// function pointers, ignoring the init priority.
297 void AsmPrinter::EmitXXStructorList(Constant *List) {
298   // Should be an array of '{ int, void ()* }' structs.  The first value is the
299   // init priority, which we ignore.
300   if (!isa<ConstantArray>(List)) return;
301   ConstantArray *InitList = cast<ConstantArray>(List);
302   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
303     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
304       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
305
306       if (CS->getOperand(1)->isNullValue())
307         return;  // Found a null terminator, exit printing.
308       // Emit the function pointer.
309       EmitGlobalConstant(CS->getOperand(1));
310     }
311 }
312
313 /// getPreferredAlignmentLog - Return the preferred alignment of the
314 /// specified global, returned in log form.  This includes an explicitly
315 /// requested alignment (if the global has one).
316 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
317   const Type *ElemType = GV->getType()->getElementType();
318   unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(ElemType);
319   if (GV->getAlignment() > (1U << Alignment))
320     Alignment = Log2_32(GV->getAlignment());
321   
322   if (GV->hasInitializer()) {
323     // Always round up alignment of global doubles to 8 bytes.
324     if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
325       Alignment = 3;
326     if (Alignment < 4) {
327       // If the global is not external, see if it is large.  If so, give it a
328       // larger alignment.
329       if (TM.getTargetData()->getTypeSize(ElemType) > 128)
330         Alignment = 4;    // 16-byte alignment.
331     }
332   }
333   return Alignment;
334 }
335
336 // EmitAlignment - Emit an alignment directive to the specified power of two.
337 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
338   if (GV && GV->getAlignment())
339     NumBits = Log2_32(GV->getAlignment());
340   if (NumBits == 0) return;   // No need to emit alignment.
341   if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
342   O << TAI->getAlignDirective() << NumBits << "\n";
343 }
344
345 /// EmitZeros - Emit a block of zeros.
346 ///
347 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
348   if (NumZeros) {
349     if (TAI->getZeroDirective()) {
350       O << TAI->getZeroDirective() << NumZeros;
351       if (TAI->getZeroDirectiveSuffix())
352         O << TAI->getZeroDirectiveSuffix();
353       O << "\n";
354     } else {
355       for (; NumZeros; --NumZeros)
356         O << TAI->getData8bitsDirective() << "0\n";
357     }
358   }
359 }
360
361 // Print out the specified constant, without a storage class.  Only the
362 // constants valid in constant expressions can occur here.
363 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
364   if (CV->isNullValue() || isa<UndefValue>(CV))
365     O << "0";
366   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
367     assert(CB == ConstantBool::True);
368     O << "1";
369   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
370     if (((CI->getValue() << 32) >> 32) == CI->getValue())
371       O << CI->getValue();
372     else
373       O << (uint64_t)CI->getValue();
374   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
375     O << CI->getValue();
376   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
377     // This is a constant address for a global variable or function. Use the
378     // name of the variable or function as the address value, possibly
379     // decorating it with GlobalVarAddrPrefix/Suffix or
380     // FunctionAddrPrefix/Suffix (these all default to "" )
381     if (isa<Function>(GV)) {
382       O << TAI->getFunctionAddrPrefix()
383         << Mang->getValueName(GV)
384         << TAI->getFunctionAddrSuffix();
385     } else {
386       O << TAI->getGlobalVarAddrPrefix()
387         << Mang->getValueName(GV)
388         << TAI->getGlobalVarAddrSuffix();
389     }
390   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
391     const TargetData *TD = TM.getTargetData();
392     switch(CE->getOpcode()) {
393     case Instruction::GetElementPtr: {
394       // generate a symbolic expression for the byte address
395       const Constant *ptrVal = CE->getOperand(0);
396       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
397       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
398         if (Offset)
399           O << "(";
400         EmitConstantValueOnly(ptrVal);
401         if (Offset > 0)
402           O << ") + " << Offset;
403         else if (Offset < 0)
404           O << ") - " << -Offset;
405       } else {
406         EmitConstantValueOnly(ptrVal);
407       }
408       break;
409     }
410     case Instruction::Cast: {
411       // Support only foldable casts to/from pointers that can be eliminated by
412       // changing the pointer to the appropriately sized integer type.
413       Constant *Op = CE->getOperand(0);
414       const Type *OpTy = Op->getType(), *Ty = CE->getType();
415
416       // Handle casts to pointers by changing them into casts to the appropriate
417       // integer type.  This promotes constant folding and simplifies this code.
418       if (isa<PointerType>(Ty)) {
419         const Type *IntPtrTy = TD->getIntPtrType();
420         Op = ConstantExpr::getCast(Op, IntPtrTy);
421         return EmitConstantValueOnly(Op);
422       }
423       
424       // We know the dest type is not a pointer.  Is the src value a pointer or
425       // integral?
426       if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
427         // We can emit the pointer value into this slot if the slot is an
428         // integer slot greater or equal to the size of the pointer.
429         if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
430           return EmitConstantValueOnly(Op);
431       }
432       
433       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
434       EmitConstantValueOnly(Op);
435       break;
436     }
437     case Instruction::Add:
438       O << "(";
439       EmitConstantValueOnly(CE->getOperand(0));
440       O << ") + (";
441       EmitConstantValueOnly(CE->getOperand(1));
442       O << ")";
443       break;
444     default:
445       assert(0 && "Unsupported operator!");
446     }
447   } else {
448     assert(0 && "Unknown constant value!");
449   }
450 }
451
452 /// toOctal - Convert the low order bits of X into an octal digit.
453 ///
454 static inline char toOctal(int X) {
455   return (X&7)+'0';
456 }
457
458 /// printAsCString - Print the specified array as a C compatible string, only if
459 /// the predicate isString is true.
460 ///
461 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
462                            unsigned LastElt) {
463   assert(CVA->isString() && "Array is not string compatible!");
464
465   O << "\"";
466   for (unsigned i = 0; i != LastElt; ++i) {
467     unsigned char C =
468         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
469
470     if (C == '"') {
471       O << "\\\"";
472     } else if (C == '\\') {
473       O << "\\\\";
474     } else if (isprint(C)) {
475       O << C;
476     } else {
477       switch(C) {
478       case '\b': O << "\\b"; break;
479       case '\f': O << "\\f"; break;
480       case '\n': O << "\\n"; break;
481       case '\r': O << "\\r"; break;
482       case '\t': O << "\\t"; break;
483       default:
484         O << '\\';
485         O << toOctal(C >> 6);
486         O << toOctal(C >> 3);
487         O << toOctal(C >> 0);
488         break;
489       }
490     }
491   }
492   O << "\"";
493 }
494
495 /// EmitString - Emit a zero-byte-terminated string constant.
496 ///
497 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
498   unsigned NumElts = CVA->getNumOperands();
499   if (TAI->getAscizDirective() && NumElts && 
500       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
501     O << TAI->getAscizDirective();
502     printAsCString(O, CVA, NumElts-1);
503   } else {
504     O << TAI->getAsciiDirective();
505     printAsCString(O, CVA, NumElts);
506   }
507   O << "\n";
508 }
509
510 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
511 ///
512 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
513   const TargetData *TD = TM.getTargetData();
514
515   if (CV->isNullValue() || isa<UndefValue>(CV)) {
516     EmitZeros(TD->getTypeSize(CV->getType()));
517     return;
518   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
519     if (CVA->isString()) {
520       EmitString(CVA);
521     } else { // Not a string.  Print the values in successive locations
522       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
523         EmitGlobalConstant(CVA->getOperand(i));
524     }
525     return;
526   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
527     // Print the fields in successive locations. Pad to align if needed!
528     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
529     uint64_t sizeSoFar = 0;
530     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
531       const Constant* field = CVS->getOperand(i);
532
533       // Check if padding is needed and insert one or more 0s.
534       uint64_t fieldSize = TD->getTypeSize(field->getType());
535       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
536                            : cvsLayout->MemberOffsets[i+1])
537                           - cvsLayout->MemberOffsets[i]) - fieldSize;
538       sizeSoFar += fieldSize + padSize;
539
540       // Now print the actual field value
541       EmitGlobalConstant(field);
542
543       // Insert the field padding unless it's zero bytes...
544       EmitZeros(padSize);
545     }
546     assert(sizeSoFar == cvsLayout->StructSize &&
547            "Layout of constant struct may be incorrect!");
548     return;
549   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
550     // FP Constants are printed as integer constants to avoid losing
551     // precision...
552     double Val = CFP->getValue();
553     if (CFP->getType() == Type::DoubleTy) {
554       if (TAI->getData64bitsDirective())
555         O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
556           << TAI->getCommentString() << " double value: " << Val << "\n";
557       else if (TD->isBigEndian()) {
558         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
559           << "\t" << TAI->getCommentString()
560           << " double most significant word " << Val << "\n";
561         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
562           << "\t" << TAI->getCommentString()
563           << " double least significant word " << Val << "\n";
564       } else {
565         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
566           << "\t" << TAI->getCommentString()
567           << " double least significant word " << Val << "\n";
568         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
569           << "\t" << TAI->getCommentString()
570           << " double most significant word " << Val << "\n";
571       }
572       return;
573     } else {
574       O << TAI->getData32bitsDirective() << FloatToBits(Val)
575         << "\t" << TAI->getCommentString() << " float " << Val << "\n";
576       return;
577     }
578   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
579     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
580       uint64_t Val = CI->getRawValue();
581
582       if (TAI->getData64bitsDirective())
583         O << TAI->getData64bitsDirective() << Val << "\n";
584       else if (TD->isBigEndian()) {
585         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
586           << "\t" << TAI->getCommentString()
587           << " Double-word most significant word " << Val << "\n";
588         O << TAI->getData32bitsDirective() << unsigned(Val)
589           << "\t" << TAI->getCommentString()
590           << " Double-word least significant word " << Val << "\n";
591       } else {
592         O << TAI->getData32bitsDirective() << unsigned(Val)
593           << "\t" << TAI->getCommentString()
594           << " Double-word least significant word " << Val << "\n";
595         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
596           << "\t" << TAI->getCommentString()
597           << " Double-word most significant word " << Val << "\n";
598       }
599       return;
600     }
601   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
602     const PackedType *PTy = CP->getType();
603     
604     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
605       EmitGlobalConstant(CP->getOperand(I));
606     
607     return;
608   }
609
610   const Type *type = CV->getType();
611   printDataDirective(type);
612   EmitConstantValueOnly(CV);
613   O << "\n";
614 }
615
616 void
617 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
618   // Target doesn't support this yet!
619   abort();
620 }
621
622 /// PrintSpecial - Print information related to the specified machine instr
623 /// that is independent of the operand, and may be independent of the instr
624 /// itself.  This can be useful for portably encoding the comment character
625 /// or other bits of target-specific knowledge into the asmstrings.  The
626 /// syntax used is ${:comment}.  Targets can override this to add support
627 /// for their own strange codes.
628 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
629   if (!strcmp(Code, "comment")) {
630     O << TAI->getCommentString();
631   } else if (!strcmp(Code, "uid")) {
632     // Assign a unique ID to this machine instruction.
633     static const MachineInstr *LastMI = 0;
634     static unsigned Counter = 0U-1;
635     // If this is a new machine instruction, bump the counter.
636     if (LastMI != MI) { ++Counter; LastMI = MI; }
637     O << Counter;
638   } else {
639     std::cerr << "Unknown special formatter '" << Code
640               << "' for machine instr: " << *MI;
641     exit(1);
642   }    
643 }
644
645
646 /// printInlineAsm - This method formats and prints the specified machine
647 /// instruction that is an inline asm.
648 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
649   unsigned NumOperands = MI->getNumOperands();
650   
651   // Count the number of register definitions.
652   unsigned NumDefs = 0;
653   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
654        ++NumDefs)
655     assert(NumDefs != NumOperands-1 && "No asm string?");
656   
657   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
658
659   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
660   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
661
662   // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
663   if (AsmStr[0] == 0) {
664     O << "\n";  // Tab already printed, avoid double indenting next instr.
665     return;
666   }
667   
668   O << TAI->getInlineAsmStart() << "\n\t";
669
670   // The variant of the current asmprinter: FIXME: change.
671   int AsmPrinterVariant = 0;
672   
673   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
674   const char *LastEmitted = AsmStr; // One past the last character emitted.
675   
676   while (*LastEmitted) {
677     switch (*LastEmitted) {
678     default: {
679       // Not a special case, emit the string section literally.
680       const char *LiteralEnd = LastEmitted+1;
681       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
682              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
683         ++LiteralEnd;
684       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
685         O.write(LastEmitted, LiteralEnd-LastEmitted);
686       LastEmitted = LiteralEnd;
687       break;
688     }
689     case '\n':
690       ++LastEmitted;   // Consume newline character.
691       O << "\n\t";     // Indent code with newline.
692       break;
693     case '$': {
694       ++LastEmitted;   // Consume '$' character.
695       if (*LastEmitted == '$') { // $$ -> $
696         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
697           O << '$';
698         ++LastEmitted;  // Consume second '$' character.
699         break;
700       }
701       
702       bool HasCurlyBraces = false;
703       if (*LastEmitted == '{') {     // ${variable}
704         ++LastEmitted;               // Consume '{' character.
705         HasCurlyBraces = true;
706       }
707       
708       const char *IDStart = LastEmitted;
709       char *IDEnd;
710       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
711       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
712         std::cerr << "Bad $ operand number in inline asm string: '" 
713                   << AsmStr << "'\n";
714         exit(1);
715       }
716       LastEmitted = IDEnd;
717       
718       char Modifier[2] = { 0, 0 };
719       
720       if (HasCurlyBraces) {
721         // If we have curly braces, check for a modifier character.  This
722         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
723         if (*LastEmitted == ':') {
724           ++LastEmitted;    // Consume ':' character.
725           if (*LastEmitted == 0) {
726             std::cerr << "Bad ${:} expression in inline asm string: '" 
727                       << AsmStr << "'\n";
728             exit(1);
729           }
730           
731           Modifier[0] = *LastEmitted;
732           ++LastEmitted;    // Consume modifier character.
733         }
734         
735         if (*LastEmitted != '}') {
736           std::cerr << "Bad ${} expression in inline asm string: '" 
737                     << AsmStr << "'\n";
738           exit(1);
739         }
740         ++LastEmitted;    // Consume '}' character.
741       }
742       
743       if ((unsigned)Val >= NumOperands-1) {
744         std::cerr << "Invalid $ operand number in inline asm string: '" 
745                   << AsmStr << "'\n";
746         exit(1);
747       }
748       
749       // Okay, we finally have a value number.  Ask the target to print this
750       // operand!
751       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
752         unsigned OpNo = 1;
753
754         bool Error = false;
755
756         // Scan to find the machine operand number for the operand.
757         for (; Val; --Val) {
758           if (OpNo >= MI->getNumOperands()) break;
759           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
760           OpNo += (OpFlags >> 3) + 1;
761         }
762
763         if (OpNo >= MI->getNumOperands()) {
764           Error = true;
765         } else {
766           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
767           ++OpNo;  // Skip over the ID number.
768
769           AsmPrinter *AP = const_cast<AsmPrinter*>(this);
770           if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
771             Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
772                                               Modifier[0] ? Modifier : 0);
773           } else {
774             Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
775                                         Modifier[0] ? Modifier : 0);
776           }
777         }
778         if (Error) {
779           std::cerr << "Invalid operand found in inline asm: '"
780                     << AsmStr << "'\n";
781           MI->dump();
782           exit(1);
783         }
784       }
785       break;
786     }
787     case '{':
788       ++LastEmitted;      // Consume '{' character.
789       if (CurVariant != -1) {
790         std::cerr << "Nested variants found in inline asm string: '"
791                   << AsmStr << "'\n";
792         exit(1);
793       }
794       CurVariant = 0;     // We're in the first variant now.
795       break;
796     case '|':
797       ++LastEmitted;  // consume '|' character.
798       if (CurVariant == -1) {
799         std::cerr << "Found '|' character outside of variant in inline asm "
800                   << "string: '" << AsmStr << "'\n";
801         exit(1);
802       }
803       ++CurVariant;   // We're in the next variant.
804       break;
805     case '}':
806       ++LastEmitted;  // consume '}' character.
807       if (CurVariant == -1) {
808         std::cerr << "Found '}' character outside of variant in inline asm "
809                   << "string: '" << AsmStr << "'\n";
810         exit(1);
811       }
812       CurVariant = -1;
813       break;
814     }
815   }
816   O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
817 }
818
819 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
820 /// instruction, using the specified assembler variant.  Targets should
821 /// overried this to format as appropriate.
822 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
823                                  unsigned AsmVariant, const char *ExtraCode) {
824   // Target doesn't support this yet!
825   return true;
826 }
827
828 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
829                                        unsigned AsmVariant,
830                                        const char *ExtraCode) {
831   // Target doesn't support this yet!
832   return true;
833 }
834
835 /// printBasicBlockLabel - This method prints the label for the specified
836 /// MachineBasicBlock
837 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
838                                       bool printColon,
839                                       bool printComment) const {
840   O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
841     << MBB->getNumber();
842   if (printColon)
843     O << ':';
844   if (printComment)
845     O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
846 }
847
848 /// printSetLabel - This method prints a set label for the specified
849 /// MachineBasicBlock
850 void AsmPrinter::printSetLabel(unsigned uid, 
851                                const MachineBasicBlock *MBB) const {
852   if (!TAI->getSetDirective())
853     return;
854   
855   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
856     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
857   printBasicBlockLabel(MBB, false, false);
858   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
859     << '_' << uid << '\n';
860 }
861
862 /// printDataDirective - This method prints the asm directive for the
863 /// specified type.
864 void AsmPrinter::printDataDirective(const Type *type) {
865   const TargetData *TD = TM.getTargetData();
866   switch (type->getTypeID()) {
867   case Type::BoolTyID:
868   case Type::UByteTyID: case Type::SByteTyID:
869     O << TAI->getData8bitsDirective();
870     break;
871   case Type::UShortTyID: case Type::ShortTyID:
872     O << TAI->getData16bitsDirective();
873     break;
874   case Type::PointerTyID:
875     if (TD->getPointerSize() == 8) {
876       assert(TAI->getData64bitsDirective() &&
877              "Target cannot handle 64-bit pointer exprs!");
878       O << TAI->getData64bitsDirective();
879       break;
880     }
881     //Fall through for pointer size == int size
882   case Type::UIntTyID: case Type::IntTyID:
883     O << TAI->getData32bitsDirective();
884     break;
885   case Type::ULongTyID: case Type::LongTyID:
886     assert(TAI->getData64bitsDirective() &&
887            "Target cannot handle 64-bit constant exprs!");
888     O << TAI->getData64bitsDirective();
889     break;
890   case Type::FloatTyID: case Type::DoubleTyID:
891     assert (0 && "Should have already output floating point constant.");
892   default:
893     assert (0 && "Can't handle printing this type of thing");
894     break;
895   }
896 }