a4556d161d0187a1baa92a18346f9bb995db64dd
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9TargetMachine.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      Sparc.cpp
5 // 
6 // Purpose:
7 //      
8 // History:
9 //      7/15/01  -  Vikram Adve  -  Created
10 //**************************************************************************/
11
12
13 #include "SparcInternals.h"
14 #include "llvm/Target/Sparc.h"
15 #include "llvm/CodeGen/InstrScheduling.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineCodeForMethod.h"
19 #include "llvm/CodeGen/RegisterAllocation.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/Method.h"
22 #include "llvm/BasicBlock.h"
23 #include "llvm/PassManager.h"
24 #include <iostream>
25 using std::cerr;
26
27 // Build the MachineInstruction Description Array...
28 const MachineInstrDescriptor SparcMachineInstrDesc[] = {
29 #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
30           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS)             \
31   { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE,             \
32           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS },
33 #include "SparcInstr.def"
34 };
35
36 //----------------------------------------------------------------------------
37 // allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
38 // that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
39 //----------------------------------------------------------------------------
40 //
41
42 TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); }
43
44
45 //---------------------------------------------------------------------------
46 // class InsertPrologEpilogCode
47 //
48 // Insert SAVE/RESTORE instructions for the method
49 //
50 // Insert prolog code at the unique method entry point.
51 // Insert epilog code at each method exit point.
52 // InsertPrologEpilog invokes these only if the method is not compiled
53 // with the leaf method optimization.
54 //
55 //---------------------------------------------------------------------------
56 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
57
58 class InsertPrologEpilogCode : public MethodPass {
59   TargetMachine &Target;
60 public:
61   inline InsertPrologEpilogCode(TargetMachine &T) : Target(T) {}
62   bool runOnMethod(Method *M) {
63     MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(M);
64     if (!mcodeInfo.isCompiledAsLeafMethod()) {
65       InsertPrologCode(M);
66       InsertEpilogCode(M);
67     }
68     return false;
69   }
70
71   void InsertPrologCode(Method *M);
72   void InsertEpilogCode(Method *M);
73 };
74
75 void InsertPrologEpilogCode::InsertPrologCode(Method* method)
76 {
77   BasicBlock* entryBB = method->getEntryNode();
78   unsigned N = GetInstructionsForProlog(entryBB, Target, minstrVec);
79   assert(N <= MAX_INSTR_PER_VMINSTR);
80   MachineCodeForBasicBlock& bbMvec = entryBB->getMachineInstrVec();
81   bbMvec.insert(bbMvec.begin(), minstrVec, minstrVec+N);
82 }
83
84
85 void InsertPrologEpilogCode::InsertEpilogCode(Method* method)
86 {
87   for (Method::iterator I=method->begin(), E=method->end(); I != E; ++I) {
88     Instruction *TermInst = (Instruction*)(*I)->getTerminator();
89     if (TermInst->getOpcode() == Instruction::Ret)
90       {
91         BasicBlock* exitBB = *I;
92         unsigned N = GetInstructionsForEpilog(exitBB, Target, minstrVec);
93         
94         MachineCodeForBasicBlock& bbMvec = exitBB->getMachineInstrVec();
95         MachineCodeForInstruction &termMvec =
96           MachineCodeForInstruction::get(TermInst);
97         
98         // Remove the NOPs in the delay slots of the return instruction
99         const MachineInstrInfo &mii = Target.getInstrInfo();
100         unsigned numNOPs = 0;
101         while (termMvec.back()->getOpCode() == NOP)
102           {
103             assert( termMvec.back() == bbMvec.back());
104             termMvec.pop_back();
105             bbMvec.pop_back();
106             ++numNOPs;
107           }
108         assert(termMvec.back() == bbMvec.back());
109         
110         // Check that we found the right number of NOPs and have the right
111         // number of instructions to replace them.
112         unsigned ndelays = mii.getNumDelaySlots(termMvec.back()->getOpCode());
113         assert(numNOPs == ndelays && "Missing NOPs in delay slots?");
114         assert(N == ndelays && "Cannot use epilog code for delay slots?");
115         
116         // Append the epilog code to the end of the basic block.
117         bbMvec.push_back(minstrVec[0]);
118       }
119   }
120 }
121
122
123 //---------------------------------------------------------------------------
124 // class UltraSparcFrameInfo 
125 // 
126 // Purpose:
127 //   Interface to stack frame layout info for the UltraSPARC.
128 //   Starting offsets for each area of the stack frame are aligned at
129 //   a multiple of getStackFrameSizeAlignment().
130 //---------------------------------------------------------------------------
131
132 int
133 UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& ,
134                                                 bool& pos) const
135 {
136   pos = false;                          // static stack area grows downwards
137   return StaticAreaOffsetFromFP;
138 }
139
140 int
141 UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo,
142                                            bool& pos) const
143 {
144   pos = false;                          // static stack area grows downwards
145   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
146   if (int mod = autoVarsSize % getStackFrameSizeAlignment())  
147     autoVarsSize += (getStackFrameSizeAlignment() - mod);
148   return StaticAreaOffsetFromFP - autoVarsSize; 
149 }
150
151 int
152 UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo,
153                                       bool& pos) const
154 {
155   pos = false;                          // static stack area grows downwards
156   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
157   unsigned int spillAreaSize = mcInfo.getRegSpillsSize();
158   int offset = autoVarsSize + spillAreaSize;
159   if (int mod = offset % getStackFrameSizeAlignment())  
160     offset += (getStackFrameSizeAlignment() - mod);
161   return StaticAreaOffsetFromFP - offset;
162 }
163
164 int
165 UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo,
166                                           bool& pos) const
167 {
168   // dynamic stack area grows downwards starting at top of opt-args area
169   unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize();
170   int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
171   assert(offset % getStackFrameSizeAlignment() == 0);
172   return offset;
173 }
174
175
176 //---------------------------------------------------------------------------
177 // class UltraSparcMachine 
178 // 
179 // Purpose:
180 //   Primary interface to machine description for the UltraSPARC.
181 //   Primarily just initializes machine-dependent parameters in
182 //   class TargetMachine, and creates machine-dependent subclasses
183 //   for classes such as MachineInstrInfo. 
184 // 
185 //---------------------------------------------------------------------------
186
187 UltraSparc::UltraSparc()
188   : TargetMachine("UltraSparc-Native"),
189     instrInfo(*this),
190     schedInfo(*this),
191     regInfo(*this),
192     frameInfo(*this),
193     cacheInfo(*this)
194 {
195   optSizeForSubWordData = 4;
196   minMemOpWordSize = 8; 
197   maxAtomicMemOpWordSize = 8;
198 }
199
200
201
202 //===---------------------------------------------------------------------===//
203 // GenerateCodeForTarget Pass
204 // 
205 // Native code generation for a specified target.
206 //===---------------------------------------------------------------------===//
207
208 class ConstructMachineCodeForMethod : public MethodPass {
209   TargetMachine &Target;
210 public:
211   inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
212   bool runOnMethod(Method *M) {
213     MachineCodeForMethod::construct(M, Target);
214     return false;
215   }
216 };
217
218 class InstructionSelection : public MethodPass {
219   TargetMachine &Target;
220 public:
221   inline InstructionSelection(TargetMachine &T) : Target(T) {}
222   bool runOnMethod(Method *M) {
223     if (SelectInstructionsForMethod(M, Target))
224       cerr << "Instr selection failed for method " << M->getName() << "\n";
225     return false;
226   }
227 };
228
229 struct FreeMachineCodeForMethod : public MethodPass {
230   static void freeMachineCode(Instruction *I) {
231     MachineCodeForInstruction::destroy(I);
232   }
233
234   bool runOnMethod(Method *M) {
235     for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
236       for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
237            I != E; ++I)
238         freeMachineCode(*I);
239
240     // Don't destruct MachineCodeForMethod - The global printer needs it
241     //MachineCodeForMethod::destruct(M);
242     return false;
243   }
244 };
245
246
247
248 // addPassesToEmitAssembly - This method controls the entire code generation
249 // process for the ultra sparc.
250 //
251 void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
252   // Construct and initialize the MachineCodeForMethod object for this method.
253   PM.add(new ConstructMachineCodeForMethod(*this));
254
255   PM.add(new InstructionSelection(*this));
256
257   //PM.add(createInstructionSchedulingWithSSAPass(*this));
258
259   PM.add(getRegisterAllocator(*this));
260   
261   //PM.add(new OptimizeLeafProcedures());
262   //PM.add(new DeleteFallThroughBranches());
263   //PM.add(new RemoveChainedBranches());    // should be folded with previous
264   //PM.add(new RemoveRedundantOps());       // operations with %g0, NOP, etc.
265   
266   PM.add(new InsertPrologEpilogCode(*this));
267   
268   // Output assembly language to the .s file.  Assembly emission is split into
269   // two parts: Method output and Global value output.  This is because method
270   // output is pipelined with all of the rest of code generation stuff,
271   // allowing machine code representations for methods to be free'd after the
272   // method has been emitted.
273   //
274   PM.add(getMethodAsmPrinterPass(PM, Out));
275   PM.add(new FreeMachineCodeForMethod());  // Free stuff no longer needed
276
277   // Emit Module level assembly after all of the methods have been processed.
278   PM.add(getModuleAsmPrinterPass(PM, Out));
279
280   // Emit bytecode to the sparc assembly file into its special section next
281   PM.add(getEmitBytecodeToAsmPass(Out));
282 }