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