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