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