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