Bug fix: need to use .reserve for uninitialized data.
[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 // The entry point of this file is the UltraSparc::emitAssembly method.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "SparcInternals.h"
12 #include "llvm/Analysis/SlotCalculator.h"
13 #include "llvm/Transforms/Linker.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/ConstPoolVals.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/Method.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/HashExtras.h"
23 #include "llvm/Support/StringExtras.h"
24 #include <locale.h>
25
26 namespace {
27
28
29 class SparcAsmPrinter {
30   typedef hash_map<const Value*, int> ValIdMap;
31   typedef ValIdMap::      iterator ValIdMapIterator;
32   typedef ValIdMap::const_iterator ValIdMapConstIterator;
33   
34   ostream &toAsm;
35   SlotCalculator Table;   // map anonymous values to unique integer IDs
36   ValIdMap valToIdMap;    // used for values not handled by SlotCalculator 
37   const UltraSparc &Target;
38   
39   enum Sections {
40     Unknown,
41     Text,
42     ReadOnlyData,
43     InitRWData,
44     UninitRWData,
45   } CurSection;
46   
47 public:
48   inline SparcAsmPrinter(ostream &o, const Module *M, const UltraSparc &t)
49     : toAsm(o), Table(SlotCalculator(M, true)), Target(t), CurSection(Unknown) {
50     emitModule(M);
51   }
52
53 private :
54   void emitModule(const Module *M);
55   void emitMethod(const Method *M);
56   void emitGlobalsAndConstants(const Module* module);
57   //void processMethodArgument(const MethodArgument *MA);
58   void emitBasicBlock(const BasicBlock *BB);
59   void emitMachineInst(const MachineInstr *MI);
60   
61   void printGlobalVariable(const GlobalVariable* GV);
62   void printConstant(const ConstPoolVal* CV, string valID = string(""));
63   
64   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
65   void printOneOperand(const MachineOperand &Op);
66
67   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
68   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
69   
70   // enterSection - Use this method to enter a different section of the output
71   // executable.  This is used to only output neccesary section transitions.
72   //
73   void enterSection(enum Sections S) {
74     if (S == CurSection) return;        // Only switch section if neccesary
75     CurSection = S;
76
77     toAsm << "\n\t.section ";
78     switch (S)
79       {
80       default: assert(0 && "Bad section name!");
81       case Text:         toAsm << "\".text\""; break;
82       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
83       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
84       case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
85       }
86     toAsm << "\n";
87   }
88
89   string getValidSymbolName(const string &S) {
90     string Result;
91     
92     // Symbol names in Sparc assembly language have these rules:
93     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
94     // (b) A name beginning in "." is treated as a local name.
95     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
96     // 
97     if (S[0] == '_' || isdigit(S[0]))
98       Result += "ll";
99     
100     for (unsigned i = 0; i < S.size(); ++i)
101       {
102         char C = S[i];
103         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
104           Result += C;
105         else
106           {
107             Result += '_';
108             Result += char('0' + ((unsigned char)C >> 4));
109             Result += char('0' + (C & 0xF));
110           }
111       }
112     return Result;
113   }
114
115   // getID - Return a valid identifier for the specified value.  Base it on
116   // the name of the identifier if possible, use a numbered value based on
117   // prefix otherwise.  FPrefix is always prepended to the output identifier.
118   //
119   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
120     string Result;
121     string FP(FPrefix ? FPrefix : "");  // "Forced prefix"
122     if (V->hasName()) {
123       Result = FP + V->getName();
124     } else {
125       int valId = Table.getValSlot(V);
126       if (valId == -1) {
127         ValIdMapConstIterator I = valToIdMap.find(V);
128         valId = (I == valToIdMap.end())? (valToIdMap[V] = valToIdMap.size())
129                                        : (*I).second;
130       }
131       Result = FP + string(Prefix) + itostr(valId);
132     }
133     return getValidSymbolName(Result);
134   }
135   
136   // getID Wrappers - Ensure consistent usage...
137   string getID(const Module *M) {
138     return getID(M, "LLVMModule_");
139   }
140   string getID(const Method *M) {
141     return getID(M, "LLVMMethod_");
142   }
143   string getID(const BasicBlock *BB) {
144     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
145   }
146   string getID(const GlobalVariable *GV) {
147     return getID(GV, "LLVMGlobal_", ".G_");
148   }
149   string getID(const ConstPoolVal *CV) {
150     return getID(CV, "LLVMConst_", ".C_");
151   }
152   
153   unsigned getOperandMask(unsigned Opcode) {
154     switch (Opcode) {
155     case SUBcc:   return 1 << 3;  // Remove CC argument
156     case BA:    case BRZ:         // Remove Arg #0, which is always null or xcc
157     case BRLEZ: case BRLZ:
158     case BRNZ:  case BRGZ:
159     case BRGEZ:   return 1 << 0;
160
161     default:      return 0;       // By default, don't hack operands...
162     }
163   }
164 };
165
166 inline bool
167 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
168                                        unsigned int opNum) {
169   switch (MI->getOpCode()) {
170   case JMPLCALL:
171   case JMPLRET: return (opNum == 0);
172   default:      return false;
173   }
174 }
175
176
177 inline bool
178 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
179                                        unsigned int opNum) {
180   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
181     return (opNum == 0);
182   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
183     return (opNum == 1);
184   else
185     return false;
186 }
187
188
189 #define PrintOp1PlusOp2(Op1, Op2) \
190   printOneOperand(Op1); toAsm << "+"; printOneOperand(Op2);
191
192
193 unsigned int
194 SparcAsmPrinter::printOperands(const MachineInstr *MI,
195                                unsigned int opNum)
196 {
197   const MachineOperand& Op = MI->getOperand(opNum);
198   
199   if (OpIsBranchTargetLabel(MI, opNum))
200     {
201       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
202       return 2;
203     }
204   else if (OpIsMemoryAddressBase(MI, opNum))
205     {
206       toAsm << "[";
207       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
208       toAsm << "]";
209       return 2;
210     }
211   else
212     {
213       printOneOperand(Op);
214       return 1;
215     }
216 }
217
218
219 void
220 SparcAsmPrinter::printOneOperand(const MachineOperand &op)
221 {
222   switch (op.getOperandType())
223     {
224     case MachineOperand::MO_VirtualRegister:
225     case MachineOperand::MO_CCRegister:
226     case MachineOperand::MO_MachineRegister:
227       {
228         int RegNum = (int)op.getAllocatedRegNum();
229         
230         // ****this code is temporary till NULL Values are fixed
231         if (RegNum == 10000) {
232           toAsm << "<NULL VALUE>";
233         } else {
234           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
235         }
236         break;
237       }
238     
239     case MachineOperand::MO_PCRelativeDisp:
240       {
241         const Value *Val = op.getVRegValue();
242         if (!Val)
243           toAsm << "\t<*NULL Value*>";
244         else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
245           toAsm << getID(BB);
246         else if (const Method *M = dyn_cast<const Method>(Val))
247           toAsm << getID(M);
248         else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
249           toAsm << getID(GV);
250         else if (const ConstPoolVal *CV = dyn_cast<const ConstPoolVal>(Val))
251           toAsm << getID(CV);
252         else
253           toAsm << "<unknown value=" << Val << ">";
254         break;
255       }
256     
257     case MachineOperand::MO_SignExtendedImmed:
258     case MachineOperand::MO_UnextendedImmed:
259       toAsm << op.getImmedValue();
260       break;
261     
262     default:
263       toAsm << op;      // use dump field
264       break;
265     }
266 }
267
268
269 void
270 SparcAsmPrinter::emitMachineInst(const MachineInstr *MI)
271 {
272   unsigned Opcode = MI->getOpCode();
273
274   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
275     return;  // IGNORE PHI NODES
276
277   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
278
279   unsigned Mask = getOperandMask(Opcode);
280   
281   bool NeedComma = false;
282   unsigned N = 1;
283   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
284     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
285       if (NeedComma) toAsm << ", ";         // Handle comma outputing
286       NeedComma = true;
287       N = printOperands(MI, OpNum);
288     }
289   else
290     N = 1;
291   
292   toAsm << endl;
293 }
294
295 void
296 SparcAsmPrinter::emitBasicBlock(const BasicBlock *BB)
297 {
298   // Emit a label for the basic block
299   toAsm << getID(BB) << ":\n";
300
301   // Get the vector of machine instructions corresponding to this bb.
302   const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
303   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
304
305   // Loop over all of the instructions in the basic block...
306   for (; MII != MIE; ++MII)
307     emitMachineInst(*MII);
308   toAsm << "\n";  // Seperate BB's with newlines
309 }
310
311 void
312 SparcAsmPrinter::emitMethod(const Method *M)
313 {
314   if (M->isExternal()) return;
315
316   // Make sure the slot table has information about this method...
317   Table.incorporateMethod(M);
318
319   string methName = getID(M);
320   toAsm << "!****** Outputing Method: " << methName << " ******\n";
321   enterSection(Text);
322   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
323   //toAsm << "\t.type\t" << methName << ",#function\n";
324   toAsm << "\t.type\t" << methName << ", 2\n";
325   toAsm << methName << ":\n";
326
327   // Output code for all of the basic blocks in the method...
328   for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
329     emitBasicBlock(*I);
330
331   // Output a .size directive so the debugger knows the extents of the function
332   toAsm << ".EndOf_" << methName << ":\n\t.size "
333         << methName << ", .EndOf_"
334         << methName << "-" << methName << endl;
335
336   // Put some spaces between the methods
337   toAsm << "\n\n";
338
339   // Forget all about M.
340   Table.purgeMethod();
341 }
342
343 inline bool
344 ArrayTypeIsString(ArrayType* arrayType)
345 {
346   return (arrayType->getElementType() == Type::UByteTy ||
347           arrayType->getElementType() == Type::SByteTy);
348 }
349
350 inline const string TypeToDataDirective(const Type* type)
351 {
352   switch(type->getPrimitiveID())
353     {
354     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
355       return ".byte";
356     case Type::UShortTyID: case Type::ShortTyID:
357       return ".half";
358     case Type::UIntTyID: case Type::IntTyID:
359       return ".word";
360     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
361       return ".xword";
362     case Type::FloatTyID:
363       return ".single";
364     case Type::DoubleTyID:
365       return ".double";
366     case Type::ArrayTyID:
367       if (ArrayTypeIsString((ArrayType*) type))
368         return ".ascii";
369       else
370         return "<InvaliDataTypeForPrinting>";
371     default:
372       return "<InvaliDataTypeForPrinting>";
373     }
374 }
375
376 inline unsigned int ConstantToSize(const ConstPoolVal* CV,
377                                    const TargetMachine& target) {
378   if (ConstPoolArray* AV = dyn_cast<ConstPoolArray>(CV))
379     if (ArrayTypeIsString((ArrayType*) CV->getType()))
380       return 1 + AV->getNumOperands();
381   
382   return target.findOptimalStorageSize(CV->getType());
383 }
384
385
386 inline
387 unsigned int TypeToSize(const Type* type, const TargetMachine& target)
388 {
389   return target.findOptimalStorageSize(type);
390 }
391
392
393 inline unsigned int
394 TypeToAlignment(const Type* type, const TargetMachine& target)
395 {
396   if (type->getPrimitiveID() == Type::ArrayTyID &&
397       ArrayTypeIsString((ArrayType*) type))
398     return target.findOptimalStorageSize(Type::LongTy);
399   
400   return target.findOptimalStorageSize(type);
401 }
402
403
404 void
405 SparcAsmPrinter::printConstant(const ConstPoolVal* CV, string valID)
406 {
407   if (valID.length() == 0)
408     valID = getID(CV);
409   
410   assert(CV->getType() != Type::VoidTy &&
411          CV->getType() != Type::TypeTy &&
412          CV->getType() != Type::LabelTy &&
413          "Unexpected type for ConstPoolVal");
414   
415   toAsm << "\t.align\t" << TypeToAlignment(CV->getType(), Target)
416         << endl;
417   
418   toAsm << valID << ":" << endl;
419   
420   toAsm << "\t"
421         << TypeToDataDirective(CV->getType()) << "\t";
422   
423   if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV))
424     if (isStringCompatible(CPA))
425       {
426         toAsm << getAsCString(CPA) << endl;
427         return;
428       }
429   
430   if (CV->getType()->isPrimitiveType())
431     {
432       if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
433         toAsm << "0r";                  // FP constants must have this prefix
434       toAsm << CV->getStrValue() << endl;
435     }
436   else if (ConstPoolPointer* CPP = dyn_cast<ConstPoolPointer>(CV))
437     {
438       if (! CPP->isNullValue())
439         assert(0 && "Cannot yet print non-null pointer constants to assembly");
440       else
441         toAsm << (void*) NULL << endl;
442     }
443   else if (ConstPoolPointerRef* CPRef = dyn_cast<ConstPoolPointerRef>(CV))
444     {
445       assert(0 && "Cannot yet initialize pointer refs in assembly");
446     }
447   else
448     {
449       assert(0 && "Cannot yet print non-primitive constants to assembly");
450       // toAsm << CV->getStrValue() << endl;
451     }
452    
453   toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
454   toAsm << "\t.size" << "\t" << valID << ","
455         << ConstantToSize(CV, Target) << endl;
456 }
457
458
459 void
460 SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
461 {
462   toAsm << "\t.global\t" << getID(GV) << endl;
463   
464   if (GV->hasInitializer())
465     printConstant(GV->getInitializer(), getID(GV));
466   else {
467     toAsm << "\t.align\t"
468           << TypeToAlignment(GV->getType()->getValueType(), Target) << endl;
469     toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
470     toAsm << "\t.reserve\t" << getID(GV) << ","
471           << TypeToSize(GV->getType()->getValueType(), Target)
472           << endl;
473   }
474 }
475
476
477 static void
478 FoldConstPools(const Module *M,
479                hash_set<const ConstPoolVal*>& moduleConstPool)
480 {
481   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
482     if (! (*I)->isExternal())
483       {
484         const hash_set<const ConstPoolVal*>& pool =
485           MachineCodeForMethod::get(*I).getConstantPoolValues();
486         moduleConstPool.insert(pool.begin(), pool.end());
487       }
488 }
489
490
491 void
492 SparcAsmPrinter::emitGlobalsAndConstants(const Module *M)
493 {
494   // First, get the constants there were marked by the code generator for
495   // inclusion in the assembly code data area and fold them all into a
496   // single constant pool since there may be lots of duplicates.  Also,
497   // lets force these constants into the slot table so that we can get
498   // unique names for unnamed constants also.
499   // 
500   hash_set<const ConstPoolVal*> moduleConstPool;
501   FoldConstPools(M, moduleConstPool);
502   
503   // Now, emit the three data sections separately; the cost of I/O should
504   // make up for the cost of extra passes over the globals list!
505   // 
506   // Read-only data section (implies initialized)
507   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
508     {
509       const GlobalVariable* GV = *GI;
510       if (GV->hasInitializer() && GV->isConstant())
511         {
512           if (GI == M->gbegin())
513             enterSection(ReadOnlyData);
514           printGlobalVariable(GV);
515         }
516   }
517   
518   for (hash_set<const ConstPoolVal*>::const_iterator I=moduleConstPool.begin(),
519          E = moduleConstPool.end();  I != E; ++I)
520     printConstant(*I);
521   
522   // Initialized read-write data section
523   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
524     {
525       const GlobalVariable* GV = *GI;
526       if (GV->hasInitializer() && ! GV->isConstant())
527         {
528           if (GI == M->gbegin())
529             enterSection(InitRWData);
530           printGlobalVariable(GV);
531         }
532   }
533
534   // Uninitialized read-write data section
535   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
536     {
537       const GlobalVariable* GV = *GI;
538       if (! GV->hasInitializer())
539         {
540           if (GI == M->gbegin())
541             enterSection(UninitRWData);
542           printGlobalVariable(GV);
543         }
544   }
545
546   toAsm << endl;
547 }
548
549
550 void
551 SparcAsmPrinter::emitModule(const Module *M)
552 {
553   // TODO: Look for a filename annotation on M to emit a .file directive
554   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
555     emitMethod(*I);
556   
557   emitGlobalsAndConstants(M);
558 }
559
560 }  // End anonymous namespace
561
562
563 //
564 // emitAssembly - Output assembly language code (a .s file) for the specified
565 // method. The specified method must have been compiled before this may be
566 // used.
567 //
568 void
569 UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
570 {
571   SparcAsmPrinter Print(toAsm, M, *this);
572 }