Method.h no longer includes BasicBlock.h
[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     if ((*I)->getTerminator()->getOpcode() == Instruction::Ret)
89       {
90         BasicBlock* exitBB = *I;
91         unsigned N = GetInstructionsForEpilog(exitBB, Target, minstrVec);
92         
93         MachineCodeForBasicBlock& bbMvec = exitBB->getMachineInstrVec();
94         MachineCodeForInstruction &termMvec =
95           MachineCodeForInstruction::get(exitBB->getTerminator());
96         
97         // Remove the NOPs in the delay slots of the return instruction
98         const MachineInstrInfo &mii = Target.getInstrInfo();
99         unsigned numNOPs = 0;
100         while (termMvec.back()->getOpCode() == NOP)
101           {
102             assert( termMvec.back() == bbMvec.back());
103             termMvec.pop_back();
104             bbMvec.pop_back();
105             ++numNOPs;
106           }
107         assert(termMvec.back() == bbMvec.back());
108         
109         // Check that we found the right number of NOPs and have the right
110         // number of instructions to replace them.
111         unsigned ndelays = mii.getNumDelaySlots(termMvec.back()->getOpCode());
112         assert(numNOPs == ndelays && "Missing NOPs in delay slots?");
113         assert(N == ndelays && "Cannot use epilog code for delay slots?");
114         
115         // Append the epilog code to the end of the basic block.
116         bbMvec.push_back(minstrVec[0]);
117       }
118 }
119
120
121 //---------------------------------------------------------------------------
122 // class UltraSparcFrameInfo 
123 // 
124 // Purpose:
125 //   Interface to stack frame layout info for the UltraSPARC.
126 //   Starting offsets for each area of the stack frame are aligned at
127 //   a multiple of getStackFrameSizeAlignment().
128 //---------------------------------------------------------------------------
129
130 int
131 UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& ,
132                                                 bool& pos) const
133 {
134   pos = false;                          // static stack area grows downwards
135   return StaticAreaOffsetFromFP;
136 }
137
138 int
139 UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo,
140                                            bool& pos) const
141 {
142   pos = false;                          // static stack area grows downwards
143   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
144   if (int mod = autoVarsSize % getStackFrameSizeAlignment())  
145     autoVarsSize += (getStackFrameSizeAlignment() - mod);
146   return StaticAreaOffsetFromFP - autoVarsSize; 
147 }
148
149 int
150 UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo,
151                                       bool& pos) const
152 {
153   pos = false;                          // static stack area grows downwards
154   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
155   unsigned int spillAreaSize = mcInfo.getRegSpillsSize();
156   int offset = autoVarsSize + spillAreaSize;
157   if (int mod = offset % getStackFrameSizeAlignment())  
158     offset += (getStackFrameSizeAlignment() - mod);
159   return StaticAreaOffsetFromFP - offset;
160 }
161
162 int
163 UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo,
164                                           bool& pos) const
165 {
166   // dynamic stack area grows downwards starting at top of opt-args area
167   unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize();
168   int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
169   assert(offset % getStackFrameSizeAlignment() == 0);
170   return offset;
171 }
172
173
174 //---------------------------------------------------------------------------
175 // class UltraSparcMachine 
176 // 
177 // Purpose:
178 //   Primary interface to machine description for the UltraSPARC.
179 //   Primarily just initializes machine-dependent parameters in
180 //   class TargetMachine, and creates machine-dependent subclasses
181 //   for classes such as MachineInstrInfo. 
182 // 
183 //---------------------------------------------------------------------------
184
185 UltraSparc::UltraSparc()
186   : TargetMachine("UltraSparc-Native"),
187     instrInfo(*this),
188     schedInfo(*this),
189     regInfo(*this),
190     frameInfo(*this),
191     cacheInfo(*this)
192 {
193   optSizeForSubWordData = 4;
194   minMemOpWordSize = 8; 
195   maxAtomicMemOpWordSize = 8;
196 }
197
198
199
200 //===---------------------------------------------------------------------===//
201 // GenerateCodeForTarget Pass
202 // 
203 // Native code generation for a specified target.
204 //===---------------------------------------------------------------------===//
205
206 class ConstructMachineCodeForMethod : public MethodPass {
207   TargetMachine &Target;
208 public:
209   inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
210   bool runOnMethod(Method *M) {
211     MachineCodeForMethod::construct(M, Target);
212     return false;
213   }
214 };
215
216 class InstructionSelection : public MethodPass {
217   TargetMachine &Target;
218 public:
219   inline InstructionSelection(TargetMachine &T) : Target(T) {}
220   bool runOnMethod(Method *M) {
221     if (SelectInstructionsForMethod(M, Target))
222       cerr << "Instr selection failed for method " << M->getName() << "\n";
223     return false;
224   }
225 };
226
227 struct FreeMachineCodeForMethod : public MethodPass {
228   static void freeMachineCode(Instruction *I) {
229     MachineCodeForInstruction::destroy(I);
230   }
231
232   bool runOnMethod(Method *M) {
233     for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
234       for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
235            I != E; ++I)
236         freeMachineCode(*I);
237
238     // Don't destruct MachineCodeForMethod - The global printer needs it
239     //MachineCodeForMethod::destruct(M);
240     return false;
241   }
242 };
243
244
245
246 // addPassesToEmitAssembly - This method controls the entire code generation
247 // process for the ultra sparc.
248 //
249 void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
250   // Construct and initialize the MachineCodeForMethod object for this method.
251   PM.add(new ConstructMachineCodeForMethod(*this));
252
253   PM.add(new InstructionSelection(*this));
254
255   //PM.add(createInstructionSchedulingWithSSAPass(*this));
256
257   PM.add(getRegisterAllocator(*this));
258   
259   //PM.add(new OptimizeLeafProcedures());
260   //PM.add(new DeleteFallThroughBranches());
261   //PM.add(new RemoveChainedBranches());    // should be folded with previous
262   //PM.add(new RemoveRedundantOps());       // operations with %g0, NOP, etc.
263   
264   PM.add(new InsertPrologEpilogCode(*this));
265   
266   // Output assembly language to the .s file.  Assembly emission is split into
267   // two parts: Method output and Global value output.  This is because method
268   // output is pipelined with all of the rest of code generation stuff,
269   // allowing machine code representations for methods to be free'd after the
270   // method has been emitted.
271   //
272   PM.add(getMethodAsmPrinterPass(PM, Out));
273   PM.add(new FreeMachineCodeForMethod());  // Free stuff no longer needed
274
275   // Emit Module level assembly after all of the methods have been processed.
276   PM.add(getModuleAsmPrinterPass(PM, Out));
277
278   // Emit bytecode to the sparc assembly file into its special section next
279   PM.add(getEmitBytecodeToAsmPass(Out));
280 }