Initial Mips support, here we go! =)
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Bruno Cardoso Lopes and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-lower"
16
17 #include "MipsISelLowering.h"
18 #include "MipsTargetMachine.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/CodeGen/SSARegMap.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/Support/Debug.h"
31 #include <queue>
32 #include <set>
33
34 using namespace llvm;
35
36 const char *MipsTargetLowering::
37 getTargetNodeName(unsigned Opcode) const 
38 {
39   switch (Opcode) 
40   {
41     case MipsISD::JmpLink   : return "MipsISD::JmpLink";
42     case MipsISD::Hi        : return "MipsISD::Hi";
43     case MipsISD::Lo        : return "MipsISD::Lo";
44     case MipsISD::Ret       : return "MipsISD::Ret";
45     default                 : return NULL;
46   }
47 }
48
49 MipsTargetLowering::
50 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM) 
51 {
52   // Mips does not have i1 type, so use i32 for
53   // setcc operations results (slt, sgt, ...). 
54   setSetCCResultType(MVT::i32);
55   setSetCCResultContents(ZeroOrOneSetCCResult);
56
57   // Set up the register classes
58   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
59
60   // Custom
61   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
62   setOperationAction(ISD::RET, MVT::Other, Custom);
63
64   // Load extented operations for i1 types must be promoted 
65   setLoadXAction(ISD::EXTLOAD,  MVT::i1,  Promote);
66   setLoadXAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
67   setLoadXAction(ISD::SEXTLOAD, MVT::i1,  Promote);
68
69   // Store operations for i1 types must be promoted
70   setStoreXAction(MVT::i1, Promote);
71
72   // Mips does not have these NodeTypes below.
73   setOperationAction(ISD::BR_JT,     MVT::Other, Expand);
74   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
75   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
76   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
77   setOperationAction(ISD::SELECT, MVT::i32, Expand);
78
79   // Mips not supported intrinsics.
80   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
81   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
82   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
83
84   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
85   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
86   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
87   setOperationAction(ISD::ROTL , MVT::i32, Expand);
88   setOperationAction(ISD::ROTR , MVT::i32, Expand);
89   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
90
91   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
92   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
93   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
94
95   // We don't have line number support yet.
96   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
97   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
98   setOperationAction(ISD::LABEL, MVT::Other, Expand);
99
100   // Use the default for now
101   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
102   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
103
104   setStackPointerRegisterToSaveRestore(Mips::SP);
105   computeRegisterProperties();
106 }
107
108
109 SDOperand MipsTargetLowering::
110 LowerOperation(SDOperand Op, SelectionDAG &DAG) 
111 {
112   switch (Op.getOpcode()) 
113   {
114     case ISD::CALL:             return LowerCALL(Op, DAG);
115     case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
116     case ISD::RET:              return LowerRET(Op, DAG);
117     case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
118     case ISD::RETURNADDR:       return LowerRETURNADDR(Op, DAG);
119   }
120   return SDOperand();
121 }
122
123 //===----------------------------------------------------------------------===//
124 //  Lower helper functions
125 //===----------------------------------------------------------------------===//
126
127 // AddLiveIn - This helper function adds the specified physical register to the
128 // MachineFunction as a live in value.  It also creates a corresponding
129 // virtual register for it.
130 static unsigned
131 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
132 {
133   assert(RC->contains(PReg) && "Not the correct regclass!");
134   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
135   MF.addLiveIn(PReg, VReg);
136   return VReg;
137 }
138
139 // Set up a frame object for the return address.
140 SDOperand MipsTargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
141   if (ReturnAddrIndex == 0) {
142     MachineFunction &MF = DAG.getMachineFunction();
143     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, 0);
144   }
145
146   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
147 }
148
149
150 //===----------------------------------------------------------------------===//
151 //  Misc Lower Operation implementation
152 //===----------------------------------------------------------------------===//
153 SDOperand MipsTargetLowering::
154 LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) 
155 {
156   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
157
158   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
159   SDOperand Hi = DAG.getNode(MipsISD::Hi, MVT::i32, GA);
160   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
161
162   return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
163 }
164
165 SDOperand MipsTargetLowering::
166 LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
167   // Depths > 0 not supported yet!
168   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
169     return SDOperand();
170   
171   // Just load the return address
172   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
173   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
174 }
175
176 //===----------------------------------------------------------------------===//
177 //                      Calling Convention Implementation
178 //
179 //  The lower operations present on calling convention works on this order:
180 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
181 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
182 //      LowerRET (virt regs --> phys regs)
183 //      LowerCALL (phys regs --> virt regs)
184 //
185 //===----------------------------------------------------------------------===//
186
187 #include "MipsGenCallingConv.inc"
188
189 //===----------------------------------------------------------------------===//
190 //                  CALL Calling Convention Implementation
191 //===----------------------------------------------------------------------===//
192
193 /// Mips custom CALL implementation
194 SDOperand MipsTargetLowering::
195 LowerCALL(SDOperand Op, SelectionDAG &DAG)
196 {
197   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
198
199   // By now, only CallingConv::C implemented
200   switch (CallingConv) 
201   {
202     default:
203       assert(0 && "Unsupported calling convention");
204     case CallingConv::Fast:
205     case CallingConv::C:
206       return LowerCCCCallTo(Op, DAG, CallingConv);
207   }
208 }
209
210 /// LowerCCCCallTo - functions arguments are copied from virtual
211 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
212 /// CALLSEQ_END are emitted.
213 /// TODO: isVarArg, isTailCall, sret, GOT, linkage types.
214 SDOperand MipsTargetLowering::
215 LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG, unsigned CC) 
216 {
217   SDOperand Chain  = Op.getOperand(0);
218   SDOperand Callee = Op.getOperand(4);
219
220   // Analyze operands of the call, assigning locations to each operand.
221   SmallVector<CCValAssign, 16> ArgLocs;
222   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
223   CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
224   
225   // Get a count of how many bytes are to be pushed on the stack.
226   unsigned NumBytes = CCInfo.getNextStackOffset();
227
228   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
229                                  getPointerTy()));
230
231   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
232   SmallVector<SDOperand, 8> MemOpChains;
233
234   SDOperand StackPtr;
235
236   // Walk the register/memloc assignments, inserting copies/loads.
237   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
238     CCValAssign &VA = ArgLocs[i];
239
240     // Arguments start after the 5 first operands of ISD::CALL
241     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
242     
243     // Promote the value if needed.
244     switch (VA.getLocInfo()) {
245       default: assert(0 && "Unknown loc info!");
246       case CCValAssign::Full: break;
247       case CCValAssign::SExt:
248         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
249         break;
250       case CCValAssign::ZExt:
251         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
252         break;
253       case CCValAssign::AExt:
254         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
255         break;
256     }
257     
258     // Arguments that can be passed on register, 
259     // must be kept at RegsToPass vector
260     if (VA.isRegLoc()) {
261       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
262     } else {
263       assert(VA.isMemLoc());
264       // Mips::SP holds our stack pointer
265       if (StackPtr.Val == 0)
266         StackPtr = DAG.getRegister(Mips::SP, getPointerTy());
267      
268       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), 
269                                          getPointerTy());
270       
271       // emit a ISD::ADD which emits the final 
272       // stack location to place the parameter
273       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
274
275       // emit ISD::STORE whichs stores the 
276       // parameter value to a stack Location
277       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
278     }
279   }
280
281   // Transform all store nodes into one single node because
282   // all store nodes ar independent of each other.
283   if (!MemOpChains.empty())     
284     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
285                         &MemOpChains[0], MemOpChains.size());
286
287   // Build a sequence of copy-to-reg nodes chained together with token 
288   // chain and flag operands which copy the outgoing args into registers.
289   // The InFlag in necessary since all emited instructions must be
290   // stuck together.
291   SDOperand InFlag;
292   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
293     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
294                              RegsToPass[i].second, InFlag);
295     InFlag = Chain.getValue(1);
296   }
297
298   // If the callee is a GlobalAddress node (quite common, every direct 
299   // call is) turn it into a TargetGlobalAddress node so that legalize 
300   // doesn't hack it.
301   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
302     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
303   } else 
304   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
305     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
306
307   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
308   //             = Chain, Callee, Reg#1, Reg#2, ...  
309   //
310   // Returns a chain & a flag for retval copy to use.
311   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
312   SmallVector<SDOperand, 8> Ops;
313   Ops.push_back(Chain);
314   Ops.push_back(Callee);
315
316   // Add argument registers to the end of the list so that they are 
317   // known live into the call.
318   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
319     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
320                                   RegsToPass[i].second.getValueType()));
321
322   if (InFlag.Val)
323     Ops.push_back(InFlag);
324
325   Chain  = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
326   InFlag = Chain.getValue(1);
327
328   // Create the CALLSEQ_END node.
329   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
330   Ops.clear();
331   Ops.push_back(Chain);
332   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
333   Ops.push_back(InFlag);
334   Chain  = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
335   InFlag = Chain.getValue(1);
336
337   // Handle result values, copying them out of physregs into vregs that we
338   // return.
339   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
340 }
341
342 /// LowerCallResult - Lower the result values of an ISD::CALL into the
343 /// appropriate copies out of appropriate physical registers.  This assumes that
344 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
345 /// being lowered. Returns a SDNode with the same number of values as the 
346 /// ISD::CALL.
347 SDNode *MipsTargetLowering::
348 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
349         unsigned CallingConv, SelectionDAG &DAG) {
350   
351   // Assign locations to each value returned by this call.
352   SmallVector<CCValAssign, 16> RVLocs;
353   CCState CCInfo(CallingConv, getTargetMachine(), RVLocs);
354   CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
355   SmallVector<SDOperand, 8> ResultVals;
356
357   // returns void
358   if (!RVLocs.size())
359     return Chain.Val;
360
361   // Copy all of the result registers out of their specified physreg.
362   for (unsigned i = 0; i != RVLocs.size(); ++i) {
363     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
364                                  RVLocs[i].getValVT(), InFlag).getValue(1);
365     InFlag = Chain.getValue(2);
366     ResultVals.push_back(Chain.getValue(0));
367   }
368   
369   // Merge everything together with a MERGE_VALUES node.
370   ResultVals.push_back(Chain);
371   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
372                        &ResultVals[0], ResultVals.size()).Val;
373 }
374
375 //===----------------------------------------------------------------------===//
376 //             FORMAL_ARGUMENTS Calling Convention Implementation
377 //===----------------------------------------------------------------------===//
378
379 /// Mips custom FORMAL_ARGUMENTS implementation
380 SDOperand MipsTargetLowering::
381 LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) 
382 {
383   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
384   switch(CC) 
385   {
386     default:
387       assert(0 && "Unsupported calling convention");
388     case CallingConv::C:
389       return LowerCCCArguments(Op, DAG);
390   }
391 }
392
393 /// LowerCCCArguments - transform physical registers into
394 /// virtual registers and generate load operations for
395 /// arguments places on the stack.
396 /// TODO: isVarArg, sret
397 SDOperand MipsTargetLowering::
398 LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) 
399 {
400   MachineFunction &MF   = DAG.getMachineFunction();
401   MachineFrameInfo *MFI = MF.getFrameInfo();
402   SDOperand Root        = Op.getOperand(0);
403
404   // Assign locations to all of the incoming arguments.
405   SmallVector<CCValAssign, 16> ArgLocs;
406   CCState CCInfo(MF.getFunction()->getCallingConv(), 
407                  getTargetMachine(), ArgLocs);
408   CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
409   SmallVector<SDOperand, 8> ArgValues;
410
411   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
412
413     CCValAssign &VA = ArgLocs[i];
414
415     // Arguments stored on registers
416     if (VA.isRegLoc()) {
417       MVT::ValueType RegVT = VA.getLocVT();
418       TargetRegisterClass *RC;
419             
420       if (RegVT == MVT::i32)
421         RC = Mips::CPURegsRegisterClass;
422       else
423         assert(0 && "support only Mips::CPURegsRegisterClass");
424       
425       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
426
427       // Transform the arguments stored on 
428       // physical registers into virtual ones
429       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
430       
431       // If this is an 8 or 16-bit value, it is really passed promoted 
432       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
433       // truncate to the right size.
434       if (VA.getLocInfo() == CCValAssign::SExt)
435         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
436                                DAG.getValueType(VA.getValVT()));
437       else if (VA.getLocInfo() == CCValAssign::ZExt)
438         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
439                                DAG.getValueType(VA.getValVT()));
440       
441       if (VA.getLocInfo() != CCValAssign::Full)
442         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
443
444       ArgValues.push_back(ArgValue);
445
446     } else {
447       // sanity check
448       assert(VA.isMemLoc());
449       
450       // Create the frame index object for this incoming parameter...
451       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
452                                       VA.getLocMemOffset());
453
454       // Create load nodes to retrieve arguments from the stack
455       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
456       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
457     }
458   }
459   ArgValues.push_back(Root);
460
461   ReturnAddrIndex = 0;
462
463   // Return the new list of results.
464   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
465                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
466 }
467
468 //===----------------------------------------------------------------------===//
469 //               Return Value Calling Convention Implementation
470 //===----------------------------------------------------------------------===//
471
472 SDOperand MipsTargetLowering::
473 LowerRET(SDOperand Op, SelectionDAG &DAG)
474 {
475   // CCValAssign - represent the assignment of
476   // the return value to a location
477   SmallVector<CCValAssign, 16> RVLocs;
478   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
479
480   // CCState - Info about the registers and stack slot.
481   CCState CCInfo(CC, getTargetMachine(), RVLocs);
482
483   // Analize return values of ISD::RET
484   CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
485
486   // If this is the first return lowered for this function, add 
487   // the regs to the liveout set for the function.
488   if (DAG.getMachineFunction().liveout_empty()) {
489     for (unsigned i = 0; i != RVLocs.size(); ++i)
490       DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
491   }
492
493   // The chain is always operand #0
494   SDOperand Chain = Op.getOperand(0);
495   SDOperand Flag;
496
497   // Copy the result values into the output registers.
498   for (unsigned i = 0; i != RVLocs.size(); ++i) {
499     CCValAssign &VA = RVLocs[i];
500     assert(VA.isRegLoc() && "Can only return in registers!");
501
502     // ISD::RET => ret chain, (regnum1,val1), ...
503     // So i*2+1 index only the regnums
504     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), 
505                                  Op.getOperand(i*2+1), Flag);
506
507     // guarantee that all emitted copies are
508     // stuck together, avoiding something bad
509     Flag = Chain.getValue(1);
510   }
511
512   // Return on Mips is always a "jr $ra"
513   if (Flag.Val)
514     return DAG.getNode(MipsISD::Ret, MVT::Other, 
515                            Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
516   else // Return Void
517     return DAG.getNode(MipsISD::Ret, MVT::Other, 
518                            Chain, DAG.getRegister(Mips::RA, MVT::i32));
519 }