Swap PPC isel operands to allow for 0-folding
[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 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 "MCTargetDesc/PPCPredicates.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 // FIXME: Remove this once the bug has been fixed!
39 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
40 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
41
42 namespace llvm {
43   void initializePPCDAGToDAGISelPass(PassRegistry&);
44 }
45
46 namespace {
47   //===--------------------------------------------------------------------===//
48   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
49   /// instructions for SelectionDAG operations.
50   ///
51   class PPCDAGToDAGISel : public SelectionDAGISel {
52     const PPCTargetMachine &TM;
53     const PPCTargetLowering &PPCLowering;
54     const PPCSubtarget &PPCSubTarget;
55     unsigned GlobalBaseReg;
56   public:
57     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
58       : SelectionDAGISel(tm), TM(tm),
59         PPCLowering(*TM.getTargetLowering()),
60         PPCSubTarget(*TM.getSubtargetImpl()) {
61       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
62     }
63
64     virtual bool runOnMachineFunction(MachineFunction &MF) {
65       // Make sure we re-emit a set of the global base reg if necessary
66       GlobalBaseReg = 0;
67       SelectionDAGISel::runOnMachineFunction(MF);
68
69       if (!PPCSubTarget.isSVR4ABI())
70         InsertVRSaveCode(MF);
71
72       return true;
73     }
74
75     virtual void PostprocessISelDAG();
76
77     /// getI32Imm - Return a target constant with the specified value, of type
78     /// i32.
79     inline SDValue getI32Imm(unsigned Imm) {
80       return CurDAG->getTargetConstant(Imm, MVT::i32);
81     }
82
83     /// getI64Imm - Return a target constant with the specified value, of type
84     /// i64.
85     inline SDValue getI64Imm(uint64_t Imm) {
86       return CurDAG->getTargetConstant(Imm, MVT::i64);
87     }
88
89     /// getSmallIPtrImm - Return a target constant of pointer type.
90     inline SDValue getSmallIPtrImm(unsigned Imm) {
91       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
92     }
93
94     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
95     /// with any number of 0s on either side.  The 1s are allowed to wrap from
96     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
97     /// 0x0F0F0000 is not, since all 1s are not contiguous.
98     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
99
100
101     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
102     /// rotate and mask opcode and mask operation.
103     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
104                                 unsigned &SH, unsigned &MB, unsigned &ME);
105
106     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
107     /// base register.  Return the virtual register that holds this value.
108     SDNode *getGlobalBaseReg();
109
110     // Select - Convert the specified operand from a target-independent to a
111     // target-specific node if it hasn't already been changed.
112     SDNode *Select(SDNode *N);
113
114     SDNode *SelectBitfieldInsert(SDNode *N);
115
116     /// SelectCC - Select a comparison of the specified values with the
117     /// specified condition code, returning the CR# of the expression.
118     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
119
120     /// SelectAddrImm - Returns true if the address N can be represented by
121     /// a base register plus a signed 16-bit displacement [r+imm].
122     bool SelectAddrImm(SDValue N, SDValue &Disp,
123                        SDValue &Base) {
124       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
125     }
126
127     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
128     /// immediate field.  Note that the operand at this point is already the
129     /// result of a prior SelectAddressRegImm call.
130     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
131       if (N.getOpcode() == ISD::TargetConstant ||
132           N.getOpcode() == ISD::TargetGlobalAddress) {
133         Out = N;
134         return true;
135       }
136
137       return false;
138     }
139
140     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
141     /// represented as an indexed [r+r] operation.  Returns false if it can
142     /// be represented by [r+imm], which are preferred.
143     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
144       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
145     }
146
147     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
148     /// represented as an indexed [r+r] operation.
149     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
150       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
151     }
152
153     /// SelectAddrImmX4 - Returns true if the address N can be represented by
154     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
155     /// Suitable for use by STD and friends.
156     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
157       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
158     }
159
160     // Select an address into a single register.
161     bool SelectAddr(SDValue N, SDValue &Base) {
162       Base = N;
163       return true;
164     }
165
166     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
167     /// inline asm expressions.  It is always correct to compute the value into
168     /// a register.  The case of adding a (possibly relocatable) constant to a
169     /// register can be improved, but it is wrong to substitute Reg+Reg for
170     /// Reg in an asm, because the load or store opcode would have to change.
171    virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
172                                               char ConstraintCode,
173                                               std::vector<SDValue> &OutOps) {
174       OutOps.push_back(Op);
175       return false;
176     }
177
178     void InsertVRSaveCode(MachineFunction &MF);
179
180     virtual const char *getPassName() const {
181       return "PowerPC DAG->DAG Pattern Instruction Selection";
182     }
183
184 // Include the pieces autogenerated from the target description.
185 #include "PPCGenDAGISel.inc"
186
187 private:
188     SDNode *SelectSETCC(SDNode *N);
189
190     void PeepholePPC64();
191     void PeepholdCROps();
192
193     bool AllUsersSelectZero(SDNode *N);
194     void SwapAllSelectUsers(SDNode *N);
195   };
196 }
197
198 /// InsertVRSaveCode - Once the entire function has been instruction selected,
199 /// all virtual registers are created and all machine instructions are built,
200 /// check to see if we need to save/restore VRSAVE.  If so, do it.
201 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
202   // Check to see if this function uses vector registers, which means we have to
203   // save and restore the VRSAVE register and update it with the regs we use.
204   //
205   // In this case, there will be virtual registers of vector type created
206   // by the scheduler.  Detect them now.
207   bool HasVectorVReg = false;
208   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
209     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
210     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
211       HasVectorVReg = true;
212       break;
213     }
214   }
215   if (!HasVectorVReg) return;  // nothing to do.
216
217   // If we have a vector register, we want to emit code into the entry and exit
218   // blocks to save and restore the VRSAVE register.  We do this here (instead
219   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
220   //
221   // 1. This (trivially) reduces the load on the register allocator, by not
222   //    having to represent the live range of the VRSAVE register.
223   // 2. This (more significantly) allows us to create a temporary virtual
224   //    register to hold the saved VRSAVE value, allowing this temporary to be
225   //    register allocated, instead of forcing it to be spilled to the stack.
226
227   // Create two vregs - one to hold the VRSAVE register that is live-in to the
228   // function and one for the value after having bits or'd into it.
229   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
230   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
231
232   const TargetInstrInfo &TII = *TM.getInstrInfo();
233   MachineBasicBlock &EntryBB = *Fn.begin();
234   DebugLoc dl;
235   // Emit the following code into the entry block:
236   // InVRSAVE = MFVRSAVE
237   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
238   // MTVRSAVE UpdatedVRSAVE
239   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
240   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
241   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
242           UpdatedVRSAVE).addReg(InVRSAVE);
243   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
244
245   // Find all return blocks, outputting a restore in each epilog.
246   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
247     if (!BB->empty() && BB->back().isReturn()) {
248       IP = BB->end(); --IP;
249
250       // Skip over all terminator instructions, which are part of the return
251       // sequence.
252       MachineBasicBlock::iterator I2 = IP;
253       while (I2 != BB->begin() && (--I2)->isTerminator())
254         IP = I2;
255
256       // Emit: MTVRSAVE InVRSave
257       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
258     }
259   }
260 }
261
262
263 /// getGlobalBaseReg - Output the instructions required to put the
264 /// base address to use for accessing globals into a register.
265 ///
266 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
267   if (!GlobalBaseReg) {
268     const TargetInstrInfo &TII = *TM.getInstrInfo();
269     // Insert the set of GlobalBaseReg into the first MBB of the function
270     MachineBasicBlock &FirstMBB = MF->front();
271     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
272     DebugLoc dl;
273
274     if (PPCLowering.getPointerTy() == MVT::i32) {
275       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
276       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
277       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
278     } else {
279       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RCRegClass);
280       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
281       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
282     }
283   }
284   return CurDAG->getRegister(GlobalBaseReg,
285                              PPCLowering.getPointerTy()).getNode();
286 }
287
288 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
289 /// or 64-bit immediate, and if the value can be accurately represented as a
290 /// sign extension from a 16-bit value.  If so, this returns true and the
291 /// immediate.
292 static bool isIntS16Immediate(SDNode *N, short &Imm) {
293   if (N->getOpcode() != ISD::Constant)
294     return false;
295
296   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
297   if (N->getValueType(0) == MVT::i32)
298     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
299   else
300     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
301 }
302
303 static bool isIntS16Immediate(SDValue Op, short &Imm) {
304   return isIntS16Immediate(Op.getNode(), Imm);
305 }
306
307
308 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
309 /// operand. If so Imm will receive the 32-bit value.
310 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
311   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
312     Imm = cast<ConstantSDNode>(N)->getZExtValue();
313     return true;
314   }
315   return false;
316 }
317
318 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
319 /// operand.  If so Imm will receive the 64-bit value.
320 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
321   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
322     Imm = cast<ConstantSDNode>(N)->getZExtValue();
323     return true;
324   }
325   return false;
326 }
327
328 // isInt32Immediate - This method tests to see if a constant operand.
329 // If so Imm will receive the 32 bit value.
330 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
331   return isInt32Immediate(N.getNode(), Imm);
332 }
333
334
335 // isOpcWithIntImmediate - This method tests to see if the node is a specific
336 // opcode and that it has a immediate integer right operand.
337 // If so Imm will receive the 32 bit value.
338 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
339   return N->getOpcode() == Opc
340          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
341 }
342
343 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
344   if (!Val)
345     return false;
346
347   if (isShiftedMask_32(Val)) {
348     // look for the first non-zero bit
349     MB = countLeadingZeros(Val);
350     // look for the first zero bit after the run of ones
351     ME = countLeadingZeros((Val - 1) ^ Val);
352     return true;
353   } else {
354     Val = ~Val; // invert mask
355     if (isShiftedMask_32(Val)) {
356       // effectively look for the first zero bit
357       ME = countLeadingZeros(Val) - 1;
358       // effectively look for the first one bit after the run of zeros
359       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
360       return true;
361     }
362   }
363   // no run present
364   return false;
365 }
366
367 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
368                                       bool isShiftMask, unsigned &SH,
369                                       unsigned &MB, unsigned &ME) {
370   // Don't even go down this path for i64, since different logic will be
371   // necessary for rldicl/rldicr/rldimi.
372   if (N->getValueType(0) != MVT::i32)
373     return false;
374
375   unsigned Shift  = 32;
376   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
377   unsigned Opcode = N->getOpcode();
378   if (N->getNumOperands() != 2 ||
379       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
380     return false;
381
382   if (Opcode == ISD::SHL) {
383     // apply shift left to mask if it comes first
384     if (isShiftMask) Mask = Mask << Shift;
385     // determine which bits are made indeterminant by shift
386     Indeterminant = ~(0xFFFFFFFFu << Shift);
387   } else if (Opcode == ISD::SRL) {
388     // apply shift right to mask if it comes first
389     if (isShiftMask) Mask = Mask >> Shift;
390     // determine which bits are made indeterminant by shift
391     Indeterminant = ~(0xFFFFFFFFu >> Shift);
392     // adjust for the left rotate
393     Shift = 32 - Shift;
394   } else if (Opcode == ISD::ROTL) {
395     Indeterminant = 0;
396   } else {
397     return false;
398   }
399
400   // if the mask doesn't intersect any Indeterminant bits
401   if (Mask && !(Mask & Indeterminant)) {
402     SH = Shift & 31;
403     // make sure the mask is still a mask (wrap arounds may not be)
404     return isRunOfOnes(Mask, MB, ME);
405   }
406   return false;
407 }
408
409 /// SelectBitfieldInsert - turn an or of two masked values into
410 /// the rotate left word immediate then mask insert (rlwimi) instruction.
411 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
412   SDValue Op0 = N->getOperand(0);
413   SDValue Op1 = N->getOperand(1);
414   SDLoc dl(N);
415
416   APInt LKZ, LKO, RKZ, RKO;
417   CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
418   CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
419
420   unsigned TargetMask = LKZ.getZExtValue();
421   unsigned InsertMask = RKZ.getZExtValue();
422
423   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
424     unsigned Op0Opc = Op0.getOpcode();
425     unsigned Op1Opc = Op1.getOpcode();
426     unsigned Value, SH = 0;
427     TargetMask = ~TargetMask;
428     InsertMask = ~InsertMask;
429
430     // If the LHS has a foldable shift and the RHS does not, then swap it to the
431     // RHS so that we can fold the shift into the insert.
432     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
433       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
434           Op0.getOperand(0).getOpcode() == ISD::SRL) {
435         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
436             Op1.getOperand(0).getOpcode() != ISD::SRL) {
437           std::swap(Op0, Op1);
438           std::swap(Op0Opc, Op1Opc);
439           std::swap(TargetMask, InsertMask);
440         }
441       }
442     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
443       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
444           Op1.getOperand(0).getOpcode() != ISD::SRL) {
445         std::swap(Op0, Op1);
446         std::swap(Op0Opc, Op1Opc);
447         std::swap(TargetMask, InsertMask);
448       }
449     }
450
451     unsigned MB, ME;
452     if (isRunOfOnes(InsertMask, MB, ME)) {
453       SDValue Tmp1, Tmp2;
454
455       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
456           isInt32Immediate(Op1.getOperand(1), Value)) {
457         Op1 = Op1.getOperand(0);
458         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
459       }
460       if (Op1Opc == ISD::AND) {
461         unsigned SHOpc = Op1.getOperand(0).getOpcode();
462         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
463             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
464           // Note that Value must be in range here (less than 32) because
465           // otherwise there would not be any bits set in InsertMask.
466           Op1 = Op1.getOperand(0).getOperand(0);
467           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
468         }
469       }
470
471       SH &= 31;
472       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
473                           getI32Imm(ME) };
474       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
475     }
476   }
477   return 0;
478 }
479
480 /// SelectCC - Select a comparison of the specified values with the specified
481 /// condition code, returning the CR# of the expression.
482 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
483                                     ISD::CondCode CC, SDLoc dl) {
484   // Always select the LHS.
485   unsigned Opc;
486
487   if (LHS.getValueType() == MVT::i32) {
488     unsigned Imm;
489     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
490       if (isInt32Immediate(RHS, Imm)) {
491         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
492         if (isUInt<16>(Imm))
493           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
494                                                 getI32Imm(Imm & 0xFFFF)), 0);
495         // If this is a 16-bit signed immediate, fold it.
496         if (isInt<16>((int)Imm))
497           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
498                                                 getI32Imm(Imm & 0xFFFF)), 0);
499
500         // For non-equality comparisons, the default code would materialize the
501         // constant, then compare against it, like this:
502         //   lis r2, 4660
503         //   ori r2, r2, 22136
504         //   cmpw cr0, r3, r2
505         // Since we are just comparing for equality, we can emit this instead:
506         //   xoris r0,r3,0x1234
507         //   cmplwi cr0,r0,0x5678
508         //   beq cr0,L6
509         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
510                                            getI32Imm(Imm >> 16)), 0);
511         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
512                                               getI32Imm(Imm & 0xFFFF)), 0);
513       }
514       Opc = PPC::CMPLW;
515     } else if (ISD::isUnsignedIntSetCC(CC)) {
516       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
517         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
518                                               getI32Imm(Imm & 0xFFFF)), 0);
519       Opc = PPC::CMPLW;
520     } else {
521       short SImm;
522       if (isIntS16Immediate(RHS, SImm))
523         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
524                                               getI32Imm((int)SImm & 0xFFFF)),
525                          0);
526       Opc = PPC::CMPW;
527     }
528   } else if (LHS.getValueType() == MVT::i64) {
529     uint64_t Imm;
530     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
531       if (isInt64Immediate(RHS.getNode(), Imm)) {
532         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
533         if (isUInt<16>(Imm))
534           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
535                                                 getI32Imm(Imm & 0xFFFF)), 0);
536         // If this is a 16-bit signed immediate, fold it.
537         if (isInt<16>(Imm))
538           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
539                                                 getI32Imm(Imm & 0xFFFF)), 0);
540
541         // For non-equality comparisons, the default code would materialize the
542         // constant, then compare against it, like this:
543         //   lis r2, 4660
544         //   ori r2, r2, 22136
545         //   cmpd cr0, r3, r2
546         // Since we are just comparing for equality, we can emit this instead:
547         //   xoris r0,r3,0x1234
548         //   cmpldi cr0,r0,0x5678
549         //   beq cr0,L6
550         if (isUInt<32>(Imm)) {
551           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
552                                              getI64Imm(Imm >> 16)), 0);
553           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
554                                                 getI64Imm(Imm & 0xFFFF)), 0);
555         }
556       }
557       Opc = PPC::CMPLD;
558     } else if (ISD::isUnsignedIntSetCC(CC)) {
559       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
560         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
561                                               getI64Imm(Imm & 0xFFFF)), 0);
562       Opc = PPC::CMPLD;
563     } else {
564       short SImm;
565       if (isIntS16Immediate(RHS, SImm))
566         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
567                                               getI64Imm(SImm & 0xFFFF)),
568                          0);
569       Opc = PPC::CMPD;
570     }
571   } else if (LHS.getValueType() == MVT::f32) {
572     Opc = PPC::FCMPUS;
573   } else {
574     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
575     Opc = PPC::FCMPUD;
576   }
577   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
578 }
579
580 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
581   switch (CC) {
582   case ISD::SETUEQ:
583   case ISD::SETONE:
584   case ISD::SETOLE:
585   case ISD::SETOGE:
586     llvm_unreachable("Should be lowered by legalize!");
587   default: llvm_unreachable("Unknown condition!");
588   case ISD::SETOEQ:
589   case ISD::SETEQ:  return PPC::PRED_EQ;
590   case ISD::SETUNE:
591   case ISD::SETNE:  return PPC::PRED_NE;
592   case ISD::SETOLT:
593   case ISD::SETLT:  return PPC::PRED_LT;
594   case ISD::SETULE:
595   case ISD::SETLE:  return PPC::PRED_LE;
596   case ISD::SETOGT:
597   case ISD::SETGT:  return PPC::PRED_GT;
598   case ISD::SETUGE:
599   case ISD::SETGE:  return PPC::PRED_GE;
600   case ISD::SETO:   return PPC::PRED_NU;
601   case ISD::SETUO:  return PPC::PRED_UN;
602     // These two are invalid for floating point.  Assume we have int.
603   case ISD::SETULT: return PPC::PRED_LT;
604   case ISD::SETUGT: return PPC::PRED_GT;
605   }
606 }
607
608 /// getCRIdxForSetCC - Return the index of the condition register field
609 /// associated with the SetCC condition, and whether or not the field is
610 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
611 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
612   Invert = false;
613   switch (CC) {
614   default: llvm_unreachable("Unknown condition!");
615   case ISD::SETOLT:
616   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
617   case ISD::SETOGT:
618   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
619   case ISD::SETOEQ:
620   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
621   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
622   case ISD::SETUGE:
623   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
624   case ISD::SETULE:
625   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
626   case ISD::SETUNE:
627   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
628   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
629   case ISD::SETUEQ:
630   case ISD::SETOGE:
631   case ISD::SETOLE:
632   case ISD::SETONE:
633     llvm_unreachable("Invalid branch code: should be expanded by legalize");
634   // These are invalid for floating point.  Assume integer.
635   case ISD::SETULT: return 0;
636   case ISD::SETUGT: return 1;
637   }
638 }
639
640 // getVCmpInst: return the vector compare instruction for the specified
641 // vector type and condition code. Since this is for altivec specific code,
642 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
643 static unsigned int getVCmpInst(MVT::SimpleValueType VecVT, ISD::CondCode CC) {
644   switch (CC) {
645     case ISD::SETEQ:
646     case ISD::SETUEQ:
647     case ISD::SETNE:
648     case ISD::SETUNE:
649       if (VecVT == MVT::v16i8)
650         return PPC::VCMPEQUB;
651       else if (VecVT == MVT::v8i16)
652         return PPC::VCMPEQUH;
653       else if (VecVT == MVT::v4i32)
654         return PPC::VCMPEQUW;
655       // v4f32 != v4f32 could be translate to unordered not equal
656       else if (VecVT == MVT::v4f32)
657         return PPC::VCMPEQFP;
658       break;
659     case ISD::SETLT:
660     case ISD::SETGT:
661     case ISD::SETLE:
662     case ISD::SETGE:
663       if (VecVT == MVT::v16i8)
664         return PPC::VCMPGTSB;
665       else if (VecVT == MVT::v8i16)
666         return PPC::VCMPGTSH;
667       else if (VecVT == MVT::v4i32)
668         return PPC::VCMPGTSW;
669       else if (VecVT == MVT::v4f32)
670         return PPC::VCMPGTFP;
671       break;
672     case ISD::SETULT:
673     case ISD::SETUGT:
674     case ISD::SETUGE:
675     case ISD::SETULE:
676       if (VecVT == MVT::v16i8)
677         return PPC::VCMPGTUB;
678       else if (VecVT == MVT::v8i16)
679         return PPC::VCMPGTUH;
680       else if (VecVT == MVT::v4i32)
681         return PPC::VCMPGTUW;
682       break;
683     case ISD::SETOEQ:
684       if (VecVT == MVT::v4f32)
685         return PPC::VCMPEQFP;
686       break;
687     case ISD::SETOLT:
688     case ISD::SETOGT:
689     case ISD::SETOLE:
690       if (VecVT == MVT::v4f32)
691         return PPC::VCMPGTFP;
692       break;
693     case ISD::SETOGE:
694       if (VecVT == MVT::v4f32)
695         return PPC::VCMPGEFP;
696       break;
697     default:
698       break;
699   }
700   llvm_unreachable("Invalid integer vector compare condition");
701 }
702
703 // getVCmpEQInst: return the equal compare instruction for the specified vector
704 // type. Since this is for altivec specific code, only support the altivec
705 // types (v16i8, v8i16, v4i32, and v4f32).
706 static unsigned int getVCmpEQInst(MVT::SimpleValueType VecVT) {
707   switch (VecVT) {
708     case MVT::v16i8:
709       return PPC::VCMPEQUB;
710     case MVT::v8i16:
711       return PPC::VCMPEQUH;
712     case MVT::v4i32:
713       return PPC::VCMPEQUW;
714     case MVT::v4f32:
715       return PPC::VCMPEQFP;
716     default:
717       llvm_unreachable("Invalid integer vector compare condition");
718   }
719 }
720
721
722 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
723   SDLoc dl(N);
724   unsigned Imm;
725   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
726   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
727   bool isPPC64 = (PtrVT == MVT::i64);
728
729   if (!PPCSubTarget.useCRBits() &&
730       isInt32Immediate(N->getOperand(1), Imm)) {
731     // We can codegen setcc op, imm very efficiently compared to a brcond.
732     // Check for those cases here.
733     // setcc op, 0
734     if (Imm == 0) {
735       SDValue Op = N->getOperand(0);
736       switch (CC) {
737       default: break;
738       case ISD::SETEQ: {
739         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
740         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
741         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
742       }
743       case ISD::SETNE: {
744         if (isPPC64) break;
745         SDValue AD =
746           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
747                                          Op, getI32Imm(~0U)), 0);
748         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
749                                     AD.getValue(1));
750       }
751       case ISD::SETLT: {
752         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
753         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
754       }
755       case ISD::SETGT: {
756         SDValue T =
757           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
758         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
759         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
760         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
761       }
762       }
763     } else if (Imm == ~0U) {        // setcc op, -1
764       SDValue Op = N->getOperand(0);
765       switch (CC) {
766       default: break;
767       case ISD::SETEQ:
768         if (isPPC64) break;
769         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
770                                             Op, getI32Imm(1)), 0);
771         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
772                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
773                                                              MVT::i32,
774                                                              getI32Imm(0)), 0),
775                                       Op.getValue(1));
776       case ISD::SETNE: {
777         if (isPPC64) break;
778         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
779         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
780                                             Op, getI32Imm(~0U));
781         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
782                                     Op, SDValue(AD, 1));
783       }
784       case ISD::SETLT: {
785         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
786                                                     getI32Imm(1)), 0);
787         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
788                                                     Op), 0);
789         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
790         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
791       }
792       case ISD::SETGT: {
793         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
794         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
795                      0);
796         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
797                                     getI32Imm(1));
798       }
799       }
800     }
801   }
802
803   SDValue LHS = N->getOperand(0);
804   SDValue RHS = N->getOperand(1);
805
806   // Altivec Vector compare instructions do not set any CR register by default and
807   // vector compare operations return the same type as the operands.
808   if (LHS.getValueType().isVector()) {
809     EVT VecVT = LHS.getValueType();
810     MVT::SimpleValueType VT = VecVT.getSimpleVT().SimpleTy;
811     unsigned int VCmpInst = getVCmpInst(VT, CC);
812
813     switch (CC) {
814       case ISD::SETEQ:
815       case ISD::SETOEQ:
816       case ISD::SETUEQ:
817         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
818       case ISD::SETNE:
819       case ISD::SETONE:
820       case ISD::SETUNE: {
821         SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
822         return CurDAG->SelectNodeTo(N, PPC::VNOR, VecVT, VCmp, VCmp);
823       } 
824       case ISD::SETLT:
825       case ISD::SETOLT:
826       case ISD::SETULT:
827         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, RHS, LHS);
828       case ISD::SETGT:
829       case ISD::SETOGT:
830       case ISD::SETUGT:
831         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
832       case ISD::SETGE:
833       case ISD::SETOGE:
834       case ISD::SETUGE: {
835         // Small optimization: Altivec provides a 'Vector Compare Greater Than
836         // or Equal To' instruction (vcmpgefp), so in this case there is no
837         // need for extra logic for the equal compare.
838         if (VecVT.getSimpleVT().isFloatingPoint()) {
839           return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
840         } else {
841           SDValue VCmpGT(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
842           unsigned int VCmpEQInst = getVCmpEQInst(VT);
843           SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
844           return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpGT, VCmpEQ);
845         }
846       }
847       case ISD::SETLE:
848       case ISD::SETOLE:
849       case ISD::SETULE: {
850         SDValue VCmpLE(CurDAG->getMachineNode(VCmpInst, dl, VecVT, RHS, LHS), 0);
851         unsigned int VCmpEQInst = getVCmpEQInst(VT);
852         SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
853         return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpLE, VCmpEQ);
854       }
855       default:
856         llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
857     }
858   }
859
860   if (PPCSubTarget.useCRBits())
861     return 0;
862
863   bool Inv;
864   unsigned Idx = getCRIdxForSetCC(CC, Inv);
865   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
866   SDValue IntCR;
867
868   // Force the ccreg into CR7.
869   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
870
871   SDValue InFlag(0, 0);  // Null incoming flag value.
872   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
873                                InFlag).getValue(1);
874
875   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
876                                          CCReg), 0);
877
878   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
879                       getI32Imm(31), getI32Imm(31) };
880   if (!Inv)
881     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
882
883   // Get the specified bit.
884   SDValue Tmp =
885     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
886   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
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   SDLoc dl(N);
894   if (N->isMachineOpcode()) {
895     N->setNodeId(-1);
896     return NULL;   // Already selected.
897   }
898
899   switch (N->getOpcode()) {
900   default: break;
901
902   case ISD::Constant: {
903     if (N->getValueType(0) == MVT::i64) {
904       // Get 64 bit value.
905       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
906       // Assume no remaining bits.
907       unsigned Remainder = 0;
908       // Assume no shift required.
909       unsigned Shift = 0;
910
911       // If it can't be represented as a 32 bit value.
912       if (!isInt<32>(Imm)) {
913         Shift = countTrailingZeros<uint64_t>(Imm);
914         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
915
916         // If the shifted value fits 32 bits.
917         if (isInt<32>(ImmSh)) {
918           // Go with the shifted value.
919           Imm = ImmSh;
920         } else {
921           // Still stuck with a 64 bit value.
922           Remainder = Imm;
923           Shift = 32;
924           Imm >>= 32;
925         }
926       }
927
928       // Intermediate operand.
929       SDNode *Result;
930
931       // Handle first 32 bits.
932       unsigned Lo = Imm & 0xFFFF;
933       unsigned Hi = (Imm >> 16) & 0xFFFF;
934
935       // Simple value.
936       if (isInt<16>(Imm)) {
937        // Just the Lo bits.
938         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
939       } else if (Lo) {
940         // Handle the Hi bits.
941         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
942         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
943         // And Lo bits.
944         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
945                                         SDValue(Result, 0), getI32Imm(Lo));
946       } else {
947        // Just the Hi bits.
948         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
949       }
950
951       // If no shift, we're done.
952       if (!Shift) return Result;
953
954       // Shift for next step if the upper 32-bits were not zero.
955       if (Imm) {
956         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
957                                         SDValue(Result, 0),
958                                         getI32Imm(Shift),
959                                         getI32Imm(63 - Shift));
960       }
961
962       // Add in the last bits as required.
963       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
964         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
965                                         SDValue(Result, 0), getI32Imm(Hi));
966       }
967       if ((Lo = Remainder & 0xFFFF)) {
968         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
969                                         SDValue(Result, 0), getI32Imm(Lo));
970       }
971
972       return Result;
973     }
974     break;
975   }
976
977   case ISD::SETCC: {
978     SDNode *SN = SelectSETCC(N);
979     if (SN)
980       return SN;
981     break;
982   }
983   case PPCISD::GlobalBaseReg:
984     return getGlobalBaseReg();
985
986   case ISD::FrameIndex: {
987     int FI = cast<FrameIndexSDNode>(N)->getIndex();
988     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
989     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
990     if (N->hasOneUse())
991       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
992                                   getSmallIPtrImm(0));
993     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
994                                   getSmallIPtrImm(0));
995   }
996
997   case PPCISD::MFOCRF: {
998     SDValue InFlag = N->getOperand(1);
999     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
1000                                   N->getOperand(0), InFlag);
1001   }
1002
1003   case ISD::SDIV: {
1004     // FIXME: since this depends on the setting of the carry flag from the srawi
1005     //        we should really be making notes about that for the scheduler.
1006     // FIXME: It sure would be nice if we could cheaply recognize the
1007     //        srl/add/sra pattern the dag combiner will generate for this as
1008     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1009     unsigned Imm;
1010     if (isInt32Immediate(N->getOperand(1), Imm)) {
1011       SDValue N0 = N->getOperand(0);
1012       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1013         SDNode *Op =
1014           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1015                                  N0, getI32Imm(Log2_32(Imm)));
1016         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1017                                     SDValue(Op, 0), SDValue(Op, 1));
1018       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1019         SDNode *Op =
1020           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1021                                  N0, getI32Imm(Log2_32(-Imm)));
1022         SDValue PT =
1023           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
1024                                          SDValue(Op, 0), SDValue(Op, 1)),
1025                     0);
1026         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1027       }
1028     }
1029
1030     // Other cases are autogenerated.
1031     break;
1032   }
1033
1034   case ISD::LOAD: {
1035     // Handle preincrement loads.
1036     LoadSDNode *LD = cast<LoadSDNode>(N);
1037     EVT LoadedVT = LD->getMemoryVT();
1038
1039     // Normal loads are handled by code generated from the .td file.
1040     if (LD->getAddressingMode() != ISD::PRE_INC)
1041       break;
1042
1043     SDValue Offset = LD->getOffset();
1044     if (Offset.getOpcode() == ISD::TargetConstant ||
1045         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1046
1047       unsigned Opcode;
1048       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1049       if (LD->getValueType(0) != MVT::i64) {
1050         // Handle PPC32 integer and normal FP loads.
1051         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1052         switch (LoadedVT.getSimpleVT().SimpleTy) {
1053           default: llvm_unreachable("Invalid PPC load type!");
1054           case MVT::f64: Opcode = PPC::LFDU; break;
1055           case MVT::f32: Opcode = PPC::LFSU; break;
1056           case MVT::i32: Opcode = PPC::LWZU; break;
1057           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1058           case MVT::i1:
1059           case MVT::i8:  Opcode = PPC::LBZU; break;
1060         }
1061       } else {
1062         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1063         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1064         switch (LoadedVT.getSimpleVT().SimpleTy) {
1065           default: llvm_unreachable("Invalid PPC load type!");
1066           case MVT::i64: Opcode = PPC::LDU; break;
1067           case MVT::i32: Opcode = PPC::LWZU8; break;
1068           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1069           case MVT::i1:
1070           case MVT::i8:  Opcode = PPC::LBZU8; break;
1071         }
1072       }
1073
1074       SDValue Chain = LD->getChain();
1075       SDValue Base = LD->getBasePtr();
1076       SDValue Ops[] = { Offset, Base, Chain };
1077       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1078                                     PPCLowering.getPointerTy(),
1079                                     MVT::Other, Ops);
1080     } else {
1081       unsigned Opcode;
1082       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1083       if (LD->getValueType(0) != MVT::i64) {
1084         // Handle PPC32 integer and normal FP loads.
1085         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1086         switch (LoadedVT.getSimpleVT().SimpleTy) {
1087           default: llvm_unreachable("Invalid PPC load type!");
1088           case MVT::f64: Opcode = PPC::LFDUX; break;
1089           case MVT::f32: Opcode = PPC::LFSUX; break;
1090           case MVT::i32: Opcode = PPC::LWZUX; break;
1091           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1092           case MVT::i1:
1093           case MVT::i8:  Opcode = PPC::LBZUX; break;
1094         }
1095       } else {
1096         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1097         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1098                "Invalid sext update load");
1099         switch (LoadedVT.getSimpleVT().SimpleTy) {
1100           default: llvm_unreachable("Invalid PPC load type!");
1101           case MVT::i64: Opcode = PPC::LDUX; break;
1102           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1103           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1104           case MVT::i1:
1105           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1106         }
1107       }
1108
1109       SDValue Chain = LD->getChain();
1110       SDValue Base = LD->getBasePtr();
1111       SDValue Ops[] = { Base, Offset, Chain };
1112       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1113                                     PPCLowering.getPointerTy(),
1114                                     MVT::Other, Ops);
1115     }
1116   }
1117
1118   case ISD::AND: {
1119     unsigned Imm, Imm2, SH, MB, ME;
1120     uint64_t Imm64;
1121
1122     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1123     // with a mask, emit rlwinm
1124     if (isInt32Immediate(N->getOperand(1), Imm) &&
1125         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1126       SDValue Val = N->getOperand(0).getOperand(0);
1127       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1128       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1129     }
1130     // If this is just a masked value where the input is not handled above, and
1131     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1132     if (isInt32Immediate(N->getOperand(1), Imm) &&
1133         isRunOfOnes(Imm, MB, ME) &&
1134         N->getOperand(0).getOpcode() != ISD::ROTL) {
1135       SDValue Val = N->getOperand(0);
1136       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1137       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1138     }
1139     // If this is a 64-bit zero-extension mask, emit rldicl.
1140     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1141         isMask_64(Imm64)) {
1142       SDValue Val = N->getOperand(0);
1143       MB = 64 - CountTrailingOnes_64(Imm64);
1144       SH = 0;
1145
1146       // If the operand is a logical right shift, we can fold it into this
1147       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
1148       // for n <= mb. The right shift is really a left rotate followed by a
1149       // mask, and this mask is a more-restrictive sub-mask of the mask implied
1150       // by the shift.
1151       if (Val.getOpcode() == ISD::SRL &&
1152           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
1153         assert(Imm < 64 && "Illegal shift amount");
1154         Val = Val.getOperand(0);
1155         SH = 64 - Imm;
1156       }
1157
1158       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
1159       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1160     }
1161     // AND X, 0 -> 0, not "rlwinm 32".
1162     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1163       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1164       return NULL;
1165     }
1166     // ISD::OR doesn't get all the bitfield insertion fun.
1167     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1168     if (isInt32Immediate(N->getOperand(1), Imm) &&
1169         N->getOperand(0).getOpcode() == ISD::OR &&
1170         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1171       unsigned MB, ME;
1172       Imm = ~(Imm^Imm2);
1173       if (isRunOfOnes(Imm, MB, ME)) {
1174         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1175                             N->getOperand(0).getOperand(1),
1176                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1177         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1178       }
1179     }
1180
1181     // Other cases are autogenerated.
1182     break;
1183   }
1184   case ISD::OR:
1185     if (N->getValueType(0) == MVT::i32)
1186       if (SDNode *I = SelectBitfieldInsert(N))
1187         return I;
1188
1189     // Other cases are autogenerated.
1190     break;
1191   case ISD::SHL: {
1192     unsigned Imm, SH, MB, ME;
1193     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1194         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1195       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1196                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1197       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1198     }
1199
1200     // Other cases are autogenerated.
1201     break;
1202   }
1203   case ISD::SRL: {
1204     unsigned Imm, SH, MB, ME;
1205     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1206         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1207       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1208                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1209       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1210     }
1211
1212     // Other cases are autogenerated.
1213     break;
1214   }
1215   // FIXME: Remove this once the ANDI glue bug is fixed:
1216   case PPCISD::ANDIo_1_EQ_BIT:
1217   case PPCISD::ANDIo_1_GT_BIT: {
1218     if (!ANDIGlueBug)
1219       break;
1220
1221     EVT InVT = N->getOperand(0).getValueType();
1222     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
1223            "Invalid input type for ANDIo_1_EQ_BIT");
1224
1225     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
1226     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
1227                                         N->getOperand(0),
1228                                         CurDAG->getTargetConstant(1, InVT)), 0);
1229     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
1230     SDValue SRIdxVal =
1231       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
1232                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
1233
1234     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
1235                                 CR0Reg, SRIdxVal,
1236                                 SDValue(AndI.getNode(), 1) /* glue */);
1237   }
1238   case ISD::SELECT_CC: {
1239     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1240     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1241     bool isPPC64 = (PtrVT == MVT::i64);
1242
1243     // If this is a select of i1 operands, we'll pattern match it.
1244     if (PPCSubTarget.useCRBits() &&
1245         N->getOperand(0).getValueType() == MVT::i1)
1246       break;
1247
1248     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1249     if (!isPPC64)
1250       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1251         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1252           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1253             if (N1C->isNullValue() && N3C->isNullValue() &&
1254                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1255                 // FIXME: Implement this optzn for PPC64.
1256                 N->getValueType(0) == MVT::i32) {
1257               SDNode *Tmp =
1258                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1259                                        N->getOperand(0), getI32Imm(~0U));
1260               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1261                                           SDValue(Tmp, 0), N->getOperand(0),
1262                                           SDValue(Tmp, 1));
1263             }
1264
1265     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1266
1267     if (N->getValueType(0) == MVT::i1) {
1268       // An i1 select is: (c & t) | (!c & f).
1269       bool Inv;
1270       unsigned Idx = getCRIdxForSetCC(CC, Inv);
1271
1272       unsigned SRI;
1273       switch (Idx) {
1274       default: llvm_unreachable("Invalid CC index");
1275       case 0: SRI = PPC::sub_lt; break;
1276       case 1: SRI = PPC::sub_gt; break;
1277       case 2: SRI = PPC::sub_eq; break;
1278       case 3: SRI = PPC::sub_un; break;
1279       }
1280
1281       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
1282
1283       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
1284                                               CCBit, CCBit), 0);
1285       SDValue C =    Inv ? NotCCBit : CCBit,
1286               NotC = Inv ? CCBit    : NotCCBit;
1287
1288       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1289                                            C, N->getOperand(2)), 0);
1290       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1291                                               NotC, N->getOperand(3)), 0);
1292
1293       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
1294     }
1295
1296     unsigned BROpc = getPredicateForSetCC(CC);
1297
1298     unsigned SelectCCOp;
1299     if (N->getValueType(0) == MVT::i32)
1300       SelectCCOp = PPC::SELECT_CC_I4;
1301     else if (N->getValueType(0) == MVT::i64)
1302       SelectCCOp = PPC::SELECT_CC_I8;
1303     else if (N->getValueType(0) == MVT::f32)
1304       SelectCCOp = PPC::SELECT_CC_F4;
1305     else if (N->getValueType(0) == MVT::f64)
1306       SelectCCOp = PPC::SELECT_CC_F8;
1307     else
1308       SelectCCOp = PPC::SELECT_CC_VRRC;
1309
1310     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1311                         getI32Imm(BROpc) };
1312     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1313   }
1314   case PPCISD::BDNZ:
1315   case PPCISD::BDZ: {
1316     bool IsPPC64 = PPCSubTarget.isPPC64();
1317     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1318     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1319                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1320                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1321                                 MVT::Other, Ops, 2);
1322   }
1323   case PPCISD::COND_BRANCH: {
1324     // Op #0 is the Chain.
1325     // Op #1 is the PPC::PRED_* number.
1326     // Op #2 is the CR#
1327     // Op #3 is the Dest MBB
1328     // Op #4 is the Flag.
1329     // Prevent PPC::PRED_* from being selected into LI.
1330     SDValue Pred =
1331       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1332     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1333       N->getOperand(0), N->getOperand(4) };
1334     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1335   }
1336   case ISD::BR_CC: {
1337     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1338     unsigned PCC = getPredicateForSetCC(CC);
1339
1340     if (N->getOperand(2).getValueType() == MVT::i1) {
1341       unsigned Opc;
1342       bool Swap;
1343       switch (PCC) {
1344       default: llvm_unreachable("Unexpected Boolean-operand predicate");
1345       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
1346       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
1347       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
1348       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
1349       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
1350       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
1351       }
1352
1353       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
1354                                              N->getOperand(Swap ? 3 : 2),
1355                                              N->getOperand(Swap ? 2 : 3)), 0);
1356       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
1357                                   BitComp, N->getOperand(4), N->getOperand(0));
1358     }
1359
1360     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1361     SDValue Ops[] = { getI32Imm(PCC), CondCode,
1362                         N->getOperand(4), N->getOperand(0) };
1363     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1364   }
1365   case ISD::BRIND: {
1366     // FIXME: Should custom lower this.
1367     SDValue Chain = N->getOperand(0);
1368     SDValue Target = N->getOperand(1);
1369     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1370     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1371     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1372                                            Chain), 0);
1373     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1374   }
1375   case PPCISD::TOC_ENTRY: {
1376     assert (PPCSubTarget.isPPC64() && "Only supported for 64-bit ABI");
1377
1378     // For medium and large code model, we generate two instructions as
1379     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1380     // selecting one of LDtoc, LDtocJTI, and LDtocCPT.
1381     CodeModel::Model CModel = TM.getCodeModel();
1382     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1383       break;
1384
1385     // The first source operand is a TargetGlobalAddress or a
1386     // TargetJumpTable.  If it is an externally defined symbol, a symbol
1387     // with common linkage, a function address, or a jump table address,
1388     // or if we are generating code for large code model, we generate:
1389     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1390     // Otherwise we generate:
1391     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1392     SDValue GA = N->getOperand(0);
1393     SDValue TOCbase = N->getOperand(1);
1394     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1395                                         TOCbase, GA);
1396
1397     if (isa<JumpTableSDNode>(GA) || CModel == CodeModel::Large)
1398       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1399                                     SDValue(Tmp, 0));
1400
1401     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1402       const GlobalValue *GValue = G->getGlobal();
1403       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
1404       const GlobalValue *RealGValue = GAlias ?
1405         GAlias->resolveAliasedGlobal(false) : GValue;
1406       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
1407       assert((GVar || isa<Function>(RealGValue)) &&
1408              "Unexpected global value subclass!");
1409
1410       // An external variable is one without an initializer.  For these,
1411       // for variables with common linkage, and for Functions, generate
1412       // the LDtocL form.
1413       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
1414           RealGValue->hasAvailableExternallyLinkage())
1415         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1416                                       SDValue(Tmp, 0));
1417     }
1418
1419     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1420                                   SDValue(Tmp, 0), GA);
1421   }
1422   case PPCISD::VADD_SPLAT: {
1423     // This expands into one of three sequences, depending on whether
1424     // the first operand is odd or even, positive or negative.
1425     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1426            isa<ConstantSDNode>(N->getOperand(1)) &&
1427            "Invalid operand on VADD_SPLAT!");
1428
1429     int Elt     = N->getConstantOperandVal(0);
1430     int EltSize = N->getConstantOperandVal(1);
1431     unsigned Opc1, Opc2, Opc3;
1432     EVT VT;
1433
1434     if (EltSize == 1) {
1435       Opc1 = PPC::VSPLTISB;
1436       Opc2 = PPC::VADDUBM;
1437       Opc3 = PPC::VSUBUBM;
1438       VT = MVT::v16i8;
1439     } else if (EltSize == 2) {
1440       Opc1 = PPC::VSPLTISH;
1441       Opc2 = PPC::VADDUHM;
1442       Opc3 = PPC::VSUBUHM;
1443       VT = MVT::v8i16;
1444     } else {
1445       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1446       Opc1 = PPC::VSPLTISW;
1447       Opc2 = PPC::VADDUWM;
1448       Opc3 = PPC::VSUBUWM;
1449       VT = MVT::v4i32;
1450     }
1451
1452     if ((Elt & 1) == 0) {
1453       // Elt is even, in the range [-32,-18] + [16,30].
1454       //
1455       // Convert: VADD_SPLAT elt, size
1456       // Into:    tmp = VSPLTIS[BHW] elt
1457       //          VADDU[BHW]M tmp, tmp
1458       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1459       SDValue EltVal = getI32Imm(Elt >> 1);
1460       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1461       SDValue TmpVal = SDValue(Tmp, 0);
1462       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1463
1464     } else if (Elt > 0) {
1465       // Elt is odd and positive, in the range [17,31].
1466       //
1467       // Convert: VADD_SPLAT elt, size
1468       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1469       //          tmp2 = VSPLTIS[BHW] -16
1470       //          VSUBU[BHW]M tmp1, tmp2
1471       SDValue EltVal = getI32Imm(Elt - 16);
1472       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1473       EltVal = getI32Imm(-16);
1474       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1475       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1476                                     SDValue(Tmp2, 0));
1477
1478     } else {
1479       // Elt is odd and negative, in the range [-31,-17].
1480       //
1481       // Convert: VADD_SPLAT elt, size
1482       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1483       //          tmp2 = VSPLTIS[BHW] -16
1484       //          VADDU[BHW]M tmp1, tmp2
1485       SDValue EltVal = getI32Imm(Elt + 16);
1486       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1487       EltVal = getI32Imm(-16);
1488       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1489       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1490                                     SDValue(Tmp2, 0));
1491     }
1492   }
1493   }
1494
1495   return SelectCode(N);
1496 }
1497
1498 /// PostprocessISelDAG - Perform some late peephole optimizations
1499 /// on the DAG representation.
1500 void PPCDAGToDAGISel::PostprocessISelDAG() {
1501
1502   // Skip peepholes at -O0.
1503   if (TM.getOptLevel() == CodeGenOpt::None)
1504     return;
1505
1506   PeepholePPC64();
1507   PeepholdCROps();
1508 }
1509
1510 // Check if all users of this node will become isel where the second operand
1511 // is the constant zero. If this is so, and if we can negate the condition,
1512 // then we can flip the true and false operands. This will allow the zero to
1513 // be folded with the isel so that we don't need to materialize a register
1514 // containing zero.
1515 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
1516   // If we're not using isel, then this does not matter.
1517   if (!PPCSubTarget.hasISEL())
1518     return false;
1519
1520   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1521        UI != UE; ++UI) {
1522     SDNode *User = *UI;
1523     if (!User->isMachineOpcode())
1524       return false;
1525     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
1526         User->getMachineOpcode() != PPC::SELECT_I8)
1527       return false;
1528
1529     SDNode *Op2 = User->getOperand(2).getNode();
1530     if (!Op2->isMachineOpcode())
1531       return false;
1532
1533     if (Op2->getMachineOpcode() != PPC::LI &&
1534         Op2->getMachineOpcode() != PPC::LI8)
1535       return false;
1536
1537     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
1538     if (!C)
1539       return false;
1540
1541     if (!C->isNullValue())
1542       return false;
1543   }
1544
1545   return true;
1546 }
1547
1548 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
1549   SmallVector<SDNode *, 4> ToReplace;
1550   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1551        UI != UE; ++UI) {
1552     SDNode *User = *UI;
1553     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
1554             User->getMachineOpcode() == PPC::SELECT_I8) &&
1555            "Must have all select users");
1556     ToReplace.push_back(User);
1557   }
1558
1559   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
1560        UE = ToReplace.end(); UI != UE; ++UI) {
1561     SDNode *User = *UI;
1562     SDNode *ResNode =
1563       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
1564                              User->getValueType(0), User->getOperand(0),
1565                              User->getOperand(2),
1566                              User->getOperand(1));
1567
1568       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1569       DEBUG(User->dump(CurDAG));
1570       DEBUG(dbgs() << "\nNew: ");
1571       DEBUG(ResNode->dump(CurDAG));
1572       DEBUG(dbgs() << "\n");
1573
1574       ReplaceUses(User, ResNode);
1575   }
1576 }
1577
1578 void PPCDAGToDAGISel::PeepholdCROps() {
1579   bool IsModified;
1580   do {
1581     IsModified = false;
1582     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1583          E = CurDAG->allnodes_end(); I != E; ++I) {
1584       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1585       if (!MachineNode || MachineNode->use_empty())
1586         continue;
1587       SDNode *ResNode = MachineNode;
1588
1589       bool Op1Set   = false, Op1Unset = false,
1590            Op1Not   = false,
1591            Op2Set   = false, Op2Unset = false,
1592            Op2Not   = false;
1593
1594       unsigned Opcode = MachineNode->getMachineOpcode();
1595       switch (Opcode) {
1596       default: break;
1597       case PPC::CRAND:
1598       case PPC::CRNAND:
1599       case PPC::CROR:
1600       case PPC::CRXOR:
1601       case PPC::CRNOR:
1602       case PPC::CREQV:
1603       case PPC::CRANDC:
1604       case PPC::CRORC: {
1605         SDValue Op = MachineNode->getOperand(1);
1606         if (Op.isMachineOpcode()) {
1607           if (Op.getMachineOpcode() == PPC::CRSET)
1608             Op2Set = true;
1609           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1610             Op2Unset = true;
1611           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1612                    Op.getOperand(0) == Op.getOperand(1))
1613             Op2Not = true;
1614         }
1615         }  // fallthrough
1616       case PPC::BC:
1617       case PPC::BCn:
1618       case PPC::SELECT_I4:
1619       case PPC::SELECT_I8:
1620       case PPC::SELECT_F4:
1621       case PPC::SELECT_F8:
1622       case PPC::SELECT_VRRC: {
1623         SDValue Op = MachineNode->getOperand(0);
1624         if (Op.isMachineOpcode()) {
1625           if (Op.getMachineOpcode() == PPC::CRSET)
1626             Op1Set = true;
1627           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1628             Op1Unset = true;
1629           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1630                    Op.getOperand(0) == Op.getOperand(1))
1631             Op1Not = true;
1632         }
1633         }
1634         break;
1635       }
1636
1637       bool SelectSwap = false;
1638       switch (Opcode) {
1639       default: break;
1640       case PPC::CRAND:
1641         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1642           // x & x = x
1643           ResNode = MachineNode->getOperand(0).getNode();
1644         else if (Op1Set)
1645           // 1 & y = y
1646           ResNode = MachineNode->getOperand(1).getNode();
1647         else if (Op2Set)
1648           // x & 1 = x
1649           ResNode = MachineNode->getOperand(0).getNode();
1650         else if (Op1Unset || Op2Unset)
1651           // x & 0 = 0 & y = 0
1652           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1653                                            MVT::i1);
1654         else if (Op1Not)
1655           // ~x & y = andc(y, x)
1656           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1657                                            MVT::i1, MachineNode->getOperand(1),
1658                                            MachineNode->getOperand(0).
1659                                              getOperand(0));
1660         else if (Op2Not)
1661           // x & ~y = andc(x, y)
1662           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1663                                            MVT::i1, MachineNode->getOperand(0),
1664                                            MachineNode->getOperand(1).
1665                                              getOperand(0));
1666         else if (AllUsersSelectZero(MachineNode))
1667           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1668                                            MVT::i1, MachineNode->getOperand(0),
1669                                            MachineNode->getOperand(1)),
1670           SelectSwap = true;
1671         break;
1672       case PPC::CRNAND:
1673         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1674           // nand(x, x) -> nor(x, x)
1675           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1676                                            MVT::i1, MachineNode->getOperand(0),
1677                                            MachineNode->getOperand(0));
1678         else if (Op1Set)
1679           // nand(1, y) -> nor(y, y)
1680           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1681                                            MVT::i1, MachineNode->getOperand(1),
1682                                            MachineNode->getOperand(1));
1683         else if (Op2Set)
1684           // nand(x, 1) -> nor(x, x)
1685           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1686                                            MVT::i1, MachineNode->getOperand(0),
1687                                            MachineNode->getOperand(0));
1688         else if (Op1Unset || Op2Unset)
1689           // nand(x, 0) = nand(0, y) = 1
1690           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1691                                            MVT::i1);
1692         else if (Op1Not)
1693           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
1694           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1695                                            MVT::i1, MachineNode->getOperand(0).
1696                                                       getOperand(0),
1697                                            MachineNode->getOperand(1));
1698         else if (Op2Not)
1699           // nand(x, ~y) = ~x | y = orc(y, x)
1700           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1701                                            MVT::i1, MachineNode->getOperand(1).
1702                                                       getOperand(0),
1703                                            MachineNode->getOperand(0));
1704         else if (AllUsersSelectZero(MachineNode))
1705           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1706                                            MVT::i1, MachineNode->getOperand(0),
1707                                            MachineNode->getOperand(1)),
1708           SelectSwap = true;
1709         break;
1710       case PPC::CROR:
1711         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1712           // x | x = x
1713           ResNode = MachineNode->getOperand(0).getNode();
1714         else if (Op1Set || Op2Set)
1715           // x | 1 = 1 | y = 1
1716           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1717                                            MVT::i1);
1718         else if (Op1Unset)
1719           // 0 | y = y
1720           ResNode = MachineNode->getOperand(1).getNode();
1721         else if (Op2Unset)
1722           // x | 0 = x
1723           ResNode = MachineNode->getOperand(0).getNode();
1724         else if (Op1Not)
1725           // ~x | y = orc(y, x)
1726           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1727                                            MVT::i1, MachineNode->getOperand(1),
1728                                            MachineNode->getOperand(0).
1729                                              getOperand(0));
1730         else if (Op2Not)
1731           // x | ~y = orc(x, y)
1732           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1733                                            MVT::i1, MachineNode->getOperand(0),
1734                                            MachineNode->getOperand(1).
1735                                              getOperand(0));
1736         else if (AllUsersSelectZero(MachineNode))
1737           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1738                                            MVT::i1, MachineNode->getOperand(0),
1739                                            MachineNode->getOperand(1)),
1740           SelectSwap = true;
1741         break;
1742       case PPC::CRXOR:
1743         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1744           // xor(x, x) = 0
1745           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1746                                            MVT::i1);
1747         else if (Op1Set)
1748           // xor(1, y) -> nor(y, y)
1749           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1750                                            MVT::i1, MachineNode->getOperand(1),
1751                                            MachineNode->getOperand(1));
1752         else if (Op2Set)
1753           // xor(x, 1) -> nor(x, x)
1754           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1755                                            MVT::i1, MachineNode->getOperand(0),
1756                                            MachineNode->getOperand(0));
1757         else if (Op1Unset)
1758           // xor(0, y) = y
1759           ResNode = MachineNode->getOperand(1).getNode();
1760         else if (Op2Unset)
1761           // xor(x, 0) = x
1762           ResNode = MachineNode->getOperand(0).getNode();
1763         else if (Op1Not)
1764           // xor(~x, y) = eqv(x, y)
1765           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1766                                            MVT::i1, MachineNode->getOperand(0).
1767                                                       getOperand(0),
1768                                            MachineNode->getOperand(1));
1769         else if (Op2Not)
1770           // xor(x, ~y) = eqv(x, y)
1771           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1772                                            MVT::i1, MachineNode->getOperand(0),
1773                                            MachineNode->getOperand(1).
1774                                              getOperand(0));
1775         else if (AllUsersSelectZero(MachineNode))
1776           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1777                                            MVT::i1, MachineNode->getOperand(0),
1778                                            MachineNode->getOperand(1)),
1779           SelectSwap = true;
1780         break;
1781       case PPC::CRNOR:
1782         if (Op1Set || Op2Set)
1783           // nor(1, y) -> 0
1784           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1785                                            MVT::i1);
1786         else if (Op1Unset)
1787           // nor(0, y) = ~y -> nor(y, y)
1788           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1789                                            MVT::i1, MachineNode->getOperand(1),
1790                                            MachineNode->getOperand(1));
1791         else if (Op2Unset)
1792           // nor(x, 0) = ~x
1793           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1794                                            MVT::i1, MachineNode->getOperand(0),
1795                                            MachineNode->getOperand(0));
1796         else if (Op1Not)
1797           // nor(~x, y) = andc(x, y)
1798           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1799                                            MVT::i1, MachineNode->getOperand(0).
1800                                                       getOperand(0),
1801                                            MachineNode->getOperand(1));
1802         else if (Op2Not)
1803           // nor(x, ~y) = andc(y, x)
1804           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1805                                            MVT::i1, MachineNode->getOperand(1).
1806                                                       getOperand(0),
1807                                            MachineNode->getOperand(0));
1808         else if (AllUsersSelectZero(MachineNode))
1809           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1810                                            MVT::i1, MachineNode->getOperand(0),
1811                                            MachineNode->getOperand(1)),
1812           SelectSwap = true;
1813         break;
1814       case PPC::CREQV:
1815         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1816           // eqv(x, x) = 1
1817           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1818                                            MVT::i1);
1819         else if (Op1Set)
1820           // eqv(1, y) = y
1821           ResNode = MachineNode->getOperand(1).getNode();
1822         else if (Op2Set)
1823           // eqv(x, 1) = x
1824           ResNode = MachineNode->getOperand(0).getNode();
1825         else if (Op1Unset)
1826           // eqv(0, y) = ~y -> nor(y, y)
1827           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1828                                            MVT::i1, MachineNode->getOperand(1),
1829                                            MachineNode->getOperand(1));
1830         else if (Op2Unset)
1831           // eqv(x, 0) = ~x
1832           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1833                                            MVT::i1, MachineNode->getOperand(0),
1834                                            MachineNode->getOperand(0));
1835         else if (Op1Not)
1836           // eqv(~x, y) = xor(x, y)
1837           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1838                                            MVT::i1, MachineNode->getOperand(0).
1839                                                       getOperand(0),
1840                                            MachineNode->getOperand(1));
1841         else if (Op2Not)
1842           // eqv(x, ~y) = xor(x, y)
1843           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1844                                            MVT::i1, MachineNode->getOperand(0),
1845                                            MachineNode->getOperand(1).
1846                                              getOperand(0));
1847         else if (AllUsersSelectZero(MachineNode))
1848           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1849                                            MVT::i1, MachineNode->getOperand(0),
1850                                            MachineNode->getOperand(1)),
1851           SelectSwap = true;
1852         break;
1853       case PPC::CRANDC:
1854         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1855           // andc(x, x) = 0
1856           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1857                                            MVT::i1);
1858         else if (Op1Set)
1859           // andc(1, y) = ~y
1860           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1861                                            MVT::i1, MachineNode->getOperand(1),
1862                                            MachineNode->getOperand(1));
1863         else if (Op1Unset || Op2Set)
1864           // andc(0, y) = andc(x, 1) = 0
1865           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1866                                            MVT::i1);
1867         else if (Op2Unset)
1868           // andc(x, 0) = x
1869           ResNode = MachineNode->getOperand(0).getNode();
1870         else if (Op1Not)
1871           // andc(~x, y) = ~(x | y) = nor(x, y)
1872           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1873                                            MVT::i1, MachineNode->getOperand(0).
1874                                                       getOperand(0),
1875                                            MachineNode->getOperand(1));
1876         else if (Op2Not)
1877           // andc(x, ~y) = x & y
1878           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1879                                            MVT::i1, MachineNode->getOperand(0),
1880                                            MachineNode->getOperand(1).
1881                                              getOperand(0));
1882         else if (AllUsersSelectZero(MachineNode))
1883           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1884                                            MVT::i1, MachineNode->getOperand(1),
1885                                            MachineNode->getOperand(0)),
1886           SelectSwap = true;
1887         break;
1888       case PPC::CRORC:
1889         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1890           // orc(x, x) = 1
1891           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1892                                            MVT::i1);
1893         else if (Op1Set || Op2Unset)
1894           // orc(1, y) = orc(x, 0) = 1
1895           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1896                                            MVT::i1);
1897         else if (Op2Set)
1898           // orc(x, 1) = x
1899           ResNode = MachineNode->getOperand(0).getNode();
1900         else if (Op1Unset)
1901           // orc(0, y) = ~y
1902           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1903                                            MVT::i1, MachineNode->getOperand(1),
1904                                            MachineNode->getOperand(1));
1905         else if (Op1Not)
1906           // orc(~x, y) = ~(x & y) = nand(x, y)
1907           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1908                                            MVT::i1, MachineNode->getOperand(0).
1909                                                       getOperand(0),
1910                                            MachineNode->getOperand(1));
1911         else if (Op2Not)
1912           // orc(x, ~y) = x | y
1913           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1914                                            MVT::i1, MachineNode->getOperand(0),
1915                                            MachineNode->getOperand(1).
1916                                              getOperand(0));
1917         else if (AllUsersSelectZero(MachineNode))
1918           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1919                                            MVT::i1, MachineNode->getOperand(1),
1920                                            MachineNode->getOperand(0)),
1921           SelectSwap = true;
1922         break;
1923       case PPC::SELECT_I4:
1924       case PPC::SELECT_I8:
1925       case PPC::SELECT_F4:
1926       case PPC::SELECT_F8:
1927       case PPC::SELECT_VRRC:
1928         if (Op1Set)
1929           ResNode = MachineNode->getOperand(1).getNode();
1930         else if (Op1Unset)
1931           ResNode = MachineNode->getOperand(2).getNode();
1932         else if (Op1Not)
1933           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
1934                                            SDLoc(MachineNode),
1935                                            MachineNode->getValueType(0),
1936                                            MachineNode->getOperand(0).
1937                                              getOperand(0),
1938                                            MachineNode->getOperand(2),
1939                                            MachineNode->getOperand(1));
1940         break;
1941       case PPC::BC:
1942       case PPC::BCn:
1943         if (Op1Not)
1944           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
1945                                                                PPC::BC,
1946                                            SDLoc(MachineNode),
1947                                            MVT::Other,
1948                                            MachineNode->getOperand(0).
1949                                              getOperand(0),
1950                                            MachineNode->getOperand(1),
1951                                            MachineNode->getOperand(2));
1952         // FIXME: Handle Op1Set, Op1Unset here too.
1953         break;
1954       }
1955
1956       // If we're inverting this node because it is used only by selects that
1957       // we'd like to swap, then swap the selects before the node replacement.
1958       if (SelectSwap)
1959         SwapAllSelectUsers(MachineNode);
1960
1961       if (ResNode != MachineNode) {
1962         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1963         DEBUG(MachineNode->dump(CurDAG));
1964         DEBUG(dbgs() << "\nNew: ");
1965         DEBUG(ResNode->dump(CurDAG));
1966         DEBUG(dbgs() << "\n");
1967
1968         ReplaceUses(MachineNode, ResNode);
1969         IsModified = true;
1970       }
1971     }
1972     if (IsModified)
1973       CurDAG->RemoveDeadNodes();
1974   } while (IsModified);
1975 }
1976
1977 void PPCDAGToDAGISel::PeepholePPC64() {
1978   // These optimizations are currently supported only for 64-bit SVR4.
1979   if (PPCSubTarget.isDarwin() || !PPCSubTarget.isPPC64())
1980     return;
1981
1982   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
1983   ++Position;
1984
1985   while (Position != CurDAG->allnodes_begin()) {
1986     SDNode *N = --Position;
1987     // Skip dead nodes and any non-machine opcodes.
1988     if (N->use_empty() || !N->isMachineOpcode())
1989       continue;
1990
1991     unsigned FirstOp;
1992     unsigned StorageOpcode = N->getMachineOpcode();
1993
1994     switch (StorageOpcode) {
1995     default: continue;
1996
1997     case PPC::LBZ:
1998     case PPC::LBZ8:
1999     case PPC::LD:
2000     case PPC::LFD:
2001     case PPC::LFS:
2002     case PPC::LHA:
2003     case PPC::LHA8:
2004     case PPC::LHZ:
2005     case PPC::LHZ8:
2006     case PPC::LWA:
2007     case PPC::LWZ:
2008     case PPC::LWZ8:
2009       FirstOp = 0;
2010       break;
2011
2012     case PPC::STB:
2013     case PPC::STB8:
2014     case PPC::STD:
2015     case PPC::STFD:
2016     case PPC::STFS:
2017     case PPC::STH:
2018     case PPC::STH8:
2019     case PPC::STW:
2020     case PPC::STW8:
2021       FirstOp = 1;
2022       break;
2023     }
2024
2025     // If this is a load or store with a zero offset, we may be able to
2026     // fold an add-immediate into the memory operation.
2027     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
2028         N->getConstantOperandVal(FirstOp) != 0)
2029       continue;
2030
2031     SDValue Base = N->getOperand(FirstOp + 1);
2032     if (!Base.isMachineOpcode())
2033       continue;
2034
2035     unsigned Flags = 0;
2036     bool ReplaceFlags = true;
2037
2038     // When the feeding operation is an add-immediate of some sort,
2039     // determine whether we need to add relocation information to the
2040     // target flags on the immediate operand when we fold it into the
2041     // load instruction.
2042     //
2043     // For something like ADDItocL, the relocation information is
2044     // inferred from the opcode; when we process it in the AsmPrinter,
2045     // we add the necessary relocation there.  A load, though, can receive
2046     // relocation from various flavors of ADDIxxx, so we need to carry
2047     // the relocation information in the target flags.
2048     switch (Base.getMachineOpcode()) {
2049     default: continue;
2050
2051     case PPC::ADDI8:
2052     case PPC::ADDI:
2053       // In some cases (such as TLS) the relocation information
2054       // is already in place on the operand, so copying the operand
2055       // is sufficient.
2056       ReplaceFlags = false;
2057       // For these cases, the immediate may not be divisible by 4, in
2058       // which case the fold is illegal for DS-form instructions.  (The
2059       // other cases provide aligned addresses and are always safe.)
2060       if ((StorageOpcode == PPC::LWA ||
2061            StorageOpcode == PPC::LD  ||
2062            StorageOpcode == PPC::STD) &&
2063           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
2064            Base.getConstantOperandVal(1) % 4 != 0))
2065         continue;
2066       break;
2067     case PPC::ADDIdtprelL:
2068       Flags = PPCII::MO_DTPREL_LO;
2069       break;
2070     case PPC::ADDItlsldL:
2071       Flags = PPCII::MO_TLSLD_LO;
2072       break;
2073     case PPC::ADDItocL:
2074       Flags = PPCII::MO_TOC_LO;
2075       break;
2076     }
2077
2078     // We found an opportunity.  Reverse the operands from the add
2079     // immediate and substitute them into the load or store.  If
2080     // needed, update the target flags for the immediate operand to
2081     // reflect the necessary relocation information.
2082     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2083     DEBUG(Base->dump(CurDAG));
2084     DEBUG(dbgs() << "\nN: ");
2085     DEBUG(N->dump(CurDAG));
2086     DEBUG(dbgs() << "\n");
2087
2088     SDValue ImmOpnd = Base.getOperand(1);
2089
2090     // If the relocation information isn't already present on the
2091     // immediate operand, add it now.
2092     if (ReplaceFlags) {
2093       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
2094         SDLoc dl(GA);
2095         const GlobalValue *GV = GA->getGlobal();
2096         // We can't perform this optimization for data whose alignment
2097         // is insufficient for the instruction encoding.
2098         if (GV->getAlignment() < 4 &&
2099             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
2100              StorageOpcode == PPC::LWA)) {
2101           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
2102           continue;
2103         }
2104         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
2105       } else if (ConstantPoolSDNode *CP =
2106                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
2107         const Constant *C = CP->getConstVal();
2108         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
2109                                                 CP->getAlignment(),
2110                                                 0, Flags);
2111       }
2112     }
2113
2114     if (FirstOp == 1) // Store
2115       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
2116                                        Base.getOperand(0), N->getOperand(3));
2117     else // Load
2118       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
2119                                        N->getOperand(2));
2120
2121     // The add-immediate may now be dead, in which case remove it.
2122     if (Base.getNode()->use_empty())
2123       CurDAG->RemoveDeadNode(Base.getNode());
2124   }
2125 }
2126
2127
2128 /// createPPCISelDag - This pass converts a legalized DAG into a
2129 /// PowerPC-specific DAG, ready for instruction scheduling.
2130 ///
2131 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
2132   return new PPCDAGToDAGISel(TM);
2133 }
2134
2135 static void initializePassOnce(PassRegistry &Registry) {
2136   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
2137   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID, 0,
2138                               false, false);
2139   Registry.registerPass(*PI, true);
2140 }
2141
2142 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
2143   CALL_ONCE_INITIALIZATION(initializePassOnce);
2144 }
2145