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