7305031a196aede2c0fedbde5c64e103aa3bf1ad
[oota-llvm.git] / lib / Target / Sparc / SparcAsmPrinter.cpp
1 //===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format Sparc V8 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcV8.h"
16 #include "SparcV8InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Mangler.h"
26 #include "Support/Statistic.h"
27 #include "Support/StringExtras.h"
28 #include "Support/CommandLine.h"
29 #include <cctype>
30 using namespace llvm;
31
32 namespace {
33   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
34
35   struct V8Printer : public MachineFunctionPass {
36     /// Output stream on which we're printing assembly code.
37     ///
38     std::ostream &O;
39
40     /// Target machine description which we query for reg. names, data
41     /// layout, etc.
42     ///
43     TargetMachine &TM;
44
45     /// Name-mangler for global names.
46     ///
47     Mangler *Mang;
48
49     V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
50
51     /// We name each basic block in a Function with a unique number, so
52     /// that we can consistently refer to them later. This is cleared
53     /// at the beginning of each call to runOnMachineFunction().
54     ///
55     typedef std::map<const Value *, unsigned> ValueMapTy;
56     ValueMapTy NumberForBB;
57
58     /// Cache of mangled name for current function. This is
59     /// recalculated at the beginning of each call to
60     /// runOnMachineFunction().
61     ///
62     std::string CurrentFnName;
63
64     virtual const char *getPassName() const {
65       return "SparcV8 Assembly Printer";
66     }
67
68     void emitConstantValueOnly(const Constant *CV);
69     void emitGlobalConstant(const Constant *CV);
70     void printConstantPool(MachineConstantPool *MCP);
71     void printOperand(const MachineOperand &MI);
72     void printMachineInstruction(const MachineInstr *MI);
73     bool runOnMachineFunction(MachineFunction &F);    
74     bool doInitialization(Module &M);
75     bool doFinalization(Module &M);
76   };
77 } // end of anonymous namespace
78
79 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description.  This should work
82 /// regardless of whether the function is in SSA form.
83 ///
84 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
85                                                   TargetMachine &tm) {
86   return new V8Printer(o, tm);
87 }
88
89 /// toOctal - Convert the low order bits of X into an octal digit.
90 ///
91 static inline char toOctal(int X) {
92   return (X&7)+'0';
93 }
94
95 /// getAsCString - Return the specified array as a C compatible
96 /// string, only if the predicate isStringCompatible is true.
97 ///
98 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
99   assert(CVA->isString() && "Array is not string compatible!");
100
101   O << "\"";
102   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
103     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
104
105     if (C == '"') {
106       O << "\\\"";
107     } else if (C == '\\') {
108       O << "\\\\";
109     } else if (isprint(C)) {
110       O << C;
111     } else {
112       switch(C) {
113       case '\b': O << "\\b"; break;
114       case '\f': O << "\\f"; break;
115       case '\n': O << "\\n"; break;
116       case '\r': O << "\\r"; break;
117       case '\t': O << "\\t"; break;
118       default:
119         O << '\\';
120         O << toOctal(C >> 6);
121         O << toOctal(C >> 3);
122         O << toOctal(C >> 0);
123         break;
124       }
125     }
126   }
127   O << "\"";
128 }
129
130 // Print out the specified constant, without a storage class.  Only the
131 // constants valid in constant expressions can occur here.
132 void V8Printer::emitConstantValueOnly(const Constant *CV) {
133   if (CV->isNullValue())
134     O << "0";
135   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
136     assert(CB == ConstantBool::True);
137     O << "1";
138   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
139     if (((CI->getValue() << 32) >> 32) == CI->getValue())
140       O << CI->getValue();
141     else
142       O << (unsigned long long)CI->getValue();
143   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
144     O << CI->getValue();
145   else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
146     // This is a constant address for a global variable or function.  Use the
147     // name of the variable or function as the address value.
148     O << Mang->getValueName(CPR->getValue());
149   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
150     const TargetData &TD = TM.getTargetData();
151     switch(CE->getOpcode()) {
152     case Instruction::GetElementPtr: {
153       // generate a symbolic expression for the byte address
154       const Constant *ptrVal = CE->getOperand(0);
155       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
156       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
157         O << "(";
158         emitConstantValueOnly(ptrVal);
159         O << ") + " << Offset;
160       } else {
161         emitConstantValueOnly(ptrVal);
162       }
163       break;
164     }
165     case Instruction::Cast: {
166       // Support only non-converting or widening casts for now, that is, ones
167       // that do not involve a change in value.  This assertion is really gross,
168       // and may not even be a complete check.
169       Constant *Op = CE->getOperand(0);
170       const Type *OpTy = Op->getType(), *Ty = CE->getType();
171
172       // Pointers on ILP32 machines can be losslessly converted back and
173       // forth into 32-bit or wider integers, regardless of signedness.
174       assert(((isa<PointerType>(OpTy)
175                && (Ty == Type::LongTy || Ty == Type::ULongTy
176                    || Ty == Type::IntTy || Ty == Type::UIntTy))
177               || (isa<PointerType>(Ty)
178                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
179                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
180               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
181                    && OpTy->isLosslesslyConvertibleTo(Ty))))
182              && "FIXME: Don't yet support this kind of constant cast expr");
183       O << "(";
184       emitConstantValueOnly(Op);
185       O << ")";
186       break;
187     }
188     case Instruction::Add:
189       O << "(";
190       emitConstantValueOnly(CE->getOperand(0));
191       O << ") + (";
192       emitConstantValueOnly(CE->getOperand(1));
193       O << ")";
194       break;
195     default:
196       assert(0 && "Unsupported operator!");
197     }
198   } else {
199     assert(0 && "Unknown constant value!");
200   }
201 }
202
203 // Print a constant value or values, with the appropriate storage class as a
204 // prefix.
205 void V8Printer::emitGlobalConstant(const Constant *CV) {  
206   const TargetData &TD = TM.getTargetData();
207
208   if (CV->isNullValue()) {
209     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
210     return;
211   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
212     if (CVA->isString()) {
213       O << "\t.ascii\t";
214       printAsCString(O, CVA);
215       O << "\n";
216     } else { // Not a string.  Print the values in successive locations
217       const std::vector<Use> &constValues = CVA->getValues();
218       for (unsigned i=0; i < constValues.size(); i++)
219         emitGlobalConstant(cast<Constant>(constValues[i].get()));
220     }
221     return;
222   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
223     // Print the fields in successive locations. Pad to align if needed!
224     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
225     const std::vector<Use>& constValues = CVS->getValues();
226     unsigned sizeSoFar = 0;
227     for (unsigned i=0, N = constValues.size(); i < N; i++) {
228       const Constant* field = cast<Constant>(constValues[i].get());
229
230       // Check if padding is needed and insert one or more 0s.
231       unsigned fieldSize = TD.getTypeSize(field->getType());
232       unsigned padSize = ((i == N-1? cvsLayout->StructSize
233                            : cvsLayout->MemberOffsets[i+1])
234                           - cvsLayout->MemberOffsets[i]) - fieldSize;
235       sizeSoFar += fieldSize + padSize;
236
237       // Now print the actual field value
238       emitGlobalConstant(field);
239
240       // Insert the field padding unless it's zero bytes...
241       if (padSize)
242         O << "\t.zero\t " << padSize << "\n";      
243     }
244     assert(sizeSoFar == cvsLayout->StructSize &&
245            "Layout of constant struct may be incorrect!");
246     return;
247   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
248     // FP Constants are printed as integer constants to avoid losing
249     // precision...
250     double Val = CFP->getValue();
251     switch (CFP->getType()->getPrimitiveID()) {
252     default: assert(0 && "Unknown floating point type!");
253     case Type::FloatTyID: {
254       union FU {                            // Abide by C TBAA rules
255         float FVal;
256         unsigned UVal;
257       } U;
258       U.FVal = Val;
259       O << ".long\t" << U.UVal << "\t! float " << Val << "\n";
260       return;
261     }
262     case Type::DoubleTyID: {
263       union DU {                            // Abide by C TBAA rules
264         double FVal;
265         uint64_t UVal;
266       } U;
267       U.FVal = Val;
268       O << ".quad\t" << U.UVal << "\t! double " << Val << "\n";
269       return;
270     }
271     }
272   }
273
274   const Type *type = CV->getType();
275   O << "\t";
276   switch (type->getPrimitiveID()) {
277   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
278     O << ".byte";
279     break;
280   case Type::UShortTyID: case Type::ShortTyID:
281     O << ".word";
282     break;
283   case Type::FloatTyID: case Type::PointerTyID:
284   case Type::UIntTyID: case Type::IntTyID:
285     O << ".long";
286     break;
287   case Type::DoubleTyID:
288   case Type::ULongTyID: case Type::LongTyID:
289     O << ".quad";
290     break;
291   default:
292     assert (0 && "Can't handle printing this type of thing");
293     break;
294   }
295   O << "\t";
296   emitConstantValueOnly(CV);
297   O << "\n";
298 }
299
300 /// printConstantPool - Print to the current output stream assembly
301 /// representations of the constants in the constant pool MCP. This is
302 /// used to print out constants which have been "spilled to memory" by
303 /// the code generator.
304 ///
305 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
306   const std::vector<Constant*> &CP = MCP->getConstants();
307   const TargetData &TD = TM.getTargetData();
308  
309   if (CP.empty()) return;
310
311   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
312     O << "\t.section .rodata\n";
313     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
314       << "\n";
315     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t!"
316       << *CP[i] << "\n";
317     emitGlobalConstant(CP[i]);
318   }
319 }
320
321 /// runOnMachineFunction - This uses the printMachineInstruction()
322 /// method to print assembly for each instruction.
323 ///
324 bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
325   // BBNumber is used here so that a given Printer will never give two
326   // BBs the same name. (If you have a better way, please let me know!)
327   static unsigned BBNumber = 0;
328
329   O << "\n\n";
330   // What's my mangled name?
331   CurrentFnName = Mang->getValueName(MF.getFunction());
332
333   // Print out constants referenced by the function
334   printConstantPool(MF.getConstantPool());
335
336   // Print out labels for the function.
337   O << "\t.text\n";
338   O << "\t.align 16\n";
339   O << "\t.globl\t" << CurrentFnName << "\n";
340   O << "\t.type\t" << CurrentFnName << ", #function\n";
341   O << CurrentFnName << ":\n";
342
343   // Number each basic block so that we can consistently refer to them
344   // in PC-relative references.
345   NumberForBB.clear();
346   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
347        I != E; ++I) {
348     NumberForBB[I->getBasicBlock()] = BBNumber++;
349   }
350
351   // Print out code for the function.
352   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
353        I != E; ++I) {
354     // Print a label for the basic block.
355     O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t! "
356       << I->getBasicBlock()->getName() << "\n";
357     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
358          II != E; ++II) {
359       // Print the assembly for the instruction.
360       O << "\t";
361       printMachineInstruction(II);
362     }
363   }
364
365   // We didn't modify anything.
366   return false;
367 }
368
369
370 std::string LowercaseString (const std::string &S) {
371   std::string result (S);
372   for (unsigned i = 0; i < S.length(); ++i) 
373     if (isupper (result[i]))
374       result[i] = tolower(result[i]);
375   return result;
376 }
377
378 void V8Printer::printOperand(const MachineOperand &MO) {
379   const MRegisterInfo &RI = *TM.getRegisterInfo();
380   switch (MO.getType()) {
381   case MachineOperand::MO_VirtualRegister:
382     if (Value *V = MO.getVRegValueOrNull()) {
383       O << "<" << V->getName() << ">";
384       return;
385     }
386     // FALLTHROUGH
387   case MachineOperand::MO_MachineRegister:
388     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
389       O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
390     else
391       O << "%reg" << MO.getReg();
392     return;
393
394   case MachineOperand::MO_SignExtendedImmed:
395   case MachineOperand::MO_UnextendedImmed:
396     O << (int)MO.getImmedValue();
397     return;
398   case MachineOperand::MO_PCRelativeDisp: {
399     if (isa<GlobalValue> (MO.getVRegValue ())) {
400       O << Mang->getValueName (MO.getVRegValue ());
401       return;
402     }
403     assert (isa<BasicBlock> (MO.getVRegValue ())
404       && "Trying to look up something which is not a BB in the NumberForBB map");
405     ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
406     assert (i != NumberForBB.end()
407             && "Could not find a BB in the NumberForBB map!");
408     O << ".LBB" << i->second << " ! PC rel: " << MO.getVRegValue()->getName();
409     return;
410   }
411   case MachineOperand::MO_GlobalAddress:
412     O << Mang->getValueName(MO.getGlobal());
413     return;
414   case MachineOperand::MO_ExternalSymbol:
415     O << MO.getSymbolName();
416     return;
417   default:
418     O << "<unknown operand type>"; return;    
419   }
420 }
421
422 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
423 /// MI in GAS syntax to the current output stream.
424 ///
425 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
426   unsigned Opcode = MI->getOpcode();
427   const TargetInstrInfo &TII = TM.getInstrInfo();
428   const TargetInstrDescriptor &Desc = TII.get(Opcode);
429   O << Desc.Name << " ";
430   
431   // print non-immediate, non-register-def operands
432   // then print immediate operands
433   // then print register-def operands.
434   std::vector<MachineOperand> print_order;
435   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
436     if (!(MI->getOperand (i).isImmediate ()
437           || (MI->getOperand (i).isRegister ()
438               && MI->getOperand (i).isDef ())))
439       print_order.push_back (MI->getOperand (i));
440   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
441     if (MI->getOperand (i).isImmediate ())
442       print_order.push_back (MI->getOperand (i));
443   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
444     if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
445       print_order.push_back (MI->getOperand (i));
446   for (unsigned i = 0, e = print_order.size (); i != e; ++i) { 
447     printOperand (print_order[i]);
448     if (i != (print_order.size () - 1))
449       O << ", ";
450   }
451   O << "\n";
452 }
453
454 bool V8Printer::doInitialization(Module &M) {
455   Mang = new Mangler(M);
456   return false; // success
457 }
458
459 // SwitchSection - Switch to the specified section of the executable if we are
460 // not already in it!
461 //
462 static void SwitchSection(std::ostream &OS, std::string &CurSection,
463                           const char *NewSection) {
464   if (CurSection != NewSection) {
465     CurSection = NewSection;
466     if (!CurSection.empty())
467       OS << "\t" << NewSection << "\n";
468   }
469 }
470
471 bool V8Printer::doFinalization(Module &M) {
472   const TargetData &TD = TM.getTargetData();
473   std::string CurSection;
474
475   // Print out module-level global variables here.
476   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
477     if (I->hasInitializer()) {   // External global require no code
478       O << "\n\n";
479       std::string name = Mang->getValueName(I);
480       Constant *C = I->getInitializer();
481       unsigned Size = TD.getTypeSize(C->getType());
482       unsigned Align = TD.getTypeAlignment(C->getType());
483
484       if (C->isNullValue() && 
485           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
486            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
487         SwitchSection(O, CurSection, ".data");
488         if (I->hasInternalLinkage())
489           O << "\t.local " << name << "\n";
490         
491         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
492           << "," << (unsigned)TD.getTypeAlignment(C->getType());
493         O << "\t\t! ";
494         WriteAsOperand(O, I, true, true, &M);
495         O << "\n";
496       } else {
497         switch (I->getLinkage()) {
498         case GlobalValue::LinkOnceLinkage:
499         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
500           // Nonnull linkonce -> weak
501           O << "\t.weak " << name << "\n";
502           SwitchSection(O, CurSection, "");
503           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
504           break;
505         
506         case GlobalValue::AppendingLinkage:
507           // FIXME: appending linkage variables should go into a section of
508           // their name or something.  For now, just emit them as external.
509         case GlobalValue::ExternalLinkage:
510           // If external or appending, declare as a global symbol
511           O << "\t.globl " << name << "\n";
512           // FALL THROUGH
513         case GlobalValue::InternalLinkage:
514           if (C->isNullValue())
515             SwitchSection(O, CurSection, ".bss");
516           else
517             SwitchSection(O, CurSection, ".data");
518           break;
519         }
520
521         O << "\t.align " << Align << "\n";
522         O << "\t.type " << name << ",#object\n";
523         O << "\t.size " << name << "," << Size << "\n";
524         O << name << ":\t\t\t\t! ";
525         WriteAsOperand(O, I, true, true, &M);
526         O << " = ";
527         WriteAsOperand(O, C, false, false, &M);
528         O << "\n";
529         emitGlobalConstant(C);
530       }
531     }
532
533   delete Mang;
534   return false; // success
535 }