add a method to remove a line # record.
[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("", 0);   // 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, 0);
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(), 0);
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(), 0);
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     // For PIC codegen, if possible we want to use the SetDirective to reduce
226     // the number of relocations the assembler will generate for the jump table.
227     // Set directives are all printed before the jump table itself.
228     std::set<MachineBasicBlock*> EmittedSets;
229     if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
230       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
231         if (EmittedSets.insert(JTBBs[ii]).second)
232           printSetLabel(i, JTBBs[ii]);
233     
234     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
235       << '_' << i << ":\n";
236     
237     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
238       O << JTEntryDirective << ' ';
239       // If we have emitted set directives for the jump table entries, print 
240       // them rather than the entries themselves.  If we're emitting PIC, then
241       // emit the table entries as differences between two text section labels.
242       // If we're emitting non-PIC code, then emit the entries as direct
243       // references to the target basic blocks.
244       if (!EmittedSets.empty()) {
245         O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
246           << '_' << i << "_set_" << JTBBs[ii]->getNumber();
247       } else if (TM.getRelocationModel() == Reloc::PIC_) {
248         printBasicBlockLabel(JTBBs[ii], false, false);
249         //If the arch uses custom Jump Table directives, don't calc relative to JT
250         if (!TAI->getJumpTableDirective()) 
251           O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
252             << getFunctionNumber() << '_' << i;
253       } else {
254         printBasicBlockLabel(JTBBs[ii], false, false);
255       }
256       O << '\n';
257     }
258   }
259 }
260
261 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
262 /// special global used by LLVM.  If so, emit it and return true, otherwise
263 /// do nothing and return false.
264 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
265   // Ignore debug and non-emitted data.
266   if (GV->getSection() == "llvm.metadata") return true;
267   
268   if (!GV->hasAppendingLinkage()) return false;
269
270   assert(GV->hasInitializer() && "Not a special LLVM global!");
271   
272   if (GV->getName() == "llvm.used") {
273     if (TAI->getUsedDirective() != 0)    // No need to emit this at all.
274       EmitLLVMUsedList(GV->getInitializer());
275     return true;
276   }
277
278   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
279     SwitchToDataSection(TAI->getStaticCtorsSection(), 0);
280     EmitAlignment(2, 0);
281     EmitXXStructorList(GV->getInitializer());
282     return true;
283   } 
284   
285   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
286     SwitchToDataSection(TAI->getStaticDtorsSection(), 0);
287     EmitAlignment(2, 0);
288     EmitXXStructorList(GV->getInitializer());
289     return true;
290   }
291   
292   return false;
293 }
294
295 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
296 /// global in the specified llvm.used list as being used with this directive.
297 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
298   const char *Directive = TAI->getUsedDirective();
299
300   // Should be an array of 'sbyte*'.
301   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
302   if (InitList == 0) return;
303   
304   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
305     O << Directive;
306     EmitConstantValueOnly(InitList->getOperand(i));
307     O << "\n";
308   }
309 }
310
311 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
312 /// function pointers, ignoring the init priority.
313 void AsmPrinter::EmitXXStructorList(Constant *List) {
314   // Should be an array of '{ int, void ()* }' structs.  The first value is the
315   // init priority, which we ignore.
316   if (!isa<ConstantArray>(List)) return;
317   ConstantArray *InitList = cast<ConstantArray>(List);
318   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
319     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
320       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
321
322       if (CS->getOperand(1)->isNullValue())
323         return;  // Found a null terminator, exit printing.
324       // Emit the function pointer.
325       EmitGlobalConstant(CS->getOperand(1));
326     }
327 }
328
329 /// getPreferredAlignmentLog - Return the preferred alignment of the
330 /// specified global, returned in log form.  This includes an explicitly
331 /// requested alignment (if the global has one).
332 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
333   const Type *ElemType = GV->getType()->getElementType();
334   unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(ElemType);
335   if (GV->getAlignment() > (1U << Alignment))
336     Alignment = Log2_32(GV->getAlignment());
337   
338   if (GV->hasInitializer()) {
339     // Always round up alignment of global doubles to 8 bytes.
340     if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
341       Alignment = 3;
342     if (Alignment < 4) {
343       // If the global is not external, see if it is large.  If so, give it a
344       // larger alignment.
345       if (TM.getTargetData()->getTypeSize(ElemType) > 128)
346         Alignment = 4;    // 16-byte alignment.
347     }
348   }
349   return Alignment;
350 }
351
352 /// getGlobalLinkName - Returns the asm/link name of of the specified
353 /// global variable.  Should be overridden by each target asm printer to
354 /// generate the appropriate value.
355 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
356   std::string LinkName;
357   // Default action is to use a global symbol.                              
358   LinkName = TAI->getGlobalPrefix();
359   LinkName += GV->getName();
360   return LinkName;
361 }
362
363 // EmitAlignment - Emit an alignment directive to the specified power of two.
364 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
365   if (GV && GV->getAlignment())
366     NumBits = Log2_32(GV->getAlignment());
367   if (NumBits == 0) return;   // No need to emit alignment.
368   if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
369   O << TAI->getAlignDirective() << NumBits << "\n";
370 }
371
372 /// EmitZeros - Emit a block of zeros.
373 ///
374 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
375   if (NumZeros) {
376     if (TAI->getZeroDirective()) {
377       O << TAI->getZeroDirective() << NumZeros;
378       if (TAI->getZeroDirectiveSuffix())
379         O << TAI->getZeroDirectiveSuffix();
380       O << "\n";
381     } else {
382       for (; NumZeros; --NumZeros)
383         O << TAI->getData8bitsDirective() << "0\n";
384     }
385   }
386 }
387
388 // Print out the specified constant, without a storage class.  Only the
389 // constants valid in constant expressions can occur here.
390 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
391   if (CV->isNullValue() || isa<UndefValue>(CV))
392     O << "0";
393   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
394     assert(CB->getValue());
395     O << "1";
396   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
397     if (((CI->getValue() << 32) >> 32) == CI->getValue())
398       O << CI->getValue();
399     else
400       O << (uint64_t)CI->getValue();
401   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
402     O << CI->getValue();
403   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
404     // This is a constant address for a global variable or function. Use the
405     // name of the variable or function as the address value, possibly
406     // decorating it with GlobalVarAddrPrefix/Suffix or
407     // FunctionAddrPrefix/Suffix (these all default to "" )
408     if (isa<Function>(GV)) {
409       O << TAI->getFunctionAddrPrefix()
410         << Mang->getValueName(GV)
411         << TAI->getFunctionAddrSuffix();
412     } else {
413       O << TAI->getGlobalVarAddrPrefix()
414         << Mang->getValueName(GV)
415         << TAI->getGlobalVarAddrSuffix();
416     }
417   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
418     const TargetData *TD = TM.getTargetData();
419     switch(CE->getOpcode()) {
420     case Instruction::GetElementPtr: {
421       // generate a symbolic expression for the byte address
422       const Constant *ptrVal = CE->getOperand(0);
423       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
424       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
425         if (Offset)
426           O << "(";
427         EmitConstantValueOnly(ptrVal);
428         if (Offset > 0)
429           O << ") + " << Offset;
430         else if (Offset < 0)
431           O << ") - " << -Offset;
432       } else {
433         EmitConstantValueOnly(ptrVal);
434       }
435       break;
436     }
437     case Instruction::Cast: {
438       // Support only foldable casts to/from pointers that can be eliminated by
439       // changing the pointer to the appropriately sized integer type.
440       Constant *Op = CE->getOperand(0);
441       const Type *OpTy = Op->getType(), *Ty = CE->getType();
442
443       // Handle casts to pointers by changing them into casts to the appropriate
444       // integer type.  This promotes constant folding and simplifies this code.
445       if (isa<PointerType>(Ty)) {
446         const Type *IntPtrTy = TD->getIntPtrType();
447         Op = ConstantExpr::getCast(Op, IntPtrTy);
448         return EmitConstantValueOnly(Op);
449       }
450       
451       // We know the dest type is not a pointer.  Is the src value a pointer or
452       // integral?
453       if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
454         // We can emit the pointer value into this slot if the slot is an
455         // integer slot greater or equal to the size of the pointer.
456         if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
457           return EmitConstantValueOnly(Op);
458       }
459       
460       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
461       EmitConstantValueOnly(Op);
462       break;
463     }
464     case Instruction::Add:
465       O << "(";
466       EmitConstantValueOnly(CE->getOperand(0));
467       O << ") + (";
468       EmitConstantValueOnly(CE->getOperand(1));
469       O << ")";
470       break;
471     default:
472       assert(0 && "Unsupported operator!");
473     }
474   } else {
475     assert(0 && "Unknown constant value!");
476   }
477 }
478
479 /// toOctal - Convert the low order bits of X into an octal digit.
480 ///
481 static inline char toOctal(int X) {
482   return (X&7)+'0';
483 }
484
485 /// printAsCString - Print the specified array as a C compatible string, only if
486 /// the predicate isString is true.
487 ///
488 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
489                            unsigned LastElt) {
490   assert(CVA->isString() && "Array is not string compatible!");
491
492   O << "\"";
493   for (unsigned i = 0; i != LastElt; ++i) {
494     unsigned char C =
495         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
496
497     if (C == '"') {
498       O << "\\\"";
499     } else if (C == '\\') {
500       O << "\\\\";
501     } else if (isprint(C)) {
502       O << C;
503     } else {
504       switch(C) {
505       case '\b': O << "\\b"; break;
506       case '\f': O << "\\f"; break;
507       case '\n': O << "\\n"; break;
508       case '\r': O << "\\r"; break;
509       case '\t': O << "\\t"; break;
510       default:
511         O << '\\';
512         O << toOctal(C >> 6);
513         O << toOctal(C >> 3);
514         O << toOctal(C >> 0);
515         break;
516       }
517     }
518   }
519   O << "\"";
520 }
521
522 /// EmitString - Emit a zero-byte-terminated string constant.
523 ///
524 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
525   unsigned NumElts = CVA->getNumOperands();
526   if (TAI->getAscizDirective() && NumElts && 
527       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
528     O << TAI->getAscizDirective();
529     printAsCString(O, CVA, NumElts-1);
530   } else {
531     O << TAI->getAsciiDirective();
532     printAsCString(O, CVA, NumElts);
533   }
534   O << "\n";
535 }
536
537 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
538 ///
539 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
540   const TargetData *TD = TM.getTargetData();
541
542   if (CV->isNullValue() || isa<UndefValue>(CV)) {
543     EmitZeros(TD->getTypeSize(CV->getType()));
544     return;
545   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
546     if (CVA->isString()) {
547       EmitString(CVA);
548     } else { // Not a string.  Print the values in successive locations
549       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
550         EmitGlobalConstant(CVA->getOperand(i));
551     }
552     return;
553   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
554     // Print the fields in successive locations. Pad to align if needed!
555     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
556     uint64_t sizeSoFar = 0;
557     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
558       const Constant* field = CVS->getOperand(i);
559
560       // Check if padding is needed and insert one or more 0s.
561       uint64_t fieldSize = TD->getTypeSize(field->getType());
562       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
563                            : cvsLayout->MemberOffsets[i+1])
564                           - cvsLayout->MemberOffsets[i]) - fieldSize;
565       sizeSoFar += fieldSize + padSize;
566
567       // Now print the actual field value
568       EmitGlobalConstant(field);
569
570       // Insert the field padding unless it's zero bytes...
571       EmitZeros(padSize);
572     }
573     assert(sizeSoFar == cvsLayout->StructSize &&
574            "Layout of constant struct may be incorrect!");
575     return;
576   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
577     // FP Constants are printed as integer constants to avoid losing
578     // precision...
579     double Val = CFP->getValue();
580     if (CFP->getType() == Type::DoubleTy) {
581       if (TAI->getData64bitsDirective())
582         O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
583           << TAI->getCommentString() << " double value: " << Val << "\n";
584       else if (TD->isBigEndian()) {
585         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
586           << "\t" << TAI->getCommentString()
587           << " double most significant word " << Val << "\n";
588         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
589           << "\t" << TAI->getCommentString()
590           << " double least significant word " << Val << "\n";
591       } else {
592         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
593           << "\t" << TAI->getCommentString()
594           << " double least significant word " << Val << "\n";
595         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
596           << "\t" << TAI->getCommentString()
597           << " double most significant word " << Val << "\n";
598       }
599       return;
600     } else {
601       O << TAI->getData32bitsDirective() << FloatToBits(Val)
602         << "\t" << TAI->getCommentString() << " float " << Val << "\n";
603       return;
604     }
605   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
606     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
607       uint64_t Val = CI->getRawValue();
608
609       if (TAI->getData64bitsDirective())
610         O << TAI->getData64bitsDirective() << Val << "\n";
611       else if (TD->isBigEndian()) {
612         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
613           << "\t" << TAI->getCommentString()
614           << " Double-word most significant word " << Val << "\n";
615         O << TAI->getData32bitsDirective() << unsigned(Val)
616           << "\t" << TAI->getCommentString()
617           << " Double-word least significant word " << Val << "\n";
618       } else {
619         O << TAI->getData32bitsDirective() << unsigned(Val)
620           << "\t" << TAI->getCommentString()
621           << " Double-word least significant word " << Val << "\n";
622         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
623           << "\t" << TAI->getCommentString()
624           << " Double-word most significant word " << Val << "\n";
625       }
626       return;
627     }
628   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
629     const PackedType *PTy = CP->getType();
630     
631     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
632       EmitGlobalConstant(CP->getOperand(I));
633     
634     return;
635   }
636
637   const Type *type = CV->getType();
638   printDataDirective(type);
639   EmitConstantValueOnly(CV);
640   O << "\n";
641 }
642
643 void
644 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
645   // Target doesn't support this yet!
646   abort();
647 }
648
649 /// PrintSpecial - Print information related to the specified machine instr
650 /// that is independent of the operand, and may be independent of the instr
651 /// itself.  This can be useful for portably encoding the comment character
652 /// or other bits of target-specific knowledge into the asmstrings.  The
653 /// syntax used is ${:comment}.  Targets can override this to add support
654 /// for their own strange codes.
655 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
656   if (!strcmp(Code, "private")) {
657     O << TAI->getPrivateGlobalPrefix();
658   } else if (!strcmp(Code, "comment")) {
659     O << TAI->getCommentString();
660   } else if (!strcmp(Code, "uid")) {
661     // Assign a unique ID to this machine instruction.
662     static const MachineInstr *LastMI = 0;
663     static unsigned Counter = 0U-1;
664     // If this is a new machine instruction, bump the counter.
665     if (LastMI != MI) { ++Counter; LastMI = MI; }
666     O << Counter;
667   } else {
668     std::cerr << "Unknown special formatter '" << Code
669               << "' for machine instr: " << *MI;
670     exit(1);
671   }    
672 }
673
674
675 /// printInlineAsm - This method formats and prints the specified machine
676 /// instruction that is an inline asm.
677 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
678   unsigned NumOperands = MI->getNumOperands();
679   
680   // Count the number of register definitions.
681   unsigned NumDefs = 0;
682   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
683        ++NumDefs)
684     assert(NumDefs != NumOperands-1 && "No asm string?");
685   
686   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
687
688   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
689   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
690
691   // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
692   if (AsmStr[0] == 0) {
693     O << "\n";  // Tab already printed, avoid double indenting next instr.
694     return;
695   }
696   
697   O << TAI->getInlineAsmStart() << "\n\t";
698
699   // The variant of the current asmprinter: FIXME: change.
700   int AsmPrinterVariant = 0;
701   
702   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
703   const char *LastEmitted = AsmStr; // One past the last character emitted.
704   
705   while (*LastEmitted) {
706     switch (*LastEmitted) {
707     default: {
708       // Not a special case, emit the string section literally.
709       const char *LiteralEnd = LastEmitted+1;
710       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
711              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
712         ++LiteralEnd;
713       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
714         O.write(LastEmitted, LiteralEnd-LastEmitted);
715       LastEmitted = LiteralEnd;
716       break;
717     }
718     case '\n':
719       ++LastEmitted;   // Consume newline character.
720       O << "\n\t";     // Indent code with newline.
721       break;
722     case '$': {
723       ++LastEmitted;   // Consume '$' character.
724       bool Done = true;
725
726       // Handle escapes.
727       switch (*LastEmitted) {
728       default: Done = false; break;
729       case '$':     // $$ -> $
730         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
731           O << '$';
732         ++LastEmitted;  // Consume second '$' character.
733         break;
734       case '(':             // $( -> same as GCC's { character.
735         ++LastEmitted;      // Consume '(' character.
736         if (CurVariant != -1) {
737           std::cerr << "Nested variants found in inline asm string: '"
738           << AsmStr << "'\n";
739           exit(1);
740         }
741         CurVariant = 0;     // We're in the first variant now.
742         break;
743       case '|':
744         ++LastEmitted;  // consume '|' character.
745         if (CurVariant == -1) {
746           std::cerr << "Found '|' character outside of variant in inline asm "
747           << "string: '" << AsmStr << "'\n";
748           exit(1);
749         }
750         ++CurVariant;   // We're in the next variant.
751         break;
752       case ')':         // $) -> same as GCC's } char.
753         ++LastEmitted;  // consume ')' character.
754         if (CurVariant == -1) {
755           std::cerr << "Found '}' character outside of variant in inline asm "
756                     << "string: '" << AsmStr << "'\n";
757           exit(1);
758         }
759         CurVariant = -1;
760         break;
761       }
762       if (Done) break;
763       
764       bool HasCurlyBraces = false;
765       if (*LastEmitted == '{') {     // ${variable}
766         ++LastEmitted;               // Consume '{' character.
767         HasCurlyBraces = true;
768       }
769       
770       const char *IDStart = LastEmitted;
771       char *IDEnd;
772       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
773       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
774         std::cerr << "Bad $ operand number in inline asm string: '" 
775                   << AsmStr << "'\n";
776         exit(1);
777       }
778       LastEmitted = IDEnd;
779       
780       char Modifier[2] = { 0, 0 };
781       
782       if (HasCurlyBraces) {
783         // If we have curly braces, check for a modifier character.  This
784         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
785         if (*LastEmitted == ':') {
786           ++LastEmitted;    // Consume ':' character.
787           if (*LastEmitted == 0) {
788             std::cerr << "Bad ${:} expression in inline asm string: '" 
789                       << AsmStr << "'\n";
790             exit(1);
791           }
792           
793           Modifier[0] = *LastEmitted;
794           ++LastEmitted;    // Consume modifier character.
795         }
796         
797         if (*LastEmitted != '}') {
798           std::cerr << "Bad ${} expression in inline asm string: '" 
799                     << AsmStr << "'\n";
800           exit(1);
801         }
802         ++LastEmitted;    // Consume '}' character.
803       }
804       
805       if ((unsigned)Val >= NumOperands-1) {
806         std::cerr << "Invalid $ operand number in inline asm string: '" 
807                   << AsmStr << "'\n";
808         exit(1);
809       }
810       
811       // Okay, we finally have a value number.  Ask the target to print this
812       // operand!
813       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
814         unsigned OpNo = 1;
815
816         bool Error = false;
817
818         // Scan to find the machine operand number for the operand.
819         for (; Val; --Val) {
820           if (OpNo >= MI->getNumOperands()) break;
821           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
822           OpNo += (OpFlags >> 3) + 1;
823         }
824
825         if (OpNo >= MI->getNumOperands()) {
826           Error = true;
827         } else {
828           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
829           ++OpNo;  // Skip over the ID number.
830
831           AsmPrinter *AP = const_cast<AsmPrinter*>(this);
832           if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
833             Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
834                                               Modifier[0] ? Modifier : 0);
835           } else {
836             Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
837                                         Modifier[0] ? Modifier : 0);
838           }
839         }
840         if (Error) {
841           std::cerr << "Invalid operand found in inline asm: '"
842                     << AsmStr << "'\n";
843           MI->dump();
844           exit(1);
845         }
846       }
847       break;
848     }
849     }
850   }
851   O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
852 }
853
854 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
855 /// instruction, using the specified assembler variant.  Targets should
856 /// overried this to format as appropriate.
857 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
858                                  unsigned AsmVariant, const char *ExtraCode) {
859   // Target doesn't support this yet!
860   return true;
861 }
862
863 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
864                                        unsigned AsmVariant,
865                                        const char *ExtraCode) {
866   // Target doesn't support this yet!
867   return true;
868 }
869
870 /// printBasicBlockLabel - This method prints the label for the specified
871 /// MachineBasicBlock
872 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
873                                       bool printColon,
874                                       bool printComment) const {
875   O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
876     << MBB->getNumber();
877   if (printColon)
878     O << ':';
879   if (printComment && MBB->getBasicBlock())
880     O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
881 }
882
883 /// printSetLabel - This method prints a set label for the specified
884 /// MachineBasicBlock
885 void AsmPrinter::printSetLabel(unsigned uid, 
886                                const MachineBasicBlock *MBB) const {
887   if (!TAI->getSetDirective())
888     return;
889   
890   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
891     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
892   printBasicBlockLabel(MBB, false, false);
893   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
894     << '_' << uid << '\n';
895 }
896
897 /// printDataDirective - This method prints the asm directive for the
898 /// specified type.
899 void AsmPrinter::printDataDirective(const Type *type) {
900   const TargetData *TD = TM.getTargetData();
901   switch (type->getTypeID()) {
902   case Type::BoolTyID:
903   case Type::UByteTyID: case Type::SByteTyID:
904     O << TAI->getData8bitsDirective();
905     break;
906   case Type::UShortTyID: case Type::ShortTyID:
907     O << TAI->getData16bitsDirective();
908     break;
909   case Type::PointerTyID:
910     if (TD->getPointerSize() == 8) {
911       assert(TAI->getData64bitsDirective() &&
912              "Target cannot handle 64-bit pointer exprs!");
913       O << TAI->getData64bitsDirective();
914       break;
915     }
916     //Fall through for pointer size == int size
917   case Type::UIntTyID: case Type::IntTyID:
918     O << TAI->getData32bitsDirective();
919     break;
920   case Type::ULongTyID: case Type::LongTyID:
921     assert(TAI->getData64bitsDirective() &&
922            "Target cannot handle 64-bit constant exprs!");
923     O << TAI->getData64bitsDirective();
924     break;
925   case Type::FloatTyID: case Type::DoubleTyID:
926     assert (0 && "Should have already output floating point constant.");
927   default:
928     assert (0 && "Can't handle printing this type of thing");
929     break;
930   }
931 }