Improve varags handling, with testcases. Patch by Sasa Stankovic
[oota-llvm.git] / lib / Target / Mips / MipsISelDAGToDAG.cpp
1 //===-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the MIPS target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "mips-isel"
15 #include "Mips.h"
16 #include "MipsMachineFunction.h"
17 #include "MipsRegisterInfo.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Type.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGISel.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 // Instruction Selector Implementation
39 //===----------------------------------------------------------------------===//
40
41 //===----------------------------------------------------------------------===//
42 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
43 // instructions for SelectionDAG operations.
44 //===----------------------------------------------------------------------===//
45 namespace {
46
47 class MipsDAGToDAGISel : public SelectionDAGISel {
48
49   /// TM - Keep a reference to MipsTargetMachine.
50   MipsTargetMachine &TM;
51
52   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
53   /// make the right decision when generating code for different targets.
54   const MipsSubtarget &Subtarget;
55
56 public:
57   explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
58   SelectionDAGISel(tm),
59   TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
60
61   // Pass Name
62   virtual const char *getPassName() const {
63     return "MIPS DAG->DAG Pattern Instruction Selection";
64   }
65
66
67 private:
68   // Include the pieces autogenerated from the target description.
69   #include "MipsGenDAGISel.inc"
70
71   /// getTargetMachine - Return a reference to the TargetMachine, casted
72   /// to the target-specific type.
73   const MipsTargetMachine &getTargetMachine() {
74     return static_cast<const MipsTargetMachine &>(TM);
75   }
76
77   /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
78   /// to the target-specific type.
79   const MipsInstrInfo *getInstrInfo() {
80     return getTargetMachine().getInstrInfo();
81   }
82
83   SDNode *getGlobalBaseReg();
84   SDNode *Select(SDNode *N);
85
86   // Complex Pattern.
87   bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset);
88
89   SDNode *SelectLoadFp64(SDNode *N);
90   SDNode *SelectStoreFp64(SDNode *N);
91
92   // getI32Imm - Return a target constant with the specified
93   // value, of type i32.
94   inline SDValue getI32Imm(unsigned Imm) {
95     return CurDAG->getTargetConstant(Imm, MVT::i32);
96   }
97 };
98
99 }
100
101
102 /// getGlobalBaseReg - Output the instructions required to put the
103 /// GOT address into a register.
104 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
105   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
106   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
107 }
108
109 /// ComplexPattern used on MipsInstrInfo
110 /// Used on Mips Load/Store instructions
111 bool MipsDAGToDAGISel::
112 SelectAddr(SDValue Addr, SDValue &Offset, SDValue &Base) {
113   // if Address is FI, get the TargetFrameIndex.
114   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
115     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
116     Offset = CurDAG->getTargetConstant(0, MVT::i32);
117     return true;
118   }
119
120   // on PIC code Load GA
121   if (TM.getRelocationModel() == Reloc::PIC_) {
122     if ((Addr.getOpcode() == ISD::TargetGlobalAddress) ||
123         (Addr.getOpcode() == ISD::TargetConstantPool) ||
124         (Addr.getOpcode() == ISD::TargetJumpTable) ||
125         (Addr.getOpcode() == ISD::TargetBlockAddress)) {
126       Base   = CurDAG->getRegister(Mips::GP, MVT::i32);
127       Offset = Addr;
128       return true;
129     }
130   } else {
131     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
132         Addr.getOpcode() == ISD::TargetGlobalAddress))
133       return false;
134   }
135
136   // Operand is a result from an ADD.
137   if (Addr.getOpcode() == ISD::ADD) {
138     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
139       if (isInt<16>(CN->getSExtValue())) {
140
141         // If the first operand is a FI, get the TargetFI Node
142         if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
143                                     (Addr.getOperand(0))) {
144           Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
145         } else {
146           Base = Addr.getOperand(0);
147         }
148
149         Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32);
150         return true;
151       }
152     }
153
154     // When loading from constant pools, load the lower address part in
155     // the instruction itself. Example, instead of:
156     //  lui $2, %hi($CPI1_0)
157     //  addiu $2, $2, %lo($CPI1_0)
158     //  lwc1 $f0, 0($2)
159     // Generate:
160     //  lui $2, %hi($CPI1_0)
161     //  lwc1 $f0, %lo($CPI1_0)($2)
162     if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi ||
163          Addr.getOperand(0).getOpcode() == ISD::LOAD) &&
164         Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
165       SDValue LoVal = Addr.getOperand(1);
166       if (dyn_cast<ConstantPoolSDNode>(LoVal.getOperand(0))) {
167         Base = Addr.getOperand(0);
168         Offset = LoVal.getOperand(0);
169         return true;
170       }
171     }
172   }
173
174   if (isa<BlockAddressSDNode>(Addr.getOperand(1))) {
175     Base = Addr.getOperand(0);
176     Offset = Addr.getOperand(1);
177   }
178
179   Base   = Addr;
180   Offset = CurDAG->getTargetConstant(0, MVT::i32);
181   return true;
182 }
183
184 SDNode *MipsDAGToDAGISel::SelectLoadFp64(SDNode *N) {
185   MVT::SimpleValueType NVT =
186     N->getValueType(0).getSimpleVT().SimpleTy;
187
188   if (!Subtarget.isMips1() || NVT != MVT::f64)
189     return NULL;
190
191   LoadSDNode *LN = cast<LoadSDNode>(N);
192   if (LN->getExtensionType() != ISD::NON_EXTLOAD ||
193       LN->getAddressingMode() != ISD::UNINDEXED)
194     return NULL;
195
196   SDValue Chain = N->getOperand(0);
197   SDValue N1 = N->getOperand(1);
198   SDValue Offset0, Offset1, Base;
199
200   if (!SelectAddr(N1, Offset0, Base) ||
201       N1.getValueType() != MVT::i32)
202     return NULL;
203
204   MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
205   MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
206   DebugLoc dl = N->getDebugLoc();
207
208   // The second load should start after for 4 bytes.
209   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Offset0))
210     Offset1 = CurDAG->getTargetConstant(C->getSExtValue()+4, MVT::i32);
211   else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Offset0))
212     Offset1 = CurDAG->getTargetConstantPool(CP->getConstVal(),
213                                             MVT::i32,
214                                             CP->getAlignment(),
215                                             CP->getOffset()+4,
216                                             CP->getTargetFlags());
217   else
218     return NULL;
219
220   // Choose the offsets depending on the endianess
221   if (TM.getTargetData()->isBigEndian())
222     std::swap(Offset0, Offset1);
223
224   // Instead of:
225   //    ldc $f0, X($3)
226   // Generate:
227   //    lwc $f0, X($3)
228   //    lwc $f1, X+4($3)
229   SDNode *LD0 = CurDAG->getMachineNode(Mips::LWC1, dl, MVT::f32,
230                                     MVT::Other, Offset0, Base, Chain);
231   SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
232                                                  dl, NVT), 0);
233   SDValue I0 = CurDAG->getTargetInsertSubreg(Mips::sub_fpeven, dl,
234                             MVT::f64, Undef, SDValue(LD0, 0));
235
236   SDNode *LD1 = CurDAG->getMachineNode(Mips::LWC1, dl, MVT::f32,
237                           MVT::Other, Offset1, Base, SDValue(LD0, 1));
238   SDValue I1 = CurDAG->getTargetInsertSubreg(Mips::sub_fpodd, dl,
239                             MVT::f64, I0, SDValue(LD1, 0));
240
241   ReplaceUses(SDValue(N, 0), I1);
242   ReplaceUses(SDValue(N, 1), Chain);
243   cast<MachineSDNode>(LD0)->setMemRefs(MemRefs0, MemRefs0 + 1);
244   cast<MachineSDNode>(LD1)->setMemRefs(MemRefs0, MemRefs0 + 1);
245   return I1.getNode();
246 }
247
248 SDNode *MipsDAGToDAGISel::SelectStoreFp64(SDNode *N) {
249
250   if (!Subtarget.isMips1() ||
251       N->getOperand(1).getValueType() != MVT::f64)
252     return NULL;
253
254   SDValue Chain = N->getOperand(0);
255
256   StoreSDNode *SN = cast<StoreSDNode>(N);
257   if (SN->isTruncatingStore() || SN->getAddressingMode() != ISD::UNINDEXED)
258     return NULL;
259
260   SDValue N1 = N->getOperand(1);
261   SDValue N2 = N->getOperand(2);
262   SDValue Offset0, Offset1, Base;
263
264   if (!SelectAddr(N2, Offset0, Base) ||
265       N1.getValueType() != MVT::f64 ||
266       N2.getValueType() != MVT::i32)
267     return NULL;
268
269   MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
270   MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
271   DebugLoc dl = N->getDebugLoc();
272
273   // Get the even and odd part from the f64 register
274   SDValue FPOdd = CurDAG->getTargetExtractSubreg(Mips::sub_fpodd,
275                                                  dl, MVT::f32, N1);
276   SDValue FPEven = CurDAG->getTargetExtractSubreg(Mips::sub_fpeven,
277                                                  dl, MVT::f32, N1);
278
279   // The second store should start after for 4 bytes.
280   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Offset0))
281     Offset1 = CurDAG->getTargetConstant(C->getSExtValue()+4, MVT::i32);
282   else
283     return NULL;
284
285   // Choose the offsets depending on the endianess
286   if (TM.getTargetData()->isBigEndian())
287     std::swap(Offset0, Offset1);
288
289   // Instead of:
290   //    sdc $f0, X($3)
291   // Generate:
292   //    swc $f0, X($3)
293   //    swc $f1, X+4($3)
294   SDValue Ops0[] = { FPEven, Offset0, Base, Chain };
295   Chain = SDValue(CurDAG->getMachineNode(Mips::SWC1, dl,
296                                        MVT::Other, Ops0, 4), 0);
297   cast<MachineSDNode>(Chain.getNode())->setMemRefs(MemRefs0, MemRefs0 + 1);
298
299   SDValue Ops1[] = { FPOdd, Offset1, Base, Chain };
300   Chain = SDValue(CurDAG->getMachineNode(Mips::SWC1, dl,
301                                        MVT::Other, Ops1, 4), 0);
302   cast<MachineSDNode>(Chain.getNode())->setMemRefs(MemRefs0, MemRefs0 + 1);
303
304   ReplaceUses(SDValue(N, 0), Chain);
305   return Chain.getNode();
306 }
307
308 /// Select instructions not customized! Used for
309 /// expanded, promoted and normal instructions
310 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
311   unsigned Opcode = Node->getOpcode();
312   DebugLoc dl = Node->getDebugLoc();
313
314   // Dump information about the Node being selected
315   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
316
317   // If we have a custom node, we already have selected!
318   if (Node->isMachineOpcode()) {
319     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
320     return NULL;
321   }
322
323   ///
324   // Instruction Selection not handled by the auto-generated
325   // tablegen selection should be handled here.
326   ///
327   switch(Opcode) {
328
329     default: break;
330
331     case ISD::SUBE:
332     case ISD::ADDE: {
333       SDValue InFlag = Node->getOperand(2), CmpLHS;
334       unsigned Opc = InFlag.getOpcode(); (void)Opc;
335       assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
336               (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
337              "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
338
339       unsigned MOp;
340       if (Opcode == ISD::ADDE) {
341         CmpLHS = InFlag.getValue(0);
342         MOp = Mips::ADDu;
343       } else {
344         CmpLHS = InFlag.getOperand(0);
345         MOp = Mips::SUBu;
346       }
347
348       SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
349
350       SDValue LHS = Node->getOperand(0);
351       SDValue RHS = Node->getOperand(1);
352
353       EVT VT = LHS.getValueType();
354       SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
355       SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
356                                                 SDValue(Carry,0), RHS);
357
358       return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
359                                   LHS, SDValue(AddCarry,0));
360     }
361
362     /// Mul/Div with two results
363     case ISD::SDIVREM:
364     case ISD::UDIVREM:
365       break;
366     case ISD::SMUL_LOHI:
367     case ISD::UMUL_LOHI: {
368       SDValue Op1 = Node->getOperand(0);
369       SDValue Op2 = Node->getOperand(1);
370
371       unsigned Op;
372       Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
373
374       SDNode *Mul = CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2);
375
376       SDValue InFlag = SDValue(Mul, 0);
377       SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32,
378                                           MVT::Glue, InFlag);
379       InFlag = SDValue(Lo,1);
380       SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
381
382       if (!SDValue(Node, 0).use_empty())
383         ReplaceUses(SDValue(Node, 0), SDValue(Lo,0));
384
385       if (!SDValue(Node, 1).use_empty())
386         ReplaceUses(SDValue(Node, 1), SDValue(Hi,0));
387
388       return NULL;
389     }
390
391     /// Special Muls
392     case ISD::MUL:
393       if (Subtarget.isMips32())
394         break;
395     case ISD::MULHS:
396     case ISD::MULHU: {
397       SDValue MulOp1 = Node->getOperand(0);
398       SDValue MulOp2 = Node->getOperand(1);
399
400       unsigned MulOp  = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
401       SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl,
402                                                MVT::Glue, MulOp1, MulOp2);
403
404       SDValue InFlag = SDValue(MulNode, 0);
405
406       if (Opcode == ISD::MUL)
407         return CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32, InFlag);
408       else
409         return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
410     }
411
412     /// Div/Rem operations
413     case ISD::SREM:
414     case ISD::UREM:
415     case ISD::SDIV:
416     case ISD::UDIV:
417       break;
418
419     // Get target GOT address.
420     case ISD::GLOBAL_OFFSET_TABLE:
421       return getGlobalBaseReg();
422
423     case ISD::ConstantFP: {
424       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
425       if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
426         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
427                                         Mips::ZERO, MVT::i32);
428         SDValue Undef = SDValue(
429           CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, MVT::f64), 0);
430         SDNode *MTC = CurDAG->getMachineNode(Mips::MTC1, dl, MVT::f32, Zero);
431         SDValue I0 = CurDAG->getTargetInsertSubreg(Mips::sub_fpeven, dl,
432                             MVT::f64, Undef, SDValue(MTC, 0));
433         SDValue I1 = CurDAG->getTargetInsertSubreg(Mips::sub_fpodd, dl,
434                             MVT::f64, I0, SDValue(MTC, 0));
435         ReplaceUses(SDValue(Node, 0), I1);
436         return I1.getNode();
437       }
438       break;
439     }
440
441     case ISD::LOAD:
442       if (SDNode *ResNode = SelectLoadFp64(Node))
443         return ResNode;
444       // Other cases are autogenerated.
445       break;
446
447     case ISD::STORE:
448       if (SDNode *ResNode = SelectStoreFp64(Node))
449         return ResNode;
450       // Other cases are autogenerated.
451       break;
452
453     /// Handle direct and indirect calls when using PIC. On PIC, when
454     /// GOT is smaller than about 64k (small code) the GA target is
455     /// loaded with only one instruction. Otherwise GA's target must
456     /// be loaded with 3 instructions.
457     case MipsISD::JmpLink: {
458       if (TM.getRelocationModel() == Reloc::PIC_) {
459         unsigned LastOpNum = Node->getNumOperands()-1;
460
461         SDValue Chain  = Node->getOperand(0);
462         SDValue Callee = Node->getOperand(1);
463         SDValue InFlag;
464
465         // Skip the incomming flag if present
466         if (Node->getOperand(LastOpNum).getValueType() == MVT::Glue)
467           LastOpNum--;
468
469         if ( (isa<GlobalAddressSDNode>(Callee)) ||
470              (isa<ExternalSymbolSDNode>(Callee)) )
471         {
472           /// Direct call for global addresses and external symbols
473           SDValue GPReg = CurDAG->getRegister(Mips::GP, MVT::i32);
474
475           // Use load to get GOT target
476           SDValue Ops[] = { Callee, GPReg, Chain };
477           SDValue Load = SDValue(CurDAG->getMachineNode(Mips::LW, dl, MVT::i32,
478                                      MVT::Other, Ops, 3), 0);
479           Chain = Load.getValue(1);
480
481           // Call target must be on T9
482           Chain = CurDAG->getCopyToReg(Chain, dl, Mips::T9, Load, InFlag);
483         } else
484           /// Indirect call
485           Chain = CurDAG->getCopyToReg(Chain, dl, Mips::T9, Callee, InFlag);
486
487         // Map the JmpLink operands to JALR
488         SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
489         SmallVector<SDValue, 8> Ops;
490         Ops.push_back(CurDAG->getRegister(Mips::T9, MVT::i32));
491
492         for (unsigned i = 2, e = LastOpNum+1; i != e; ++i)
493           Ops.push_back(Node->getOperand(i));
494         Ops.push_back(Chain);
495         Ops.push_back(Chain.getValue(1));
496
497         // Emit Jump and Link Register
498         SDNode *ResNode = CurDAG->getMachineNode(Mips::JALR, dl, NodeTys,
499                                   &Ops[0], Ops.size());
500
501         // Replace Chain and InFlag
502         ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
503         ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 1));
504         return ResNode;
505       }
506     }
507   }
508
509   // Select the default instruction
510   SDNode *ResNode = SelectCode(Node);
511
512   DEBUG(errs() << "=> ");
513   if (ResNode == NULL || ResNode == Node)
514     DEBUG(Node->dump(CurDAG));
515   else
516     DEBUG(ResNode->dump(CurDAG));
517   DEBUG(errs() << "\n");
518   return ResNode;
519 }
520
521 /// createMipsISelDag - This pass converts a legalized DAG into a
522 /// MIPS-specific DAG, ready for instruction scheduling.
523 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
524   return new MipsDAGToDAGISel(TM);
525 }