BA no longer has the unused CC operand.
[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 std::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 name is external or accessible from external code.
91   // Only functions can currently be external.  "main" is the only name
92   // that is visible externally.
93   bool isExternal(const Value* V) {
94     const Function *F = dyn_cast<Function>(V);
95     return F && (F->isExternal() || F->getName() == "main");
96   }
97   
98   // enterSection - Use this method to enter a different section of the output
99   // executable.  This is used to only output neccesary section transitions.
100   //
101   void enterSection(enum Sections S) {
102     if (S == CurSection) return;        // Only switch section if neccesary
103     CurSection = S;
104
105     toAsm << "\n\t.section ";
106     switch (S)
107       {
108       default: assert(0 && "Bad section name!");
109       case Text:         toAsm << "\".text\""; break;
110       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
111       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
112       case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
113       }
114     toAsm << "\n";
115   }
116
117   static std::string getValidSymbolName(const string &S) {
118     string Result;
119     
120     // Symbol names in Sparc assembly language have these rules:
121     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
122     // (b) A name beginning in "." is treated as a local name.
123     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
124     // 
125     if (S[0] == '_' || isdigit(S[0]))
126       Result += "ll";
127     
128     for (unsigned i = 0; i < S.size(); ++i)
129       {
130         char C = S[i];
131         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
132           Result += C;
133         else
134           {
135             Result += '_';
136             Result += char('0' + ((unsigned char)C >> 4));
137             Result += char('0' + (C & 0xF));
138           }
139       }
140     return Result;
141   }
142
143   // getID - Return a valid identifier for the specified value.  Base it on
144   // the name of the identifier if possible (qualified by the type), and
145   // use a numbered value based on prefix otherwise.
146   // FPrefix is always prepended to the output identifier.
147   //
148   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
149     string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
150     
151     Result = Result + (V->hasName()? V->getName() : string(Prefix));
152     
153     // Qualify all internal names with a unique id.
154     if (!isExternal(V)) {
155       int valId = idTable->Table.getValSlot(V);
156       if (valId == -1) {
157         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
158         if (I == idTable->valToIdMap.end())
159           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
160         else
161           valId = I->second;
162       }
163       Result = Result + "_" + itostr(valId);
164     }
165     
166     return getValidSymbolName(Result);
167   }
168   
169   // getID Wrappers - Ensure consistent usage...
170   string getID(const Function *F) {
171     return getID(F, "LLVMFunction_");
172   }
173   string getID(const BasicBlock *BB) {
174     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
175   }
176   string getID(const GlobalVariable *GV) {
177     return getID(GV, "LLVMGlobal_", ".G_");
178   }
179   string getID(const Constant *CV) {
180     return getID(CV, "LLVMConst_", ".C_");
181   }
182 };
183
184
185
186 //===----------------------------------------------------------------------===//
187 //   SparcFunctionAsmPrinter Code
188 //===----------------------------------------------------------------------===//
189
190 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
191   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
192     : AsmPrinter(os, t) {}
193
194   const char *getPassName() const {
195     return "Output Sparc Assembly for Functions";
196   }
197
198   virtual bool doInitialization(Module &M) {
199     startModule(M);
200     return false;
201   }
202
203   virtual bool runOnFunction(Function &F) {
204     startFunction(F);
205     emitFunction(F);
206     endFunction(F);
207     return false;
208   }
209
210   virtual bool doFinalization(Module &M) {
211     endModule();
212     return false;
213   }
214
215   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
216     AU.setPreservesAll();
217   }
218
219   void emitFunction(const Function &F);
220 private :
221   void emitBasicBlock(const BasicBlock *BB);
222   void emitMachineInst(const MachineInstr *MI);
223   
224   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
225   void printOneOperand(const MachineOperand &Op);
226
227   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
228   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
229   
230   unsigned getOperandMask(unsigned Opcode) {
231     switch (Opcode) {
232     case SUBcc:   return 1 << 3;  // Remove CC argument
233   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
234     default:      return 0;       // By default, don't hack operands...
235     }
236   }
237 };
238
239 inline bool
240 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
241                                                unsigned int opNum) {
242   switch (MI->getOpCode()) {
243   case JMPLCALL:
244   case JMPLRET: return (opNum == 0);
245   default:      return false;
246   }
247 }
248
249
250 inline bool
251 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
252                                                unsigned int opNum) {
253   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
254     return (opNum == 0);
255   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
256     return (opNum == 1);
257   else
258     return false;
259 }
260
261
262 #define PrintOp1PlusOp2(Op1, Op2) \
263   printOneOperand(Op1); \
264   toAsm << "+"; \
265   printOneOperand(Op2);
266
267 unsigned int
268 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
269                                unsigned int opNum)
270 {
271   const MachineOperand& Op = MI->getOperand(opNum);
272   
273   if (OpIsBranchTargetLabel(MI, opNum))
274     {
275       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
276       return 2;
277     }
278   else if (OpIsMemoryAddressBase(MI, opNum))
279     {
280       toAsm << "[";
281       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
282       toAsm << "]";
283       return 2;
284     }
285   else
286     {
287       printOneOperand(Op);
288       return 1;
289     }
290 }
291
292
293 void
294 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
295 {
296   switch (op.getOperandType())
297     {
298     case MachineOperand::MO_VirtualRegister:
299     case MachineOperand::MO_CCRegister:
300     case MachineOperand::MO_MachineRegister:
301       {
302         int RegNum = (int)op.getAllocatedRegNum();
303         
304         // better to print code with NULL registers than to die
305         if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
306           toAsm << "<NULL VALUE>";
307         } else {
308           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
309         }
310         break;
311       }
312     
313     case MachineOperand::MO_PCRelativeDisp:
314       {
315         const Value *Val = op.getVRegValue();
316         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
317         
318         if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
319           toAsm << getID(BB);
320         else if (const Function *M = dyn_cast<Function>(Val))
321           toAsm << getID(M);
322         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
323           toAsm << getID(GV);
324         else if (const Constant *CV = dyn_cast<Constant>(Val))
325           toAsm << getID(CV);
326         else
327           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
328         break;
329       }
330     
331     case MachineOperand::MO_SignExtendedImmed:
332       toAsm << op.getImmedValue();
333       break;
334
335     case MachineOperand::MO_UnextendedImmed:
336       toAsm << (uint64_t) op.getImmedValue();
337       break;
338     
339     default:
340       toAsm << op;      // use dump field
341       break;
342     }
343 }
344
345
346 void
347 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
348 {
349   unsigned Opcode = MI->getOpCode();
350
351   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
352     return;  // IGNORE PHI NODES
353
354   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
355
356   unsigned Mask = getOperandMask(Opcode);
357   
358   bool NeedComma = false;
359   unsigned N = 1;
360   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
361     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
362       if (NeedComma) toAsm << ", ";         // Handle comma outputing
363       NeedComma = true;
364       N = printOperands(MI, OpNum);
365     }
366   else
367     N = 1;
368   
369   toAsm << "\n";
370 }
371
372 void
373 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
374 {
375   // Emit a label for the basic block
376   toAsm << getID(BB) << ":\n";
377
378   // Get the vector of machine instructions corresponding to this bb.
379   const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
380   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
381
382   // Loop over all of the instructions in the basic block...
383   for (; MII != MIE; ++MII)
384     emitMachineInst(*MII);
385   toAsm << "\n";  // Seperate BB's with newlines
386 }
387
388 void
389 SparcFunctionAsmPrinter::emitFunction(const Function &F)
390 {
391   string methName = getID(&F);
392   toAsm << "!****** Outputing Function: " << methName << " ******\n";
393   enterSection(AsmPrinter::Text);
394   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
395   //toAsm << "\t.type\t" << methName << ",#function\n";
396   toAsm << "\t.type\t" << methName << ", 2\n";
397   toAsm << methName << ":\n";
398
399   // Output code for all of the basic blocks in the function...
400   for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
401     emitBasicBlock(I);
402
403   // Output a .size directive so the debugger knows the extents of the function
404   toAsm << ".EndOf_" << methName << ":\n\t.size "
405            << methName << ", .EndOf_"
406            << methName << "-" << methName << "\n";
407
408   // Put some spaces between the functions
409   toAsm << "\n\n";
410 }
411
412 }  // End anonymous namespace
413
414 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
415   return new SparcFunctionAsmPrinter(Out, *this);
416 }
417
418
419
420
421
422 //===----------------------------------------------------------------------===//
423 //   SparcFunctionAsmPrinter Code
424 //===----------------------------------------------------------------------===//
425
426 namespace {
427
428 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
429 public:
430   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
431     : AsmPrinter(os, t) {}
432
433   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
434
435   virtual bool run(Module &M) {
436     startModule(M);
437     emitGlobalsAndConstants(M);
438     endModule();
439     return false;
440   }
441
442   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
443     AU.setPreservesAll();
444   }
445
446 private:
447   void emitGlobalsAndConstants(const Module &M);
448
449   void printGlobalVariable(const GlobalVariable *GV);
450   void printSingleConstant(   const Constant* CV);
451   void printConstantValueOnly(const Constant* CV);
452   void printConstant(         const Constant* CV, std::string valID = "");
453
454   static void FoldConstants(const Module &M,
455                             std::hash_set<const Constant*> &moduleConstants);
456 };
457
458
459 // Can we treat the specified array as a string?  Only if it is an array of
460 // ubytes or non-negative sbytes.
461 //
462 static bool isStringCompatible(const ConstantArray *CPA) {
463   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
464   if (ETy == Type::UByteTy) return true;
465   if (ETy != Type::SByteTy) return false;
466
467   for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
468     if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
469       return false;
470
471   return true;
472 }
473
474 // toOctal - Convert the low order bits of X into an octal letter
475 static inline char toOctal(int X) {
476   return (X&7)+'0';
477 }
478
479 // getAsCString - Return the specified array as a C compatible string, only if
480 // the predicate isStringCompatible is true.
481 //
482 static string getAsCString(const ConstantArray *CPA) {
483   assert(isStringCompatible(CPA) && "Array is not string compatible!");
484
485   string Result;
486   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
487   Result = "\"";
488   for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
489     unsigned char C = (ETy == Type::SByteTy) ?
490       (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
491       (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
492
493     if (C == '"') {
494       Result += "\\\"";
495     } else if (isprint(C)) {
496       Result += C;
497     } else {
498       switch(C) {
499       case '\a': Result += "\\a"; break;
500       case '\b': Result += "\\b"; break;
501       case '\f': Result += "\\f"; break;
502       case '\n': Result += "\\n"; break;
503       case '\r': Result += "\\r"; break;
504       case '\t': Result += "\\t"; break;
505       case '\v': Result += "\\v"; break;
506       default:
507         Result += '\\';
508         Result += toOctal(C >> 6);
509         Result += toOctal(C >> 3);
510         Result += toOctal(C >> 0);
511         break;
512       }
513     }
514   }
515   Result += "\"";
516
517   return Result;
518 }
519
520 inline bool
521 ArrayTypeIsString(const ArrayType* arrayType)
522 {
523   return (arrayType->getElementType() == Type::UByteTy ||
524           arrayType->getElementType() == Type::SByteTy);
525 }
526
527 inline const string
528 TypeToDataDirective(const Type* type)
529 {
530   switch(type->getPrimitiveID())
531     {
532     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
533       return ".byte";
534     case Type::UShortTyID: case Type::ShortTyID:
535       return ".half";
536     case Type::UIntTyID: case Type::IntTyID:
537       return ".word";
538     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
539       return ".xword";
540     case Type::FloatTyID:
541       return ".word";
542     case Type::DoubleTyID:
543       return ".xword";
544     case Type::ArrayTyID:
545       if (ArrayTypeIsString((ArrayType*) type))
546         return ".ascii";
547       else
548         return "<InvaliDataTypeForPrinting>";
549     default:
550       return "<InvaliDataTypeForPrinting>";
551     }
552 }
553
554 // Get the size of the constant for the given target.
555 // If this is an unsized array, return 0.
556 // 
557 inline unsigned int
558 ConstantToSize(const Constant* CV, const TargetMachine& target)
559 {
560   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
561     {
562       const ArrayType *aty = cast<ArrayType>(CPA->getType());
563       if (ArrayTypeIsString(aty))
564         return 1 + CPA->getNumOperands();
565     }
566   
567   return target.findOptimalStorageSize(CV->getType());
568 }
569
570
571
572 // Align data larger than one L1 cache line on L1 cache line boundaries.
573 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
574 // 
575 inline unsigned int
576 SizeToAlignment(unsigned int size, const TargetMachine& target)
577 {
578   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
579   if (size > (unsigned) cacheLineSize / 2)
580     return cacheLineSize;
581   else
582     for (unsigned sz=1; /*no condition*/; sz *= 2)
583       if (sz >= size)
584         return sz;
585 }
586
587 // Get the size of the type and then use SizeToAlignment.
588 // 
589 inline unsigned int
590 TypeToAlignment(const Type* type, const TargetMachine& target)
591 {
592   return SizeToAlignment(target.findOptimalStorageSize(type), target);
593 }
594
595 // Get the size of the constant and then use SizeToAlignment.
596 // Handles strings as a special case;
597 inline unsigned int
598 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
599 {
600   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
601     if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
602       return SizeToAlignment(1 + CPA->getNumOperands(), target);
603   
604   return TypeToAlignment(CV->getType(), target);
605 }
606
607
608 // Print a single constant value.
609 void
610 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
611 {
612   assert(CV->getType() != Type::VoidTy &&
613          CV->getType() != Type::TypeTy &&
614          CV->getType() != Type::LabelTy &&
615          "Unexpected type for Constant");
616   
617   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
618          && "Aggregate types should be handled outside this function");
619   
620   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
621   
622   if (CV->getType()->isPrimitiveType())
623     {
624       if (CV->getType()->isFloatingPoint()) {
625         // FP Constants are printed as integer constants to avoid losing
626         // precision...
627         double Val = cast<ConstantFP>(CV)->getValue();
628         if (CV->getType() == Type::FloatTy) {
629           float FVal = (float)Val;
630           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
631           toAsm << *(unsigned int*)ProxyPtr;            
632         } else if (CV->getType() == Type::DoubleTy) {
633           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
634           toAsm << *(uint64_t*)ProxyPtr;            
635         } else {
636           assert(0 && "Unknown floating point type!");
637         }
638         
639         toAsm << "\t! " << CV->getType()->getDescription()
640               << " value: " << Val << "\n";
641       } else {
642         WriteAsOperand(toAsm, CV, false, false) << "\n";
643       }
644     }
645   else if (const ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
646     {
647       assert(CPP->isNullValue() &&
648              "Cannot yet print non-null pointer constants to assembly");
649       toAsm << "0\n";
650     }
651   else if (isa<ConstantPointerRef>(CV))
652     {
653       assert(0 && "Cannot yet initialize pointer refs in assembly");
654     }
655   else
656     {
657       assert(0 && "Unknown elementary type for constant");
658     }
659 }
660
661 // Print a constant value or values (it may be an aggregate).
662 // Uses printSingleConstant() to print each individual value.
663 void
664 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
665 {
666   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
667   
668   if (CPA && isStringCompatible(CPA))
669     { // print the string alone and return
670       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
671     }
672   else if (CPA)
673     { // Not a string.  Print the values in successive locations
674       const std::vector<Use> &constValues = CPA->getValues();
675       for (unsigned i=0; i < constValues.size(); i++)
676         printConstantValueOnly(cast<Constant>(constValues[i].get()));
677     }
678   else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
679     { // Print the fields in successive locations
680       const std::vector<Use>& constValues = CPS->getValues();
681       for (unsigned i=0; i < constValues.size(); i++)
682         printConstantValueOnly(cast<Constant>(constValues[i].get()));
683     }
684   else
685     printSingleConstant(CV);
686 }
687
688 // Print a constant (which may be an aggregate) prefixed by all the
689 // appropriate directives.  Uses printConstantValueOnly() to print the
690 // value or values.
691 void
692 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
693 {
694   if (valID.length() == 0)
695     valID = getID(CV);
696   
697   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
698   
699   // Print .size and .type only if it is not a string.
700   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
701   if (CPA && isStringCompatible(CPA))
702     { // print it as a string and return
703       toAsm << valID << ":\n";
704       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
705       return;
706     }
707   
708   toAsm << "\t.type" << "\t" << valID << ",#object\n";
709
710   unsigned int constSize = ConstantToSize(CV, Target);
711   if (constSize)
712     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
713   
714   toAsm << valID << ":\n";
715   
716   printConstantValueOnly(CV);
717 }
718
719
720 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
721                                           std::hash_set<const Constant*> &MC) {
722   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
723     if (!I->isExternal()) {
724       const std::hash_set<const Constant*> &pool =
725         MachineCodeForMethod::get(I).getConstantPoolValues();
726       MC.insert(pool.begin(), pool.end());
727     }
728 }
729
730 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
731 {
732   toAsm << "\t.global\t" << getID(GV) << "\n";
733   
734   if (GV->hasInitializer())
735     printConstant(GV->getInitializer(), getID(GV));
736   else {
737     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
738                                                 Target) << "\n";
739     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
740     toAsm << "\t.reserve\t" << getID(GV) << ","
741           << Target.findOptimalStorageSize(GV->getType()->getElementType())
742           << "\n";
743   }
744 }
745
746
747 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
748   // First, get the constants there were marked by the code generator for
749   // inclusion in the assembly code data area and fold them all into a
750   // single constant pool since there may be lots of duplicates.  Also,
751   // lets force these constants into the slot table so that we can get
752   // unique names for unnamed constants also.
753   // 
754   std::hash_set<const Constant*> moduleConstants;
755   FoldConstants(M, moduleConstants);
756     
757   // Now, emit the three data sections separately; the cost of I/O should
758   // make up for the cost of extra passes over the globals list!
759   
760   // Section 1 : Read-only data section (implies initialized)
761   enterSection(AsmPrinter::ReadOnlyData);
762   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
763     if (GI->hasInitializer() && GI->isConstant())
764       printGlobalVariable(GI);
765   
766   for (std::hash_set<const Constant*>::const_iterator
767          I = moduleConstants.begin(),
768          E = moduleConstants.end();  I != E; ++I)
769     printConstant(*I);
770   
771   // Section 2 : Initialized read-write data section
772   enterSection(AsmPrinter::InitRWData);
773   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
774     if (GI->hasInitializer() && !GI->isConstant())
775       printGlobalVariable(GI);
776   
777   // Section 3 : Uninitialized read-write data section
778   enterSection(AsmPrinter::UninitRWData);
779   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
780     if (!GI->hasInitializer())
781       printGlobalVariable(GI);
782   
783   toAsm << "\n";
784 }
785
786 }  // End anonymous namespace
787
788 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
789   return new SparcModuleAsmPrinter(Out, *this);
790 }