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