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