Change code to not use the copyOperands method added to User. It's now
[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/MachineCodeForBasicBlock.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Module.h"
24 #include "llvm/SlotCalculator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "Support/StringExtras.h"
28 #include <iostream>
29 using std::string;
30
31 namespace {
32
33 class GlobalIdTable: public Annotation {
34   static AnnotationID AnnotId;
35   friend class AsmPrinter;              // give access to AnnotId
36   
37   typedef hash_map<const Value*, int> ValIdMap;
38   typedef ValIdMap::const_iterator ValIdMapConstIterator;
39   typedef ValIdMap::      iterator ValIdMapIterator;
40 public:
41   SlotCalculator Table;    // map anonymous values to unique integer IDs
42   ValIdMap valToIdMap;     // used for values not handled by SlotCalculator 
43   
44   GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
45 };
46
47 AnnotationID GlobalIdTable::AnnotId =
48   AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
49   
50 //===---------------------------------------------------------------------===//
51 //   Code Shared By the two printer passes, as a mixin
52 //===---------------------------------------------------------------------===//
53
54 class AsmPrinter {
55   GlobalIdTable* idTable;
56 public:
57   std::ostream &toAsm;
58   const TargetMachine &Target;
59   
60   enum Sections {
61     Unknown,
62     Text,
63     ReadOnlyData,
64     InitRWData,
65     UninitRWData,
66   } CurSection;
67
68   AsmPrinter(std::ostream &os, const TargetMachine &T)
69     : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
70   
71   // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
72   void startModule(Module &M) {
73     // Create the global id table if it does not already exist
74     idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
75     if (idTable == NULL) {
76       idTable = new GlobalIdTable(&M);
77       M.addAnnotation(idTable);
78     }
79   }
80   void startFunction(Function &F) {
81     // Make sure the slot table has information about this function...
82     idTable->Table.incorporateFunction(&F);
83   }
84   void endFunction(Function &) {
85     idTable->Table.purgeFunction();  // Forget all about F
86   }
87   void endModule() {
88   }
89
90   // Check if a value is external or accessible from external code.
91   bool isExternal(const Value* V) {
92     const GlobalValue *GV = dyn_cast<GlobalValue>(V);
93     return GV && GV->hasExternalLinkage();
94   }
95   
96   // enterSection - Use this method to enter a different section of the output
97   // executable.  This is used to only output neccesary section transitions.
98   //
99   void enterSection(enum Sections S) {
100     if (S == CurSection) return;        // Only switch section if neccesary
101     CurSection = S;
102
103     toAsm << "\n\t.section ";
104     switch (S)
105       {
106       default: assert(0 && "Bad section name!");
107       case Text:         toAsm << "\".text\""; break;
108       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
109       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
110       case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
111       }
112     toAsm << "\n";
113   }
114
115   static std::string getValidSymbolName(const string &S) {
116     string Result;
117     
118     // Symbol names in Sparc assembly language have these rules:
119     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
120     // (b) A name beginning in "." is treated as a local name.
121     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
122     // 
123     if (S[0] == '_' || isdigit(S[0]))
124       Result += "ll";
125     
126     for (unsigned i = 0; i < S.size(); ++i)
127       {
128         char C = S[i];
129         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
130           Result += C;
131         else
132           {
133             Result += '_';
134             Result += char('0' + ((unsigned char)C >> 4));
135             Result += char('0' + (C & 0xF));
136           }
137       }
138     return Result;
139   }
140
141   // getID - Return a valid identifier for the specified value.  Base it on
142   // the name of the identifier if possible (qualified by the type), and
143   // use a numbered value based on prefix otherwise.
144   // FPrefix is always prepended to the output identifier.
145   //
146   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
147     string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
148     
149     Result +=  V->hasName() ? V->getName() : string(Prefix);
150     
151     // Qualify all internal names with a unique id.
152     if (!isExternal(V)) {
153       int valId = idTable->Table.getValSlot(V);
154       if (valId == -1) {
155         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
156         if (I == idTable->valToIdMap.end())
157           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
158         else
159           valId = I->second;
160       }
161       Result = Result + "_" + itostr(valId);
162     }
163     
164     return getValidSymbolName(Result);
165   }
166   
167   // getID Wrappers - Ensure consistent usage...
168   string getID(const Function *F) {
169     return getID(F, "LLVMFunction_");
170   }
171   string getID(const BasicBlock *BB) {
172     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
173   }
174   string getID(const GlobalVariable *GV) {
175     return getID(GV, "LLVMGlobal_");
176   }
177   string getID(const Constant *CV) {
178     return getID(CV, "LLVMConst_", ".C_");
179   }
180   string getID(const GlobalValue *GV) {
181     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
182       return getID(V);
183     else if (const Function *F = dyn_cast<Function>(GV))
184       return getID(F);
185     assert(0 && "Unexpected type of GlobalValue!");
186     return "";
187   }
188
189   // ConstantExprToString() - Convert a ConstantExpr to a C expression, and
190   // return this as a string.
191   //
192   std::string ConstantExprToString(const ConstantExpr* CE,
193                                    const TargetMachine& target) {
194     std::string S;
195
196     switch(CE->getOpcode()) {
197     case Instruction::GetElementPtr:
198       {
199         const Value* ptrVal = CE->getOperand(0);
200         valToExprString(ptrVal, target, S);
201         std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
202         uint64_t byteOffset =
203           target.DataLayout.getIndexedOffset(ptrVal->getType(), idxVec);
204
205         const Type *PtrElTy =
206           cast<PointerType>(ptrVal->getType())->getElementType();
207         uint64_t eltSize = target.DataLayout.getTypeSize(PtrElTy);
208
209         S += " + " + utostr(byteOffset / eltSize);
210         break;
211       }
212
213     default:
214       assert(0 && "Unsupported operator in ConstantExprToString()");
215       break;
216     }
217
218     return S;
219   }
220
221   // valToExprString - Helper function for ConstantExprToString().
222   // Appends result to argument string S.
223   // 
224   void valToExprString(const Value* V, const TargetMachine& target,
225                        std::string& S) {
226     bool failed = false;
227     if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
228
229       if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
230         S += std::string(CB == ConstantBool::True ? "1" : "0");
231       else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
232         S += itostr(CI->getValue());
233       else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
234         S += utostr(CI->getValue());
235       else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
236         S += ftostr(CFP->getValue());
237       else if (isa<ConstantPointerNull>(CV))
238         S += "0";
239       else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
240         valToExprString(CPR->getValue(), target, S);
241       else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
242         S += ConstantExprToString(CE, target);
243       else
244         failed = true;
245
246     } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
247       S += getID(GV);
248     }
249     else
250       failed = true;
251
252     if (failed) {
253       assert(0 && "Cannot convert value to string");
254       S += "<illegal-value>";
255     }
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 BasicBlock *BB);
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.getOperandType())
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 BasicBlock *BB)
466 {
467   // Emit a label for the basic block
468   toAsm << getID(BB) << ":\n";
469
470   // Get the vector of machine instructions corresponding to this bb.
471   const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
472   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
473
474   // Loop over all of the instructions in the basic block...
475   for (; MII != MIE; ++MII)
476     emitMachineInst(*MII);
477   toAsm << "\n";  // Seperate BB's with newlines
478 }
479
480 void
481 SparcFunctionAsmPrinter::emitFunction(const Function &F)
482 {
483   string methName = getID(&F);
484   toAsm << "!****** Outputing Function: " << methName << " ******\n";
485   enterSection(AsmPrinter::Text);
486   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
487   //toAsm << "\t.type\t" << methName << ",#function\n";
488   toAsm << "\t.type\t" << methName << ", 2\n";
489   toAsm << methName << ":\n";
490
491   // Output code for all of the basic blocks in the function...
492   for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
493     emitBasicBlock(I);
494
495   // Output a .size directive so the debugger knows the extents of the function
496   toAsm << ".EndOf_" << methName << ":\n\t.size "
497            << methName << ", .EndOf_"
498            << methName << "-" << methName << "\n";
499
500   // Put some spaces between the functions
501   toAsm << "\n\n";
502 }
503
504 }  // End anonymous namespace
505
506 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
507   return new SparcFunctionAsmPrinter(Out, *this);
508 }
509
510
511
512
513
514 //===----------------------------------------------------------------------===//
515 //   SparcFunctionAsmPrinter Code
516 //===----------------------------------------------------------------------===//
517
518 namespace {
519
520 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
521 public:
522   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
523     : AsmPrinter(os, t) {}
524
525   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
526
527   virtual bool run(Module &M) {
528     startModule(M);
529     emitGlobalsAndConstants(M);
530     endModule();
531     return false;
532   }
533
534   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
535     AU.setPreservesAll();
536   }
537
538 private:
539   void emitGlobalsAndConstants(const Module &M);
540
541   void printGlobalVariable(const GlobalVariable *GV);
542   void printSingleConstant(   const Constant* CV);
543   void printConstantValueOnly(const Constant* CV);
544   void printConstant(         const Constant* CV, std::string valID = "");
545
546   static void FoldConstants(const Module &M,
547                             hash_set<const Constant*> &moduleConstants);
548 };
549
550
551 // Can we treat the specified array as a string?  Only if it is an array of
552 // ubytes or non-negative sbytes.
553 //
554 static bool isStringCompatible(const ConstantArray *CPA) {
555   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
556   if (ETy == Type::UByteTy) return true;
557   if (ETy != Type::SByteTy) return false;
558
559   for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
560     if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
561       return false;
562
563   return true;
564 }
565
566 // toOctal - Convert the low order bits of X into an octal letter
567 static inline char toOctal(int X) {
568   return (X&7)+'0';
569 }
570
571 // getAsCString - Return the specified array as a C compatible string, only if
572 // the predicate isStringCompatible is true.
573 //
574 static string getAsCString(const ConstantArray *CPA) {
575   assert(isStringCompatible(CPA) && "Array is not string compatible!");
576
577   string Result;
578   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
579   Result = "\"";
580   for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
581     unsigned char C = (ETy == Type::SByteTy) ?
582       (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
583       (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
584
585     if (C == '"') {
586       Result += "\\\"";
587     } else if (isprint(C)) {
588       Result += C;
589     } else {
590       switch(C) {
591       case '\a': Result += "\\a"; break;
592       case '\b': Result += "\\b"; break;
593       case '\f': Result += "\\f"; break;
594       case '\n': Result += "\\n"; break;
595       case '\r': Result += "\\r"; break;
596       case '\t': Result += "\\t"; break;
597       case '\v': Result += "\\v"; break;
598       default:
599         Result += '\\';
600         Result += toOctal(C >> 6);
601         Result += toOctal(C >> 3);
602         Result += toOctal(C >> 0);
603         break;
604       }
605     }
606   }
607   Result += "\"";
608
609   return Result;
610 }
611
612 inline bool
613 ArrayTypeIsString(const ArrayType* arrayType)
614 {
615   return (arrayType->getElementType() == Type::UByteTy ||
616           arrayType->getElementType() == Type::SByteTy);
617 }
618
619
620 inline const string
621 TypeToDataDirective(const Type* type)
622 {
623   switch(type->getPrimitiveID())
624     {
625     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
626       return ".byte";
627     case Type::UShortTyID: case Type::ShortTyID:
628       return ".half";
629     case Type::UIntTyID: case Type::IntTyID:
630       return ".word";
631     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
632       return ".xword";
633     case Type::FloatTyID:
634       return ".word";
635     case Type::DoubleTyID:
636       return ".xword";
637     case Type::ArrayTyID:
638       if (ArrayTypeIsString((ArrayType*) type))
639         return ".ascii";
640       else
641         return "<InvaliDataTypeForPrinting>";
642     default:
643       return "<InvaliDataTypeForPrinting>";
644     }
645 }
646
647 // Get the size of the constant for the given target.
648 // If this is an unsized array, return 0.
649 // 
650 inline unsigned int
651 ConstantToSize(const Constant* CV, const TargetMachine& target)
652 {
653   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
654     {
655       const ArrayType *aty = cast<ArrayType>(CPA->getType());
656       if (ArrayTypeIsString(aty))
657         return 1 + CPA->getNumOperands();
658     }
659   
660   return target.findOptimalStorageSize(CV->getType());
661 }
662
663
664
665 // Align data larger than one L1 cache line on L1 cache line boundaries.
666 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
667 // 
668 inline unsigned int
669 SizeToAlignment(unsigned int size, const TargetMachine& target)
670 {
671   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
672   if (size > (unsigned) cacheLineSize / 2)
673     return cacheLineSize;
674   else
675     for (unsigned sz=1; /*no condition*/; sz *= 2)
676       if (sz >= size)
677         return sz;
678 }
679
680 // Get the size of the type and then use SizeToAlignment.
681 // 
682 inline unsigned int
683 TypeToAlignment(const Type* type, const TargetMachine& target)
684 {
685   return SizeToAlignment(target.findOptimalStorageSize(type), target);
686 }
687
688 // Get the size of the constant and then use SizeToAlignment.
689 // Handles strings as a special case;
690 inline unsigned int
691 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
692 {
693   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
694     if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
695       return SizeToAlignment(1 + CPA->getNumOperands(), target);
696   
697   return TypeToAlignment(CV->getType(), target);
698 }
699
700
701 // Print a single constant value.
702 void
703 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
704 {
705   assert(CV->getType() != Type::VoidTy &&
706          CV->getType() != Type::TypeTy &&
707          CV->getType() != Type::LabelTy &&
708          "Unexpected type for Constant");
709   
710   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
711          && "Aggregate types should be handled outside this function");
712   
713   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
714   
715   if (CV->getType()->isPrimitiveType())
716     {
717       if (CV->getType()->isFloatingPoint()) {
718         // FP Constants are printed as integer constants to avoid losing
719         // precision...
720         double Val = cast<ConstantFP>(CV)->getValue();
721         if (CV->getType() == Type::FloatTy) {
722           float FVal = (float)Val;
723           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
724           toAsm << *(unsigned int*)ProxyPtr;            
725         } else if (CV->getType() == Type::DoubleTy) {
726           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
727           toAsm << *(uint64_t*)ProxyPtr;            
728         } else {
729           assert(0 && "Unknown floating point type!");
730         }
731         
732         toAsm << "\t! " << CV->getType()->getDescription()
733               << " value: " << Val << "\n";
734       } else {
735         WriteAsOperand(toAsm, CV, false, false) << "\n";
736       }
737     }
738   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
739     { // This is a constant address for a global variable or method.
740       // Use the name of the variable or method as the address value.
741       toAsm << getID(CPR->getValue()) << "\n";
742     }
743   else if (isa<ConstantPointerNull>(CV))
744     { // Null pointer value
745       toAsm << "0\n";
746     }
747   else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
748     { // Constant expression built from operators, constants, and symbolic addrs
749       toAsm << ConstantExprToString(CE, Target) << "\n";
750     }
751   else
752     {
753       assert(0 && "Unknown elementary type for constant");
754     }
755 }
756
757 // Print a constant value or values (it may be an aggregate).
758 // Uses printSingleConstant() to print each individual value.
759 void
760 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
761 {
762   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
763   
764   if (CPA && isStringCompatible(CPA))
765     { // print the string alone and return
766       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
767     }
768   else if (CPA)
769     { // Not a string.  Print the values in successive locations
770       const std::vector<Use> &constValues = CPA->getValues();
771       for (unsigned i=0; i < constValues.size(); i++)
772         printConstantValueOnly(cast<Constant>(constValues[i].get()));
773     }
774   else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
775     { // Print the fields in successive locations
776       const std::vector<Use>& constValues = CPS->getValues();
777       for (unsigned i=0; i < constValues.size(); i++)
778         printConstantValueOnly(cast<Constant>(constValues[i].get()));
779     }
780   else
781     printSingleConstant(CV);
782 }
783
784 // Print a constant (which may be an aggregate) prefixed by all the
785 // appropriate directives.  Uses printConstantValueOnly() to print the
786 // value or values.
787 void
788 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
789 {
790   if (valID.length() == 0)
791     valID = getID(CV);
792   
793   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
794   
795   // Print .size and .type only if it is not a string.
796   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
797   if (CPA && isStringCompatible(CPA))
798     { // print it as a string and return
799       toAsm << valID << ":\n";
800       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
801       return;
802     }
803   
804   toAsm << "\t.type" << "\t" << valID << ",#object\n";
805
806   unsigned int constSize = ConstantToSize(CV, Target);
807   if (constSize)
808     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
809   
810   toAsm << valID << ":\n";
811   
812   printConstantValueOnly(CV);
813 }
814
815
816 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
817                                           hash_set<const Constant*> &MC) {
818   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
819     if (!I->isExternal()) {
820       const hash_set<const Constant*> &pool =
821         MachineCodeForMethod::get(I).getConstantPoolValues();
822       MC.insert(pool.begin(), pool.end());
823     }
824 }
825
826 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
827 {
828   toAsm << "\t.global\t" << getID(GV) << "\n";
829   
830   if (GV->hasInitializer())
831     printConstant(GV->getInitializer(), getID(GV));
832   else {
833     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
834                                                 Target) << "\n";
835     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
836     toAsm << "\t.reserve\t" << getID(GV) << ","
837           << Target.findOptimalStorageSize(GV->getType()->getElementType())
838           << "\n";
839   }
840 }
841
842
843 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
844   // First, get the constants there were marked by the code generator for
845   // inclusion in the assembly code data area and fold them all into a
846   // single constant pool since there may be lots of duplicates.  Also,
847   // lets force these constants into the slot table so that we can get
848   // unique names for unnamed constants also.
849   // 
850   hash_set<const Constant*> moduleConstants;
851   FoldConstants(M, moduleConstants);
852     
853   // Output constants spilled to memory
854   enterSection(AsmPrinter::ReadOnlyData);
855   for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
856          E = moduleConstants.end();  I != E; ++I)
857     printConstant(*I);
858
859   // Output global variables...
860   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI) {
861     if (GI->hasInitializer() && GI->isConstant()) {
862       enterSection(AsmPrinter::ReadOnlyData);  // read-only, initialized data
863     } else if (GI->hasInitializer() && !GI->isConstant()) { // read-write data
864       enterSection(AsmPrinter::ReadOnlyData);  // read-only, initialized data
865     } else if (GI->hasInitializer() && !GI->isConstant()) { // read-write data
866       enterSection(AsmPrinter::InitRWData);
867     } else {
868       assert (!GI->hasInitializer() && "Unexpected global variable type found");
869       enterSection(AsmPrinter::UninitRWData);       // Uninitialized data
870     }
871     printGlobalVariable(GI);
872   }
873
874   toAsm << "\n";
875 }
876
877 }  // End anonymous namespace
878
879 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
880   return new SparcModuleAsmPrinter(Out, *this);
881 }