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