Several major fixes, particularly in emitting constant aggregates:
[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/Module.h"
22 #include "llvm/SlotCalculator.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "Support/StringExtras.h"
26 #include <iostream>
27 using std::string;
28
29 namespace {
30
31 class GlobalIdTable: public Annotation {
32   static AnnotationID AnnotId;
33   friend class AsmPrinter;              // give access to AnnotId
34   
35   typedef hash_map<const Value*, int> ValIdMap;
36   typedef ValIdMap::const_iterator ValIdMapConstIterator;
37   typedef ValIdMap::      iterator ValIdMapIterator;
38 public:
39   SlotCalculator Table;    // map anonymous values to unique integer IDs
40   ValIdMap valToIdMap;     // used for values not handled by SlotCalculator 
41   
42   GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
43 };
44
45 AnnotationID GlobalIdTable::AnnotId =
46   AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
47   
48 //===---------------------------------------------------------------------===//
49 //   Code Shared By the two printer passes, as a mixin
50 //===---------------------------------------------------------------------===//
51
52 class AsmPrinter {
53   GlobalIdTable* idTable;
54 public:
55   std::ostream &toAsm;
56   const TargetMachine &Target;
57   
58   enum Sections {
59     Unknown,
60     Text,
61     ReadOnlyData,
62     InitRWData,
63     ZeroInitRWData,
64   } CurSection;
65
66   AsmPrinter(std::ostream &os, const TargetMachine &T)
67     : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
68   
69   // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
70   void startModule(Module &M) {
71     // Create the global id table if it does not already exist
72     idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
73     if (idTable == NULL) {
74       idTable = new GlobalIdTable(&M);
75       M.addAnnotation(idTable);
76     }
77   }
78   void startFunction(Function &F) {
79     // Make sure the slot table has information about this function...
80     idTable->Table.incorporateFunction(&F);
81   }
82   void endFunction(Function &) {
83     idTable->Table.purgeFunction();  // Forget all about F
84   }
85   void endModule() {
86   }
87
88   // Check if a value is external or accessible from external code.
89   bool isExternal(const Value* V) {
90     const GlobalValue *GV = dyn_cast<GlobalValue>(V);
91     return GV && GV->hasExternalLinkage();
92   }
93   
94   // enterSection - Use this method to enter a different section of the output
95   // executable.  This is used to only output neccesary section transitions.
96   //
97   void enterSection(enum Sections S) {
98     if (S == CurSection) return;        // Only switch section if neccesary
99     CurSection = S;
100
101     toAsm << "\n\t.section ";
102     switch (S)
103       {
104       default: assert(0 && "Bad section name!");
105       case Text:         toAsm << "\".text\""; break;
106       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
107       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
108       case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
109       }
110     toAsm << "\n";
111   }
112
113   static std::string getValidSymbolName(const string &S) {
114     string Result;
115     
116     // Symbol names in Sparc assembly language have these rules:
117     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
118     // (b) A name beginning in "." is treated as a local name.
119     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
120     // 
121     if (S[0] == '_' || isdigit(S[0]))
122       Result += "ll";
123     
124     for (unsigned i = 0; i < S.size(); ++i)
125       {
126         char C = S[i];
127         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
128           Result += C;
129         else
130           {
131             Result += '_';
132             Result += char('0' + ((unsigned char)C >> 4));
133             Result += char('0' + (C & 0xF));
134           }
135       }
136     return Result;
137   }
138
139   // getID - Return a valid identifier for the specified value.  Base it on
140   // the name of the identifier if possible (qualified by the type), and
141   // use a numbered value based on prefix otherwise.
142   // FPrefix is always prepended to the output identifier.
143   //
144   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
145     string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
146     
147     Result +=  V->hasName() ? V->getName() : string(Prefix);
148     
149     // Qualify all internal names with a unique id.
150     if (!isExternal(V)) {
151       int valId = idTable->Table.getValSlot(V);
152       if (valId == -1) {
153         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
154         if (I == idTable->valToIdMap.end())
155           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
156         else
157           valId = I->second;
158       }
159       Result = Result + "_" + itostr(valId);
160     }
161     
162     return getValidSymbolName(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   std::string ConstantExprToString(const ConstantExpr* CE,
190                                    const TargetMachine& target) {
191     std::string S;
192
193     switch(CE->getOpcode()) {
194     case Instruction::GetElementPtr:
195       { // generate a symbolic expression for the byte address
196         const Value* ptrVal = CE->getOperand(0);
197         std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
198         S += "(" + valToExprString(ptrVal, target) + ") + ("
199           + utostr(target.DataLayout.getIndexedOffset(ptrVal->getType(),idxVec))
200           + ")";
201         break;
202       }
203
204     case Instruction::Cast:
205       // Support only non-converting casts for now, i.e., a no-op.
206       // This assertion is not a complete check.
207       assert(target.DataLayout.getTypeSize(CE->getType()) ==
208              target.DataLayout.getTypeSize(CE->getOperand(0)->getType()));
209       S += "(" + valToExprString(CE->getOperand(0), target) + ")";
210       break;
211
212     case Instruction::Add:
213       S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
214                + valToExprString(CE->getOperand(1), target) + ")";
215       break;
216
217     default:
218       assert(0 && "Unsupported operator in ConstantExprToString()");
219       break;
220     }
221
222     return S;
223   }
224
225   // valToExprString - Helper function for ConstantExprToString().
226   // Appends result to argument string S.
227   // 
228   std::string valToExprString(const Value* V, const TargetMachine& target) {
229     std::string S;
230     bool failed = false;
231     if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
232
233       if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
234         S += std::string(CB == ConstantBool::True ? "1" : "0");
235       else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
236         S += itostr(CI->getValue());
237       else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
238         S += utostr(CI->getValue());
239       else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
240         S += ftostr(CFP->getValue());
241       else if (isa<ConstantPointerNull>(CV))
242         S += "0";
243       else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
244         S += valToExprString(CPR->getValue(), target);
245       else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
246         S += ConstantExprToString(CE, target);
247       else
248         failed = true;
249
250     } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
251       S += getID(GV);
252     }
253     else
254       failed = true;
255
256     if (failed) {
257       assert(0 && "Cannot convert value to string");
258       S += "<illegal-value>";
259     }
260     return S;
261   }
262
263 };
264
265
266
267 //===----------------------------------------------------------------------===//
268 //   SparcFunctionAsmPrinter Code
269 //===----------------------------------------------------------------------===//
270
271 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
272   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
273     : AsmPrinter(os, t) {}
274
275   const char *getPassName() const {
276     return "Output Sparc Assembly for Functions";
277   }
278
279   virtual bool doInitialization(Module &M) {
280     startModule(M);
281     return false;
282   }
283
284   virtual bool runOnFunction(Function &F) {
285     startFunction(F);
286     emitFunction(F);
287     endFunction(F);
288     return false;
289   }
290
291   virtual bool doFinalization(Module &M) {
292     endModule();
293     return false;
294   }
295
296   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
297     AU.setPreservesAll();
298   }
299
300   void emitFunction(const Function &F);
301 private :
302   void emitBasicBlock(const BasicBlock *BB);
303   void emitMachineInst(const MachineInstr *MI);
304   
305   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
306   void printOneOperand(const MachineOperand &Op);
307
308   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
309   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
310   
311   unsigned getOperandMask(unsigned Opcode) {
312     switch (Opcode) {
313     case SUBcc:   return 1 << 3;  // Remove CC argument
314   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
315     default:      return 0;       // By default, don't hack operands...
316     }
317   }
318 };
319
320 inline bool
321 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
322                                                unsigned int opNum) {
323   switch (MI->getOpCode()) {
324   case JMPLCALL:
325   case JMPLRET: return (opNum == 0);
326   default:      return false;
327   }
328 }
329
330
331 inline bool
332 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
333                                                unsigned int opNum) {
334   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
335     return (opNum == 0);
336   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
337     return (opNum == 1);
338   else
339     return false;
340 }
341
342
343 #define PrintOp1PlusOp2(mop1, mop2) \
344   printOneOperand(mop1); \
345   toAsm << "+"; \
346   printOneOperand(mop2);
347
348 unsigned int
349 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
350                                unsigned int opNum)
351 {
352   const MachineOperand& mop = MI->getOperand(opNum);
353   
354   if (OpIsBranchTargetLabel(MI, opNum))
355     {
356       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
357       return 2;
358     }
359   else if (OpIsMemoryAddressBase(MI, opNum))
360     {
361       toAsm << "[";
362       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
363       toAsm << "]";
364       return 2;
365     }
366   else
367     {
368       printOneOperand(mop);
369       return 1;
370     }
371 }
372
373
374 void
375 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop)
376 {
377   bool needBitsFlag = true;
378   
379   if (mop.opHiBits32())
380     toAsm << "%lm(";
381   else if (mop.opLoBits32())
382     toAsm << "%lo(";
383   else if (mop.opHiBits64())
384     toAsm << "%hh(";
385   else if (mop.opLoBits64())
386     toAsm << "%hm(";
387   else
388     needBitsFlag = false;
389   
390   switch (mop.getOperandType())
391     {
392     case MachineOperand::MO_VirtualRegister:
393     case MachineOperand::MO_CCRegister:
394     case MachineOperand::MO_MachineRegister:
395       {
396         int RegNum = (int)mop.getAllocatedRegNum();
397         
398         // better to print code with NULL registers than to die
399         if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
400           toAsm << "<NULL VALUE>";
401         } else {
402           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
403         }
404         break;
405       }
406     
407     case MachineOperand::MO_PCRelativeDisp:
408       {
409         const Value *Val = mop.getVRegValue();
410         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
411         
412         if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
413           toAsm << getID(BB);
414         else if (const Function *M = dyn_cast<Function>(Val))
415           toAsm << getID(M);
416         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
417           toAsm << getID(GV);
418         else if (const Constant *CV = dyn_cast<Constant>(Val))
419           toAsm << getID(CV);
420         else
421           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
422         break;
423       }
424     
425     case MachineOperand::MO_SignExtendedImmed:
426       toAsm << mop.getImmedValue();
427       break;
428
429     case MachineOperand::MO_UnextendedImmed:
430       toAsm << (uint64_t) mop.getImmedValue();
431       break;
432     
433     default:
434       toAsm << mop;      // use dump field
435       break;
436     }
437   
438   if (needBitsFlag)
439     toAsm << ")";
440 }
441
442
443 void
444 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
445 {
446   unsigned Opcode = MI->getOpCode();
447
448   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
449     return;  // IGNORE PHI NODES
450
451   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
452
453   unsigned Mask = getOperandMask(Opcode);
454   
455   bool NeedComma = false;
456   unsigned N = 1;
457   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
458     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
459       if (NeedComma) toAsm << ", ";         // Handle comma outputing
460       NeedComma = true;
461       N = printOperands(MI, OpNum);
462     }
463   else
464     N = 1;
465   
466   toAsm << "\n";
467 }
468
469 void
470 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
471 {
472   // Emit a label for the basic block
473   toAsm << getID(BB) << ":\n";
474
475   // Get the vector of machine instructions corresponding to this bb.
476   const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
477   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
478
479   // Loop over all of the instructions in the basic block...
480   for (; MII != MIE; ++MII)
481     emitMachineInst(*MII);
482   toAsm << "\n";  // Seperate BB's with newlines
483 }
484
485 void
486 SparcFunctionAsmPrinter::emitFunction(const Function &F)
487 {
488   string methName = getID(&F);
489   toAsm << "!****** Outputing Function: " << methName << " ******\n";
490   enterSection(AsmPrinter::Text);
491   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
492   //toAsm << "\t.type\t" << methName << ",#function\n";
493   toAsm << "\t.type\t" << methName << ", 2\n";
494   toAsm << methName << ":\n";
495
496   // Output code for all of the basic blocks in the function...
497   for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
498     emitBasicBlock(I);
499
500   // Output a .size directive so the debugger knows the extents of the function
501   toAsm << ".EndOf_" << methName << ":\n\t.size "
502            << methName << ", .EndOf_"
503            << methName << "-" << methName << "\n";
504
505   // Put some spaces between the functions
506   toAsm << "\n\n";
507 }
508
509 }  // End anonymous namespace
510
511 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
512   return new SparcFunctionAsmPrinter(Out, *this);
513 }
514
515
516
517
518
519 //===----------------------------------------------------------------------===//
520 //   SparcFunctionAsmPrinter Code
521 //===----------------------------------------------------------------------===//
522
523 namespace {
524
525 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
526 public:
527   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
528     : AsmPrinter(os, t) {}
529
530   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
531
532   virtual bool run(Module &M) {
533     startModule(M);
534     emitGlobalsAndConstants(M);
535     endModule();
536     return false;
537   }
538
539   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
540     AU.setPreservesAll();
541   }
542
543 private:
544   void emitGlobalsAndConstants  (const Module &M);
545
546   void printGlobalVariable      (const GlobalVariable *GV);
547   void PrintZeroBytesToPad      (int numBytes);
548   void printSingleConstantValue (const Constant* CV);
549   void printConstantValueOnly   (const Constant* CV, int numPadBytes = 0);
550   void printConstant            (const Constant* CV, std::string valID = "");
551
552   static void FoldConstants     (const Module &M,
553                                  hash_set<const Constant*> &moduleConstants);
554 };
555
556
557 // Can we treat the specified array as a string?  Only if it is an array of
558 // ubytes or non-negative sbytes.
559 //
560 static bool isStringCompatible(const ConstantArray *CVA) {
561   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
562   if (ETy == Type::UByteTy) return true;
563   if (ETy != Type::SByteTy) return false;
564
565   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
566     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
567       return false;
568
569   return true;
570 }
571
572 // toOctal - Convert the low order bits of X into an octal letter
573 static inline char toOctal(int X) {
574   return (X&7)+'0';
575 }
576
577 // getAsCString - Return the specified array as a C compatible string, only if
578 // the predicate isStringCompatible is true.
579 //
580 static string getAsCString(const ConstantArray *CVA) {
581   assert(isStringCompatible(CVA) && "Array is not string compatible!");
582
583   string Result;
584   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
585   Result = "\"";
586   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
587     unsigned char C = (ETy == Type::SByteTy) ?
588       (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
589       (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
590
591     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 numPadBytes /* = 0*/)
790 {
791   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
792
793   if (numPadBytes)
794     PrintZeroBytesToPad(numPadBytes);
795
796   if (CVA && isStringCompatible(CVA))
797     { // print the string alone and return
798       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
799     }
800   else if (CVA)
801     { // Not a string.  Print the values in successive locations
802       const std::vector<Use> &constValues = CVA->getValues();
803       for (unsigned i=0; i < constValues.size(); i++)
804         printConstantValueOnly(cast<Constant>(constValues[i].get()));
805     }
806   else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
807     { // Print the fields in successive locations. Pad to align if needed!
808       const StructLayout *cvsLayout =
809         Target.DataLayout.getStructLayout(CVS->getType());
810       const std::vector<Use>& constValues = CVS->getValues();
811       unsigned sizeSoFar = 0;
812       for (unsigned i=0, N = constValues.size(); i < N; i++)
813         {
814           const Constant* field = cast<Constant>(constValues[i].get());
815
816           // Check if padding is needed and insert one or more 0s.
817           unsigned fieldSize = Target.DataLayout.getTypeSize(field->getType());
818           int padSize = ((i == N-1? cvsLayout->StructSize
819                                   : cvsLayout->MemberOffsets[i+1])
820                          - cvsLayout->MemberOffsets[i]) - fieldSize;
821           sizeSoFar += (fieldSize + padSize);
822
823           // Now print the actual field value
824           printConstantValueOnly(field, padSize);
825         }
826       assert(sizeSoFar == cvsLayout->StructSize &&
827              "Layout of constant struct may be incorrect!");
828     }
829   else
830     printSingleConstantValue(CV);
831 }
832
833 // Print a constant (which may be an aggregate) prefixed by all the
834 // appropriate directives.  Uses printConstantValueOnly() to print the
835 // value or values.
836 void
837 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
838 {
839   if (valID.length() == 0)
840     valID = getID(CV);
841   
842   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
843   
844   // Print .size and .type only if it is not a string.
845   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
846   if (CVA && isStringCompatible(CVA))
847     { // print it as a string and return
848       toAsm << valID << ":\n";
849       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
850       return;
851     }
852   
853   toAsm << "\t.type" << "\t" << valID << ",#object\n";
854
855   unsigned int constSize = ConstantToSize(CV, Target);
856   if (constSize)
857     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
858   
859   toAsm << valID << ":\n";
860   
861   printConstantValueOnly(CV);
862 }
863
864
865 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
866                                           hash_set<const Constant*> &MC) {
867   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
868     if (!I->isExternal()) {
869       const hash_set<const Constant*> &pool =
870         MachineCodeForMethod::get(I).getConstantPoolValues();
871       MC.insert(pool.begin(), pool.end());
872     }
873 }
874
875 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
876 {
877   if (GV->hasExternalLinkage())
878     toAsm << "\t.global\t" << getID(GV) << "\n";
879   
880   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
881     printConstant(GV->getInitializer(), getID(GV));
882   else {
883     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
884                                                 Target) << "\n";
885     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
886     toAsm << "\t.reserve\t" << getID(GV) << ","
887           << TypeToSize(GV->getType()->getElementType(), Target)
888           << "\n";
889   }
890 }
891
892
893 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
894   // First, get the constants there were marked by the code generator for
895   // inclusion in the assembly code data area and fold them all into a
896   // single constant pool since there may be lots of duplicates.  Also,
897   // lets force these constants into the slot table so that we can get
898   // unique names for unnamed constants also.
899   // 
900   hash_set<const Constant*> moduleConstants;
901   FoldConstants(M, moduleConstants);
902     
903   // Output constants spilled to memory
904   enterSection(AsmPrinter::ReadOnlyData);
905   for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
906          E = moduleConstants.end();  I != E; ++I)
907     printConstant(*I);
908
909   // Output global variables...
910   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
911     if (! GI->isExternal()) {
912       assert(GI->hasInitializer());
913       if (GI->isConstant())
914         enterSection(AsmPrinter::ReadOnlyData);   // read-only, initialized data
915       else if (GI->getInitializer()->isNullValue())
916         enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
917       else
918         enterSection(AsmPrinter::InitRWData);     // read-write non-zero data
919
920       printGlobalVariable(GI);
921     }
922
923   toAsm << "\n";
924 }
925
926 }  // End anonymous namespace
927
928 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
929   return new SparcModuleAsmPrinter(Out, *this);
930 }