]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "ppc-codegen"
16 #include "PPC.h"
17 #include "PPCTargetMachine.h"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.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/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 namespace {
36   //===--------------------------------------------------------------------===//
37   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
38   /// instructions for SelectionDAG operations.
39   ///
40   class PPCDAGToDAGISel : public SelectionDAGISel {
41     const PPCTargetMachine &TM;
42     const PPCTargetLowering &PPCLowering;
43     const PPCSubtarget &PPCSubTarget;
44     unsigned GlobalBaseReg;
45   public:
46     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
47       : SelectionDAGISel(tm), TM(tm),
48         PPCLowering(*TM.getTargetLowering()),
49         PPCSubTarget(*TM.getSubtargetImpl()) {}
50
51     virtual bool runOnMachineFunction(MachineFunction &MF) {
52       // Make sure we re-emit a set of the global base reg if necessary
53       GlobalBaseReg = 0;
54       SelectionDAGISel::runOnMachineFunction(MF);
55
56       if (!PPCSubTarget.isSVR4ABI())
57         InsertVRSaveCode(MF);
58
59       return true;
60     }
61
62     /// getI32Imm - Return a target constant with the specified value, of type
63     /// i32.
64     inline SDValue 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 SDValue getI64Imm(uint64_t Imm) {
71       return CurDAG->getTargetConstant(Imm, MVT::i64);
72     }
73
74     /// getSmallIPtrImm - Return a target constant of pointer type.
75     inline SDValue 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(SDNode *N);
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     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, DebugLoc dl);
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(SDValue N, SDValue &Disp,
108                        SDValue &Base) {
109       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG);
110     }
111
112     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
113     /// immediate field.  Because preinc imms have already been validated, just
114     /// accept it.
115     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
116       if (isa<ConstantSDNode>(N) || N.getOpcode() == PPCISD::Lo ||
117           N.getOpcode() == ISD::TargetGlobalAddress) {
118         Out = N;
119         return true;
120       }
121
122       return false;
123     }
124
125     /// SelectAddrIdxOffs - Return true if the operand is valid for a preinc
126     /// index field.  Because preinc imms have already been validated, just
127     /// accept it.
128     bool SelectAddrIdxOffs(SDValue N, SDValue &Out) const {
129       if (isa<ConstantSDNode>(N) || N.getOpcode() == PPCISD::Lo ||
130           N.getOpcode() == ISD::TargetGlobalAddress)
131         return false;
132
133       Out = N;
134       return true;
135     }
136
137     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
138     /// represented as an indexed [r+r] operation.  Returns false if it can
139     /// be represented by [r+imm], which are preferred.
140     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
141       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
142     }
143
144     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
145     /// represented as an indexed [r+r] operation.
146     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
147       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
148     }
149
150     /// SelectAddrImmShift - Returns true if the address N can be represented by
151     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
152     /// for use by STD and friends.
153     bool SelectAddrImmShift(SDValue N, SDValue &Disp, SDValue &Base) {
154       return PPCLowering.SelectAddressRegImmShift(N, Disp, Base, *CurDAG);
155     }
156
157     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
158     /// inline asm expressions.  It is always correct to compute the value into
159     /// a register.  The case of adding a (possibly relocatable) constant to a
160     /// register can be improved, but it is wrong to substitute Reg+Reg for
161     /// Reg in an asm, because the load or store opcode would have to change.
162    virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
163                                               char ConstraintCode,
164                                               std::vector<SDValue> &OutOps) {
165       OutOps.push_back(Op);
166       return false;
167     }
168
169     void InsertVRSaveCode(MachineFunction &MF);
170
171     virtual const char *getPassName() const {
172       return "PowerPC DAG->DAG Pattern Instruction Selection";
173     }
174
175 // Include the pieces autogenerated from the target description.
176 #include "PPCGenDAGISel.inc"
177
178 private:
179     SDNode *SelectSETCC(SDNode *N);
180   };
181 }
182
183 /// InsertVRSaveCode - Once the entire function has been instruction selected,
184 /// all virtual registers are created and all machine instructions are built,
185 /// check to see if we need to save/restore VRSAVE.  If so, do it.
186 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
187   // Check to see if this function uses vector registers, which means we have to
188   // save and restore the VRSAVE register and update it with the regs we use.
189   //
190   // In this case, there will be virtual registers of vector type created
191   // by the scheduler.  Detect them now.
192   bool HasVectorVReg = false;
193   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
194     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
195     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
196       HasVectorVReg = true;
197       break;
198     }
199   }
200   if (!HasVectorVReg) return;  // nothing to do.
201
202   // If we have a vector register, we want to emit code into the entry and exit
203   // blocks to save and restore the VRSAVE register.  We do this here (instead
204   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
205   //
206   // 1. This (trivially) reduces the load on the register allocator, by not
207   //    having to represent the live range of the VRSAVE register.
208   // 2. This (more significantly) allows us to create a temporary virtual
209   //    register to hold the saved VRSAVE value, allowing this temporary to be
210   //    register allocated, instead of forcing it to be spilled to the stack.
211
212   // Create two vregs - one to hold the VRSAVE register that is live-in to the
213   // function and one for the value after having bits or'd into it.
214   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
215   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
216
217   const TargetInstrInfo &TII = *TM.getInstrInfo();
218   MachineBasicBlock &EntryBB = *Fn.begin();
219   DebugLoc dl;
220   // Emit the following code into the entry block:
221   // InVRSAVE = MFVRSAVE
222   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
223   // MTVRSAVE UpdatedVRSAVE
224   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
225   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
226   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
227           UpdatedVRSAVE).addReg(InVRSAVE);
228   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
229
230   // Find all return blocks, outputting a restore in each epilog.
231   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
232     if (!BB->empty() && BB->back().isReturn()) {
233       IP = BB->end(); --IP;
234
235       // Skip over all terminator instructions, which are part of the return
236       // sequence.
237       MachineBasicBlock::iterator I2 = IP;
238       while (I2 != BB->begin() && (--I2)->isTerminator())
239         IP = I2;
240
241       // Emit: MTVRSAVE InVRSave
242       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
243     }
244   }
245 }
246
247
248 /// getGlobalBaseReg - Output the instructions required to put the
249 /// base address to use for accessing globals into a register.
250 ///
251 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
252   if (!GlobalBaseReg) {
253     const TargetInstrInfo &TII = *TM.getInstrInfo();
254     // Insert the set of GlobalBaseReg into the first MBB of the function
255     MachineBasicBlock &FirstMBB = MF->front();
256     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
257     DebugLoc dl;
258
259     if (PPCLowering.getPointerTy() == MVT::i32) {
260       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
261       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
262       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
263     } else {
264       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RCRegClass);
265       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
266       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
267     }
268   }
269   return CurDAG->getRegister(GlobalBaseReg,
270                              PPCLowering.getPointerTy()).getNode();
271 }
272
273 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
274 /// or 64-bit immediate, and if the value can be accurately represented as a
275 /// sign extension from a 16-bit value.  If so, this returns true and the
276 /// immediate.
277 static bool isIntS16Immediate(SDNode *N, short &Imm) {
278   if (N->getOpcode() != ISD::Constant)
279     return false;
280
281   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
282   if (N->getValueType(0) == MVT::i32)
283     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
284   else
285     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
286 }
287
288 static bool isIntS16Immediate(SDValue Op, short &Imm) {
289   return isIntS16Immediate(Op.getNode(), Imm);
290 }
291
292
293 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
294 /// operand. If so Imm will receive the 32-bit value.
295 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
296   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
297     Imm = cast<ConstantSDNode>(N)->getZExtValue();
298     return true;
299   }
300   return false;
301 }
302
303 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
304 /// operand.  If so Imm will receive the 64-bit value.
305 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
306   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
307     Imm = cast<ConstantSDNode>(N)->getZExtValue();
308     return true;
309   }
310   return false;
311 }
312
313 // isInt32Immediate - This method tests to see if a constant operand.
314 // If so Imm will receive the 32 bit value.
315 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
316   return isInt32Immediate(N.getNode(), Imm);
317 }
318
319
320 // isOpcWithIntImmediate - This method tests to see if the node is a specific
321 // opcode and that it has a immediate integer right operand.
322 // If so Imm will receive the 32 bit value.
323 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
324   return N->getOpcode() == Opc
325          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
326 }
327
328 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
329   if (isShiftedMask_32(Val)) {
330     // look for the first non-zero bit
331     MB = CountLeadingZeros_32(Val);
332     // look for the first zero bit after the run of ones
333     ME = CountLeadingZeros_32((Val - 1) ^ Val);
334     return true;
335   } else {
336     Val = ~Val; // invert mask
337     if (isShiftedMask_32(Val)) {
338       // effectively look for the first zero bit
339       ME = CountLeadingZeros_32(Val) - 1;
340       // effectively look for the first one bit after the run of zeros
341       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
342       return true;
343     }
344   }
345   // no run present
346   return false;
347 }
348
349 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
350                                       bool isShiftMask, unsigned &SH,
351                                       unsigned &MB, unsigned &ME) {
352   // Don't even go down this path for i64, since different logic will be
353   // necessary for rldicl/rldicr/rldimi.
354   if (N->getValueType(0) != MVT::i32)
355     return false;
356
357   unsigned Shift  = 32;
358   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
359   unsigned Opcode = N->getOpcode();
360   if (N->getNumOperands() != 2 ||
361       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
362     return false;
363
364   if (Opcode == ISD::SHL) {
365     // apply shift left to mask if it comes first
366     if (isShiftMask) Mask = Mask << Shift;
367     // determine which bits are made indeterminant by shift
368     Indeterminant = ~(0xFFFFFFFFu << Shift);
369   } else if (Opcode == ISD::SRL) {
370     // apply shift right to mask if it comes first
371     if (isShiftMask) Mask = Mask >> Shift;
372     // determine which bits are made indeterminant by shift
373     Indeterminant = ~(0xFFFFFFFFu >> Shift);
374     // adjust for the left rotate
375     Shift = 32 - Shift;
376   } else if (Opcode == ISD::ROTL) {
377     Indeterminant = 0;
378   } else {
379     return false;
380   }
381
382   // if the mask doesn't intersect any Indeterminant bits
383   if (Mask && !(Mask & Indeterminant)) {
384     SH = Shift & 31;
385     // make sure the mask is still a mask (wrap arounds may not be)
386     return isRunOfOnes(Mask, MB, ME);
387   }
388   return false;
389 }
390
391 /// SelectBitfieldInsert - turn an or of two masked values into
392 /// the rotate left word immediate then mask insert (rlwimi) instruction.
393 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
394   SDValue Op0 = N->getOperand(0);
395   SDValue Op1 = N->getOperand(1);
396   DebugLoc dl = N->getDebugLoc();
397
398   APInt LKZ, LKO, RKZ, RKO;
399   CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
400   CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
401
402   unsigned TargetMask = LKZ.getZExtValue();
403   unsigned InsertMask = RKZ.getZExtValue();
404
405   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
406     unsigned Op0Opc = Op0.getOpcode();
407     unsigned Op1Opc = Op1.getOpcode();
408     unsigned Value, SH = 0;
409     TargetMask = ~TargetMask;
410     InsertMask = ~InsertMask;
411
412     // If the LHS has a foldable shift and the RHS does not, then swap it to the
413     // RHS so that we can fold the shift into the insert.
414     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
415       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
416           Op0.getOperand(0).getOpcode() == ISD::SRL) {
417         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
418             Op1.getOperand(0).getOpcode() != ISD::SRL) {
419           std::swap(Op0, Op1);
420           std::swap(Op0Opc, Op1Opc);
421           std::swap(TargetMask, InsertMask);
422         }
423       }
424     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
425       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
426           Op1.getOperand(0).getOpcode() != ISD::SRL) {
427         std::swap(Op0, Op1);
428         std::swap(Op0Opc, Op1Opc);
429         std::swap(TargetMask, InsertMask);
430       }
431     }
432
433     unsigned MB, ME;
434     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
435       SDValue Tmp1, Tmp2;
436
437       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
438           isInt32Immediate(Op1.getOperand(1), Value)) {
439         Op1 = Op1.getOperand(0);
440         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
441       }
442       if (Op1Opc == ISD::AND) {
443         unsigned SHOpc = Op1.getOperand(0).getOpcode();
444         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
445             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
446           Op1 = Op1.getOperand(0).getOperand(0);
447           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
448         } else {
449           Op1 = Op1.getOperand(0);
450         }
451       }
452
453       SH &= 31;
454       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
455                           getI32Imm(ME) };
456       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
457     }
458   }
459   return 0;
460 }
461
462 /// SelectCC - Select a comparison of the specified values with the specified
463 /// condition code, returning the CR# of the expression.
464 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
465                                     ISD::CondCode CC, DebugLoc dl) {
466   // Always select the LHS.
467   unsigned Opc;
468
469   if (LHS.getValueType() == MVT::i32) {
470     unsigned Imm;
471     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
472       if (isInt32Immediate(RHS, Imm)) {
473         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
474         if (isUInt<16>(Imm))
475           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
476                                                 getI32Imm(Imm & 0xFFFF)), 0);
477         // If this is a 16-bit signed immediate, fold it.
478         if (isInt<16>((int)Imm))
479           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
480                                                 getI32Imm(Imm & 0xFFFF)), 0);
481
482         // For non-equality comparisons, the default code would materialize the
483         // constant, then compare against it, like this:
484         //   lis r2, 4660
485         //   ori r2, r2, 22136
486         //   cmpw cr0, r3, r2
487         // Since we are just comparing for equality, we can emit this instead:
488         //   xoris r0,r3,0x1234
489         //   cmplwi cr0,r0,0x5678
490         //   beq cr0,L6
491         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
492                                            getI32Imm(Imm >> 16)), 0);
493         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
494                                               getI32Imm(Imm & 0xFFFF)), 0);
495       }
496       Opc = PPC::CMPLW;
497     } else if (ISD::isUnsignedIntSetCC(CC)) {
498       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
499         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
500                                               getI32Imm(Imm & 0xFFFF)), 0);
501       Opc = PPC::CMPLW;
502     } else {
503       short SImm;
504       if (isIntS16Immediate(RHS, SImm))
505         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
506                                               getI32Imm((int)SImm & 0xFFFF)),
507                          0);
508       Opc = PPC::CMPW;
509     }
510   } else if (LHS.getValueType() == MVT::i64) {
511     uint64_t Imm;
512     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
513       if (isInt64Immediate(RHS.getNode(), Imm)) {
514         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
515         if (isUInt<16>(Imm))
516           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
517                                                 getI32Imm(Imm & 0xFFFF)), 0);
518         // If this is a 16-bit signed immediate, fold it.
519         if (isInt<16>(Imm))
520           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
521                                                 getI32Imm(Imm & 0xFFFF)), 0);
522
523         // For non-equality comparisons, the default code would materialize the
524         // constant, then compare against it, like this:
525         //   lis r2, 4660
526         //   ori r2, r2, 22136
527         //   cmpd cr0, r3, r2
528         // Since we are just comparing for equality, we can emit this instead:
529         //   xoris r0,r3,0x1234
530         //   cmpldi cr0,r0,0x5678
531         //   beq cr0,L6
532         if (isUInt<32>(Imm)) {
533           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
534                                              getI64Imm(Imm >> 16)), 0);
535           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
536                                                 getI64Imm(Imm & 0xFFFF)), 0);
537         }
538       }
539       Opc = PPC::CMPLD;
540     } else if (ISD::isUnsignedIntSetCC(CC)) {
541       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
542         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
543                                               getI64Imm(Imm & 0xFFFF)), 0);
544       Opc = PPC::CMPLD;
545     } else {
546       short SImm;
547       if (isIntS16Immediate(RHS, SImm))
548         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
549                                               getI64Imm(SImm & 0xFFFF)),
550                          0);
551       Opc = PPC::CMPD;
552     }
553   } else if (LHS.getValueType() == MVT::f32) {
554     Opc = PPC::FCMPUS;
555   } else {
556     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
557     Opc = PPC::FCMPUD;
558   }
559   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
560 }
561
562 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
563   switch (CC) {
564   case ISD::SETUEQ:
565   case ISD::SETONE:
566   case ISD::SETOLE:
567   case ISD::SETOGE:
568     llvm_unreachable("Should be lowered by legalize!");
569   default: llvm_unreachable("Unknown condition!");
570   case ISD::SETOEQ:
571   case ISD::SETEQ:  return PPC::PRED_EQ;
572   case ISD::SETUNE:
573   case ISD::SETNE:  return PPC::PRED_NE;
574   case ISD::SETOLT:
575   case ISD::SETLT:  return PPC::PRED_LT;
576   case ISD::SETULE:
577   case ISD::SETLE:  return PPC::PRED_LE;
578   case ISD::SETOGT:
579   case ISD::SETGT:  return PPC::PRED_GT;
580   case ISD::SETUGE:
581   case ISD::SETGE:  return PPC::PRED_GE;
582   case ISD::SETO:   return PPC::PRED_NU;
583   case ISD::SETUO:  return PPC::PRED_UN;
584     // These two are invalid for floating point.  Assume we have int.
585   case ISD::SETULT: return PPC::PRED_LT;
586   case ISD::SETUGT: return PPC::PRED_GT;
587   }
588 }
589
590 /// getCRIdxForSetCC - Return the index of the condition register field
591 /// associated with the SetCC condition, and whether or not the field is
592 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
593 ///
594 /// If this returns with Other != -1, then the returned comparison is an or of
595 /// two simpler comparisons.  In this case, Invert is guaranteed to be false.
596 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert, int &Other) {
597   Invert = false;
598   Other = -1;
599   switch (CC) {
600   default: llvm_unreachable("Unknown condition!");
601   case ISD::SETOLT:
602   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
603   case ISD::SETOGT:
604   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
605   case ISD::SETOEQ:
606   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
607   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
608   case ISD::SETUGE:
609   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
610   case ISD::SETULE:
611   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
612   case ISD::SETUNE:
613   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
614   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
615   case ISD::SETUEQ:
616   case ISD::SETOGE:
617   case ISD::SETOLE:
618   case ISD::SETONE:
619     llvm_unreachable("Invalid branch code: should be expanded by legalize");
620   // These are invalid for floating point.  Assume integer.
621   case ISD::SETULT: return 0;
622   case ISD::SETUGT: return 1;
623   }
624 }
625
626 // getVCmpInst: return the vector compare instruction for the specified
627 // vector type and condition code. Since this is for altivec specific code,
628 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
629 static unsigned int getVCmpInst(MVT::SimpleValueType VecVT, ISD::CondCode CC) {
630   switch (CC) {
631     case ISD::SETEQ:
632     case ISD::SETUEQ:
633     case ISD::SETNE:
634     case ISD::SETUNE:
635       if (VecVT == MVT::v16i8)
636         return PPC::VCMPEQUB;
637       else if (VecVT == MVT::v8i16)
638         return PPC::VCMPEQUH;
639       else if (VecVT == MVT::v4i32)
640         return PPC::VCMPEQUW;
641       // v4f32 != v4f32 could be translate to unordered not equal
642       else if (VecVT == MVT::v4f32)
643         return PPC::VCMPEQFP;
644       break;
645     case ISD::SETLT:
646     case ISD::SETGT:
647     case ISD::SETLE:
648     case ISD::SETGE:
649       if (VecVT == MVT::v16i8)
650         return PPC::VCMPGTSB;
651       else if (VecVT == MVT::v8i16)
652         return PPC::VCMPGTSH;
653       else if (VecVT == MVT::v4i32)
654         return PPC::VCMPGTSW;
655       else if (VecVT == MVT::v4f32)
656         return PPC::VCMPGTFP;
657       break;
658     case ISD::SETULT:
659     case ISD::SETUGT:
660     case ISD::SETUGE:
661     case ISD::SETULE:
662       if (VecVT == MVT::v16i8)
663         return PPC::VCMPGTUB;
664       else if (VecVT == MVT::v8i16)
665         return PPC::VCMPGTUH;
666       else if (VecVT == MVT::v4i32)
667         return PPC::VCMPGTUW;
668       break;
669     case ISD::SETOEQ:
670       if (VecVT == MVT::v4f32)
671         return PPC::VCMPEQFP;
672       break;
673     case ISD::SETOLT:
674     case ISD::SETOGT:
675     case ISD::SETOLE:
676       if (VecVT == MVT::v4f32)
677         return PPC::VCMPGTFP;
678       break;
679     case ISD::SETOGE:
680       if (VecVT == MVT::v4f32)
681         return PPC::VCMPGEFP;
682       break;
683     default:
684       break;
685   }
686   llvm_unreachable("Invalid integer vector compare condition");
687 }
688
689 // getVCmpEQInst: return the equal compare instruction for the specified vector
690 // type. Since this is for altivec specific code, only support the altivec
691 // types (v16i8, v8i16, v4i32, and v4f32).
692 static unsigned int getVCmpEQInst(MVT::SimpleValueType VecVT) {
693   switch (VecVT) {
694     case MVT::v16i8:
695       return PPC::VCMPEQUB;
696     case MVT::v8i16:
697       return PPC::VCMPEQUH;
698     case MVT::v4i32:
699       return PPC::VCMPEQUW;
700     case MVT::v4f32:
701       return PPC::VCMPEQFP;
702     default:
703       llvm_unreachable("Invalid integer vector compare condition");
704   }
705 }
706
707
708 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
709   DebugLoc dl = N->getDebugLoc();
710   unsigned Imm;
711   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
712   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
713   bool isPPC64 = (PtrVT == MVT::i64);
714
715   if (isInt32Immediate(N->getOperand(1), Imm)) {
716     // We can codegen setcc op, imm very efficiently compared to a brcond.
717     // Check for those cases here.
718     // setcc op, 0
719     if (Imm == 0) {
720       SDValue Op = N->getOperand(0);
721       switch (CC) {
722       default: break;
723       case ISD::SETEQ: {
724         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
725         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
726         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
727       }
728       case ISD::SETNE: {
729         if (isPPC64) break;
730         SDValue AD =
731           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
732                                          Op, getI32Imm(~0U)), 0);
733         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
734                                     AD.getValue(1));
735       }
736       case ISD::SETLT: {
737         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
738         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
739       }
740       case ISD::SETGT: {
741         SDValue T =
742           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
743         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
744         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
745         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
746       }
747       }
748     } else if (Imm == ~0U) {        // setcc op, -1
749       SDValue Op = N->getOperand(0);
750       switch (CC) {
751       default: break;
752       case ISD::SETEQ:
753         if (isPPC64) break;
754         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
755                                             Op, getI32Imm(1)), 0);
756         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
757                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
758                                                              MVT::i32,
759                                                              getI32Imm(0)), 0),
760                                       Op.getValue(1));
761       case ISD::SETNE: {
762         if (isPPC64) break;
763         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
764         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
765                                             Op, getI32Imm(~0U));
766         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
767                                     Op, SDValue(AD, 1));
768       }
769       case ISD::SETLT: {
770         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
771                                                     getI32Imm(1)), 0);
772         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
773                                                     Op), 0);
774         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
775         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
776       }
777       case ISD::SETGT: {
778         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
779         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4),
780                      0);
781         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
782                                     getI32Imm(1));
783       }
784       }
785     }
786   }
787
788   SDValue LHS = N->getOperand(0);
789   SDValue RHS = N->getOperand(1);
790
791   // Altivec Vector compare instructions do not set any CR register by default and
792   // vector compare operations return the same type as the operands.
793   if (LHS.getValueType().isVector()) {
794     EVT VecVT = LHS.getValueType();
795     MVT::SimpleValueType VT = VecVT.getSimpleVT().SimpleTy;
796     unsigned int VCmpInst = getVCmpInst(VT, CC);
797
798     switch (CC) {
799       case ISD::SETEQ:
800       case ISD::SETOEQ:
801       case ISD::SETUEQ:
802         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
803       case ISD::SETNE:
804       case ISD::SETONE:
805       case ISD::SETUNE: {
806         SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
807         return CurDAG->SelectNodeTo(N, PPC::VNOR, VecVT, VCmp, VCmp);
808       } 
809       case ISD::SETLT:
810       case ISD::SETOLT:
811       case ISD::SETULT:
812         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, RHS, LHS);
813       case ISD::SETGT:
814       case ISD::SETOGT:
815       case ISD::SETUGT:
816         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
817       case ISD::SETGE:
818       case ISD::SETOGE:
819       case ISD::SETUGE: {
820         // Small optimization: Altivec provides a 'Vector Compare Greater Than
821         // or Equal To' instruction (vcmpgefp), so in this case there is no
822         // need for extra logic for the equal compare.
823         if (VecVT.getSimpleVT().isFloatingPoint()) {
824           return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
825         } else {
826           SDValue VCmpGT(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
827           unsigned int VCmpEQInst = getVCmpEQInst(VT);
828           SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
829           return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpGT, VCmpEQ);
830         }
831       }
832       case ISD::SETLE:
833       case ISD::SETOLE:
834       case ISD::SETULE: {
835         SDValue VCmpLE(CurDAG->getMachineNode(VCmpInst, dl, VecVT, RHS, LHS), 0);
836         unsigned int VCmpEQInst = getVCmpEQInst(VT);
837         SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
838         return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpLE, VCmpEQ);
839       }
840       default:
841         llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
842     }
843   }
844
845   bool Inv;
846   int OtherCondIdx;
847   unsigned Idx = getCRIdxForSetCC(CC, Inv, OtherCondIdx);
848   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
849   SDValue IntCR;
850
851   // Force the ccreg into CR7.
852   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
853
854   SDValue InFlag(0, 0);  // Null incoming flag value.
855   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
856                                InFlag).getValue(1);
857
858   if (PPCSubTarget.hasMFOCRF() && OtherCondIdx == -1)
859     IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
860                                            CCReg), 0);
861   else
862     IntCR = SDValue(CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
863                                            CR7Reg, CCReg), 0);
864
865   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
866                       getI32Imm(31), getI32Imm(31) };
867   if (OtherCondIdx == -1 && !Inv)
868     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
869
870   // Get the specified bit.
871   SDValue Tmp =
872     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
873   if (Inv) {
874     assert(OtherCondIdx == -1 && "Can't have split plus negation");
875     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
876   }
877
878   // Otherwise, we have to turn an operation like SETONE -> SETOLT | SETOGT.
879   // We already got the bit for the first part of the comparison (e.g. SETULE).
880
881   // Get the other bit of the comparison.
882   Ops[1] = getI32Imm((32-(3-OtherCondIdx)) & 31);
883   SDValue OtherCond =
884     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
885
886   return CurDAG->SelectNodeTo(N, PPC::OR, MVT::i32, Tmp, OtherCond);
887 }
888
889
890 // Select - Convert the specified operand from a target-independent to a
891 // target-specific node if it hasn't already been changed.
892 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
893   DebugLoc dl = N->getDebugLoc();
894   if (N->isMachineOpcode())
895     return NULL;   // Already selected.
896
897   switch (N->getOpcode()) {
898   default: break;
899
900   case ISD::Constant: {
901     if (N->getValueType(0) == MVT::i64) {
902       // Get 64 bit value.
903       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
904       // Assume no remaining bits.
905       unsigned Remainder = 0;
906       // Assume no shift required.
907       unsigned Shift = 0;
908
909       // If it can't be represented as a 32 bit value.
910       if (!isInt<32>(Imm)) {
911         Shift = CountTrailingZeros_64(Imm);
912         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
913
914         // If the shifted value fits 32 bits.
915         if (isInt<32>(ImmSh)) {
916           // Go with the shifted value.
917           Imm = ImmSh;
918         } else {
919           // Still stuck with a 64 bit value.
920           Remainder = Imm;
921           Shift = 32;
922           Imm >>= 32;
923         }
924       }
925
926       // Intermediate operand.
927       SDNode *Result;
928
929       // Handle first 32 bits.
930       unsigned Lo = Imm & 0xFFFF;
931       unsigned Hi = (Imm >> 16) & 0xFFFF;
932
933       // Simple value.
934       if (isInt<16>(Imm)) {
935        // Just the Lo bits.
936         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
937       } else if (Lo) {
938         // Handle the Hi bits.
939         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
940         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
941         // And Lo bits.
942         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
943                                         SDValue(Result, 0), getI32Imm(Lo));
944       } else {
945        // Just the Hi bits.
946         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
947       }
948
949       // If no shift, we're done.
950       if (!Shift) return Result;
951
952       // Shift for next step if the upper 32-bits were not zero.
953       if (Imm) {
954         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
955                                         SDValue(Result, 0),
956                                         getI32Imm(Shift),
957                                         getI32Imm(63 - Shift));
958       }
959
960       // Add in the last bits as required.
961       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
962         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
963                                         SDValue(Result, 0), getI32Imm(Hi));
964       }
965       if ((Lo = Remainder & 0xFFFF)) {
966         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
967                                         SDValue(Result, 0), getI32Imm(Lo));
968       }
969
970       return Result;
971     }
972     break;
973   }
974
975   case ISD::SETCC:
976     return SelectSETCC(N);
977   case PPCISD::GlobalBaseReg:
978     return getGlobalBaseReg();
979
980   case ISD::FrameIndex: {
981     int FI = cast<FrameIndexSDNode>(N)->getIndex();
982     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
983     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
984     if (N->hasOneUse())
985       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
986                                   getSmallIPtrImm(0));
987     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
988                                   getSmallIPtrImm(0));
989   }
990
991   case PPCISD::MFCR: {
992     SDValue InFlag = N->getOperand(1);
993     // Use MFOCRF if supported.
994     if (PPCSubTarget.hasMFOCRF())
995       return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
996                                     N->getOperand(0), InFlag);
997     else
998       return CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
999                                     N->getOperand(0), InFlag);
1000   }
1001
1002   case ISD::SDIV: {
1003     // FIXME: since this depends on the setting of the carry flag from the srawi
1004     //        we should really be making notes about that for the scheduler.
1005     // FIXME: It sure would be nice if we could cheaply recognize the
1006     //        srl/add/sra pattern the dag combiner will generate for this as
1007     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1008     unsigned Imm;
1009     if (isInt32Immediate(N->getOperand(1), Imm)) {
1010       SDValue N0 = N->getOperand(0);
1011       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1012         SDNode *Op =
1013           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1014                                  N0, getI32Imm(Log2_32(Imm)));
1015         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1016                                     SDValue(Op, 0), SDValue(Op, 1));
1017       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1018         SDNode *Op =
1019           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1020                                  N0, getI32Imm(Log2_32(-Imm)));
1021         SDValue PT =
1022           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
1023                                          SDValue(Op, 0), SDValue(Op, 1)),
1024                     0);
1025         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1026       }
1027     }
1028
1029     // Other cases are autogenerated.
1030     break;
1031   }
1032
1033   case ISD::LOAD: {
1034     // Handle preincrement loads.
1035     LoadSDNode *LD = cast<LoadSDNode>(N);
1036     EVT LoadedVT = LD->getMemoryVT();
1037
1038     // Normal loads are handled by code generated from the .td file.
1039     if (LD->getAddressingMode() != ISD::PRE_INC)
1040       break;
1041
1042     SDValue Offset = LD->getOffset();
1043     if (isa<ConstantSDNode>(Offset) ||
1044         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1045
1046       unsigned Opcode;
1047       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1048       if (LD->getValueType(0) != MVT::i64) {
1049         // Handle PPC32 integer and normal FP loads.
1050         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1051         switch (LoadedVT.getSimpleVT().SimpleTy) {
1052           default: llvm_unreachable("Invalid PPC load type!");
1053           case MVT::f64: Opcode = PPC::LFDU; break;
1054           case MVT::f32: Opcode = PPC::LFSU; break;
1055           case MVT::i32: Opcode = PPC::LWZU; break;
1056           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1057           case MVT::i1:
1058           case MVT::i8:  Opcode = PPC::LBZU; break;
1059         }
1060       } else {
1061         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1062         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1063         switch (LoadedVT.getSimpleVT().SimpleTy) {
1064           default: llvm_unreachable("Invalid PPC load type!");
1065           case MVT::i64: Opcode = PPC::LDU; break;
1066           case MVT::i32: Opcode = PPC::LWZU8; break;
1067           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1068           case MVT::i1:
1069           case MVT::i8:  Opcode = PPC::LBZU8; break;
1070         }
1071       }
1072
1073       SDValue Chain = LD->getChain();
1074       SDValue Base = LD->getBasePtr();
1075       SDValue Ops[] = { Offset, Base, Chain };
1076       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1077                                     PPCLowering.getPointerTy(),
1078                                     MVT::Other, Ops, 3);
1079     } else {
1080       unsigned Opcode;
1081       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1082       if (LD->getValueType(0) != MVT::i64) {
1083         // Handle PPC32 integer and normal FP loads.
1084         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1085         switch (LoadedVT.getSimpleVT().SimpleTy) {
1086           default: llvm_unreachable("Invalid PPC load type!");
1087           case MVT::f64: Opcode = PPC::LFDUX; break;
1088           case MVT::f32: Opcode = PPC::LFSUX; break;
1089           case MVT::i32: Opcode = PPC::LWZUX; break;
1090           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1091           case MVT::i1:
1092           case MVT::i8:  Opcode = PPC::LBZUX; break;
1093         }
1094       } else {
1095         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1096         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1097                "Invalid sext update load");
1098         switch (LoadedVT.getSimpleVT().SimpleTy) {
1099           default: llvm_unreachable("Invalid PPC load type!");
1100           case MVT::i64: Opcode = PPC::LDUX; break;
1101           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1102           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1103           case MVT::i1:
1104           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1105         }
1106       }
1107
1108       SDValue Chain = LD->getChain();
1109       SDValue Base = LD->getBasePtr();
1110       SDValue Ops[] = { Offset, Base, Chain };
1111       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1112                                     PPCLowering.getPointerTy(),
1113                                     MVT::Other, Ops, 3);
1114     }
1115   }
1116
1117   case ISD::AND: {
1118     unsigned Imm, Imm2, SH, MB, ME;
1119     uint64_t Imm64;
1120
1121     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1122     // with a mask, emit rlwinm
1123     if (isInt32Immediate(N->getOperand(1), Imm) &&
1124         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1125       SDValue Val = N->getOperand(0).getOperand(0);
1126       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1127       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1128     }
1129     // If this is just a masked value where the input is not handled above, and
1130     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1131     if (isInt32Immediate(N->getOperand(1), Imm) &&
1132         isRunOfOnes(Imm, MB, ME) &&
1133         N->getOperand(0).getOpcode() != ISD::ROTL) {
1134       SDValue Val = N->getOperand(0);
1135       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1136       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1137     }
1138     // If this is a 64-bit zero-extension mask, emit rldicl.
1139     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1140         isMask_64(Imm64)) {
1141       SDValue Val = N->getOperand(0);
1142       MB = 64 - CountTrailingOnes_64(Imm64);
1143       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB) };
1144       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1145     }
1146     // AND X, 0 -> 0, not "rlwinm 32".
1147     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1148       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1149       return NULL;
1150     }
1151     // ISD::OR doesn't get all the bitfield insertion fun.
1152     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1153     if (isInt32Immediate(N->getOperand(1), Imm) &&
1154         N->getOperand(0).getOpcode() == ISD::OR &&
1155         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1156       unsigned MB, ME;
1157       Imm = ~(Imm^Imm2);
1158       if (isRunOfOnes(Imm, MB, ME)) {
1159         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1160                             N->getOperand(0).getOperand(1),
1161                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1162         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
1163       }
1164     }
1165
1166     // Other cases are autogenerated.
1167     break;
1168   }
1169   case ISD::OR:
1170     if (N->getValueType(0) == MVT::i32)
1171       if (SDNode *I = SelectBitfieldInsert(N))
1172         return I;
1173
1174     // Other cases are autogenerated.
1175     break;
1176   case ISD::SHL: {
1177     unsigned Imm, SH, MB, ME;
1178     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1179         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1180       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1181                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1182       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1183     }
1184
1185     // Other cases are autogenerated.
1186     break;
1187   }
1188   case ISD::SRL: {
1189     unsigned Imm, SH, MB, ME;
1190     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1191         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1192       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1193                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1194       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1195     }
1196
1197     // Other cases are autogenerated.
1198     break;
1199   }
1200   case ISD::SELECT_CC: {
1201     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1202     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1203     bool isPPC64 = (PtrVT == MVT::i64);
1204
1205     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1206     if (!isPPC64)
1207       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1208         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1209           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1210             if (N1C->isNullValue() && N3C->isNullValue() &&
1211                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1212                 // FIXME: Implement this optzn for PPC64.
1213                 N->getValueType(0) == MVT::i32) {
1214               SDNode *Tmp =
1215                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1216                                        N->getOperand(0), getI32Imm(~0U));
1217               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1218                                           SDValue(Tmp, 0), N->getOperand(0),
1219                                           SDValue(Tmp, 1));
1220             }
1221
1222     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1223     unsigned BROpc = getPredicateForSetCC(CC);
1224
1225     unsigned SelectCCOp;
1226     if (N->getValueType(0) == MVT::i32)
1227       SelectCCOp = PPC::SELECT_CC_I4;
1228     else if (N->getValueType(0) == MVT::i64)
1229       SelectCCOp = PPC::SELECT_CC_I8;
1230     else if (N->getValueType(0) == MVT::f32)
1231       SelectCCOp = PPC::SELECT_CC_F4;
1232     else if (N->getValueType(0) == MVT::f64)
1233       SelectCCOp = PPC::SELECT_CC_F8;
1234     else
1235       SelectCCOp = PPC::SELECT_CC_VRRC;
1236
1237     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1238                         getI32Imm(BROpc) };
1239     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1240   }
1241   case PPCISD::COND_BRANCH: {
1242     // Op #0 is the Chain.
1243     // Op #1 is the PPC::PRED_* number.
1244     // Op #2 is the CR#
1245     // Op #3 is the Dest MBB
1246     // Op #4 is the Flag.
1247     // Prevent PPC::PRED_* from being selected into LI.
1248     SDValue Pred =
1249       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1250     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1251       N->getOperand(0), N->getOperand(4) };
1252     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1253   }
1254   case ISD::BR_CC: {
1255     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1256     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1257     SDValue Ops[] = { getI32Imm(getPredicateForSetCC(CC)), CondCode,
1258                         N->getOperand(4), N->getOperand(0) };
1259     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1260   }
1261   case ISD::BRIND: {
1262     // FIXME: Should custom lower this.
1263     SDValue Chain = N->getOperand(0);
1264     SDValue Target = N->getOperand(1);
1265     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1266     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1267     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1268                                            Chain), 0);
1269     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1270   }
1271   }
1272
1273   return SelectCode(N);
1274 }
1275
1276
1277
1278 /// createPPCISelDag - This pass converts a legalized DAG into a
1279 /// PowerPC-specific DAG, ready for instruction scheduling.
1280 ///
1281 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1282   return new PPCDAGToDAGISel(TM);
1283 }
1284