FPSelect and more custom lowering
[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   ///
39   class AlphaDAGToDAGISel : public SelectionDAGISel {
40     AlphaTargetLowering AlphaLowering;
41
42     static const int IMM_LOW  = -32768;
43     static const int IMM_HIGH = 32767;
44     static const int IMM_MULT = 65536;
45     
46   public:
47     AlphaDAGToDAGISel(TargetMachine &TM)
48       : SelectionDAGISel(AlphaLowering), AlphaLowering(TM) {}
49
50     /// getI64Imm - Return a target constant with the specified value, of type
51     /// i64.
52     inline SDOperand getI64Imm(int64_t Imm) {
53       return CurDAG->getTargetConstant(Imm, MVT::i64);
54     }
55
56     // Select - Convert the specified operand from a target-independent to a
57     // target-specific node if it hasn't already been changed.
58     SDOperand Select(SDOperand Op);
59     
60     /// InstructionSelectBasicBlock - This callback is invoked by
61     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
62     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
63     
64     virtual const char *getPassName() const {
65       return "Alpha DAG->DAG Pattern Instruction Selection";
66     } 
67
68 // Include the pieces autogenerated from the target description.
69 #include "AlphaGenDAGISel.inc"
70     
71 private:
72     SDOperand getGlobalBaseReg();
73     SDOperand SelectCALL(SDOperand Op);
74
75   };
76 }
77
78 /// getGlobalBaseReg - Output the instructions required to put the
79 /// GOT address into a register.
80 ///
81 SDOperand AlphaDAGToDAGISel::getGlobalBaseReg() {
82   return CurDAG->getRegister(AlphaLowering.getVRegGP(), MVT::i64);
83 }
84
85 /// InstructionSelectBasicBlock - This callback is invoked by
86 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
87 void AlphaDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
88   DEBUG(BB->dump());
89   
90   // Select target instructions for the DAG.
91   DAG.setRoot(Select(DAG.getRoot()));
92   CodeGenMap.clear();
93   DAG.RemoveDeadNodes();
94   
95   // Emit machine code to BB. 
96   ScheduleAndEmitDAG(DAG);
97 }
98
99 // Select - Convert the specified operand from a target-independent to a
100 // target-specific node if it hasn't already been changed.
101 SDOperand AlphaDAGToDAGISel::Select(SDOperand Op) {
102   SDNode *N = Op.Val;
103   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
104       N->getOpcode() < AlphaISD::FIRST_NUMBER)
105     return Op;   // Already selected.
106
107   // If this has already been converted, use it.
108   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
109   if (CGMI != CodeGenMap.end()) return CGMI->second;
110   
111   switch (N->getOpcode()) {
112   default: break;
113   case ISD::TAILCALL:
114   case ISD::CALL: return SelectCALL(Op);
115
116   case ISD::DYNAMIC_STACKALLOC: {
117     if (!isa<ConstantSDNode>(N->getOperand(2)) ||
118         cast<ConstantSDNode>(N->getOperand(2))->getValue() != 0) {
119       std::cerr << "Cannot allocate stack object with greater alignment than"
120                 << " the stack alignment yet!";
121       abort();
122     }
123
124     SDOperand Chain = Select(N->getOperand(0));
125     SDOperand Amt   = Select(N->getOperand(1));
126     SDOperand Reg = CurDAG->getRegister(Alpha::R30, MVT::i64);
127     SDOperand Val = CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64);
128     Chain = Val.getValue(1);
129     
130     // Subtract the amount (guaranteed to be a multiple of the stack alignment)
131     // from the stack pointer, giving us the result pointer.
132     SDOperand Result = CurDAG->getTargetNode(Alpha::SUBQ, MVT::i64, Val, Amt);
133     
134     // Copy this result back into R30.
135     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg, Result);
136     
137     // Copy this result back out of R30 to make sure we're not using the stack
138     // space without decrementing the stack pointer.
139     Result = CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64);
140   
141     // Finally, replace the DYNAMIC_STACKALLOC with the copyfromreg.
142     CodeGenMap[Op.getValue(0)] = Result;
143     CodeGenMap[Op.getValue(1)] = Result.getValue(1);
144     return SDOperand(Result.Val, Op.ResNo);
145   }
146   case ISD::BRCOND: {
147     SDOperand Chain = Select(N->getOperand(0));
148     SDOperand CC = Select(N->getOperand(1));
149     MachineBasicBlock *Dest =
150       cast<BasicBlockSDNode>(N->getOperand(2))->getBasicBlock();
151     CurDAG->SelectNodeTo(N, Alpha::BNE, MVT::Other, CC, CurDAG->getBasicBlock(Dest), Chain);
152     return SDOperand(N, 0);
153   }
154   case ISD::LOAD:
155   case ISD::EXTLOAD:
156   case ISD::ZEXTLOAD:
157   case ISD::SEXTLOAD: {
158     SDOperand Chain = Select(N->getOperand(0));
159     SDOperand Address = Select(N->getOperand(1));
160     unsigned opcode = N->getOpcode();
161     unsigned Opc = Alpha::WTF;
162     if (opcode == ISD::LOAD)
163       switch (N->getValueType(0)) {
164       default: N->dump(); assert(0 && "Bad load!");
165       case MVT::i64: Opc = Alpha::LDQ; break;
166       case MVT::f64: Opc = Alpha::LDT; break;
167       case MVT::f32: Opc = Alpha::LDS; break;
168       }
169     else
170       switch (cast<VTSDNode>(N->getOperand(3))->getVT()) {
171       default: N->dump(); assert(0 && "Bad sign extend!");
172       case MVT::i32: Opc = Alpha::LDL;
173         assert(opcode != ISD::ZEXTLOAD && "Not sext"); break;
174       case MVT::i16: Opc = Alpha::LDWU;
175         assert(opcode != ISD::SEXTLOAD && "Not zext"); break;
176       case MVT::i1: //FIXME: Treat i1 as i8 since there are problems otherwise
177       case MVT::i8: Opc = Alpha::LDBU;
178           assert(opcode != ISD::SEXTLOAD && "Not zext"); break;
179       }
180
181     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
182                          getI64Imm(0), Address, Chain);
183     return SDOperand(N, Op.ResNo);
184   }
185   case ISD::STORE:
186   case ISD::TRUNCSTORE: {
187     SDOperand Chain = Select(N->getOperand(0));
188     SDOperand Value = Select(N->getOperand(1));
189     SDOperand Address = Select(N->getOperand(2));
190
191     unsigned Opc = Alpha::WTF;
192
193     if (N->getOpcode() == ISD::STORE) {
194       switch (N->getOperand(1).getValueType()) {
195       case MVT::i64: Opc = Alpha::STQ; break;
196       case MVT::f64: Opc = Alpha::STT; break;
197       case MVT::f32: Opc = Alpha::STS; break;
198       default: assert(0 && "Bad store!");
199       };
200     } else { //TRUNCSTORE
201       switch (cast<VTSDNode>(N->getOperand(4))->getVT()) {
202       case MVT::i32: Opc = Alpha::STL; break;
203       case MVT::i16: Opc = Alpha::STW; break;
204       case MVT::i8: Opc = Alpha::STB; break;
205       default: assert(0 && "Bad truncstore!");
206       };
207     }
208     CurDAG->SelectNodeTo(N, Opc, MVT::Other, Value, getI64Imm(0), Address, 
209                          Chain);
210     return SDOperand(N, 0);
211   }
212
213   case ISD::BR: {
214     CurDAG->SelectNodeTo(N, Alpha::BR_DAG, MVT::Other, N->getOperand(1),
215                          Select(N->getOperand(0)));
216     return SDOperand(N, 0);
217   }
218
219   case ISD::FrameIndex: {
220     int FI = cast<FrameIndexSDNode>(N)->getIndex();
221     CurDAG->SelectNodeTo(N, Alpha::LDA, MVT::i64,
222                          CurDAG->getTargetFrameIndex(FI, MVT::i32),
223                          getI64Imm(0));
224     return SDOperand(N, 0);
225   }
226   case ISD::ConstantPool: {
227     Constant *C = cast<ConstantPoolSDNode>(N)->get();
228     SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
229     Tmp = CurDAG->getTargetNode(Alpha::LDAHr, MVT::i64, CPI, getGlobalBaseReg());
230     CurDAG->SelectNodeTo(N, Alpha::LDAr, MVT::i64, CPI, Tmp);
231     return SDOperand(N, 0);
232   }
233   case ISD::GlobalAddress: {
234     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
235     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i64);
236     CurDAG->SelectNodeTo(N, Alpha::LDQl, MVT::i64, GA, getGlobalBaseReg());
237     return SDOperand(N, 0);
238   }
239   case ISD::ExternalSymbol:
240     CurDAG->SelectNodeTo(N, Alpha::LDQl, MVT::i64, 
241                          CurDAG->getTargetExternalSymbol(cast<ExternalSymbolSDNode>(N)->getSymbol(), MVT::i64),
242                          CurDAG->getRegister(AlphaLowering.getVRegGP(), MVT::i64));
243     return SDOperand(N, 0);
244
245   case ISD::CALLSEQ_START:
246   case ISD::CALLSEQ_END: {
247     unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
248     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
249                        Alpha::ADJUSTSTACKDOWN : Alpha::ADJUSTSTACKUP;
250     CurDAG->SelectNodeTo(N, Opc, MVT::Other,
251                          getI64Imm(Amt), Select(N->getOperand(0)));
252     return SDOperand(N, 0);
253   }
254   case ISD::RET: {
255     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
256
257     if (N->getNumOperands() == 2) {
258       SDOperand Val = Select(N->getOperand(1));
259       if (N->getOperand(1).getValueType() == MVT::i64) {
260         Chain = CurDAG->getCopyToReg(Chain, Alpha::R0, Val);
261       }
262     }
263     //BuildMI(BB, Alpha::RET, 2, Alpha::R31).addReg(Alpha::R26).addImm(1);
264
265     // FIXME: add restoring of the RA to R26 to the chain
266     // Finally, select this to a ret instruction.
267     CurDAG->SelectNodeTo(N, Alpha::RETDAG, MVT::Other, Chain);
268     return SDOperand(N, 0);
269   }
270   case ISD::Constant: {
271     int64_t val = (int64_t)cast<ConstantSDNode>(N)->getValue();
272     if (val > (int64_t)IMM_HIGH +(int64_t)IMM_HIGH* (int64_t)IMM_MULT ||
273         val < (int64_t)IMM_LOW + (int64_t)IMM_LOW * (int64_t)IMM_MULT) {
274       MachineConstantPool *CP = BB->getParent()->getConstantPool();
275       ConstantUInt *C =
276         ConstantUInt::get(Type::getPrimitiveType(Type::ULongTyID) , val);
277       SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
278       Tmp = CurDAG->getTargetNode(Alpha::LDAHr, MVT::i64, CPI, getGlobalBaseReg());
279       CurDAG->SelectNodeTo(N, Alpha::LDAr, MVT::i64, CPI, Tmp);
280       return SDOperand(N, 0);
281     }
282     break;
283   }
284   case ISD::ConstantFP:
285     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) {
286       bool isDouble = N->getValueType(0) == MVT::f64;
287       MVT::ValueType T = isDouble ? MVT::f64 : MVT::f32;
288       if (CN->isExactlyValue(+0.0)) {
289         CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYST : Alpha::CPYSS, T,
290                              CurDAG->getRegister(Alpha::F31, T),
291                              CurDAG->getRegister(Alpha::F31, T));
292         return SDOperand(N, 0);
293       } else if ( CN->isExactlyValue(-0.0)) {
294         CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYSNT : Alpha::CPYSNS, T,
295                              CurDAG->getRegister(Alpha::F31, T),
296                              CurDAG->getRegister(Alpha::F31, T));
297         return SDOperand(N, 0);
298       } else {
299         abort();
300       }
301       break;
302     }
303   case ISD::SDIV:
304   case ISD::UDIV:
305   case ISD::UREM:
306   case ISD::SREM:
307     if (MVT::isInteger(N->getValueType(0))) {
308       const char* opstr = 0;
309       switch(N->getOpcode()) {
310       case ISD::UREM: opstr = "__remqu"; break;
311       case ISD::SREM: opstr = "__remq";  break;
312       case ISD::UDIV: opstr = "__divqu"; break;
313       case ISD::SDIV: opstr = "__divq";  break;
314       }
315       SDOperand Tmp1 = Select(N->getOperand(0)),
316         Tmp2 = Select(N->getOperand(1)),
317         Addr = CurDAG->getExternalSymbol(opstr, AlphaLowering.getPointerTy());
318       SDOperand Tmp3 = Select(Addr);
319       SDOperand Chain = CurDAG->getCopyToReg(CurDAG->getRoot(), Alpha::R24, 
320                                              Tmp1, SDOperand());
321       Chain = CurDAG->getCopyToReg(CurDAG->getRoot(), Alpha::R25, 
322                                    Tmp2, Chain.getValue(1));
323       Chain = CurDAG->getCopyToReg(CurDAG->getRoot(), Alpha::R27, 
324                                    Tmp3, Chain.getValue(1));
325       Chain = CurDAG->getTargetNode(Alpha::JSRs, MVT::i64, MVT::Flag,
326                                     CurDAG->getRegister(Alpha::R27, MVT::i64),
327                                     getI64Imm(0));
328       return CurDAG->getCopyFromReg(Chain.getValue(1), Alpha::R27, MVT::i64, 
329                                     Chain.getValue(1));
330     }
331     break;
332
333   case ISD::SETCC:
334     if (MVT::isFloatingPoint(N->getOperand(0).Val->getValueType(0))) {
335       unsigned Opc = Alpha::WTF;
336       ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
337       bool rev = false;
338       switch(CC) {
339       default: N->dump(); assert(0 && "Unknown FP comparison!");
340       case ISD::SETEQ: Opc = Alpha::CMPTEQ; break;
341       case ISD::SETLT: Opc = Alpha::CMPTLT; break;
342       case ISD::SETLE: Opc = Alpha::CMPTLE; break;
343       case ISD::SETGT: Opc = Alpha::CMPTLT; rev = true; break;
344       case ISD::SETGE: Opc = Alpha::CMPTLE; rev = true; break;
345         //case ISD::SETNE: Opc = Alpha::CMPTEQ; inv = true; break;
346       };
347       SDOperand tmp1 = Select(N->getOperand(0)),
348         tmp2 = Select(N->getOperand(1));
349       SDOperand cmp = CurDAG->getTargetNode(Opc, MVT::f64, 
350                                             rev?tmp2:tmp1,
351                                             rev?tmp1:tmp2);
352       SDOperand LD;
353       if (AlphaLowering.hasITOF()) {
354         LD = CurDAG->getNode(AlphaISD::FTOIT_, MVT::i64, cmp);
355       } else {
356         int FrameIdx =
357           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
358         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
359         SDOperand ST = CurDAG->getTargetNode(Alpha::STT, MVT::Other, 
360                                              cmp, FI, CurDAG->getRegister(Alpha::R31, MVT::i64));
361         LD = CurDAG->getTargetNode(Alpha::LDQ, MVT::i64, FI, 
362                                    CurDAG->getRegister(Alpha::R31, MVT::i64),
363                                    ST);
364       }
365       SDOperand FP = CurDAG->getTargetNode(Alpha::CMPULT, MVT::i64, 
366                                            CurDAG->getRegister(Alpha::R31, MVT::i64),
367                                            LD);
368       return FP;
369     }
370     break;
371
372   case ISD::SELECT:
373     if (MVT::isFloatingPoint(N->getValueType(0))) {
374       //move int to fp
375       SDOperand LD,
376         cond = Select(N->getOperand(0)),
377         TV = Select(N->getOperand(1)),
378         FV = Select(N->getOperand(2));
379       
380       if (AlphaLowering.hasITOF()) {
381         LD = CurDAG->getNode(AlphaISD::ITOFT_, MVT::f64, cond);
382       } else {
383         int FrameIdx =
384           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
385         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
386         SDOperand ST = CurDAG->getTargetNode(Alpha::STQ, MVT::Other, 
387                                              cond, FI, CurDAG->getRegister(Alpha::R31, MVT::i64));
388         LD = CurDAG->getTargetNode(Alpha::LDT, MVT::f64, FI, 
389                                    CurDAG->getRegister(Alpha::R31, MVT::i64),
390                                    ST);
391       }
392       SDOperand FP = CurDAG->getTargetNode(Alpha::FCMOVEQ, MVT::f64, TV, FV, LD);
393       return FP;
394     }
395     break;
396
397
398   }
399
400   return SelectCode(Op);
401 }
402
403 SDOperand AlphaDAGToDAGISel::SelectCALL(SDOperand Op) {
404   //TODO: add flag stuff to prevent nondeturministic breakage!
405
406   SDNode *N = Op.Val;
407   SDOperand Chain = Select(N->getOperand(0));
408   SDOperand Addr = Select(N->getOperand(1));
409
410 //   unsigned CallOpcode;
411    std::vector<SDOperand> CallOperands;
412    std::vector<MVT::ValueType> TypeOperands;
413   
414    //grab the arguments
415    for(int i = 2, e = N->getNumOperands(); i < e; ++i) {
416      TypeOperands.push_back(N->getOperand(i).getValueType());
417      CallOperands.push_back(Select(N->getOperand(i)));
418    }
419    int count = N->getNumOperands() - 2;
420
421    static const unsigned args_int[] = {Alpha::R16, Alpha::R17, Alpha::R18,
422                                        Alpha::R19, Alpha::R20, Alpha::R21};
423    static const unsigned args_float[] = {Alpha::F16, Alpha::F17, Alpha::F18,
424                                          Alpha::F19, Alpha::F20, Alpha::F21};
425    
426    for (int i = 0; i < std::min(6, count); ++i) {
427      if (MVT::isInteger(TypeOperands[i])) {
428        Chain = CurDAG->getCopyToReg(Chain, args_int[i], CallOperands[i]);
429      } else if (TypeOperands[i] == MVT::f32 || TypeOperands[i] == MVT::f64) {
430        Chain = CurDAG->getCopyToReg(Chain, args_float[i], CallOperands[i]);
431      } else
432        assert(0 && "Unknown operand"); 
433    }
434    for (int i = 6; i < count; ++i) {
435      unsigned Opc = Alpha::WTF;
436      if (MVT::isInteger(TypeOperands[i])) {
437        Opc = Alpha::STQ;
438      } else if (TypeOperands[i] == MVT::f32) {
439        Opc = Alpha::STS;
440      } else if (TypeOperands[i] == MVT::f64) {
441        Opc = Alpha::STT;
442      } else
443        assert(0 && "Unknown operand"); 
444      Chain = CurDAG->getTargetNode(Opc, MVT::Other, CallOperands[i], 
445                                    getI64Imm((i - 6) * 8), 
446                                    CurDAG->getRegister(Alpha::R30, MVT::i64),
447                                    Chain);
448    }
449
450    Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, Addr);
451    // Finally, once everything is in registers to pass to the call, emit the
452    // call itself.
453    Chain = CurDAG->getTargetNode(Alpha::JSRDAG, MVT::Other, Chain );
454   
455    std::vector<SDOperand> CallResults;
456   
457    switch (N->getValueType(0)) {
458    default: assert(0 && "Unexpected ret value!");
459      case MVT::Other: break;
460    case MVT::i64:
461      Chain = CurDAG->getCopyFromReg(Chain, Alpha::R0, MVT::i64).getValue(1);
462      CallResults.push_back(Chain.getValue(0));
463      break;
464    case MVT::f32:
465      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f32).getValue(1);
466      CallResults.push_back(Chain.getValue(0));
467      break;
468    case MVT::f64:
469      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f64).getValue(1);
470      CallResults.push_back(Chain.getValue(0));
471      break;
472    }
473
474    CallResults.push_back(Chain);
475    for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
476      CodeGenMap[Op.getValue(i)] = CallResults[i];
477    return CallResults[Op.ResNo];
478 }
479
480
481 /// createAlphaISelDag - This pass converts a legalized DAG into a 
482 /// Alpha-specific DAG, ready for instruction scheduling.
483 ///
484 FunctionPass *llvm::createAlphaISelDag(TargetMachine &TM) {
485   return new AlphaDAGToDAGISel(TM);
486 }