add an initial cut at preinc loads for ppc32. This is broken for ppc64
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner 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 PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.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/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Compiler.h"
32 #include <iostream>
33 #include <queue>
34 #include <set>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
39     
40   //===--------------------------------------------------------------------===//
41   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
42   /// instructions for SelectionDAG operations.
43   ///
44   class VISIBILITY_HIDDEN PPCDAGToDAGISel : public SelectionDAGISel {
45     PPCTargetMachine &TM;
46     PPCTargetLowering PPCLowering;
47     unsigned GlobalBaseReg;
48   public:
49     PPCDAGToDAGISel(PPCTargetMachine &tm)
50       : SelectionDAGISel(PPCLowering), TM(tm),
51         PPCLowering(*TM.getTargetLowering()) {}
52     
53     virtual bool runOnFunction(Function &Fn) {
54       // Make sure we re-emit a set of the global base reg if necessary
55       GlobalBaseReg = 0;
56       SelectionDAGISel::runOnFunction(Fn);
57       
58       InsertVRSaveCode(Fn);
59       return true;
60     }
61    
62     /// getI32Imm - Return a target constant with the specified value, of type
63     /// i32.
64     inline SDOperand getI32Imm(unsigned Imm) {
65       return CurDAG->getTargetConstant(Imm, MVT::i32);
66     }
67
68     /// getI64Imm - Return a target constant with the specified value, of type
69     /// i64.
70     inline SDOperand getI64Imm(uint64_t Imm) {
71       return CurDAG->getTargetConstant(Imm, MVT::i64);
72     }
73     
74     /// getSmallIPtrImm - Return a target constant of pointer type.
75     inline SDOperand getSmallIPtrImm(unsigned Imm) {
76       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
77     }
78     
79     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s 
80     /// with any number of 0s on either side.  The 1s are allowed to wrap from
81     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
82     /// 0x0F0F0000 is not, since all 1s are not contiguous.
83     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
84
85
86     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
87     /// rotate and mask opcode and mask operation.
88     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
89                                 unsigned &SH, unsigned &MB, unsigned &ME);
90     
91     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
92     /// base register.  Return the virtual register that holds this value.
93     SDNode *getGlobalBaseReg();
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     SDNode *Select(SDOperand Op);
98     
99     SDNode *SelectBitfieldInsert(SDNode *N);
100
101     /// SelectCC - Select a comparison of the specified values with the
102     /// specified condition code, returning the CR# of the expression.
103     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
104
105     /// SelectAddrImm - Returns true if the address N can be represented by
106     /// a base register plus a signed 16-bit displacement [r+imm].
107     bool SelectAddrImm(SDOperand Op, SDOperand N, SDOperand &Disp,
108                        SDOperand &Base) {
109       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG);
110     }
111       
112     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
113     /// represented as an indexed [r+r] operation.  Returns false if it can
114     /// be represented by [r+imm], which are preferred.
115     bool SelectAddrIdx(SDOperand Op, SDOperand N, SDOperand &Base,
116                        SDOperand &Index) {
117       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
118     }
119     
120     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
121     /// represented as an indexed [r+r] operation.
122     bool SelectAddrIdxOnly(SDOperand Op, SDOperand N, SDOperand &Base,
123                            SDOperand &Index) {
124       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
125     }
126
127     /// SelectAddrImmShift - Returns true if the address N can be represented by
128     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
129     /// for use by STD and friends.
130     bool SelectAddrImmShift(SDOperand Op, SDOperand N, SDOperand &Disp,
131                             SDOperand &Base) {
132       return PPCLowering.SelectAddressRegImmShift(N, Disp, Base, *CurDAG);
133     }
134       
135     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
136     /// inline asm expressions.
137     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
138                                               char ConstraintCode,
139                                               std::vector<SDOperand> &OutOps,
140                                               SelectionDAG &DAG) {
141       SDOperand Op0, Op1;
142       switch (ConstraintCode) {
143       default: return true;
144       case 'm':   // memory
145         if (!SelectAddrIdx(Op, Op, Op0, Op1))
146           SelectAddrImm(Op, Op, Op0, Op1);
147         break;
148       case 'o':   // offsetable
149         if (!SelectAddrImm(Op, Op, Op0, Op1)) {
150           Op0 = Op;
151           AddToISelQueue(Op0);     // r+0.
152           Op1 = getSmallIPtrImm(0);
153         }
154         break;
155       case 'v':   // not offsetable
156         SelectAddrIdxOnly(Op, Op, Op0, Op1);
157         break;
158       }
159       
160       OutOps.push_back(Op0);
161       OutOps.push_back(Op1);
162       return false;
163     }
164     
165     SDOperand BuildSDIVSequence(SDNode *N);
166     SDOperand BuildUDIVSequence(SDNode *N);
167     
168     /// InstructionSelectBasicBlock - This callback is invoked by
169     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
170     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
171     
172     void InsertVRSaveCode(Function &Fn);
173
174     virtual const char *getPassName() const {
175       return "PowerPC DAG->DAG Pattern Instruction Selection";
176     } 
177     
178     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
179     /// this target when scheduling the DAG.
180     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
181       // Should use subtarget info to pick the right hazard recognizer.  For
182       // now, always return a PPC970 recognizer.
183       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
184       assert(II && "No InstrInfo?");
185       return new PPCHazardRecognizer970(*II); 
186     }
187
188 // Include the pieces autogenerated from the target description.
189 #include "PPCGenDAGISel.inc"
190     
191 private:
192     SDNode *SelectSETCC(SDOperand Op);
193     SDNode *MySelect_PPCbctrl(SDOperand N);
194     SDNode *MySelect_PPCcall(SDOperand N);
195   };
196 }
197
198 /// InstructionSelectBasicBlock - This callback is invoked by
199 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
200 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
201   DEBUG(BB->dump());
202
203   // Select target instructions for the DAG.
204   DAG.setRoot(SelectRoot(DAG.getRoot()));
205   DAG.RemoveDeadNodes();
206   
207   // Emit machine code to BB.
208   ScheduleAndEmitDAG(DAG);
209 }
210
211 /// InsertVRSaveCode - Once the entire function has been instruction selected,
212 /// all virtual registers are created and all machine instructions are built,
213 /// check to see if we need to save/restore VRSAVE.  If so, do it.
214 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
215   // Check to see if this function uses vector registers, which means we have to
216   // save and restore the VRSAVE register and update it with the regs we use.  
217   //
218   // In this case, there will be virtual registers of vector type type created
219   // by the scheduler.  Detect them now.
220   MachineFunction &Fn = MachineFunction::get(&F);
221   SSARegMap *RegMap = Fn.getSSARegMap();
222   bool HasVectorVReg = false;
223   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
224        e = RegMap->getLastVirtReg()+1; i != e; ++i)
225     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
226       HasVectorVReg = true;
227       break;
228     }
229   if (!HasVectorVReg) return;  // nothing to do.
230       
231   // If we have a vector register, we want to emit code into the entry and exit
232   // blocks to save and restore the VRSAVE register.  We do this here (instead
233   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
234   //
235   // 1. This (trivially) reduces the load on the register allocator, by not
236   //    having to represent the live range of the VRSAVE register.
237   // 2. This (more significantly) allows us to create a temporary virtual
238   //    register to hold the saved VRSAVE value, allowing this temporary to be
239   //    register allocated, instead of forcing it to be spilled to the stack.
240
241   // Create two vregs - one to hold the VRSAVE register that is live-in to the
242   // function and one for the value after having bits or'd into it.
243   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
244   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
245   
246   MachineBasicBlock &EntryBB = *Fn.begin();
247   // Emit the following code into the entry block:
248   // InVRSAVE = MFVRSAVE
249   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
250   // MTVRSAVE UpdatedVRSAVE
251   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
252   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
253   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
254   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
255   
256   // Find all return blocks, outputting a restore in each epilog.
257   const TargetInstrInfo &TII = *TM.getInstrInfo();
258   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
259     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
260       IP = BB->end(); --IP;
261       
262       // Skip over all terminator instructions, which are part of the return
263       // sequence.
264       MachineBasicBlock::iterator I2 = IP;
265       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
266         IP = I2;
267       
268       // Emit: MTVRSAVE InVRSave
269       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
270     }        
271   }
272 }
273
274
275 /// getGlobalBaseReg - Output the instructions required to put the
276 /// base address to use for accessing globals into a register.
277 ///
278 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
279   if (!GlobalBaseReg) {
280     // Insert the set of GlobalBaseReg into the first MBB of the function
281     MachineBasicBlock &FirstMBB = BB->getParent()->front();
282     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
283     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
284
285     if (PPCLowering.getPointerTy() == MVT::i32)
286       GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
287     else
288       GlobalBaseReg = RegMap->createVirtualRegister(PPC::G8RCRegisterClass);
289     
290     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
291     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
292   }
293   return CurDAG->getRegister(GlobalBaseReg, PPCLowering.getPointerTy()).Val;
294 }
295
296 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
297 /// or 64-bit immediate, and if the value can be accurately represented as a
298 /// sign extension from a 16-bit value.  If so, this returns true and the
299 /// immediate.
300 static bool isIntS16Immediate(SDNode *N, short &Imm) {
301   if (N->getOpcode() != ISD::Constant)
302     return false;
303
304   Imm = (short)cast<ConstantSDNode>(N)->getValue();
305   if (N->getValueType(0) == MVT::i32)
306     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
307   else
308     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
309 }
310
311 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
312   return isIntS16Immediate(Op.Val, Imm);
313 }
314
315
316 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
317 /// operand. If so Imm will receive the 32-bit value.
318 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
319   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
320     Imm = cast<ConstantSDNode>(N)->getValue();
321     return true;
322   }
323   return false;
324 }
325
326 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
327 /// operand.  If so Imm will receive the 64-bit value.
328 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
329   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
330     Imm = cast<ConstantSDNode>(N)->getValue();
331     return true;
332   }
333   return false;
334 }
335
336 // isInt32Immediate - This method tests to see if a constant operand.
337 // If so Imm will receive the 32 bit value.
338 static bool isInt32Immediate(SDOperand N, unsigned &Imm) {
339   return isInt32Immediate(N.Val, Imm);
340 }
341
342
343 // isOpcWithIntImmediate - This method tests to see if the node is a specific
344 // opcode and that it has a immediate integer right operand.
345 // If so Imm will receive the 32 bit value.
346 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
347   return N->getOpcode() == Opc && isInt32Immediate(N->getOperand(1).Val, Imm);
348 }
349
350 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
351   if (isShiftedMask_32(Val)) {
352     // look for the first non-zero bit
353     MB = CountLeadingZeros_32(Val);
354     // look for the first zero bit after the run of ones
355     ME = CountLeadingZeros_32((Val - 1) ^ Val);
356     return true;
357   } else {
358     Val = ~Val; // invert mask
359     if (isShiftedMask_32(Val)) {
360       // effectively look for the first zero bit
361       ME = CountLeadingZeros_32(Val) - 1;
362       // effectively look for the first one bit after the run of zeros
363       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
364       return true;
365     }
366   }
367   // no run present
368   return false;
369 }
370
371 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 
372                                       bool IsShiftMask, unsigned &SH, 
373                                       unsigned &MB, unsigned &ME) {
374   // Don't even go down this path for i64, since different logic will be
375   // necessary for rldicl/rldicr/rldimi.
376   if (N->getValueType(0) != MVT::i32)
377     return false;
378
379   unsigned Shift  = 32;
380   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
381   unsigned Opcode = N->getOpcode();
382   if (N->getNumOperands() != 2 ||
383       !isInt32Immediate(N->getOperand(1).Val, Shift) || (Shift > 31))
384     return false;
385   
386   if (Opcode == ISD::SHL) {
387     // apply shift left to mask if it comes first
388     if (IsShiftMask) Mask = Mask << Shift;
389     // determine which bits are made indeterminant by shift
390     Indeterminant = ~(0xFFFFFFFFu << Shift);
391   } else if (Opcode == ISD::SRL) { 
392     // apply shift right to mask if it comes first
393     if (IsShiftMask) Mask = Mask >> Shift;
394     // determine which bits are made indeterminant by shift
395     Indeterminant = ~(0xFFFFFFFFu >> Shift);
396     // adjust for the left rotate
397     Shift = 32 - Shift;
398   } else if (Opcode == ISD::ROTL) {
399     Indeterminant = 0;
400   } else {
401     return false;
402   }
403   
404   // if the mask doesn't intersect any Indeterminant bits
405   if (Mask && !(Mask & Indeterminant)) {
406     SH = Shift & 31;
407     // make sure the mask is still a mask (wrap arounds may not be)
408     return isRunOfOnes(Mask, MB, ME);
409   }
410   return false;
411 }
412
413 /// SelectBitfieldInsert - turn an or of two masked values into
414 /// the rotate left word immediate then mask insert (rlwimi) instruction.
415 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
416   SDOperand Op0 = N->getOperand(0);
417   SDOperand Op1 = N->getOperand(1);
418   
419   uint64_t LKZ, LKO, RKZ, RKO;
420   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
421   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
422   
423   unsigned TargetMask = LKZ;
424   unsigned InsertMask = RKZ;
425   
426   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
427     unsigned Op0Opc = Op0.getOpcode();
428     unsigned Op1Opc = Op1.getOpcode();
429     unsigned Value, SH = 0;
430     TargetMask = ~TargetMask;
431     InsertMask = ~InsertMask;
432
433     // If the LHS has a foldable shift and the RHS does not, then swap it to the
434     // RHS so that we can fold the shift into the insert.
435     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
436       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
437           Op0.getOperand(0).getOpcode() == ISD::SRL) {
438         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
439             Op1.getOperand(0).getOpcode() != ISD::SRL) {
440           std::swap(Op0, Op1);
441           std::swap(Op0Opc, Op1Opc);
442           std::swap(TargetMask, InsertMask);
443         }
444       }
445     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
446       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
447           Op1.getOperand(0).getOpcode() != ISD::SRL) {
448         std::swap(Op0, Op1);
449         std::swap(Op0Opc, Op1Opc);
450         std::swap(TargetMask, InsertMask);
451       }
452     }
453     
454     unsigned MB, ME;
455     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
456       SDOperand Tmp1, Tmp2, Tmp3;
457       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
458
459       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
460           isInt32Immediate(Op1.getOperand(1), Value)) {
461         Op1 = Op1.getOperand(0);
462         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
463       }
464       if (Op1Opc == ISD::AND) {
465         unsigned SHOpc = Op1.getOperand(0).getOpcode();
466         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
467             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
468           Op1 = Op1.getOperand(0).getOperand(0);
469           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
470         } else {
471           Op1 = Op1.getOperand(0);
472         }
473       }
474       
475       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
476       AddToISelQueue(Tmp3);
477       AddToISelQueue(Op1);
478       SH &= 31;
479       SDOperand Ops[] = { Tmp3, Op1, getI32Imm(SH), getI32Imm(MB),
480                           getI32Imm(ME) };
481       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Ops, 5);
482     }
483   }
484   return 0;
485 }
486
487 /// SelectCC - Select a comparison of the specified values with the specified
488 /// condition code, returning the CR# of the expression.
489 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
490                                     ISD::CondCode CC) {
491   // Always select the LHS.
492   AddToISelQueue(LHS);
493   unsigned Opc;
494   
495   if (LHS.getValueType() == MVT::i32) {
496     unsigned Imm;
497     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
498       if (isInt32Immediate(RHS, Imm)) {
499         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
500         if (isUInt16(Imm))
501           return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
502                                                  getI32Imm(Imm & 0xFFFF)), 0);
503         // If this is a 16-bit signed immediate, fold it.
504         if (isInt16(Imm))
505           return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
506                                                  getI32Imm(Imm & 0xFFFF)), 0);
507         
508         // For non-equality comparisons, the default code would materialize the
509         // constant, then compare against it, like this:
510         //   lis r2, 4660
511         //   ori r2, r2, 22136 
512         //   cmpw cr0, r3, r2
513         // Since we are just comparing for equality, we can emit this instead:
514         //   xoris r0,r3,0x1234
515         //   cmplwi cr0,r0,0x5678
516         //   beq cr0,L6
517         SDOperand Xor(CurDAG->getTargetNode(PPC::XORIS, MVT::i32, LHS,
518                                             getI32Imm(Imm >> 16)), 0);
519         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, Xor,
520                                                getI32Imm(Imm & 0xFFFF)), 0);
521       }
522       Opc = PPC::CMPLW;
523     } else if (ISD::isUnsignedIntSetCC(CC)) {
524       if (isInt32Immediate(RHS, Imm) && isUInt16(Imm))
525         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
526                                                getI32Imm(Imm & 0xFFFF)), 0);
527       Opc = PPC::CMPLW;
528     } else {
529       short SImm;
530       if (isIntS16Immediate(RHS, SImm))
531         return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
532                                                getI32Imm((int)SImm & 0xFFFF)),
533                          0);
534       Opc = PPC::CMPW;
535     }
536   } else if (LHS.getValueType() == MVT::i64) {
537     uint64_t Imm;
538     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
539       if (isInt64Immediate(RHS.Val, Imm)) {
540         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
541         if (isUInt16(Imm))
542           return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
543                                                  getI32Imm(Imm & 0xFFFF)), 0);
544         // If this is a 16-bit signed immediate, fold it.
545         if (isInt16(Imm))
546           return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
547                                                  getI32Imm(Imm & 0xFFFF)), 0);
548         
549         // For non-equality comparisons, the default code would materialize the
550         // constant, then compare against it, like this:
551         //   lis r2, 4660
552         //   ori r2, r2, 22136 
553         //   cmpd cr0, r3, r2
554         // Since we are just comparing for equality, we can emit this instead:
555         //   xoris r0,r3,0x1234
556         //   cmpldi cr0,r0,0x5678
557         //   beq cr0,L6
558         if (isUInt32(Imm)) {
559           SDOperand Xor(CurDAG->getTargetNode(PPC::XORIS8, MVT::i64, LHS,
560                                               getI64Imm(Imm >> 16)), 0);
561           return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, Xor,
562                                                  getI64Imm(Imm & 0xFFFF)), 0);
563         }
564       }
565       Opc = PPC::CMPLD;
566     } else if (ISD::isUnsignedIntSetCC(CC)) {
567       if (isInt64Immediate(RHS.Val, Imm) && isUInt16(Imm))
568         return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
569                                                getI64Imm(Imm & 0xFFFF)), 0);
570       Opc = PPC::CMPLD;
571     } else {
572       short SImm;
573       if (isIntS16Immediate(RHS, SImm))
574         return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
575                                                getI64Imm(SImm & 0xFFFF)),
576                          0);
577       Opc = PPC::CMPD;
578     }
579   } else if (LHS.getValueType() == MVT::f32) {
580     Opc = PPC::FCMPUS;
581   } else {
582     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
583     Opc = PPC::FCMPUD;
584   }
585   AddToISelQueue(RHS);
586   return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0);
587 }
588
589 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
590 /// to Condition.
591 static unsigned getBCCForSetCC(ISD::CondCode CC) {
592   switch (CC) {
593   default: assert(0 && "Unknown condition!"); abort();
594   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
595   case ISD::SETUEQ:
596   case ISD::SETEQ:  return PPC::BEQ;
597   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
598   case ISD::SETUNE:
599   case ISD::SETNE:  return PPC::BNE;
600   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
601   case ISD::SETULT:
602   case ISD::SETLT:  return PPC::BLT;
603   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
604   case ISD::SETULE:
605   case ISD::SETLE:  return PPC::BLE;
606   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
607   case ISD::SETUGT:
608   case ISD::SETGT:  return PPC::BGT;
609   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
610   case ISD::SETUGE:
611   case ISD::SETGE:  return PPC::BGE;
612     
613   case ISD::SETO:   return PPC::BNU;
614   case ISD::SETUO:  return PPC::BUN;
615   }
616   return 0;
617 }
618
619 /// getCRIdxForSetCC - Return the index of the condition register field
620 /// associated with the SetCC condition, and whether or not the field is
621 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
622 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
623   switch (CC) {
624   default: assert(0 && "Unknown condition!"); abort();
625   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
626   case ISD::SETULT:
627   case ISD::SETLT:  Inv = false;  return 0;
628   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
629   case ISD::SETUGE:
630   case ISD::SETGE:  Inv = true;   return 0;
631   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
632   case ISD::SETUGT:
633   case ISD::SETGT:  Inv = false;  return 1;
634   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
635   case ISD::SETULE:
636   case ISD::SETLE:  Inv = true;   return 1;
637   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
638   case ISD::SETUEQ:
639   case ISD::SETEQ:  Inv = false;  return 2;
640   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
641   case ISD::SETUNE:
642   case ISD::SETNE:  Inv = true;   return 2;
643   case ISD::SETO:   Inv = true;   return 3;
644   case ISD::SETUO:  Inv = false;  return 3;
645   }
646   return 0;
647 }
648
649 SDNode *PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
650   SDNode *N = Op.Val;
651   unsigned Imm;
652   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
653   if (isInt32Immediate(N->getOperand(1), Imm)) {
654     // We can codegen setcc op, imm very efficiently compared to a brcond.
655     // Check for those cases here.
656     // setcc op, 0
657     if (Imm == 0) {
658       SDOperand Op = N->getOperand(0);
659       AddToISelQueue(Op);
660       switch (CC) {
661       default: break;
662       case ISD::SETEQ: {
663         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
664         SDOperand Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
665         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
666       }
667       case ISD::SETNE: {
668         SDOperand AD =
669           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
670                                           Op, getI32Imm(~0U)), 0);
671         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
672                                     AD.getValue(1));
673       }
674       case ISD::SETLT: {
675         SDOperand Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
676         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
677       }
678       case ISD::SETGT: {
679         SDOperand T =
680           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
681         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
682         SDOperand Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
683         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
684       }
685       }
686     } else if (Imm == ~0U) {        // setcc op, -1
687       SDOperand Op = N->getOperand(0);
688       AddToISelQueue(Op);
689       switch (CC) {
690       default: break;
691       case ISD::SETEQ:
692         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
693                                              Op, getI32Imm(1)), 0);
694         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
695                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
696                                                               getI32Imm(0)), 0),
697                                     Op.getValue(1));
698       case ISD::SETNE: {
699         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
700         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
701                                            Op, getI32Imm(~0U));
702         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
703                                     Op, SDOperand(AD, 1));
704       }
705       case ISD::SETLT: {
706         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
707                                                        getI32Imm(1)), 0);
708         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
709                                                        Op), 0);
710         SDOperand Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
711         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
712       }
713       case ISD::SETGT: {
714         SDOperand Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
715         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Ops, 4), 0);
716         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, 
717                                     getI32Imm(1));
718       }
719       }
720     }
721   }
722   
723   bool Inv;
724   unsigned Idx = getCRIdxForSetCC(CC, Inv);
725   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
726   SDOperand IntCR;
727   
728   // Force the ccreg into CR7.
729   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
730   
731   SDOperand InFlag(0, 0);  // Null incoming flag value.
732   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
733                                InFlag).getValue(1);
734   
735   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
736     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
737                                             CCReg), 0);
738   else
739     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
740   
741   SDOperand Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
742                       getI32Imm(31), getI32Imm(31) };
743   if (!Inv) {
744     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
745   } else {
746     SDOperand Tmp =
747       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Ops, 4), 0);
748     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
749   }
750 }
751
752
753 // Select - Convert the specified operand from a target-independent to a
754 // target-specific node if it hasn't already been changed.
755 SDNode *PPCDAGToDAGISel::Select(SDOperand Op) {
756   SDNode *N = Op.Val;
757   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
758       N->getOpcode() < PPCISD::FIRST_NUMBER)
759     return NULL;   // Already selected.
760
761   switch (N->getOpcode()) {
762   default: break;
763   case ISD::SETCC:
764     return SelectSETCC(Op);
765   case PPCISD::GlobalBaseReg:
766     return getGlobalBaseReg();
767     
768   case ISD::FrameIndex: {
769     int FI = cast<FrameIndexSDNode>(N)->getIndex();
770     SDOperand TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
771     unsigned Opc = Op.getValueType() == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
772     if (N->hasOneUse())
773       return CurDAG->SelectNodeTo(N, Opc, Op.getValueType(), TFI,
774                                   getSmallIPtrImm(0));
775     return CurDAG->getTargetNode(Opc, Op.getValueType(), TFI,
776                                  getSmallIPtrImm(0));
777   }
778
779   case PPCISD::MFCR: {
780     SDOperand InFlag = N->getOperand(1);
781     AddToISelQueue(InFlag);
782     // Use MFOCRF if supported.
783     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
784       return CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
785                                    N->getOperand(0), InFlag);
786     else
787       return CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag);
788   }
789     
790   case ISD::SDIV: {
791     // FIXME: since this depends on the setting of the carry flag from the srawi
792     //        we should really be making notes about that for the scheduler.
793     // FIXME: It sure would be nice if we could cheaply recognize the 
794     //        srl/add/sra pattern the dag combiner will generate for this as
795     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
796     unsigned Imm;
797     if (isInt32Immediate(N->getOperand(1), Imm)) {
798       SDOperand N0 = N->getOperand(0);
799       AddToISelQueue(N0);
800       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
801         SDNode *Op =
802           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
803                                 N0, getI32Imm(Log2_32(Imm)));
804         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
805                                     SDOperand(Op, 0), SDOperand(Op, 1));
806       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
807         SDNode *Op =
808           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
809                                 N0, getI32Imm(Log2_32(-Imm)));
810         SDOperand PT =
811           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
812                                           SDOperand(Op, 0), SDOperand(Op, 1)),
813                     0);
814         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
815       }
816     }
817     
818     // Other cases are autogenerated.
819     break;
820   }
821     
822   case ISD::LOAD: {
823     // Handle preincrement loads.
824     LoadSDNode *LD = cast<LoadSDNode>(Op);
825     MVT::ValueType LoadedVT = LD->getLoadedVT();
826     
827     // Normal loads are handled by code generated from the .td file.
828     if (LD->getAddressingMode() != ISD::PRE_INC)
829       break;
830     
831     unsigned Opcode;
832     bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
833     assert(!isSExt || LoadedVT == MVT::i16 && "Invalid sext update load");
834     switch (LoadedVT) {
835     default: assert(0 && "Invalid PPC load type!");
836     case MVT::f64: Opcode = PPC::LFDU; break;
837     case MVT::f32: Opcode = PPC::LFSU; break;
838     case MVT::i32: Opcode = PPC::LWZU; break;
839     case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
840     case MVT::i8:  Opcode = PPC::LBZU; break;
841     }
842     
843     SDOperand Offset = LD->getOffset();
844     if (isa<ConstantSDNode>(Offset)) {
845       SDOperand Chain = LD->getChain();
846       SDOperand Base = LD->getBasePtr();
847       AddToISelQueue(Chain);
848       AddToISelQueue(Base);
849       AddToISelQueue(Offset);
850       SDOperand Ops[] = { Offset, Base, Chain };
851       // FIXME: PPC64
852       return CurDAG->getTargetNode(Opcode, MVT::i32, MVT::i32,
853                                    MVT::Other, Ops, 3);
854     } else {
855       assert(0 && "R+R preindex loads not supported yet!");
856     }
857   }
858     
859   case ISD::AND: {
860     unsigned Imm, Imm2, SH, MB, ME;
861
862     // If this is an and of a value rotated between 0 and 31 bits and then and'd
863     // with a mask, emit rlwinm
864     if (isInt32Immediate(N->getOperand(1), Imm) &&
865         isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
866       SDOperand Val = N->getOperand(0).getOperand(0);
867       AddToISelQueue(Val);
868       SDOperand Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
869       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
870     }
871     // If this is just a masked value where the input is not handled above, and
872     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
873     if (isInt32Immediate(N->getOperand(1), Imm) &&
874         isRunOfOnes(Imm, MB, ME) && 
875         N->getOperand(0).getOpcode() != ISD::ROTL) {
876       SDOperand Val = N->getOperand(0);
877       AddToISelQueue(Val);
878       SDOperand Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
879       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
880     }
881     // AND X, 0 -> 0, not "rlwinm 32".
882     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
883       AddToISelQueue(N->getOperand(1));
884       ReplaceUses(SDOperand(N, 0), N->getOperand(1));
885       return NULL;
886     }
887     // ISD::OR doesn't get all the bitfield insertion fun.
888     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
889     if (isInt32Immediate(N->getOperand(1), Imm) && 
890         N->getOperand(0).getOpcode() == ISD::OR &&
891         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
892       unsigned MB, ME;
893       Imm = ~(Imm^Imm2);
894       if (isRunOfOnes(Imm, MB, ME)) {
895         AddToISelQueue(N->getOperand(0).getOperand(0));
896         AddToISelQueue(N->getOperand(0).getOperand(1));
897         SDOperand Ops[] = { N->getOperand(0).getOperand(0),
898                             N->getOperand(0).getOperand(1),
899                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
900         return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Ops, 5);
901       }
902     }
903     
904     // Other cases are autogenerated.
905     break;
906   }
907   case ISD::OR:
908     if (N->getValueType(0) == MVT::i32)
909       if (SDNode *I = SelectBitfieldInsert(N))
910         return I;
911       
912     // Other cases are autogenerated.
913     break;
914   case ISD::SHL: {
915     unsigned Imm, SH, MB, ME;
916     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
917         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
918       AddToISelQueue(N->getOperand(0).getOperand(0));
919       SDOperand Ops[] = { N->getOperand(0).getOperand(0),
920                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
921       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
922     }
923     
924     // Other cases are autogenerated.
925     break;
926   }
927   case ISD::SRL: {
928     unsigned Imm, SH, MB, ME;
929     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
930         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
931       AddToISelQueue(N->getOperand(0).getOperand(0));
932       SDOperand Ops[] = { N->getOperand(0).getOperand(0),
933                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
934       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
935     }
936     
937     // Other cases are autogenerated.
938     break;
939   }
940   case ISD::SELECT_CC: {
941     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
942     
943     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
944     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
945       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
946         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
947           if (N1C->isNullValue() && N3C->isNullValue() &&
948               N2C->getValue() == 1ULL && CC == ISD::SETNE &&
949               // FIXME: Implement this optzn for PPC64.
950               N->getValueType(0) == MVT::i32) {
951             AddToISelQueue(N->getOperand(0));
952             SDNode *Tmp =
953               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
954                                     N->getOperand(0), getI32Imm(~0U));
955             return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
956                                         SDOperand(Tmp, 0), N->getOperand(0),
957                                         SDOperand(Tmp, 1));
958           }
959
960     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
961     unsigned BROpc = getBCCForSetCC(CC);
962
963     unsigned SelectCCOp;
964     if (N->getValueType(0) == MVT::i32)
965       SelectCCOp = PPC::SELECT_CC_I4;
966     else if (N->getValueType(0) == MVT::i64)
967       SelectCCOp = PPC::SELECT_CC_I8;
968     else if (N->getValueType(0) == MVT::f32)
969       SelectCCOp = PPC::SELECT_CC_F4;
970     else if (N->getValueType(0) == MVT::f64)
971       SelectCCOp = PPC::SELECT_CC_F8;
972     else
973       SelectCCOp = PPC::SELECT_CC_VRRC;
974
975     AddToISelQueue(N->getOperand(2));
976     AddToISelQueue(N->getOperand(3));
977     SDOperand Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
978                         getI32Imm(BROpc) };
979     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
980   }
981   case ISD::BR_CC: {
982     AddToISelQueue(N->getOperand(0));
983     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
984     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
985     SDOperand Ops[] = { CondCode, getI32Imm(getBCCForSetCC(CC)), 
986                         N->getOperand(4), N->getOperand(0) };
987     return CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, Ops, 4);
988   }
989   case ISD::BRIND: {
990     // FIXME: Should custom lower this.
991     SDOperand Chain = N->getOperand(0);
992     SDOperand Target = N->getOperand(1);
993     AddToISelQueue(Chain);
994     AddToISelQueue(Target);
995     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
996     Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target,
997                                             Chain), 0);
998     return CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
999   }
1000   // FIXME: These are manually selected because tblgen isn't handling varargs
1001   // nodes correctly.
1002   case PPCISD::BCTRL:            return MySelect_PPCbctrl(Op);
1003   case PPCISD::CALL:             return MySelect_PPCcall(Op);
1004   }
1005   
1006   return SelectCode(Op);
1007 }
1008
1009
1010 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1011 // correctly.
1012 SDNode *PPCDAGToDAGISel::MySelect_PPCbctrl(SDOperand N) {
1013   SDOperand Chain(0, 0);
1014   
1015   bool hasFlag =
1016     N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1017
1018   SmallVector<SDOperand, 8> Ops;
1019   // Push varargs arguments, including optional flag.
1020   for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1021     Chain = N.getOperand(i);
1022     AddToISelQueue(Chain);
1023     Ops.push_back(Chain);
1024   }
1025
1026   Chain = N.getOperand(0);
1027   AddToISelQueue(Chain);
1028   Ops.push_back(Chain);
1029
1030   if (hasFlag) {
1031     Chain = N.getOperand(N.getNumOperands()-1);
1032     AddToISelQueue(Chain);
1033     Ops.push_back(Chain);
1034   }
1035   
1036   return CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag,
1037                                &Ops[0], Ops.size());
1038 }
1039
1040 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1041 // correctly.
1042 SDNode *PPCDAGToDAGISel::MySelect_PPCcall(SDOperand N) {
1043   SDOperand Chain(0, 0);
1044   SDOperand N1(0, 0);
1045   SDOperand Tmp0(0, 0);
1046   Chain = N.getOperand(0);
1047   N1 = N.getOperand(1);
1048   
1049   // Pattern: (PPCcall:void (imm:i32):$func)
1050   // Emits: (BLA:void (imm:i32):$func)
1051   // Pattern complexity = 4  cost = 1
1052   if (N1.getOpcode() == ISD::Constant) {
1053     unsigned Tmp0C = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1054     
1055     SmallVector<SDOperand, 8> Ops;
1056     Ops.push_back(CurDAG->getTargetConstant(Tmp0C, MVT::i32));
1057
1058     bool hasFlag =
1059       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1060     
1061     // Push varargs arguments, not including optional flag.
1062     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1063       Chain = N.getOperand(i);
1064       AddToISelQueue(Chain);
1065       Ops.push_back(Chain);
1066     }
1067     Chain = N.getOperand(0);
1068     AddToISelQueue(Chain);
1069     Ops.push_back(Chain);
1070     if (hasFlag) {
1071       Chain = N.getOperand(N.getNumOperands()-1);
1072       AddToISelQueue(Chain);
1073       Ops.push_back(Chain);
1074     }
1075     return CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag,
1076                                  &Ops[0], Ops.size());
1077   }
1078   
1079   // Pattern: (PPCcall:void (tglobaladdr:i32):$dst)
1080   // Emits: (BL:void (tglobaladdr:i32):$dst)
1081   // Pattern complexity = 4  cost = 1
1082   if (N1.getOpcode() == ISD::TargetGlobalAddress) {
1083     SmallVector<SDOperand, 8> Ops;
1084     Ops.push_back(N1);
1085     
1086     bool hasFlag =
1087       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1088
1089     // Push varargs arguments, not including optional flag.
1090     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1091       Chain = N.getOperand(i);
1092       AddToISelQueue(Chain);
1093       Ops.push_back(Chain);
1094     }
1095     Chain = N.getOperand(0);
1096     AddToISelQueue(Chain);
1097     Ops.push_back(Chain);
1098     if (hasFlag) {
1099       Chain = N.getOperand(N.getNumOperands()-1);
1100       AddToISelQueue(Chain);
1101       Ops.push_back(Chain);
1102     }
1103     
1104     return CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag,
1105                                  &Ops[0], Ops.size());
1106   }
1107   
1108   // Pattern: (PPCcall:void (texternalsym:i32):$dst)
1109   // Emits: (BL:void (texternalsym:i32):$dst)
1110   // Pattern complexity = 4  cost = 1
1111   if (N1.getOpcode() == ISD::TargetExternalSymbol) {
1112     std::vector<SDOperand> Ops;
1113     Ops.push_back(N1);
1114     
1115     bool hasFlag =
1116       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1117
1118     // Push varargs arguments, not including optional flag.
1119     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1120       Chain = N.getOperand(i);
1121       AddToISelQueue(Chain);
1122       Ops.push_back(Chain);
1123     }
1124     Chain = N.getOperand(0);
1125     AddToISelQueue(Chain);
1126     Ops.push_back(Chain);
1127     if (hasFlag) {
1128       Chain = N.getOperand(N.getNumOperands()-1);
1129       AddToISelQueue(Chain);
1130       Ops.push_back(Chain);
1131     }
1132     
1133     return CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag,
1134                                  &Ops[0], Ops.size());
1135   }
1136   std::cerr << "Cannot yet select: ";
1137   N.Val->dump(CurDAG);
1138   std::cerr << '\n';
1139   abort();
1140
1141   return NULL;
1142 }
1143
1144
1145 /// createPPCISelDag - This pass converts a legalized DAG into a 
1146 /// PowerPC-specific DAG, ready for instruction scheduling.
1147 ///
1148 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1149   return new PPCDAGToDAGISel(TM);
1150 }
1151