use a 'register pressure reducing' scheduler
[oota-llvm.git] / lib / Target / ARM / ARMISelDAGToDAG.cpp
1 //===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the ARM target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Support/Debug.h"
28 #include <iostream>
29 #include <set>
30 using namespace llvm;
31
32 namespace {
33   class ARMTargetLowering : public TargetLowering {
34   public:
35     ARMTargetLowering(TargetMachine &TM);
36     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
37     virtual const char *getTargetNodeName(unsigned Opcode) const;
38   };
39
40 }
41
42 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
43   : TargetLowering(TM) {
44   setOperationAction(ISD::RET,           MVT::Other, Custom);
45   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
46   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
47
48   setSchedulingPreference(SchedulingForRegPressure);
49 }
50
51 namespace llvm {
52   namespace ARMISD {
53     enum NodeType {
54       // Start the numbering where the builting ops and target ops leave off.
55       FIRST_NUMBER = ISD::BUILTIN_OP_END+ARM::INSTRUCTION_LIST_END,
56       /// CALL - A direct function call.
57       CALL,
58
59       /// Return with a flag operand.
60       RET_FLAG
61     };
62   }
63 }
64
65 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
66   switch (Opcode) {
67   default: return 0;
68   case ARMISD::CALL:          return "ARMISD::CALL";
69   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
70   }
71 }
72
73 // This transforms a ISD::CALL node into a
74 // callseq_star <- ARMISD:CALL <- callseq_end
75 // chain
76 static SDOperand LowerCALL(SDOperand Op, SelectionDAG &DAG) {
77   SDOperand Chain    = Op.getOperand(0);
78   unsigned CallConv  = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
79   assert(CallConv == CallingConv::C && "unknown calling convention");
80   bool isVarArg      = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
81   assert(isVarArg == false && "VarArg not supported");
82   bool isTailCall    = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
83   assert(isTailCall == false && "tail call not supported");
84   SDOperand Callee   = Op.getOperand(4);
85   unsigned NumOps    = (Op.getNumOperands() - 5) / 2;
86
87   // Count how many bytes are to be pushed on the stack. Initially
88   // only the link register.
89   unsigned NumBytes = 4;
90
91   assert(NumOps <= 4); //no args on the stack
92
93   // Adjust the stack pointer for the new arguments...
94   // These operations are automatically eliminated by the prolog/epilog pass
95   Chain = DAG.getCALLSEQ_START(Chain,
96                                DAG.getConstant(NumBytes, MVT::i32));
97
98   static const unsigned regs[] = {
99     ARM::R0, ARM::R1, ARM::R2, ARM::R3
100   };
101
102   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
103
104   for (unsigned i = 0; i != NumOps; ++i) {
105     SDOperand Arg = Op.getOperand(5+2*i);
106     RegsToPass.push_back(std::make_pair(regs[i], Arg));
107   }
108
109   // Build a sequence of copy-to-reg nodes chained together with token chain
110   // and flag operands which copy the outgoing args into the appropriate regs.
111   SDOperand InFlag;
112   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
113     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
114                              InFlag);
115     InFlag = Chain.getValue(1);
116   }
117
118   std::vector<MVT::ValueType> NodeTys;
119   NodeTys.push_back(MVT::Other);   // Returns a chain
120   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
121
122   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
123   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
124   // node so that legalize doesn't hack it.
125   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
126     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
127
128   // If this is a direct call, pass the chain and the callee.
129   assert (Callee.Val);
130   std::vector<SDOperand> Ops;
131   Ops.push_back(Chain);
132   Ops.push_back(Callee);
133
134   unsigned CallOpc = ARMISD::CALL;
135   if (InFlag.Val)
136     Ops.push_back(InFlag);
137   Chain = DAG.getNode(CallOpc, NodeTys, Ops);
138   InFlag = Chain.getValue(1);
139
140   std::vector<SDOperand> ResultVals;
141   NodeTys.clear();
142
143   // If the call has results, copy the values out of the ret val registers.
144   switch (Op.Val->getValueType(0)) {
145   default: assert(0 && "Unexpected ret value!");
146   case MVT::Other:
147     break;
148   case MVT::i32:
149     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
150     ResultVals.push_back(Chain.getValue(0));
151     NodeTys.push_back(MVT::i32);
152   }
153
154   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
155                       DAG.getConstant(NumBytes, MVT::i32));
156   NodeTys.push_back(MVT::Other);
157
158   if (ResultVals.empty())
159     return Chain;
160
161   ResultVals.push_back(Chain);
162   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals);
163   return Res.getValue(Op.ResNo);
164 }
165
166 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
167   SDOperand Copy;
168   SDOperand Chain = Op.getOperand(0);
169   switch(Op.getNumOperands()) {
170   default:
171     assert(0 && "Do not know how to return this many arguments!");
172     abort();
173   case 1: {
174     SDOperand LR = DAG.getRegister(ARM::R14, MVT::i32);
175     return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Chain);
176   }
177   case 3:
178     Copy = DAG.getCopyToReg(Chain, ARM::R0, Op.getOperand(1), SDOperand());
179     if (DAG.getMachineFunction().liveout_empty())
180       DAG.getMachineFunction().addLiveOut(ARM::R0);
181     break;
182   }
183
184   //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
185   return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
186 }
187
188 static SDOperand LowerFORMAL_ARGUMENT(SDOperand Op, SelectionDAG &DAG,
189                                       unsigned ArgNo) {
190   MachineFunction &MF = DAG.getMachineFunction();
191   MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
192   assert (ObjectVT == MVT::i32);
193   SDOperand Root = Op.getOperand(0);
194   SSARegMap *RegMap = MF.getSSARegMap();
195
196   unsigned num_regs = 4;
197   static const unsigned REGS[] = {
198     ARM::R0, ARM::R1, ARM::R2, ARM::R3
199   };
200
201   if(ArgNo < num_regs) {
202     unsigned VReg = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
203     MF.addLiveIn(REGS[ArgNo], VReg);
204     return DAG.getCopyFromReg(Root, VReg, MVT::i32);
205   } else {
206     // If the argument is actually used, emit a load from the right stack
207       // slot.
208     if (!Op.Val->hasNUsesOfValue(0, ArgNo)) {
209       unsigned ArgOffset = (ArgNo - num_regs) * 4;
210
211       MachineFrameInfo *MFI = MF.getFrameInfo();
212       unsigned ObjSize = MVT::getSizeInBits(ObjectVT)/8;
213       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
214       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
215       return DAG.getLoad(ObjectVT, Root, FIN,
216                          DAG.getSrcValue(NULL));
217     } else {
218       // Don't emit a dead load.
219       return DAG.getNode(ISD::UNDEF, ObjectVT);
220     }
221   }
222 }
223
224 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
225   MVT::ValueType PtrVT = Op.getValueType();
226   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
227   Constant *C = CP->get();
228   SDOperand CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
229
230   return CPI;
231 }
232
233 static SDOperand LowerGlobalAddress(SDOperand Op,
234                                     SelectionDAG &DAG) {
235   GlobalValue  *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
236   SDOperand CPAddr = DAG.getConstantPool(GV, MVT::i32, 2);
237   return DAG.getLoad(MVT::i32, DAG.getEntryNode(), CPAddr,
238                      DAG.getSrcValue(NULL));
239 }
240
241 static SDOperand LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
242   std::vector<SDOperand> ArgValues;
243   SDOperand Root = Op.getOperand(0);
244
245   for (unsigned ArgNo = 0, e = Op.Val->getNumValues()-1; ArgNo != e; ++ArgNo) {
246     SDOperand ArgVal = LowerFORMAL_ARGUMENT(Op, DAG, ArgNo);
247
248     ArgValues.push_back(ArgVal);
249   }
250
251   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
252   assert(!isVarArg);
253
254   ArgValues.push_back(Root);
255
256   // Return the new list of results.
257   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
258                                     Op.Val->value_end());
259   return DAG.getNode(ISD::MERGE_VALUES, RetVT, ArgValues);
260 }
261
262 SDOperand ARMTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
263   switch (Op.getOpcode()) {
264   default:
265     assert(0 && "Should not custom lower this!");
266     abort();
267   case ISD::ConstantPool:
268     return LowerConstantPool(Op, DAG);
269   case ISD::GlobalAddress:
270     return LowerGlobalAddress(Op, DAG);
271   case ISD::FORMAL_ARGUMENTS:
272     return LowerFORMAL_ARGUMENTS(Op, DAG);
273   case ISD::CALL:
274     return LowerCALL(Op, DAG);
275   case ISD::RET:
276     return LowerRET(Op, DAG);
277   }
278 }
279
280 //===----------------------------------------------------------------------===//
281 // Instruction Selector Implementation
282 //===----------------------------------------------------------------------===//
283
284 //===--------------------------------------------------------------------===//
285 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
286 /// instructions for SelectionDAG operations.
287 ///
288 namespace {
289 class ARMDAGToDAGISel : public SelectionDAGISel {
290   ARMTargetLowering Lowering;
291
292 public:
293   ARMDAGToDAGISel(TargetMachine &TM)
294     : SelectionDAGISel(Lowering), Lowering(TM) {
295   }
296
297   void Select(SDOperand &Result, SDOperand Op);
298   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
299   bool SelectAddrRegImm(SDOperand N, SDOperand &Offset, SDOperand &Base);
300
301   // Include the pieces autogenerated from the target description.
302 #include "ARMGenDAGISel.inc"
303 };
304
305 void ARMDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
306   DEBUG(BB->dump());
307
308   DAG.setRoot(SelectRoot(DAG.getRoot()));
309   CodeGenMap.clear();
310   HandleMap.clear();
311   ReplaceMap.clear();
312   DAG.RemoveDeadNodes();
313
314   ScheduleAndEmitDAG(DAG);
315 }
316
317 //register plus/minus 12 bit offset
318 bool ARMDAGToDAGISel::SelectAddrRegImm(SDOperand N, SDOperand &Offset,
319                                     SDOperand &Base) {
320   Offset = CurDAG->getTargetConstant(0, MVT::i32);
321   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
322     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
323   }
324   else
325     Base = N;
326   return true;      //any address fits in a register
327 }
328
329 void ARMDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
330   SDNode *N = Op.Val;
331
332   switch (N->getOpcode()) {
333   default:
334     SelectCode(Result, Op);
335     break;
336   }
337 }
338
339 }  // end anonymous namespace
340
341 /// createARMISelDag - This pass converts a legalized DAG into a
342 /// ARM-specific DAG, ready for instruction scheduling.
343 ///
344 FunctionPass *llvm::createARMISelDag(TargetMachine &TM) {
345   return new ARMDAGToDAGISel(TM);
346 }