Add all arithmetic operators to ConstantExprToString().
[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     case Instruction::Sub:
217       S += "(" + valToExprString(CE->getOperand(0), target) + ") - ("
218                + valToExprString(CE->getOperand(1), target) + ")";
219       break;
220
221     case Instruction::Mul:
222       S += "(" + valToExprString(CE->getOperand(0), target) + ") * ("
223                + valToExprString(CE->getOperand(1), target) + ")";
224       break;
225
226     case Instruction::Div:
227       S += "(" + valToExprString(CE->getOperand(0), target) + ") / ("
228                + valToExprString(CE->getOperand(1), target) + ")";
229       break;
230
231     case Instruction::Rem:
232       S += "(" + valToExprString(CE->getOperand(0), target) + ") % ("
233                + valToExprString(CE->getOperand(1), target) + ")";
234       break;
235
236     case Instruction::And:
237       // Logical && for booleans; bitwise & otherwise
238       S += "(" + valToExprString(CE->getOperand(0), target)
239                + ((CE->getType() == Type::BoolTy)? ") && (" : ") & (")
240                + valToExprString(CE->getOperand(1), target) + ")";
241       break;
242
243     case Instruction::Or:
244       // Logical || for booleans; bitwise | otherwise
245       S += "(" + valToExprString(CE->getOperand(0), target)
246                + ((CE->getType() == Type::BoolTy)? ") || (" : ") | (")
247                + valToExprString(CE->getOperand(1), target) + ")";
248       break;
249
250     case Instruction::Xor:
251       // Bitwise ^ for all types
252       S += "(" + valToExprString(CE->getOperand(0), target) + ") ^ ("
253                + valToExprString(CE->getOperand(1), target) + ")";
254       break;
255
256     default:
257       assert(0 && "Unsupported operator in ConstantExprToString()");
258       break;
259     }
260
261     return S;
262   }
263
264   // valToExprString - Helper function for ConstantExprToString().
265   // Appends result to argument string S.
266   // 
267   string valToExprString(const Value* V, const TargetMachine& target) {
268     string S;
269     bool failed = false;
270     if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
271
272       if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
273         S += string(CB == ConstantBool::True ? "1" : "0");
274       else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
275         S += itostr(CI->getValue());
276       else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
277         S += utostr(CI->getValue());
278       else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
279         S += ftostr(CFP->getValue());
280       else if (isa<ConstantPointerNull>(CV))
281         S += "0";
282       else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
283         S += valToExprString(CPR->getValue(), target);
284       else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
285         S += ConstantExprToString(CE, target);
286       else
287         failed = true;
288
289     } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
290       S += getID(GV);
291     }
292     else
293       failed = true;
294
295     if (failed) {
296       assert(0 && "Cannot convert value to string");
297       S += "<illegal-value>";
298     }
299     return S;
300   }
301
302 };
303
304
305
306 //===----------------------------------------------------------------------===//
307 //   SparcFunctionAsmPrinter Code
308 //===----------------------------------------------------------------------===//
309
310 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
311   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
312     : AsmPrinter(os, t) {}
313
314   const char *getPassName() const {
315     return "Output Sparc Assembly for Functions";
316   }
317
318   virtual bool doInitialization(Module &M) {
319     startModule(M);
320     return false;
321   }
322
323   virtual bool runOnFunction(Function &F) {
324     startFunction(F);
325     emitFunction(F);
326     endFunction(F);
327     return false;
328   }
329
330   virtual bool doFinalization(Module &M) {
331     endModule();
332     return false;
333   }
334
335   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
336     AU.setPreservesAll();
337   }
338
339   void emitFunction(const Function &F);
340 private :
341   void emitBasicBlock(const MachineBasicBlock &MBB);
342   void emitMachineInst(const MachineInstr *MI);
343   
344   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
345   void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
346
347   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
348   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
349   
350   unsigned getOperandMask(unsigned Opcode) {
351     switch (Opcode) {
352     case V9::SUBccr:
353     case V9::SUBcci:   return 1 << 3;  // Remove CC argument
354   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
355     default:      return 0;       // By default, don't hack operands...
356     }
357   }
358 };
359
360 inline bool
361 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
362                                                unsigned int opNum) {
363   switch (MI->getOpCode()) {
364   case V9::JMPLCALLr:
365   case V9::JMPLCALLi:
366   case V9::JMPLRETr:
367   case V9::JMPLRETi:
368     return (opNum == 0);
369   default:
370     return false;
371   }
372 }
373
374
375 inline bool
376 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
377                                                unsigned int opNum) {
378   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
379     return (opNum == 0);
380   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
381     return (opNum == 1);
382   else
383     return false;
384 }
385
386
387 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
388   printOneOperand(mop1, opCode); \
389   toAsm << "+"; \
390   printOneOperand(mop2, opCode);
391
392 unsigned int
393 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
394                                unsigned int opNum)
395 {
396   const MachineOperand& mop = MI->getOperand(opNum);
397   
398   if (OpIsBranchTargetLabel(MI, opNum))
399     {
400       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
401       return 2;
402     }
403   else if (OpIsMemoryAddressBase(MI, opNum))
404     {
405       toAsm << "[";
406       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
407       toAsm << "]";
408       return 2;
409     }
410   else
411     {
412       printOneOperand(mop, MI->getOpCode());
413       return 1;
414     }
415 }
416
417 void
418 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
419                                          MachineOpCode opCode)
420 {
421   bool needBitsFlag = true;
422   
423   if (mop.opHiBits32())
424     toAsm << "%lm(";
425   else if (mop.opLoBits32())
426     toAsm << "%lo(";
427   else if (mop.opHiBits64())
428     toAsm << "%hh(";
429   else if (mop.opLoBits64())
430     toAsm << "%hm(";
431   else
432     needBitsFlag = false;
433   
434   switch (mop.getType())
435     {
436     case MachineOperand::MO_VirtualRegister:
437     case MachineOperand::MO_CCRegister:
438     case MachineOperand::MO_MachineRegister:
439       {
440         int regNum = (int)mop.getAllocatedRegNum();
441         
442         if (regNum == Target.getRegInfo().getInvalidRegNum()) {
443           // better to print code with NULL registers than to die
444           toAsm << "<NULL VALUE>";
445         } else {
446           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
447         }
448         break;
449       }
450     
451     case MachineOperand::MO_PCRelativeDisp:
452       {
453         const Value *Val = mop.getVRegValue();
454         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
455         
456         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
457           toAsm << getID(BB);
458         else if (const Function *M = dyn_cast<Function>(Val))
459           toAsm << getID(M);
460         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
461           toAsm << getID(GV);
462         else if (const Constant *CV = dyn_cast<Constant>(Val))
463           toAsm << getID(CV);
464         else
465           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
466         break;
467       }
468     
469     case MachineOperand::MO_SignExtendedImmed:
470       toAsm << mop.getImmedValue();
471       break;
472
473     case MachineOperand::MO_UnextendedImmed:
474       toAsm << (uint64_t) mop.getImmedValue();
475       break;
476     
477     default:
478       toAsm << mop;      // use dump field
479       break;
480     }
481   
482   if (needBitsFlag)
483     toAsm << ")";
484 }
485
486
487 void
488 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
489 {
490   unsigned Opcode = MI->getOpCode();
491
492   if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
493     return;  // IGNORE PHI NODES
494
495   toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
496
497   unsigned Mask = getOperandMask(Opcode);
498   
499   bool NeedComma = false;
500   unsigned N = 1;
501   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
502     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
503       if (NeedComma) toAsm << ", ";         // Handle comma outputing
504       NeedComma = true;
505       N = printOperands(MI, OpNum);
506     } else
507       N = 1;
508   
509   toAsm << "\n";
510 }
511
512 void
513 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
514 {
515   // Emit a label for the basic block
516   toAsm << getID(MBB.getBasicBlock()) << ":\n";
517
518   // Loop over all of the instructions in the basic block...
519   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
520        MII != MIE; ++MII)
521     emitMachineInst(*MII);
522   toAsm << "\n";  // Separate BB's with newlines
523 }
524
525 void
526 SparcFunctionAsmPrinter::emitFunction(const Function &F)
527 {
528   string methName = getID(&F);
529   toAsm << "!****** Outputing Function: " << methName << " ******\n";
530   enterSection(AsmPrinter::Text);
531   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
532   //toAsm << "\t.type\t" << methName << ",#function\n";
533   toAsm << "\t.type\t" << methName << ", 2\n";
534   toAsm << methName << ":\n";
535
536   // Output code for all of the basic blocks in the function...
537   MachineFunction &MF = MachineFunction::get(&F);
538   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
539     emitBasicBlock(*I);
540
541   // Output a .size directive so the debugger knows the extents of the function
542   toAsm << ".EndOf_" << methName << ":\n\t.size "
543            << methName << ", .EndOf_"
544            << methName << "-" << methName << "\n";
545
546   // Put some spaces between the functions
547   toAsm << "\n\n";
548 }
549
550 }  // End anonymous namespace
551
552 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
553   return new SparcFunctionAsmPrinter(Out, *this);
554 }
555
556
557
558
559
560 //===----------------------------------------------------------------------===//
561 //   SparcFunctionAsmPrinter Code
562 //===----------------------------------------------------------------------===//
563
564 namespace {
565
566 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
567 public:
568   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
569     : AsmPrinter(os, t) {}
570
571   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
572
573   virtual bool run(Module &M) {
574     startModule(M);
575     emitGlobalsAndConstants(M);
576     endModule();
577     return false;
578   }
579
580   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
581     AU.setPreservesAll();
582   }
583
584 private:
585   void emitGlobalsAndConstants  (const Module &M);
586
587   void printGlobalVariable      (const GlobalVariable *GV);
588   void PrintZeroBytesToPad      (int numBytes);
589   void printSingleConstantValue (const Constant* CV);
590   void printConstantValueOnly   (const Constant* CV, int numPadBytesAfter = 0);
591   void printConstant            (const Constant* CV, string valID = "");
592
593   static void FoldConstants     (const Module &M,
594                                  hash_set<const Constant*> &moduleConstants);
595 };
596
597
598 // Can we treat the specified array as a string?  Only if it is an array of
599 // ubytes or non-negative sbytes.
600 //
601 static bool isStringCompatible(const ConstantArray *CVA) {
602   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
603   if (ETy == Type::UByteTy) return true;
604   if (ETy != Type::SByteTy) return false;
605
606   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
607     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
608       return false;
609
610   return true;
611 }
612
613 // toOctal - Convert the low order bits of X into an octal letter
614 static inline char toOctal(int X) {
615   return (X&7)+'0';
616 }
617
618 // getAsCString - Return the specified array as a C compatible string, only if
619 // the predicate isStringCompatible is true.
620 //
621 static string getAsCString(const ConstantArray *CVA) {
622   assert(isStringCompatible(CVA) && "Array is not string compatible!");
623
624   string Result;
625   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
626   Result = "\"";
627   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
628     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
629
630     if (C == '"') {
631       Result += "\\\"";
632     } else if (C == '\\') {
633       Result += "\\\\";
634     } else if (isprint(C)) {
635       Result += C;
636     } else {
637       Result += '\\';                   // print all other chars as octal value
638       Result += toOctal(C >> 6);
639       Result += toOctal(C >> 3);
640       Result += toOctal(C >> 0);
641     }
642   }
643   Result += "\"";
644
645   return Result;
646 }
647
648 inline bool
649 ArrayTypeIsString(const ArrayType* arrayType)
650 {
651   return (arrayType->getElementType() == Type::UByteTy ||
652           arrayType->getElementType() == Type::SByteTy);
653 }
654
655
656 inline const string
657 TypeToDataDirective(const Type* type)
658 {
659   switch(type->getPrimitiveID())
660     {
661     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
662       return ".byte";
663     case Type::UShortTyID: case Type::ShortTyID:
664       return ".half";
665     case Type::UIntTyID: case Type::IntTyID:
666       return ".word";
667     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
668       return ".xword";
669     case Type::FloatTyID:
670       return ".word";
671     case Type::DoubleTyID:
672       return ".xword";
673     case Type::ArrayTyID:
674       if (ArrayTypeIsString((ArrayType*) type))
675         return ".ascii";
676       else
677         return "<InvaliDataTypeForPrinting>";
678     default:
679       return "<InvaliDataTypeForPrinting>";
680     }
681 }
682
683 // Get the size of the type
684 // 
685 inline unsigned int
686 TypeToSize(const Type* type, const TargetMachine& target)
687 {
688   return target.findOptimalStorageSize(type);
689 }
690
691 // Get the size of the constant for the given target.
692 // If this is an unsized array, return 0.
693 // 
694 inline unsigned int
695 ConstantToSize(const Constant* CV, const TargetMachine& target)
696 {
697   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
698     {
699       const ArrayType *aty = cast<ArrayType>(CVA->getType());
700       if (ArrayTypeIsString(aty))
701         return 1 + CVA->getNumOperands();
702     }
703   
704   return TypeToSize(CV->getType(), target);
705 }
706
707 // Align data larger than one L1 cache line on L1 cache line boundaries.
708 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
709 // 
710 inline unsigned int
711 SizeToAlignment(unsigned int size, const TargetMachine& target)
712 {
713   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
714   if (size > (unsigned) cacheLineSize / 2)
715     return cacheLineSize;
716   else
717     for (unsigned sz=1; /*no condition*/; sz *= 2)
718       if (sz >= size)
719         return sz;
720 }
721
722 // Get the size of the type and then use SizeToAlignment.
723 // 
724 inline unsigned int
725 TypeToAlignment(const Type* type, const TargetMachine& target)
726 {
727   return SizeToAlignment(TypeToSize(type, target), target);
728 }
729
730 // Get the size of the constant and then use SizeToAlignment.
731 // Handles strings as a special case;
732 inline unsigned int
733 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
734 {
735   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
736     if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
737       return SizeToAlignment(1 + CVA->getNumOperands(), target);
738   
739   return TypeToAlignment(CV->getType(), target);
740 }
741
742
743 // Print a single constant value.
744 void
745 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
746 {
747   assert(CV->getType() != Type::VoidTy &&
748          CV->getType() != Type::TypeTy &&
749          CV->getType() != Type::LabelTy &&
750          "Unexpected type for Constant");
751   
752   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
753          && "Aggregate types should be handled outside this function");
754   
755   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
756   
757   if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
758     { // This is a constant address for a global variable or method.
759       // Use the name of the variable or method as the address value.
760       assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
761       toAsm << getID(CPR->getValue()) << "\n";
762     }
763   else if (isa<ConstantPointerNull>(CV))
764     { // Null pointer value
765       toAsm << "0\n";
766     }
767   else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
768     { // Constant expression built from operators, constants, and symbolic addrs
769       toAsm << ConstantExprToString(CE, Target) << "\n";
770     }
771   else if (CV->getType()->isPrimitiveType())     // Check primitive types last
772     {
773       if (CV->getType()->isFloatingPoint()) {
774         // FP Constants are printed as integer constants to avoid losing
775         // precision...
776         double Val = cast<ConstantFP>(CV)->getValue();
777         if (CV->getType() == Type::FloatTy) {
778           float FVal = (float)Val;
779           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
780           toAsm << *(unsigned int*)ProxyPtr;            
781         } else if (CV->getType() == Type::DoubleTy) {
782           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
783           toAsm << *(uint64_t*)ProxyPtr;            
784         } else {
785           assert(0 && "Unknown floating point type!");
786         }
787         
788         toAsm << "\t! " << CV->getType()->getDescription()
789               << " value: " << Val << "\n";
790       } else {
791         WriteAsOperand(toAsm, CV, false, false) << "\n";
792       }
793     }
794   else
795     {
796       assert(0 && "Unknown elementary type for constant");
797     }
798 }
799
800 void
801 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
802 {
803   for ( ; numBytes >= 8; numBytes -= 8)
804     printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
805
806   if (numBytes >= 4)
807     {
808       printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
809       numBytes -= 4;
810     }
811
812   while (numBytes--)
813     printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
814 }
815
816 // Print a constant value or values (it may be an aggregate).
817 // Uses printSingleConstantValue() to print each individual value.
818 void
819 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
820                                               int numPadBytesAfter /* = 0*/)
821 {
822   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
823
824   if (CVA && isStringCompatible(CVA))
825     { // print the string alone and return
826       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
827     }
828   else if (CVA)
829     { // Not a string.  Print the values in successive locations
830       const std::vector<Use> &constValues = CVA->getValues();
831       for (unsigned i=0; i < constValues.size(); i++)
832         printConstantValueOnly(cast<Constant>(constValues[i].get()));
833     }
834   else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
835     { // Print the fields in successive locations. Pad to align if needed!
836       const StructLayout *cvsLayout =
837         Target.getTargetData().getStructLayout(CVS->getType());
838       const std::vector<Use>& constValues = CVS->getValues();
839       unsigned sizeSoFar = 0;
840       for (unsigned i=0, N = constValues.size(); i < N; i++)
841         {
842           const Constant* field = cast<Constant>(constValues[i].get());
843
844           // Check if padding is needed and insert one or more 0s.
845           unsigned fieldSize =
846             Target.getTargetData().getTypeSize(field->getType());
847           int padSize = ((i == N-1? cvsLayout->StructSize
848                                   : cvsLayout->MemberOffsets[i+1])
849                          - cvsLayout->MemberOffsets[i]) - fieldSize;
850           sizeSoFar += (fieldSize + padSize);
851
852           // Now print the actual field value
853           printConstantValueOnly(field, padSize);
854         }
855       assert(sizeSoFar == cvsLayout->StructSize &&
856              "Layout of constant struct may be incorrect!");
857     }
858   else
859     printSingleConstantValue(CV);
860
861   if (numPadBytesAfter)
862     PrintZeroBytesToPad(numPadBytesAfter);
863 }
864
865 // Print a constant (which may be an aggregate) prefixed by all the
866 // appropriate directives.  Uses printConstantValueOnly() to print the
867 // value or values.
868 void
869 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
870 {
871   if (valID.length() == 0)
872     valID = getID(CV);
873   
874   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
875   
876   // Print .size and .type only if it is not a string.
877   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
878   if (CVA && isStringCompatible(CVA))
879     { // print it as a string and return
880       toAsm << valID << ":\n";
881       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
882       return;
883     }
884   
885   toAsm << "\t.type" << "\t" << valID << ",#object\n";
886
887   unsigned int constSize = ConstantToSize(CV, Target);
888   if (constSize)
889     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
890   
891   toAsm << valID << ":\n";
892   
893   printConstantValueOnly(CV);
894 }
895
896
897 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
898                                           hash_set<const Constant*> &MC) {
899   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
900     if (!I->isExternal()) {
901       const hash_set<const Constant*> &pool =
902         MachineFunction::get(I).getInfo()->getConstantPoolValues();
903       MC.insert(pool.begin(), pool.end());
904     }
905 }
906
907 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
908 {
909   if (GV->hasExternalLinkage())
910     toAsm << "\t.global\t" << getID(GV) << "\n";
911   
912   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
913     printConstant(GV->getInitializer(), getID(GV));
914   else {
915     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
916                                                 Target) << "\n";
917     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
918     toAsm << "\t.reserve\t" << getID(GV) << ","
919           << TypeToSize(GV->getType()->getElementType(), Target)
920           << "\n";
921   }
922 }
923
924
925 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
926   // First, get the constants there were marked by the code generator for
927   // inclusion in the assembly code data area and fold them all into a
928   // single constant pool since there may be lots of duplicates.  Also,
929   // lets force these constants into the slot table so that we can get
930   // unique names for unnamed constants also.
931   // 
932   hash_set<const Constant*> moduleConstants;
933   FoldConstants(M, moduleConstants);
934     
935   // Output constants spilled to memory
936   enterSection(AsmPrinter::ReadOnlyData);
937   for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
938          E = moduleConstants.end();  I != E; ++I)
939     printConstant(*I);
940
941   // Output global variables...
942   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
943     if (! GI->isExternal()) {
944       assert(GI->hasInitializer());
945       if (GI->isConstant())
946         enterSection(AsmPrinter::ReadOnlyData);   // read-only, initialized data
947       else if (GI->getInitializer()->isNullValue())
948         enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
949       else
950         enterSection(AsmPrinter::InitRWData);     // read-write non-zero data
951
952       printGlobalVariable(GI);
953     }
954
955   toAsm << "\n";
956 }
957
958 }  // End anonymous namespace
959
960 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
961   return new SparcModuleAsmPrinter(Out, *this);
962 }