typeo
[oota-llvm.git] / lib / Target / Alpha / AlphaISelDAGToDAG.cpp
1 //===-- AlphaISelDAGToDAG.cpp - Alpha pattern matching inst selector ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Andrew Lenharth and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for Alpha,
11 // converting from a legalized dag to a Alpha dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Alpha.h"
16 #include "AlphaTargetMachine.h"
17 #include "AlphaISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 namespace {
34
35   //===--------------------------------------------------------------------===//
36   /// AlphaDAGToDAGISel - Alpha specific code to select Alpha machine
37   /// instructions for SelectionDAG operations.
38   class AlphaDAGToDAGISel : public SelectionDAGISel {
39     AlphaTargetLowering AlphaLowering;
40
41     static const int64_t IMM_LOW  = -32768;
42     static const int64_t IMM_HIGH = 32767;
43     static const int64_t IMM_MULT = 65536;
44     static const int64_t IMM_FULLHIGH = IMM_HIGH + IMM_HIGH * IMM_MULT;
45     static const int64_t IMM_FULLLOW = IMM_LOW + IMM_LOW  * IMM_MULT;
46
47     static int64_t get_ldah16(int64_t x) {
48       int64_t y = x / IMM_MULT;
49       if (x % IMM_MULT > IMM_HIGH)
50         ++y;
51       return y;
52     }
53
54     static int64_t get_lda16(int64_t x) {
55       return x - get_ldah16(x) * IMM_MULT;
56     }
57
58     static uint64_t get_zapImm(uint64_t x) {
59       unsigned int build = 0;
60       for(int i = 0; i < 8; ++i)
61         {
62           if ((x & 0x00FF) == 0x00FF)
63             build |= 1 << i;
64           else if ((x & 0x00FF) != 0)
65             { build = 0; break; }
66           x >>= 8;
67         }
68       return build;
69     }
70
71     static bool isFPZ(SDOperand N) {
72       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
73       return (CN && (CN->isExactlyValue(+0.0) || CN->isExactlyValue(-0.0)));
74     }
75     static bool isFPZn(SDOperand N) {
76       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
77       return (CN && CN->isExactlyValue(-0.0));
78     }
79     static bool isFPZp(SDOperand N) {
80       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
81       return (CN && CN->isExactlyValue(+0.0));
82     }
83
84   public:
85     AlphaDAGToDAGISel(TargetMachine &TM)
86       : SelectionDAGISel(AlphaLowering), AlphaLowering(TM) 
87     {}
88
89     /// getI64Imm - Return a target constant with the specified value, of type
90     /// i64.
91     inline SDOperand getI64Imm(int64_t Imm) {
92       return CurDAG->getTargetConstant(Imm, MVT::i64);
93     }
94
95     // Select - Convert the specified operand from a target-independent to a
96     // target-specific node if it hasn't already been changed.
97     SDOperand Select(SDOperand Op);
98     
99     /// InstructionSelectBasicBlock - This callback is invoked by
100     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
101     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
102     
103     virtual const char *getPassName() const {
104       return "Alpha DAG->DAG Pattern Instruction Selection";
105     } 
106
107 // Include the pieces autogenerated from the target description.
108 #include "AlphaGenDAGISel.inc"
109     
110 private:
111     SDOperand getGlobalBaseReg();
112     SDOperand getRASaveReg();
113     SDOperand SelectCALL(SDOperand Op);
114
115   };
116 }
117
118 /// getGlobalBaseReg - Output the instructions required to put the
119 /// GOT address into a register.
120 ///
121 SDOperand AlphaDAGToDAGISel::getGlobalBaseReg() {
122   return CurDAG->getCopyFromReg(CurDAG->getEntryNode(), 
123                                 AlphaLowering.getVRegGP(), 
124                                 MVT::i64);
125 }
126
127 /// getRASaveReg - Grab the return address
128 ///
129 SDOperand AlphaDAGToDAGISel::getRASaveReg() {
130   return CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
131                                 AlphaLowering.getVRegRA(), 
132                                 MVT::i64);
133 }
134
135 /// InstructionSelectBasicBlock - This callback is invoked by
136 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
137 void AlphaDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
138   DEBUG(BB->dump());
139   
140   // Select target instructions for the DAG.
141   DAG.setRoot(Select(DAG.getRoot()));
142   CodeGenMap.clear();
143   DAG.RemoveDeadNodes();
144   
145   // Emit machine code to BB. 
146   ScheduleAndEmitDAG(DAG);
147 }
148
149 // Select - Convert the specified operand from a target-independent to a
150 // target-specific node if it hasn't already been changed.
151 SDOperand AlphaDAGToDAGISel::Select(SDOperand Op) {
152   SDNode *N = Op.Val;
153   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
154       N->getOpcode() < AlphaISD::FIRST_NUMBER)
155     return Op;   // Already selected.
156
157   // If this has already been converted, use it.
158   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
159   if (CGMI != CodeGenMap.end()) return CGMI->second;
160   
161   switch (N->getOpcode()) {
162   default: break;
163   case ISD::TAILCALL:
164   case ISD::CALL: return SelectCALL(Op);
165
166   case ISD::DYNAMIC_STACKALLOC: {
167     if (!isa<ConstantSDNode>(N->getOperand(2)) ||
168         cast<ConstantSDNode>(N->getOperand(2))->getValue() != 0) {
169       std::cerr << "Cannot allocate stack object with greater alignment than"
170                 << " the stack alignment yet!";
171       abort();
172     }
173
174     SDOperand Chain = Select(N->getOperand(0));
175     SDOperand Amt   = Select(N->getOperand(1));
176     SDOperand Reg = CurDAG->getRegister(Alpha::R30, MVT::i64);
177     SDOperand Val = CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64);
178     Chain = Val.getValue(1);
179     
180     // Subtract the amount (guaranteed to be a multiple of the stack alignment)
181     // from the stack pointer, giving us the result pointer.
182     SDOperand Result = CurDAG->getTargetNode(Alpha::SUBQ, MVT::i64, Val, Amt);
183     
184     // Copy this result back into R30.
185     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg, Result);
186     
187     // Copy this result back out of R30 to make sure we're not using the stack
188     // space without decrementing the stack pointer.
189     Result = CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64);
190   
191     // Finally, replace the DYNAMIC_STACKALLOC with the copyfromreg.
192     CodeGenMap[Op.getValue(0)] = Result;
193     CodeGenMap[Op.getValue(1)] = Result.getValue(1);
194     return SDOperand(Result.Val, Op.ResNo);
195   }
196
197   case ISD::FrameIndex: {
198     int FI = cast<FrameIndexSDNode>(N)->getIndex();
199     return CurDAG->SelectNodeTo(N, Alpha::LDA, MVT::i64,
200                                 CurDAG->getTargetFrameIndex(FI, MVT::i32),
201                                 getI64Imm(0));
202   }
203   case AlphaISD::GlobalBaseReg: 
204     return getGlobalBaseReg();
205   
206   case AlphaISD::DivCall: {
207     SDOperand Chain = CurDAG->getEntryNode();
208     Chain = CurDAG->getCopyToReg(Chain, Alpha::R24, Select(Op.getOperand(1)), 
209                                  SDOperand(0,0));
210     Chain = CurDAG->getCopyToReg(Chain, Alpha::R25, Select(Op.getOperand(2)), 
211                                  Chain.getValue(1));
212     Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, Select(Op.getOperand(0)), 
213                                  Chain.getValue(1));
214     Chain = CurDAG->getTargetNode(Alpha::JSRs, MVT::Other, MVT::Flag, 
215                                   Chain, Chain.getValue(1));
216     Chain = CurDAG->getCopyFromReg(Chain, Alpha::R27, MVT::i64, 
217                                   Chain.getValue(1));
218     return CurDAG->SelectNodeTo(N, Alpha::BIS, MVT::i64, Chain, Chain);
219   }
220
221   case ISD::RET: {
222     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
223     SDOperand InFlag;
224
225     if (N->getNumOperands() == 2) {
226       SDOperand Val = Select(N->getOperand(1));
227       if (N->getOperand(1).getValueType() == MVT::i64) {
228         Chain = CurDAG->getCopyToReg(Chain, Alpha::R0, Val, InFlag);
229         InFlag = Chain.getValue(1);
230       } else if (N->getOperand(1).getValueType() == MVT::f64 ||
231                  N->getOperand(1).getValueType() == MVT::f32) {
232         Chain = CurDAG->getCopyToReg(Chain, Alpha::F0, Val, InFlag);
233         InFlag = Chain.getValue(1);
234       }
235     }
236     Chain = CurDAG->getCopyToReg(Chain, Alpha::R26, getRASaveReg(), InFlag);
237     InFlag = Chain.getValue(1);
238     
239     // Finally, select this to a ret instruction.
240     return CurDAG->SelectNodeTo(N, Alpha::RETDAG, MVT::Other, Chain, InFlag);
241   }
242   case ISD::Constant: {
243     uint64_t uval = cast<ConstantSDNode>(N)->getValue();
244     int64_t val = (int64_t)uval;
245     int32_t val32 = (int32_t)val;
246     if (val <= IMM_HIGH + IMM_HIGH * IMM_MULT &&
247         val >= IMM_LOW  + IMM_LOW  * IMM_MULT)
248       break; //(LDAH (LDA))
249     if ((uval >> 32) == 0 && //empty upper bits
250         val32 <= IMM_HIGH + IMM_HIGH * IMM_MULT)
251       //        val32 >= IMM_LOW  + IMM_LOW  * IMM_MULT) //always true
252       break; //(zext (LDAH (LDA)))
253     //Else use the constant pool
254     MachineConstantPool *CP = BB->getParent()->getConstantPool();
255     ConstantUInt *C =
256       ConstantUInt::get(Type::getPrimitiveType(Type::ULongTyID) , uval);
257     SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
258     Tmp = CurDAG->getTargetNode(Alpha::LDAHr, MVT::i64, CPI, getGlobalBaseReg());
259     return CurDAG->SelectNodeTo(N, Alpha::LDQr, MVT::i64, MVT::Other, 
260                                 CPI, Tmp, CurDAG->getEntryNode());
261   }
262   case ISD::ConstantFP:
263     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) {
264       bool isDouble = N->getValueType(0) == MVT::f64;
265       MVT::ValueType T = isDouble ? MVT::f64 : MVT::f32;
266       if (CN->isExactlyValue(+0.0)) {
267         return CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYST : Alpha::CPYSS,
268                                     T, CurDAG->getRegister(Alpha::F31, T),
269                                     CurDAG->getRegister(Alpha::F31, T));
270       } else if ( CN->isExactlyValue(-0.0)) {
271         return CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYSNT : Alpha::CPYSNS,
272                                     T, CurDAG->getRegister(Alpha::F31, T),
273                                     CurDAG->getRegister(Alpha::F31, T));
274       } else {
275         abort();
276       }
277       break;
278     }
279
280   case ISD::SETCC:
281     if (MVT::isFloatingPoint(N->getOperand(0).Val->getValueType(0))) {
282       unsigned Opc = Alpha::WTF;
283       ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
284       bool rev = false;
285       bool isNE = false;
286       switch(CC) {
287       default: N->dump(); assert(0 && "Unknown FP comparison!");
288       case ISD::SETEQ: Opc = Alpha::CMPTEQ; break;
289       case ISD::SETLT: Opc = Alpha::CMPTLT; break;
290       case ISD::SETLE: Opc = Alpha::CMPTLE; break;
291       case ISD::SETGT: Opc = Alpha::CMPTLT; rev = true; break;
292       case ISD::SETGE: Opc = Alpha::CMPTLE; rev = true; break;
293       case ISD::SETNE: Opc = Alpha::CMPTEQ; isNE = true; break;
294       };
295       SDOperand tmp1 = Select(N->getOperand(0)),
296         tmp2 = Select(N->getOperand(1));
297       SDOperand cmp = CurDAG->getTargetNode(Opc, MVT::f64, 
298                                             rev?tmp2:tmp1,
299                                             rev?tmp1:tmp2);
300       if (isNE) 
301         cmp = CurDAG->getTargetNode(Alpha::CMPTEQ, MVT::f64, cmp, 
302                                     CurDAG->getRegister(Alpha::F31, MVT::f64));
303       
304       SDOperand LD;
305       if (AlphaLowering.hasITOF()) {
306         LD = CurDAG->getNode(AlphaISD::FTOIT_, MVT::i64, cmp);
307       } else {
308         int FrameIdx =
309           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
310         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
311         SDOperand ST = CurDAG->getTargetNode(Alpha::STT, MVT::Other, 
312                                              cmp, FI, CurDAG->getRegister(Alpha::R31, MVT::i64));
313         LD = CurDAG->getTargetNode(Alpha::LDQ, MVT::i64, FI, 
314                                    CurDAG->getRegister(Alpha::R31, MVT::i64),
315                                    ST);
316       }
317       SDOperand FP = CurDAG->getTargetNode(Alpha::CMPULT, MVT::i64, 
318                                            CurDAG->getRegister(Alpha::R31, MVT::i64),
319                                            LD);
320       return FP;
321     }
322     break;
323
324   case ISD::SELECT:
325     if (MVT::isFloatingPoint(N->getValueType(0)) &&
326         (N->getOperand(0).getOpcode() != ISD::SETCC ||
327          !MVT::isFloatingPoint(N->getOperand(0).getOperand(1).getValueType()))) {
328       //This should be the condition not covered by the Patterns
329       //FIXME: Don't have SelectCode die, but rather return something testable
330       // so that things like this can be caught in fall though code
331       //move int to fp
332       bool isDouble = N->getValueType(0) == MVT::f64;
333       SDOperand LD,
334         cond = Select(N->getOperand(0)),
335         TV = Select(N->getOperand(1)),
336         FV = Select(N->getOperand(2));
337       
338       if (AlphaLowering.hasITOF()) {
339         LD = CurDAG->getNode(AlphaISD::ITOFT_, MVT::f64, cond);
340       } else {
341         int FrameIdx =
342           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
343         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
344         SDOperand ST = CurDAG->getTargetNode(Alpha::STQ, MVT::Other,
345                                              cond, FI, CurDAG->getRegister(Alpha::R31, MVT::i64));
346         LD = CurDAG->getTargetNode(Alpha::LDT, MVT::f64, FI,
347                                    CurDAG->getRegister(Alpha::R31, MVT::i64),
348                                    ST);
349       }
350       SDOperand FP = CurDAG->getTargetNode(isDouble?Alpha::FCMOVNET:Alpha::FCMOVNES,
351                                            MVT::f64, FV, TV, LD);
352       return FP;
353     }
354     break;
355
356   }
357
358   return SelectCode(Op);
359 }
360
361 SDOperand AlphaDAGToDAGISel::SelectCALL(SDOperand Op) {
362   //TODO: add flag stuff to prevent nondeturministic breakage!
363
364   SDNode *N = Op.Val;
365   SDOperand Chain = Select(N->getOperand(0));
366   SDOperand Addr = N->getOperand(1);
367   SDOperand InFlag;  // Null incoming flag value.
368
369    std::vector<SDOperand> CallOperands;
370    std::vector<MVT::ValueType> TypeOperands;
371   
372    //grab the arguments
373    for(int i = 2, e = N->getNumOperands(); i < e; ++i) {
374      TypeOperands.push_back(N->getOperand(i).getValueType());
375      CallOperands.push_back(Select(N->getOperand(i)));
376    }
377    int count = N->getNumOperands() - 2;
378
379    static const unsigned args_int[] = {Alpha::R16, Alpha::R17, Alpha::R18,
380                                        Alpha::R19, Alpha::R20, Alpha::R21};
381    static const unsigned args_float[] = {Alpha::F16, Alpha::F17, Alpha::F18,
382                                          Alpha::F19, Alpha::F20, Alpha::F21};
383    
384    for (int i = 6; i < count; ++i) {
385      unsigned Opc = Alpha::WTF;
386      if (MVT::isInteger(TypeOperands[i])) {
387        Opc = Alpha::STQ;
388      } else if (TypeOperands[i] == MVT::f32) {
389        Opc = Alpha::STS;
390      } else if (TypeOperands[i] == MVT::f64) {
391        Opc = Alpha::STT;
392      } else
393        assert(0 && "Unknown operand"); 
394      Chain = CurDAG->getTargetNode(Opc, MVT::Other, CallOperands[i], 
395                                    getI64Imm((i - 6) * 8), 
396                                    CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64),
397                                    Chain);
398    }
399    for (int i = 0; i < std::min(6, count); ++i) {
400      if (MVT::isInteger(TypeOperands[i])) {
401        Chain = CurDAG->getCopyToReg(Chain, args_int[i], CallOperands[i], InFlag);
402        InFlag = Chain.getValue(1);
403      } else if (TypeOperands[i] == MVT::f32 || TypeOperands[i] == MVT::f64) {
404        Chain = CurDAG->getCopyToReg(Chain, args_float[i], CallOperands[i], InFlag);
405        InFlag = Chain.getValue(1);
406      } else
407        assert(0 && "Unknown operand"); 
408    }
409
410
411    // Finally, once everything is in registers to pass to the call, emit the
412    // call itself.
413    if (Addr.getOpcode() == AlphaISD::GPRelLo) {
414      SDOperand GOT = getGlobalBaseReg();
415      Chain = CurDAG->getCopyToReg(Chain, Alpha::R29, GOT, InFlag);
416      InFlag = Chain.getValue(1);
417      Chain = CurDAG->getTargetNode(Alpha::BSR, MVT::Other, MVT::Flag, 
418                                    Addr.getOperand(0), Chain, InFlag);
419    } else {
420      Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, Select(Addr), InFlag);
421      InFlag = Chain.getValue(1);
422      Chain = CurDAG->getTargetNode(Alpha::JSR, MVT::Other, MVT::Flag, 
423                                    Chain, InFlag );
424    }
425    InFlag = Chain.getValue(1);
426
427    std::vector<SDOperand> CallResults;
428   
429    switch (N->getValueType(0)) {
430    default: assert(0 && "Unexpected ret value!");
431      case MVT::Other: break;
432    case MVT::i64:
433      Chain = CurDAG->getCopyFromReg(Chain, Alpha::R0, MVT::i64, InFlag).getValue(1);
434      CallResults.push_back(Chain.getValue(0));
435      break;
436    case MVT::f32:
437      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f32, InFlag).getValue(1);
438      CallResults.push_back(Chain.getValue(0));
439      break;
440    case MVT::f64:
441      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f64, InFlag).getValue(1);
442      CallResults.push_back(Chain.getValue(0));
443      break;
444    }
445
446    CallResults.push_back(Chain);
447    for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
448      CodeGenMap[Op.getValue(i)] = CallResults[i];
449    return CallResults[Op.ResNo];
450 }
451
452
453 /// createAlphaISelDag - This pass converts a legalized DAG into a 
454 /// Alpha-specific DAG, ready for instruction scheduling.
455 ///
456 FunctionPass *llvm::createAlphaISelDag(TargetMachine &TM) {
457   return new AlphaDAGToDAGISel(TM);
458 }