DAG->DAG instruction selection for ia64! "hello world" works, not much else.
[oota-llvm.git] / lib / Target / IA64 / IA64ISelDAGToDAG.cpp
1 //===---- IA64ISelDAGToDAG.cpp - IA64 pattern matching inst selector ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Duraid Madina 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 IA64,
11 // converting a legalized dag to an IA64 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "IA64.h"
16 #include "IA64TargetMachine.h"
17 #include "IA64ISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> FusedFP ("ia64-codegen", "Number of fused fp operations");
33   Statistic<> FrameOff("ia64-codegen", "Number of frame idx offsets collapsed");
34     
35   //===--------------------------------------------------------------------===//
36   /// IA64DAGToDAGISel - IA64 specific code to select IA64 machine
37   /// instructions for SelectionDAG operations.
38   ///
39   class IA64DAGToDAGISel : public SelectionDAGISel {
40     IA64TargetLowering IA64Lowering;
41     unsigned GlobalBaseReg;
42   public:
43     IA64DAGToDAGISel(TargetMachine &TM)
44       : SelectionDAGISel(IA64Lowering), IA64Lowering(TM) {}
45     
46     virtual bool runOnFunction(Function &Fn) {
47       // Make sure we re-emit a set of the global base reg if necessary
48       GlobalBaseReg = 0;
49       return SelectionDAGISel::runOnFunction(Fn);
50     }
51  
52     /// getI64Imm - Return a target constant with the specified value, of type
53     /// i64.
54     inline SDOperand getI64Imm(uint64_t Imm) {
55       return CurDAG->getTargetConstant(Imm, MVT::i64);
56     }
57
58     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
59     /// base register.  Return the virtual register that holds this value.
60     // SDOperand getGlobalBaseReg(); TODO: hmm
61     
62     // Select - Convert the specified operand from a target-independent to a
63     // target-specific node if it hasn't already been changed.
64     SDOperand Select(SDOperand Op);
65     
66     SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
67                                    unsigned OCHi, unsigned OCLo,
68                                    bool IsArithmetic = false,
69                                    bool Negate = false);
70     SDNode *SelectBitfieldInsert(SDNode *N);
71
72     /// SelectCC - Select a comparison of the specified values with the
73     /// specified condition code, returning the CR# of the expression.
74     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
75
76     /// SelectAddr - Given the specified address, return the two operands for a
77     /// load/store instruction, and return true if it should be an indexed [r+r]
78     /// operation.
79     bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
80
81     SDOperand BuildSDIVSequence(SDNode *N);
82     SDOperand BuildUDIVSequence(SDNode *N);
83     
84     /// InstructionSelectBasicBlock - This callback is invoked by
85     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
86     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
87     
88     virtual const char *getPassName() const {
89       return "IA64 (Itanium) DAG->DAG Instruction Selector";
90     } 
91
92 // Include the pieces autogenerated from the target description.
93 #include "IA64GenDAGISel.inc"
94     
95 private:
96     SDOperand SelectCALL(SDOperand Op);
97   };
98 }
99
100 /// InstructionSelectBasicBlock - This callback is invoked by
101 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
102 void IA64DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
103   DEBUG(BB->dump());
104   
105   // The selection process is inherently a bottom-up recursive process (users
106   // select their uses before themselves).  Given infinite stack space, we
107   // could just start selecting on the root and traverse the whole graph.  In
108   // practice however, this causes us to run out of stack space on large basic
109   // blocks.  To avoid this problem, select the entry node, then all its uses,
110   // iteratively instead of recursively.
111   std::vector<SDOperand> Worklist;
112   Worklist.push_back(DAG.getEntryNode());
113   
114   // Note that we can do this in the IA64 target (scanning forward across token
115   // chain edges) because no nodes ever get folded across these edges.  On a
116   // target like X86 which supports load/modify/store operations, this would
117   // have to be more careful.
118   while (!Worklist.empty()) {
119     SDOperand Node = Worklist.back();
120     Worklist.pop_back();
121     
122     // Chose from the least deep of the top two nodes.
123     if (!Worklist.empty() &&
124         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
125       std::swap(Worklist.back(), Node);
126     
127     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
128          Node.Val->getOpcode() < IA64ISD::FIRST_NUMBER) ||
129         CodeGenMap.count(Node)) continue;
130     
131     for (SDNode::use_iterator UI = Node.Val->use_begin(),
132          E = Node.Val->use_end(); UI != E; ++UI) {
133       // Scan the values.  If this use has a value that is a token chain, add it
134       // to the worklist.
135       SDNode *User = *UI;
136       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
137         if (User->getValueType(i) == MVT::Other) {
138           Worklist.push_back(SDOperand(User, i));
139           break; 
140         }
141     }
142
143     // Finally, legalize this node.
144     Select(Node);
145   }
146     
147   // Select target instructions for the DAG.
148   DAG.setRoot(Select(DAG.getRoot()));
149   CodeGenMap.clear();
150   DAG.RemoveDeadNodes();
151   
152   // Emit machine code to BB. 
153   ScheduleAndEmitDAG(DAG);
154 }
155
156
157 SDOperand IA64DAGToDAGISel::SelectCALL(SDOperand Op) {
158   SDNode *N = Op.Val;
159   SDOperand Chain = Select(N->getOperand(0));
160   
161   unsigned CallOpcode;
162   std::vector<SDOperand> CallOperands;
163
164   // save the current GP, SP and RP : FIXME: do we need to do all 3 always?
165   SDOperand GPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r1, MVT::i64);
166   Chain = GPBeforeCall.getValue(1);
167   SDOperand SPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r12, MVT::i64);
168   Chain = SPBeforeCall.getValue(1);
169   SDOperand RPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::rp, MVT::i64);
170   Chain = RPBeforeCall.getValue(1);
171
172   // if we can call directly, do so
173   if (GlobalAddressSDNode *GASD =
174       dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
175     CallOpcode = IA64::BRCALL_IPREL;
176     CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
177                                                           MVT::i64));
178   } else if (ExternalSymbolSDNode *ESSDN = // FIXME: we currently NEED this
179                                          // case for correctness, to avoid
180                                          // "non-pic code with imm reloc.n
181                                          // against dynamic symbol" errors
182              dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
183     CallOpcode = IA64::BRCALL_IPREL;
184     CallOperands.push_back(N->getOperand(1));
185   } else {
186     // otherwise we need to load the function descriptor,
187     // load the branch target (function)'s entry point and GP,
188     //  branch (call) then restore the
189     // GP
190     
191     SDOperand FnDescriptor = Select(N->getOperand(1));
192    
193     // load the branch target's entry point [mem] and 
194     // GP value [mem+8]
195     SDOperand targetEntryPoint=CurDAG->getLoad(MVT::i64, Chain, FnDescriptor,
196                                         CurDAG->getSrcValue(0));
197     SDOperand targetGPAddr=CurDAG->getNode(ISD::ADD, MVT::i64, FnDescriptor, 
198                             CurDAG->getConstant(8, MVT::i64));
199     SDOperand targetGP=CurDAG->getLoad(MVT::i64, Chain, targetGPAddr,
200                                         CurDAG->getSrcValue(0));
201     
202     // Copy the callee address into the b6 branch register
203     SDOperand B6 = CurDAG->getRegister(IA64::B6, MVT::i64);
204     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, B6,
205                      targetEntryPoint);
206     
207     CallOperands.push_back(B6);
208     CallOpcode = IA64::BRCALL_INDIRECT;
209   }
210  
211   // TODO: support in-memory arguments
212   unsigned used_FPArgs=0; // how many FP args have been used so far?
213
214   unsigned intArgs[] = {IA64::out0, IA64::out1, IA64::out2, IA64::out3,
215                         IA64::out4, IA64::out5, IA64::out6, IA64::out7 };
216   unsigned FPArgs[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
217                        IA64::F12, IA64::F13, IA64::F14, IA64::F15 };
218
219   SDOperand InFlag;  // Null incoming flag value.
220   
221   for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
222     unsigned DestReg = 0;
223     MVT::ValueType RegTy = N->getOperand(i).getValueType();
224     if (RegTy == MVT::i64) {
225       assert((i-2) < 8 && "Too many int args");
226       DestReg = intArgs[i-2];
227     } else {
228       assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
229              "Unpromoted integer arg?");
230       assert(used_FPArgs < 8 && "Too many fp args");
231       DestReg = FPArgs[used_FPArgs++];
232     }
233     
234     if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
235       SDOperand Val = Select(N->getOperand(i));
236       Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
237       InFlag = Chain.getValue(1);
238       CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
239     }
240   }
241   
242   // Finally, once everything is in registers to pass to the call, emit the
243   // call itself.
244   if (InFlag.Val)
245     CallOperands.push_back(InFlag);   // Strong dep on register copies.
246   else
247     CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
248   Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
249                                 CallOperands);
250  
251 //  return Chain; // HACK: err, this means that functions never return anything. need to intergrate this with the code immediately below FIXME XXX
252
253   std::vector<SDOperand> CallResults;
254   
255   // If the call has results, copy the values out of the ret val registers.
256   switch (N->getValueType(0)) {
257     default: assert(0 && "Unexpected ret value!");
258     case MVT::Other: break;
259     case MVT::i64:
260         Chain = CurDAG->getCopyFromReg(Chain, IA64::r8, MVT::i64,
261                                        Chain.getValue(1)).getValue(1);
262         CallResults.push_back(Chain.getValue(0));
263       break;
264     case MVT::f64:
265       Chain = CurDAG->getCopyFromReg(Chain, IA64::F8, N->getValueType(0),
266                                      Chain.getValue(1)).getValue(1);
267       CallResults.push_back(Chain.getValue(0));
268       break;
269   }
270    // restore GP, SP and RP
271   Chain = CurDAG->getCopyToReg(Chain, IA64::r1, GPBeforeCall);
272   Chain = CurDAG->getCopyToReg(Chain, IA64::r12, SPBeforeCall);
273   Chain = CurDAG->getCopyToReg(Chain, IA64::rp, RPBeforeCall);
274  
275   CallResults.push_back(Chain);
276
277   for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
278     CodeGenMap[Op.getValue(i)] = CallResults[i];
279  
280   return CallResults[Op.ResNo];
281 }
282
283 // Select - Convert the specified operand from a target-independent to a
284 // target-specific node if it hasn't already been changed.
285 SDOperand IA64DAGToDAGISel::Select(SDOperand Op) {
286   SDNode *N = Op.Val;
287   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
288       N->getOpcode() < IA64ISD::FIRST_NUMBER)
289     return Op;   // Already selected.
290
291   // If this has already been converted, use it.
292   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
293   if (CGMI != CodeGenMap.end()) return CGMI->second;
294   
295   switch (N->getOpcode()) {
296   default: break;
297
298   case ISD::CALL:
299   case ISD::TAILCALL: return SelectCALL(Op);
300  
301 /* todo:
302  * case ISD::DYNAMIC_STACKALLOC:
303 */
304
305   case ISD::FrameIndex: { // TODO: reduce creepyness
306     int FI = cast<FrameIndexSDNode>(N)->getIndex();
307     if (N->hasOneUse()) {
308       CurDAG->SelectNodeTo(N, IA64::MOV, MVT::i64,
309                            CurDAG->getTargetFrameIndex(FI, MVT::i64));
310       return SDOperand(N, 0);
311     }
312     return CurDAG->getTargetNode(IA64::MOV, MVT::i64,
313                                 CurDAG->getTargetFrameIndex(FI, MVT::i64));
314   }
315
316   case ISD::TokenFactor: {
317     SDOperand New;
318     if (N->getNumOperands() == 2) {
319       SDOperand Op0 = Select(N->getOperand(0));
320       SDOperand Op1 = Select(N->getOperand(1));
321       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
322     } else {
323       std::vector<SDOperand> Ops;
324       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
325         Ops.push_back(Select(N->getOperand(i)));
326       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
327     }
328     
329     CodeGenMap[Op] = New;
330     return New;
331   }
332   case ISD::CopyFromReg: {
333     SDOperand Chain = Select(N->getOperand(0));
334     if (Chain == N->getOperand(0)) return Op; // No change
335     SDOperand New = CurDAG->getCopyFromReg(Chain,
336          cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
337     return New.getValue(Op.ResNo);
338   }
339   case ISD::CopyToReg: {
340     SDOperand Chain = Select(N->getOperand(0));
341     SDOperand Reg = N->getOperand(1);
342     SDOperand Val = Select(N->getOperand(2));
343     SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
344                                     Chain, Reg, Val);
345     CodeGenMap[Op] = New;
346     return New;
347   }
348
349   case ISD::GlobalAddress: {
350     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
351     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i64);
352     SDOperand Tmp = CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, 
353                                   CurDAG->getRegister(IA64::r1, MVT::i64), GA);
354     return CurDAG->getTargetNode(IA64::LD8, MVT::i64, Tmp);
355   }
356                            
357   case ISD::LOAD:
358   case ISD::EXTLOAD:
359   case ISD::ZEXTLOAD: {
360     SDOperand Chain = Select(N->getOperand(0));
361     SDOperand Address = Select(N->getOperand(1));
362
363     MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
364       N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
365     unsigned Opc;
366     switch (TypeBeingLoaded) {
367     default: N->dump(); assert(0 && "Cannot load this type!");
368     // FIXME: bools? case MVT::i1:
369     case MVT::i8:  Opc = IA64::LD1; break;
370     case MVT::i16: Opc = IA64::LD2; break;
371     case MVT::i32: Opc = IA64::LD4; break;
372     case MVT::i64: Opc = IA64::LD8; break;
373     
374     case MVT::f32: Opc = IA64::LDF4; break;
375     case MVT::f64: Opc = IA64::LDF8; break;
376     }
377
378     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
379                              Address, Chain); // TODO: comment this
380     
381     return SDOperand(N, Op.ResNo);
382   }
383   
384   case ISD::TRUNCSTORE:
385   case ISD::STORE: {
386     SDOperand Address = Select(N->getOperand(2));
387
388     unsigned Opc;
389     if (N->getOpcode() == ISD::STORE) {
390       switch (N->getOperand(1).getValueType()) {
391       default: assert(0 && "unknown Type in store");
392       case MVT::i64: Opc = IA64::ST8;  break;
393       case MVT::f64: Opc = IA64::STF8; break;
394      }
395     } else { //ISD::TRUNCSTORE
396       switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
397       default: assert(0 && "unknown Type in store");
398       case MVT::i8:  Opc = IA64::ST1;  break;
399       case MVT::i16: Opc = IA64::ST2;  break;
400       case MVT::i32: Opc = IA64::ST4;  break;
401       case MVT::f32: Opc = IA64::STF4; break;
402       }
403     }
404     
405     CurDAG->SelectNodeTo(N, Opc, MVT::Other, Select(N->getOperand(2)),
406                          Select(N->getOperand(1)), Select(N->getOperand(0)));
407     return SDOperand(N, 0);
408   }
409
410   case ISD::BRCOND: {
411     SDOperand Chain = Select(N->getOperand(0));
412     SDOperand CC = Select(N->getOperand(1));
413     MachineBasicBlock *Dest =
414       cast<BasicBlockSDNode>(N->getOperand(2))->getBasicBlock();
415     //FIXME - we do NOT need long branches all the time
416     CurDAG->SelectNodeTo(N, IA64::BRLCOND_NOTCALL, MVT::Other, CC, CurDAG->getBasicBlock(Dest), Chain);
417     return SDOperand(N, 0);
418   }
419
420   case ISD::CALLSEQ_START:
421   case ISD::CALLSEQ_END: {
422     int64_t Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
423     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
424                        IA64::ADJUSTCALLSTACKDOWN : IA64::ADJUSTCALLSTACKUP;
425     CurDAG->SelectNodeTo(N, Opc, MVT::Other,
426                          getI64Imm(Amt), Select(N->getOperand(0)));
427     return SDOperand(N, 0);
428   }
429
430   case ISD::RET: {
431     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
432
433     switch (N->getNumOperands()) {
434     default:
435       assert(0 && "Unknown return instruction!");
436     case 2: {
437       SDOperand RetVal = Select(N->getOperand(1));
438       switch (RetVal.getValueType()) {
439       default: assert(0 && "I don't know how to return this type! (promote?)");
440                // FIXME: do I need to add support for bools here?
441                // (return '0' or '1' in r8, basically...)
442                //
443                // FIXME: need to round floats - 80 bits is bad, the tester
444                // told me so
445       case MVT::i64:
446         // we mark r8 as live on exit up above in LowerArguments()
447         // BuildMI(BB, IA64::MOV, 1, IA64::r8).addReg(Tmp1);
448         Chain = CurDAG->getCopyToReg(Chain, IA64::r8, RetVal);
449         break;
450       case MVT::f64:
451         // we mark F8 as live on exit up above in LowerArguments()
452         // BuildMI(BB, IA64::FMOV, 1, IA64::F8).addReg(Tmp1);
453         Chain = CurDAG->getCopyToReg(Chain, IA64::F8, RetVal);
454         break;
455       }
456       break;
457       }
458     case 1:
459       break;
460     }
461
462     // we need to copy VirtGPR (the vreg (to become a real reg)) that holds
463     // the output of this function's alloc instruction back into ar.pfs
464     // before we return. this copy must not float up above the last 
465     // outgoing call in this function!!!
466     SDOperand AR_PFSVal = CurDAG->getCopyFromReg(Chain, IA64Lowering.VirtGPR,
467                                                   MVT::i64);
468     Chain = AR_PFSVal.getValue(1);
469     Chain = CurDAG->getCopyToReg(Chain, IA64::AR_PFS, AR_PFSVal);
470
471     CurDAG->SelectNodeTo(N, IA64::RET, MVT::Other, Chain); // and then just emit a 'ret' instruction
472     
473     // before returning, restore the ar.pfs register (set by the 'alloc' up top)
474     // BuildMI(BB, IA64::MOV, 1).addReg(IA64::AR_PFS).addReg(IA64Lowering.VirtGPR);
475     //
476     return SDOperand(N, 0);
477   }
478   
479   case ISD::BR:
480                  // FIXME: we don't need long branches all the time!
481     CurDAG->SelectNodeTo(N, IA64::BRL_NOTCALL, MVT::Other, N->getOperand(1),
482                          Select(N->getOperand(0)));
483     return SDOperand(N, 0);
484   
485   }
486   
487   return SelectCode(Op);
488 }
489
490
491 /// createIA64DAGToDAGInstructionSelector - This pass converts a legalized DAG
492 /// into an IA64-specific DAG, ready for instruction scheduling.
493 ///
494 FunctionPass *llvm::createIA64DAGToDAGInstructionSelector(TargetMachine &TM) {
495   return new IA64DAGToDAGISel(TM);
496 }
497