Use higher level methods, don't use TargetInstrDescriptors directly!
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
2 //
3 // This file implements all of the stuff neccesary to output a .s file from
4 // LLVM.  The code in this file assumes that the specified module has already
5 // been compiled into the internal data structures of the Module.
6 //
7 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
8 // The FunctionPass is pipelined together with all of the rest of the code
9 // generation stages, and the Pass runs at the end to emit code for global
10 // variables and such.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcInternals.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "Support/StringExtras.h"
24 using std::string;
25
26 namespace {
27
28 class GlobalIdTable: public Annotation {
29   static AnnotationID AnnotId;
30   friend class AsmPrinter;              // give access to AnnotId
31   
32   typedef hash_map<const Value*, int> ValIdMap;
33   typedef ValIdMap::const_iterator ValIdMapConstIterator;
34   typedef ValIdMap::      iterator ValIdMapIterator;
35 public:
36   SlotCalculator Table;    // map anonymous values to unique integer IDs
37   ValIdMap valToIdMap;     // used for values not handled by SlotCalculator 
38   
39   GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
40 };
41
42 AnnotationID GlobalIdTable::AnnotId =
43   AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
44   
45 //===---------------------------------------------------------------------===//
46 //   Code Shared By the two printer passes, as a mixin
47 //===---------------------------------------------------------------------===//
48
49 class AsmPrinter {
50   GlobalIdTable* idTable;
51 public:
52   std::ostream &toAsm;
53   const TargetMachine &Target;
54   
55   enum Sections {
56     Unknown,
57     Text,
58     ReadOnlyData,
59     InitRWData,
60     ZeroInitRWData,
61   } CurSection;
62
63   AsmPrinter(std::ostream &os, const TargetMachine &T)
64     : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
65   
66   // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
67   void startModule(Module &M) {
68     // Create the global id table if it does not already exist
69     idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
70     if (idTable == NULL) {
71       idTable = new GlobalIdTable(&M);
72       M.addAnnotation(idTable);
73     }
74   }
75   void startFunction(Function &F) {
76     // Make sure the slot table has information about this function...
77     idTable->Table.incorporateFunction(&F);
78   }
79   void endFunction(Function &) {
80     idTable->Table.purgeFunction();  // Forget all about F
81   }
82   void endModule() {
83   }
84
85   // Check if a value is external or accessible from external code.
86   bool isExternal(const Value* V) {
87     const GlobalValue *GV = dyn_cast<GlobalValue>(V);
88     return GV && GV->hasExternalLinkage();
89   }
90   
91   // enterSection - Use this method to enter a different section of the output
92   // executable.  This is used to only output neccesary section transitions.
93   //
94   void enterSection(enum Sections S) {
95     if (S == CurSection) return;        // Only switch section if neccesary
96     CurSection = S;
97
98     toAsm << "\n\t.section ";
99     switch (S)
100       {
101       default: assert(0 && "Bad section name!");
102       case Text:         toAsm << "\".text\""; break;
103       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
104       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
105       case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
106       }
107     toAsm << "\n";
108   }
109
110   static string getValidSymbolName(const string &S) {
111     string Result;
112     
113     // Symbol names in Sparc assembly language have these rules:
114     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
115     // (b) A name beginning in "." is treated as a local name.
116     // 
117     if (isdigit(S[0]))
118       Result = "ll";
119     
120     for (unsigned i = 0; i < S.size(); ++i)
121       {
122         char C = S[i];
123         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
124           Result += C;
125         else
126           {
127             Result += '_';
128             Result += char('0' + ((unsigned char)C >> 4));
129             Result += char('0' + (C & 0xF));
130           }
131       }
132     return Result;
133   }
134
135   // getID - Return a valid identifier for the specified value.  Base it on
136   // the name of the identifier if possible (qualified by the type), and
137   // use a numbered value based on prefix otherwise.
138   // FPrefix is always prepended to the output identifier.
139   //
140   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
141     string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
142     
143     Result +=  V->hasName() ? V->getName() : string(Prefix);
144     
145     // Qualify all internal names with a unique id.
146     if (!isExternal(V)) {
147       int valId = idTable->Table.getValSlot(V);
148       if (valId == -1) {
149         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
150         if (I == idTable->valToIdMap.end())
151           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
152         else
153           valId = I->second;
154       }
155       Result = Result + "_" + itostr(valId);
156     }
157     
158     return getValidSymbolName(Result);
159   }
160   
161   // getID Wrappers - Ensure consistent usage...
162   string getID(const Function *F) {
163     return getID(F, "LLVMFunction_");
164   }
165   string getID(const BasicBlock *BB) {
166     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
167   }
168   string getID(const GlobalVariable *GV) {
169     return getID(GV, "LLVMGlobal_");
170   }
171   string getID(const Constant *CV) {
172     return getID(CV, "LLVMConst_", ".C_");
173   }
174   string getID(const GlobalValue *GV) {
175     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
176       return getID(V);
177     else if (const Function *F = dyn_cast<Function>(GV))
178       return getID(F);
179     assert(0 && "Unexpected type of GlobalValue!");
180     return "";
181   }
182
183   // ConstantExprToString() - Convert a ConstantExpr to an asm expression
184   // and return this as a string.
185   string ConstantExprToString(const ConstantExpr* CE,
186                               const TargetMachine& target) {
187     string S;
188     switch(CE->getOpcode()) {
189     case Instruction::GetElementPtr:
190       { // generate a symbolic expression for the byte address
191         const Value* ptrVal = CE->getOperand(0);
192         std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
193         S += "(" + valToExprString(ptrVal, target) + ") + ("
194           + utostr(target.DataLayout.getIndexedOffset(ptrVal->getType(),idxVec))
195           + ")";
196         break;
197       }
198
199     case Instruction::Cast:
200       // Support only non-converting casts for now, i.e., a no-op.
201       // This assertion is not a complete check.
202       assert(target.DataLayout.getTypeSize(CE->getType()) ==
203              target.DataLayout.getTypeSize(CE->getOperand(0)->getType()));
204       S += "(" + valToExprString(CE->getOperand(0), target) + ")";
205       break;
206
207     case Instruction::Add:
208       S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
209                + valToExprString(CE->getOperand(1), target) + ")";
210       break;
211
212     default:
213       assert(0 && "Unsupported operator in ConstantExprToString()");
214       break;
215     }
216
217     return S;
218   }
219
220   // valToExprString - Helper function for ConstantExprToString().
221   // Appends result to argument string S.
222   // 
223   string valToExprString(const Value* V, const TargetMachine& target) {
224     string S;
225     bool failed = false;
226     if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
227
228       if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
229         S += string(CB == ConstantBool::True ? "1" : "0");
230       else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
231         S += itostr(CI->getValue());
232       else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
233         S += utostr(CI->getValue());
234       else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
235         S += ftostr(CFP->getValue());
236       else if (isa<ConstantPointerNull>(CV))
237         S += "0";
238       else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
239         S += valToExprString(CPR->getValue(), target);
240       else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
241         S += ConstantExprToString(CE, target);
242       else
243         failed = true;
244
245     } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
246       S += getID(GV);
247     }
248     else
249       failed = true;
250
251     if (failed) {
252       assert(0 && "Cannot convert value to string");
253       S += "<illegal-value>";
254     }
255     return S;
256   }
257
258 };
259
260
261
262 //===----------------------------------------------------------------------===//
263 //   SparcFunctionAsmPrinter Code
264 //===----------------------------------------------------------------------===//
265
266 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
267   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
268     : AsmPrinter(os, t) {}
269
270   const char *getPassName() const {
271     return "Output Sparc Assembly for Functions";
272   }
273
274   virtual bool doInitialization(Module &M) {
275     startModule(M);
276     return false;
277   }
278
279   virtual bool runOnFunction(Function &F) {
280     startFunction(F);
281     emitFunction(F);
282     endFunction(F);
283     return false;
284   }
285
286   virtual bool doFinalization(Module &M) {
287     endModule();
288     return false;
289   }
290
291   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
292     AU.setPreservesAll();
293   }
294
295   void emitFunction(const Function &F);
296 private :
297   void emitBasicBlock(const MachineBasicBlock &MBB);
298   void emitMachineInst(const MachineInstr *MI);
299   
300   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
301   void printOneOperand(const MachineOperand &Op);
302
303   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
304   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
305   
306   unsigned getOperandMask(unsigned Opcode) {
307     switch (Opcode) {
308     case SUBcc:   return 1 << 3;  // Remove CC argument
309   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
310     default:      return 0;       // By default, don't hack operands...
311     }
312   }
313 };
314
315 inline bool
316 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
317                                                unsigned int opNum) {
318   switch (MI->getOpCode()) {
319   case JMPLCALL:
320   case JMPLRET: return (opNum == 0);
321   default:      return false;
322   }
323 }
324
325
326 inline bool
327 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
328                                                unsigned int opNum) {
329   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
330     return (opNum == 0);
331   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
332     return (opNum == 1);
333   else
334     return false;
335 }
336
337
338 #define PrintOp1PlusOp2(mop1, mop2) \
339   printOneOperand(mop1); \
340   toAsm << "+"; \
341   printOneOperand(mop2);
342
343 unsigned int
344 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
345                                unsigned int opNum)
346 {
347   const MachineOperand& mop = MI->getOperand(opNum);
348   
349   if (OpIsBranchTargetLabel(MI, opNum))
350     {
351       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
352       return 2;
353     }
354   else if (OpIsMemoryAddressBase(MI, opNum))
355     {
356       toAsm << "[";
357       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
358       toAsm << "]";
359       return 2;
360     }
361   else
362     {
363       printOneOperand(mop);
364       return 1;
365     }
366 }
367
368
369 void
370 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop)
371 {
372   bool needBitsFlag = true;
373   
374   if (mop.opHiBits32())
375     toAsm << "%lm(";
376   else if (mop.opLoBits32())
377     toAsm << "%lo(";
378   else if (mop.opHiBits64())
379     toAsm << "%hh(";
380   else if (mop.opLoBits64())
381     toAsm << "%hm(";
382   else
383     needBitsFlag = false;
384   
385   switch (mop.getType())
386     {
387     case MachineOperand::MO_VirtualRegister:
388     case MachineOperand::MO_CCRegister:
389     case MachineOperand::MO_MachineRegister:
390       {
391         int RegNum = (int)mop.getAllocatedRegNum();
392         
393         // better to print code with NULL registers than to die
394         if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
395           toAsm << "<NULL VALUE>";
396         } else {
397           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
398         }
399         break;
400       }
401     
402     case MachineOperand::MO_PCRelativeDisp:
403       {
404         const Value *Val = mop.getVRegValue();
405         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
406         
407         if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
408           toAsm << getID(BB);
409         else if (const Function *M = dyn_cast<Function>(Val))
410           toAsm << getID(M);
411         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
412           toAsm << getID(GV);
413         else if (const Constant *CV = dyn_cast<Constant>(Val))
414           toAsm << getID(CV);
415         else
416           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
417         break;
418       }
419     
420     case MachineOperand::MO_SignExtendedImmed:
421       toAsm << mop.getImmedValue();
422       break;
423
424     case MachineOperand::MO_UnextendedImmed:
425       toAsm << (uint64_t) mop.getImmedValue();
426       break;
427     
428     default:
429       toAsm << mop;      // use dump field
430       break;
431     }
432   
433   if (needBitsFlag)
434     toAsm << ")";
435 }
436
437
438 void
439 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
440 {
441   unsigned Opcode = MI->getOpCode();
442
443   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
444     return;  // IGNORE PHI NODES
445
446   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
447
448   unsigned Mask = getOperandMask(Opcode);
449   
450   bool NeedComma = false;
451   unsigned N = 1;
452   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
453     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
454       if (NeedComma) toAsm << ", ";         // Handle comma outputing
455       NeedComma = true;
456       N = printOperands(MI, OpNum);
457     }
458   else
459     N = 1;
460   
461   toAsm << "\n";
462 }
463
464 void
465 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
466 {
467   // Emit a label for the basic block
468   toAsm << getID(MBB.getBasicBlock()) << ":\n";
469
470   // Loop over all of the instructions in the basic block...
471   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
472        MII != MIE; ++MII)
473     emitMachineInst(*MII);
474   toAsm << "\n";  // Seperate BB's with newlines
475 }
476
477 void
478 SparcFunctionAsmPrinter::emitFunction(const Function &F)
479 {
480   string methName = getID(&F);
481   toAsm << "!****** Outputing Function: " << methName << " ******\n";
482   enterSection(AsmPrinter::Text);
483   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
484   //toAsm << "\t.type\t" << methName << ",#function\n";
485   toAsm << "\t.type\t" << methName << ", 2\n";
486   toAsm << methName << ":\n";
487
488   // Output code for all of the basic blocks in the function...
489   MachineFunction &MF = MachineFunction::get(&F);
490   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E; ++I)
491     emitBasicBlock(*I);
492
493   // Output a .size directive so the debugger knows the extents of the function
494   toAsm << ".EndOf_" << methName << ":\n\t.size "
495            << methName << ", .EndOf_"
496            << methName << "-" << methName << "\n";
497
498   // Put some spaces between the functions
499   toAsm << "\n\n";
500 }
501
502 }  // End anonymous namespace
503
504 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
505   return new SparcFunctionAsmPrinter(Out, *this);
506 }
507
508
509
510
511
512 //===----------------------------------------------------------------------===//
513 //   SparcFunctionAsmPrinter Code
514 //===----------------------------------------------------------------------===//
515
516 namespace {
517
518 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
519 public:
520   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
521     : AsmPrinter(os, t) {}
522
523   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
524
525   virtual bool run(Module &M) {
526     startModule(M);
527     emitGlobalsAndConstants(M);
528     endModule();
529     return false;
530   }
531
532   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
533     AU.setPreservesAll();
534   }
535
536 private:
537   void emitGlobalsAndConstants  (const Module &M);
538
539   void printGlobalVariable      (const GlobalVariable *GV);
540   void PrintZeroBytesToPad      (int numBytes);
541   void printSingleConstantValue (const Constant* CV);
542   void printConstantValueOnly   (const Constant* CV, int numPadBytes = 0);
543   void printConstant            (const Constant* CV, string valID = "");
544
545   static void FoldConstants     (const Module &M,
546                                  hash_set<const Constant*> &moduleConstants);
547 };
548
549
550 // Can we treat the specified array as a string?  Only if it is an array of
551 // ubytes or non-negative sbytes.
552 //
553 static bool isStringCompatible(const ConstantArray *CVA) {
554   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
555   if (ETy == Type::UByteTy) return true;
556   if (ETy != Type::SByteTy) return false;
557
558   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
559     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
560       return false;
561
562   return true;
563 }
564
565 // toOctal - Convert the low order bits of X into an octal letter
566 static inline char toOctal(int X) {
567   return (X&7)+'0';
568 }
569
570 // getAsCString - Return the specified array as a C compatible string, only if
571 // the predicate isStringCompatible is true.
572 //
573 static string getAsCString(const ConstantArray *CVA) {
574   assert(isStringCompatible(CVA) && "Array is not string compatible!");
575
576   string Result;
577   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
578   Result = "\"";
579   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
580     unsigned char C = (ETy == Type::SByteTy) ?
581       (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
582       (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
583
584     if (C == '"') {
585       Result += "\\\"";
586     } else if (C == '\\') {
587       Result += "\\\\";
588     } else if (isprint(C)) {
589       Result += C;
590     } else {
591       switch(C) {
592       case '\a': Result += "\\a"; break;
593       case '\b': Result += "\\b"; break;
594       case '\f': Result += "\\f"; break;
595       case '\n': Result += "\\n"; break;
596       case '\r': Result += "\\r"; break;
597       case '\t': Result += "\\t"; break;
598       case '\v': Result += "\\v"; break;
599       default:
600         Result += '\\';
601         Result += toOctal(C >> 6);
602         Result += toOctal(C >> 3);
603         Result += toOctal(C >> 0);
604         break;
605       }
606     }
607   }
608   Result += "\"";
609
610   return Result;
611 }
612
613 inline bool
614 ArrayTypeIsString(const ArrayType* arrayType)
615 {
616   return (arrayType->getElementType() == Type::UByteTy ||
617           arrayType->getElementType() == Type::SByteTy);
618 }
619
620
621 inline const string
622 TypeToDataDirective(const Type* type)
623 {
624   switch(type->getPrimitiveID())
625     {
626     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
627       return ".byte";
628     case Type::UShortTyID: case Type::ShortTyID:
629       return ".half";
630     case Type::UIntTyID: case Type::IntTyID:
631       return ".word";
632     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
633       return ".xword";
634     case Type::FloatTyID:
635       return ".word";
636     case Type::DoubleTyID:
637       return ".xword";
638     case Type::ArrayTyID:
639       if (ArrayTypeIsString((ArrayType*) type))
640         return ".ascii";
641       else
642         return "<InvaliDataTypeForPrinting>";
643     default:
644       return "<InvaliDataTypeForPrinting>";
645     }
646 }
647
648 // Get the size of the type
649 // 
650 inline unsigned int
651 TypeToSize(const Type* type, const TargetMachine& target)
652 {
653   return target.findOptimalStorageSize(type);
654 }
655
656 // Get the size of the constant for the given target.
657 // If this is an unsized array, return 0.
658 // 
659 inline unsigned int
660 ConstantToSize(const Constant* CV, const TargetMachine& target)
661 {
662   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
663     {
664       const ArrayType *aty = cast<ArrayType>(CVA->getType());
665       if (ArrayTypeIsString(aty))
666         return 1 + CVA->getNumOperands();
667     }
668   
669   return TypeToSize(CV->getType(), target);
670 }
671
672 // Align data larger than one L1 cache line on L1 cache line boundaries.
673 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
674 // 
675 inline unsigned int
676 SizeToAlignment(unsigned int size, const TargetMachine& target)
677 {
678   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
679   if (size > (unsigned) cacheLineSize / 2)
680     return cacheLineSize;
681   else
682     for (unsigned sz=1; /*no condition*/; sz *= 2)
683       if (sz >= size)
684         return sz;
685 }
686
687 // Get the size of the type and then use SizeToAlignment.
688 // 
689 inline unsigned int
690 TypeToAlignment(const Type* type, const TargetMachine& target)
691 {
692   return SizeToAlignment(TypeToSize(type, target), target);
693 }
694
695 // Get the size of the constant and then use SizeToAlignment.
696 // Handles strings as a special case;
697 inline unsigned int
698 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
699 {
700   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
701     if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
702       return SizeToAlignment(1 + CVA->getNumOperands(), target);
703   
704   return TypeToAlignment(CV->getType(), target);
705 }
706
707
708 // Print a single constant value.
709 void
710 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
711 {
712   assert(CV->getType() != Type::VoidTy &&
713          CV->getType() != Type::TypeTy &&
714          CV->getType() != Type::LabelTy &&
715          "Unexpected type for Constant");
716   
717   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
718          && "Aggregate types should be handled outside this function");
719   
720   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
721   
722   if (CV->getType()->isPrimitiveType())
723     {
724       if (CV->getType()->isFloatingPoint()) {
725         // FP Constants are printed as integer constants to avoid losing
726         // precision...
727         double Val = cast<ConstantFP>(CV)->getValue();
728         if (CV->getType() == Type::FloatTy) {
729           float FVal = (float)Val;
730           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
731           toAsm << *(unsigned int*)ProxyPtr;            
732         } else if (CV->getType() == Type::DoubleTy) {
733           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
734           toAsm << *(uint64_t*)ProxyPtr;            
735         } else {
736           assert(0 && "Unknown floating point type!");
737         }
738         
739         toAsm << "\t! " << CV->getType()->getDescription()
740               << " value: " << Val << "\n";
741       } else {
742         WriteAsOperand(toAsm, CV, false, false) << "\n";
743       }
744     }
745   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
746     { // This is a constant address for a global variable or method.
747       // Use the name of the variable or method as the address value.
748       toAsm << getID(CPR->getValue()) << "\n";
749     }
750   else if (isa<ConstantPointerNull>(CV))
751     { // Null pointer value
752       toAsm << "0\n";
753     }
754   else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
755     { // Constant expression built from operators, constants, and symbolic addrs
756       toAsm << ConstantExprToString(CE, Target) << "\n";
757     }
758   else
759     {
760       assert(0 && "Unknown elementary type for constant");
761     }
762 }
763
764 void
765 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
766 {
767   for ( ; numBytes >= 8; numBytes -= 8)
768     printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
769
770   if (numBytes >= 4)
771     {
772       printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
773       numBytes -= 4;
774     }
775
776   while (numBytes--)
777     printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
778 }
779
780 // Print a constant value or values (it may be an aggregate).
781 // Uses printSingleConstantValue() to print each individual value.
782 void
783 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
784                                               int numPadBytes /* = 0*/)
785 {
786   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
787
788   if (numPadBytes)
789     PrintZeroBytesToPad(numPadBytes);
790
791   if (CVA && isStringCompatible(CVA))
792     { // print the string alone and return
793       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
794     }
795   else if (CVA)
796     { // Not a string.  Print the values in successive locations
797       const std::vector<Use> &constValues = CVA->getValues();
798       for (unsigned i=0; i < constValues.size(); i++)
799         printConstantValueOnly(cast<Constant>(constValues[i].get()));
800     }
801   else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
802     { // Print the fields in successive locations. Pad to align if needed!
803       const StructLayout *cvsLayout =
804         Target.DataLayout.getStructLayout(CVS->getType());
805       const std::vector<Use>& constValues = CVS->getValues();
806       unsigned sizeSoFar = 0;
807       for (unsigned i=0, N = constValues.size(); i < N; i++)
808         {
809           const Constant* field = cast<Constant>(constValues[i].get());
810
811           // Check if padding is needed and insert one or more 0s.
812           unsigned fieldSize = Target.DataLayout.getTypeSize(field->getType());
813           int padSize = ((i == N-1? cvsLayout->StructSize
814                                   : cvsLayout->MemberOffsets[i+1])
815                          - cvsLayout->MemberOffsets[i]) - fieldSize;
816           sizeSoFar += (fieldSize + padSize);
817
818           // Now print the actual field value
819           printConstantValueOnly(field, padSize);
820         }
821       assert(sizeSoFar == cvsLayout->StructSize &&
822              "Layout of constant struct may be incorrect!");
823     }
824   else
825     printSingleConstantValue(CV);
826 }
827
828 // Print a constant (which may be an aggregate) prefixed by all the
829 // appropriate directives.  Uses printConstantValueOnly() to print the
830 // value or values.
831 void
832 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
833 {
834   if (valID.length() == 0)
835     valID = getID(CV);
836   
837   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
838   
839   // Print .size and .type only if it is not a string.
840   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
841   if (CVA && isStringCompatible(CVA))
842     { // print it as a string and return
843       toAsm << valID << ":\n";
844       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
845       return;
846     }
847   
848   toAsm << "\t.type" << "\t" << valID << ",#object\n";
849
850   unsigned int constSize = ConstantToSize(CV, Target);
851   if (constSize)
852     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
853   
854   toAsm << valID << ":\n";
855   
856   printConstantValueOnly(CV);
857 }
858
859
860 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
861                                           hash_set<const Constant*> &MC) {
862   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
863     if (!I->isExternal()) {
864       const hash_set<const Constant*> &pool =
865         MachineFunction::get(I).getConstantPoolValues();
866       MC.insert(pool.begin(), pool.end());
867     }
868 }
869
870 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
871 {
872   if (GV->hasExternalLinkage())
873     toAsm << "\t.global\t" << getID(GV) << "\n";
874   
875   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
876     printConstant(GV->getInitializer(), getID(GV));
877   else {
878     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
879                                                 Target) << "\n";
880     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
881     toAsm << "\t.reserve\t" << getID(GV) << ","
882           << TypeToSize(GV->getType()->getElementType(), Target)
883           << "\n";
884   }
885 }
886
887
888 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
889   // First, get the constants there were marked by the code generator for
890   // inclusion in the assembly code data area and fold them all into a
891   // single constant pool since there may be lots of duplicates.  Also,
892   // lets force these constants into the slot table so that we can get
893   // unique names for unnamed constants also.
894   // 
895   hash_set<const Constant*> moduleConstants;
896   FoldConstants(M, moduleConstants);
897     
898   // Output constants spilled to memory
899   enterSection(AsmPrinter::ReadOnlyData);
900   for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
901          E = moduleConstants.end();  I != E; ++I)
902     printConstant(*I);
903
904   // Output global variables...
905   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
906     if (! GI->isExternal()) {
907       assert(GI->hasInitializer());
908       if (GI->isConstant())
909         enterSection(AsmPrinter::ReadOnlyData);   // read-only, initialized data
910       else if (GI->getInitializer()->isNullValue())
911         enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
912       else
913         enterSection(AsmPrinter::InitRWData);     // read-write non-zero data
914
915       printGlobalVariable(GI);
916     }
917
918   toAsm << "\n";
919 }
920
921 }  // End anonymous namespace
922
923 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
924   return new SparcModuleAsmPrinter(Out, *this);
925 }