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