Revert "Prevent alias from pointing to weak aliases."
[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::GPRC_NOR0RegClass);
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::G8RC_NOX0RegClass);
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 = PPCSubTarget.hasVSX() ? PPC::XSCMPUDP : 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                                 bool HasVSX) {
645   switch (CC) {
646     case ISD::SETEQ:
647     case ISD::SETUEQ:
648     case ISD::SETNE:
649     case ISD::SETUNE:
650       if (VecVT == MVT::v16i8)
651         return PPC::VCMPEQUB;
652       else if (VecVT == MVT::v8i16)
653         return PPC::VCMPEQUH;
654       else if (VecVT == MVT::v4i32)
655         return PPC::VCMPEQUW;
656       // v4f32 != v4f32 could be translate to unordered not equal
657       else if (VecVT == MVT::v4f32)
658         return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
659       else if (VecVT == MVT::v2f64)
660         return PPC::XVCMPEQDP;
661       break;
662     case ISD::SETLT:
663     case ISD::SETGT:
664     case ISD::SETLE:
665     case ISD::SETGE:
666       if (VecVT == MVT::v16i8)
667         return PPC::VCMPGTSB;
668       else if (VecVT == MVT::v8i16)
669         return PPC::VCMPGTSH;
670       else if (VecVT == MVT::v4i32)
671         return PPC::VCMPGTSW;
672       else if (VecVT == MVT::v4f32)
673         return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
674       else if (VecVT == MVT::v2f64)
675         return PPC::XVCMPGTDP;
676       break;
677     case ISD::SETULT:
678     case ISD::SETUGT:
679     case ISD::SETUGE:
680     case ISD::SETULE:
681       if (VecVT == MVT::v16i8)
682         return PPC::VCMPGTUB;
683       else if (VecVT == MVT::v8i16)
684         return PPC::VCMPGTUH;
685       else if (VecVT == MVT::v4i32)
686         return PPC::VCMPGTUW;
687       break;
688     case ISD::SETOEQ:
689       if (VecVT == MVT::v4f32)
690         return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
691       else if (VecVT == MVT::v2f64)
692         return PPC::XVCMPEQDP;
693       break;
694     case ISD::SETOLT:
695     case ISD::SETOGT:
696     case ISD::SETOLE:
697       if (VecVT == MVT::v4f32)
698         return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
699       else if (VecVT == MVT::v2f64)
700         return PPC::XVCMPGTDP;
701       break;
702     case ISD::SETOGE:
703       if (VecVT == MVT::v4f32)
704         return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
705       else if (VecVT == MVT::v2f64)
706         return PPC::XVCMPGEDP;
707       break;
708     default:
709       break;
710   }
711   llvm_unreachable("Invalid integer vector compare condition");
712 }
713
714 // getVCmpEQInst: return the equal compare instruction for the specified vector
715 // type. Since this is for altivec specific code, only support the altivec
716 // types (v16i8, v8i16, v4i32, and v4f32).
717 static unsigned int getVCmpEQInst(MVT::SimpleValueType VecVT, bool HasVSX) {
718   switch (VecVT) {
719     case MVT::v16i8:
720       return PPC::VCMPEQUB;
721     case MVT::v8i16:
722       return PPC::VCMPEQUH;
723     case MVT::v4i32:
724       return PPC::VCMPEQUW;
725     case MVT::v4f32:
726       return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
727     case MVT::v2f64:
728       return PPC::XVCMPEQDP;
729     default:
730       llvm_unreachable("Invalid integer vector compare condition");
731   }
732 }
733
734 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
735   SDLoc dl(N);
736   unsigned Imm;
737   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
738   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
739   bool isPPC64 = (PtrVT == MVT::i64);
740
741   if (!PPCSubTarget.useCRBits() &&
742       isInt32Immediate(N->getOperand(1), Imm)) {
743     // We can codegen setcc op, imm very efficiently compared to a brcond.
744     // Check for those cases here.
745     // setcc op, 0
746     if (Imm == 0) {
747       SDValue Op = N->getOperand(0);
748       switch (CC) {
749       default: break;
750       case ISD::SETEQ: {
751         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
752         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
753         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
754       }
755       case ISD::SETNE: {
756         if (isPPC64) break;
757         SDValue AD =
758           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
759                                          Op, getI32Imm(~0U)), 0);
760         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
761                                     AD.getValue(1));
762       }
763       case ISD::SETLT: {
764         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
765         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
766       }
767       case ISD::SETGT: {
768         SDValue T =
769           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
770         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
771         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
772         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
773       }
774       }
775     } else if (Imm == ~0U) {        // setcc op, -1
776       SDValue Op = N->getOperand(0);
777       switch (CC) {
778       default: break;
779       case ISD::SETEQ:
780         if (isPPC64) break;
781         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
782                                             Op, getI32Imm(1)), 0);
783         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
784                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
785                                                              MVT::i32,
786                                                              getI32Imm(0)), 0),
787                                       Op.getValue(1));
788       case ISD::SETNE: {
789         if (isPPC64) break;
790         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
791         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
792                                             Op, getI32Imm(~0U));
793         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
794                                     Op, SDValue(AD, 1));
795       }
796       case ISD::SETLT: {
797         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
798                                                     getI32Imm(1)), 0);
799         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
800                                                     Op), 0);
801         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
802         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
803       }
804       case ISD::SETGT: {
805         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
806         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
807                      0);
808         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
809                                     getI32Imm(1));
810       }
811       }
812     }
813   }
814
815   SDValue LHS = N->getOperand(0);
816   SDValue RHS = N->getOperand(1);
817
818   // Altivec Vector compare instructions do not set any CR register by default and
819   // vector compare operations return the same type as the operands.
820   if (LHS.getValueType().isVector()) {
821     EVT VecVT = LHS.getValueType();
822     MVT::SimpleValueType VT = VecVT.getSimpleVT().SimpleTy;
823     unsigned int VCmpInst = getVCmpInst(VT, CC, PPCSubTarget.hasVSX());
824
825     switch (CC) {
826       case ISD::SETEQ:
827       case ISD::SETOEQ:
828       case ISD::SETUEQ:
829         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
830       case ISD::SETNE:
831       case ISD::SETONE:
832       case ISD::SETUNE: {
833         SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
834         return CurDAG->SelectNodeTo(N, PPC::VNOR, VecVT, VCmp, VCmp);
835       } 
836       case ISD::SETLT:
837       case ISD::SETOLT:
838       case ISD::SETULT:
839         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, RHS, LHS);
840       case ISD::SETGT:
841       case ISD::SETOGT:
842       case ISD::SETUGT:
843         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
844       case ISD::SETGE:
845       case ISD::SETOGE:
846       case ISD::SETUGE: {
847         // Small optimization: Altivec provides a 'Vector Compare Greater Than
848         // or Equal To' instruction (vcmpgefp), so in this case there is no
849         // need for extra logic for the equal compare.
850         if (VecVT.getSimpleVT().isFloatingPoint()) {
851           return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
852         } else {
853           SDValue VCmpGT(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
854           unsigned int VCmpEQInst = getVCmpEQInst(VT, PPCSubTarget.hasVSX());
855           SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
856           return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpGT, VCmpEQ);
857         }
858       }
859       case ISD::SETLE:
860       case ISD::SETOLE:
861       case ISD::SETULE: {
862         SDValue VCmpLE(CurDAG->getMachineNode(VCmpInst, dl, VecVT, RHS, LHS), 0);
863         unsigned int VCmpEQInst = getVCmpEQInst(VT, PPCSubTarget.hasVSX());
864         SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
865         return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpLE, VCmpEQ);
866       }
867       default:
868         llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
869     }
870   }
871
872   if (PPCSubTarget.useCRBits())
873     return 0;
874
875   bool Inv;
876   unsigned Idx = getCRIdxForSetCC(CC, Inv);
877   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
878   SDValue IntCR;
879
880   // Force the ccreg into CR7.
881   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
882
883   SDValue InFlag(0, 0);  // Null incoming flag value.
884   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
885                                InFlag).getValue(1);
886
887   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
888                                          CCReg), 0);
889
890   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
891                       getI32Imm(31), getI32Imm(31) };
892   if (!Inv)
893     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
894
895   // Get the specified bit.
896   SDValue Tmp =
897     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
898   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
899 }
900
901
902 // Select - Convert the specified operand from a target-independent to a
903 // target-specific node if it hasn't already been changed.
904 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
905   SDLoc dl(N);
906   if (N->isMachineOpcode()) {
907     N->setNodeId(-1);
908     return NULL;   // Already selected.
909   }
910
911   switch (N->getOpcode()) {
912   default: break;
913
914   case ISD::Constant: {
915     if (N->getValueType(0) == MVT::i64) {
916       // Get 64 bit value.
917       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
918       // Assume no remaining bits.
919       unsigned Remainder = 0;
920       // Assume no shift required.
921       unsigned Shift = 0;
922
923       // If it can't be represented as a 32 bit value.
924       if (!isInt<32>(Imm)) {
925         Shift = countTrailingZeros<uint64_t>(Imm);
926         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
927
928         // If the shifted value fits 32 bits.
929         if (isInt<32>(ImmSh)) {
930           // Go with the shifted value.
931           Imm = ImmSh;
932         } else {
933           // Still stuck with a 64 bit value.
934           Remainder = Imm;
935           Shift = 32;
936           Imm >>= 32;
937         }
938       }
939
940       // Intermediate operand.
941       SDNode *Result;
942
943       // Handle first 32 bits.
944       unsigned Lo = Imm & 0xFFFF;
945       unsigned Hi = (Imm >> 16) & 0xFFFF;
946
947       // Simple value.
948       if (isInt<16>(Imm)) {
949        // Just the Lo bits.
950         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
951       } else if (Lo) {
952         // Handle the Hi bits.
953         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
954         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
955         // And Lo bits.
956         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
957                                         SDValue(Result, 0), getI32Imm(Lo));
958       } else {
959        // Just the Hi bits.
960         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
961       }
962
963       // If no shift, we're done.
964       if (!Shift) return Result;
965
966       // Shift for next step if the upper 32-bits were not zero.
967       if (Imm) {
968         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
969                                         SDValue(Result, 0),
970                                         getI32Imm(Shift),
971                                         getI32Imm(63 - Shift));
972       }
973
974       // Add in the last bits as required.
975       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
976         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
977                                         SDValue(Result, 0), getI32Imm(Hi));
978       }
979       if ((Lo = Remainder & 0xFFFF)) {
980         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
981                                         SDValue(Result, 0), getI32Imm(Lo));
982       }
983
984       return Result;
985     }
986     break;
987   }
988
989   case ISD::SETCC: {
990     SDNode *SN = SelectSETCC(N);
991     if (SN)
992       return SN;
993     break;
994   }
995   case PPCISD::GlobalBaseReg:
996     return getGlobalBaseReg();
997
998   case ISD::FrameIndex: {
999     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1000     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
1001     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
1002     if (N->hasOneUse())
1003       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
1004                                   getSmallIPtrImm(0));
1005     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
1006                                   getSmallIPtrImm(0));
1007   }
1008
1009   case PPCISD::MFOCRF: {
1010     SDValue InFlag = N->getOperand(1);
1011     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
1012                                   N->getOperand(0), InFlag);
1013   }
1014
1015   case ISD::SDIV: {
1016     // FIXME: since this depends on the setting of the carry flag from the srawi
1017     //        we should really be making notes about that for the scheduler.
1018     // FIXME: It sure would be nice if we could cheaply recognize the
1019     //        srl/add/sra pattern the dag combiner will generate for this as
1020     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1021     unsigned Imm;
1022     if (isInt32Immediate(N->getOperand(1), Imm)) {
1023       SDValue N0 = N->getOperand(0);
1024       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1025         SDNode *Op =
1026           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1027                                  N0, getI32Imm(Log2_32(Imm)));
1028         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1029                                     SDValue(Op, 0), SDValue(Op, 1));
1030       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1031         SDNode *Op =
1032           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1033                                  N0, getI32Imm(Log2_32(-Imm)));
1034         SDValue PT =
1035           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
1036                                          SDValue(Op, 0), SDValue(Op, 1)),
1037                     0);
1038         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1039       }
1040     }
1041
1042     // Other cases are autogenerated.
1043     break;
1044   }
1045
1046   case ISD::LOAD: {
1047     // Handle preincrement loads.
1048     LoadSDNode *LD = cast<LoadSDNode>(N);
1049     EVT LoadedVT = LD->getMemoryVT();
1050
1051     // Normal loads are handled by code generated from the .td file.
1052     if (LD->getAddressingMode() != ISD::PRE_INC)
1053       break;
1054
1055     SDValue Offset = LD->getOffset();
1056     if (Offset.getOpcode() == ISD::TargetConstant ||
1057         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1058
1059       unsigned Opcode;
1060       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1061       if (LD->getValueType(0) != MVT::i64) {
1062         // Handle PPC32 integer and normal FP loads.
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::f64: Opcode = PPC::LFDU; break;
1067           case MVT::f32: Opcode = PPC::LFSU; break;
1068           case MVT::i32: Opcode = PPC::LWZU; break;
1069           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1070           case MVT::i1:
1071           case MVT::i8:  Opcode = PPC::LBZU; break;
1072         }
1073       } else {
1074         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1075         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1076         switch (LoadedVT.getSimpleVT().SimpleTy) {
1077           default: llvm_unreachable("Invalid PPC load type!");
1078           case MVT::i64: Opcode = PPC::LDU; break;
1079           case MVT::i32: Opcode = PPC::LWZU8; break;
1080           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1081           case MVT::i1:
1082           case MVT::i8:  Opcode = PPC::LBZU8; break;
1083         }
1084       }
1085
1086       SDValue Chain = LD->getChain();
1087       SDValue Base = LD->getBasePtr();
1088       SDValue Ops[] = { Offset, Base, Chain };
1089       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1090                                     PPCLowering.getPointerTy(),
1091                                     MVT::Other, Ops);
1092     } else {
1093       unsigned Opcode;
1094       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1095       if (LD->getValueType(0) != MVT::i64) {
1096         // Handle PPC32 integer and normal FP loads.
1097         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1098         switch (LoadedVT.getSimpleVT().SimpleTy) {
1099           default: llvm_unreachable("Invalid PPC load type!");
1100           case MVT::f64: Opcode = PPC::LFDUX; break;
1101           case MVT::f32: Opcode = PPC::LFSUX; break;
1102           case MVT::i32: Opcode = PPC::LWZUX; break;
1103           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1104           case MVT::i1:
1105           case MVT::i8:  Opcode = PPC::LBZUX; break;
1106         }
1107       } else {
1108         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1109         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1110                "Invalid sext update load");
1111         switch (LoadedVT.getSimpleVT().SimpleTy) {
1112           default: llvm_unreachable("Invalid PPC load type!");
1113           case MVT::i64: Opcode = PPC::LDUX; break;
1114           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1115           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1116           case MVT::i1:
1117           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1118         }
1119       }
1120
1121       SDValue Chain = LD->getChain();
1122       SDValue Base = LD->getBasePtr();
1123       SDValue Ops[] = { Base, Offset, Chain };
1124       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1125                                     PPCLowering.getPointerTy(),
1126                                     MVT::Other, Ops);
1127     }
1128   }
1129
1130   case ISD::AND: {
1131     unsigned Imm, Imm2, SH, MB, ME;
1132     uint64_t Imm64;
1133
1134     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1135     // with a mask, emit rlwinm
1136     if (isInt32Immediate(N->getOperand(1), Imm) &&
1137         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1138       SDValue Val = N->getOperand(0).getOperand(0);
1139       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1140       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1141     }
1142     // If this is just a masked value where the input is not handled above, and
1143     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1144     if (isInt32Immediate(N->getOperand(1), Imm) &&
1145         isRunOfOnes(Imm, MB, ME) &&
1146         N->getOperand(0).getOpcode() != ISD::ROTL) {
1147       SDValue Val = N->getOperand(0);
1148       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1149       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1150     }
1151     // If this is a 64-bit zero-extension mask, emit rldicl.
1152     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1153         isMask_64(Imm64)) {
1154       SDValue Val = N->getOperand(0);
1155       MB = 64 - CountTrailingOnes_64(Imm64);
1156       SH = 0;
1157
1158       // If the operand is a logical right shift, we can fold it into this
1159       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
1160       // for n <= mb. The right shift is really a left rotate followed by a
1161       // mask, and this mask is a more-restrictive sub-mask of the mask implied
1162       // by the shift.
1163       if (Val.getOpcode() == ISD::SRL &&
1164           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
1165         assert(Imm < 64 && "Illegal shift amount");
1166         Val = Val.getOperand(0);
1167         SH = 64 - Imm;
1168       }
1169
1170       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
1171       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1172     }
1173     // AND X, 0 -> 0, not "rlwinm 32".
1174     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1175       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1176       return NULL;
1177     }
1178     // ISD::OR doesn't get all the bitfield insertion fun.
1179     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1180     if (isInt32Immediate(N->getOperand(1), Imm) &&
1181         N->getOperand(0).getOpcode() == ISD::OR &&
1182         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1183       unsigned MB, ME;
1184       Imm = ~(Imm^Imm2);
1185       if (isRunOfOnes(Imm, MB, ME)) {
1186         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1187                             N->getOperand(0).getOperand(1),
1188                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1189         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1190       }
1191     }
1192
1193     // Other cases are autogenerated.
1194     break;
1195   }
1196   case ISD::OR:
1197     if (N->getValueType(0) == MVT::i32)
1198       if (SDNode *I = SelectBitfieldInsert(N))
1199         return I;
1200
1201     // Other cases are autogenerated.
1202     break;
1203   case ISD::SHL: {
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   case ISD::SRL: {
1216     unsigned Imm, SH, MB, ME;
1217     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1218         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1219       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1220                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1221       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1222     }
1223
1224     // Other cases are autogenerated.
1225     break;
1226   }
1227   // FIXME: Remove this once the ANDI glue bug is fixed:
1228   case PPCISD::ANDIo_1_EQ_BIT:
1229   case PPCISD::ANDIo_1_GT_BIT: {
1230     if (!ANDIGlueBug)
1231       break;
1232
1233     EVT InVT = N->getOperand(0).getValueType();
1234     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
1235            "Invalid input type for ANDIo_1_EQ_BIT");
1236
1237     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
1238     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
1239                                         N->getOperand(0),
1240                                         CurDAG->getTargetConstant(1, InVT)), 0);
1241     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
1242     SDValue SRIdxVal =
1243       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
1244                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
1245
1246     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
1247                                 CR0Reg, SRIdxVal,
1248                                 SDValue(AndI.getNode(), 1) /* glue */);
1249   }
1250   case ISD::SELECT_CC: {
1251     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1252     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1253     bool isPPC64 = (PtrVT == MVT::i64);
1254
1255     // If this is a select of i1 operands, we'll pattern match it.
1256     if (PPCSubTarget.useCRBits() &&
1257         N->getOperand(0).getValueType() == MVT::i1)
1258       break;
1259
1260     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1261     if (!isPPC64)
1262       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1263         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1264           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1265             if (N1C->isNullValue() && N3C->isNullValue() &&
1266                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1267                 // FIXME: Implement this optzn for PPC64.
1268                 N->getValueType(0) == MVT::i32) {
1269               SDNode *Tmp =
1270                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1271                                        N->getOperand(0), getI32Imm(~0U));
1272               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1273                                           SDValue(Tmp, 0), N->getOperand(0),
1274                                           SDValue(Tmp, 1));
1275             }
1276
1277     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1278
1279     if (N->getValueType(0) == MVT::i1) {
1280       // An i1 select is: (c & t) | (!c & f).
1281       bool Inv;
1282       unsigned Idx = getCRIdxForSetCC(CC, Inv);
1283
1284       unsigned SRI;
1285       switch (Idx) {
1286       default: llvm_unreachable("Invalid CC index");
1287       case 0: SRI = PPC::sub_lt; break;
1288       case 1: SRI = PPC::sub_gt; break;
1289       case 2: SRI = PPC::sub_eq; break;
1290       case 3: SRI = PPC::sub_un; break;
1291       }
1292
1293       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
1294
1295       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
1296                                               CCBit, CCBit), 0);
1297       SDValue C =    Inv ? NotCCBit : CCBit,
1298               NotC = Inv ? CCBit    : NotCCBit;
1299
1300       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1301                                            C, N->getOperand(2)), 0);
1302       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1303                                               NotC, N->getOperand(3)), 0);
1304
1305       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
1306     }
1307
1308     unsigned BROpc = getPredicateForSetCC(CC);
1309
1310     unsigned SelectCCOp;
1311     if (N->getValueType(0) == MVT::i32)
1312       SelectCCOp = PPC::SELECT_CC_I4;
1313     else if (N->getValueType(0) == MVT::i64)
1314       SelectCCOp = PPC::SELECT_CC_I8;
1315     else if (N->getValueType(0) == MVT::f32)
1316       SelectCCOp = PPC::SELECT_CC_F4;
1317     else if (N->getValueType(0) == MVT::f64)
1318       SelectCCOp = PPC::SELECT_CC_F8;
1319     else
1320       SelectCCOp = PPC::SELECT_CC_VRRC;
1321
1322     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1323                         getI32Imm(BROpc) };
1324     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1325   }
1326   case PPCISD::BDNZ:
1327   case PPCISD::BDZ: {
1328     bool IsPPC64 = PPCSubTarget.isPPC64();
1329     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1330     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1331                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1332                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1333                                 MVT::Other, Ops, 2);
1334   }
1335   case PPCISD::COND_BRANCH: {
1336     // Op #0 is the Chain.
1337     // Op #1 is the PPC::PRED_* number.
1338     // Op #2 is the CR#
1339     // Op #3 is the Dest MBB
1340     // Op #4 is the Flag.
1341     // Prevent PPC::PRED_* from being selected into LI.
1342     SDValue Pred =
1343       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1344     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1345       N->getOperand(0), N->getOperand(4) };
1346     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1347   }
1348   case ISD::BR_CC: {
1349     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1350     unsigned PCC = getPredicateForSetCC(CC);
1351
1352     if (N->getOperand(2).getValueType() == MVT::i1) {
1353       unsigned Opc;
1354       bool Swap;
1355       switch (PCC) {
1356       default: llvm_unreachable("Unexpected Boolean-operand predicate");
1357       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
1358       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
1359       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
1360       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
1361       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
1362       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
1363       }
1364
1365       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
1366                                              N->getOperand(Swap ? 3 : 2),
1367                                              N->getOperand(Swap ? 2 : 3)), 0);
1368       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
1369                                   BitComp, N->getOperand(4), N->getOperand(0));
1370     }
1371
1372     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1373     SDValue Ops[] = { getI32Imm(PCC), CondCode,
1374                         N->getOperand(4), N->getOperand(0) };
1375     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1376   }
1377   case ISD::BRIND: {
1378     // FIXME: Should custom lower this.
1379     SDValue Chain = N->getOperand(0);
1380     SDValue Target = N->getOperand(1);
1381     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1382     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1383     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1384                                            Chain), 0);
1385     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1386   }
1387   case PPCISD::TOC_ENTRY: {
1388     assert (PPCSubTarget.isPPC64() && "Only supported for 64-bit ABI");
1389
1390     // For medium and large code model, we generate two instructions as
1391     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1392     // selecting one of LDtoc, LDtocJTI, and LDtocCPT.
1393     CodeModel::Model CModel = TM.getCodeModel();
1394     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1395       break;
1396
1397     // The first source operand is a TargetGlobalAddress or a
1398     // TargetJumpTable.  If it is an externally defined symbol, a symbol
1399     // with common linkage, a function address, or a jump table address,
1400     // or if we are generating code for large code model, we generate:
1401     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1402     // Otherwise we generate:
1403     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1404     SDValue GA = N->getOperand(0);
1405     SDValue TOCbase = N->getOperand(1);
1406     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1407                                         TOCbase, GA);
1408
1409     if (isa<JumpTableSDNode>(GA) || CModel == CodeModel::Large)
1410       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1411                                     SDValue(Tmp, 0));
1412
1413     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1414       const GlobalValue *GValue = G->getGlobal();
1415       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
1416       const GlobalValue *RealGValue = GAlias ?
1417         GAlias->resolveAliasedGlobal(false) : GValue;
1418       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
1419       assert((GVar || isa<Function>(RealGValue)) &&
1420              "Unexpected global value subclass!");
1421
1422       // An external variable is one without an initializer.  For these,
1423       // for variables with common linkage, and for Functions, generate
1424       // the LDtocL form.
1425       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
1426           RealGValue->hasAvailableExternallyLinkage())
1427         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1428                                       SDValue(Tmp, 0));
1429     }
1430
1431     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1432                                   SDValue(Tmp, 0), GA);
1433   }
1434   case PPCISD::VADD_SPLAT: {
1435     // This expands into one of three sequences, depending on whether
1436     // the first operand is odd or even, positive or negative.
1437     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1438            isa<ConstantSDNode>(N->getOperand(1)) &&
1439            "Invalid operand on VADD_SPLAT!");
1440
1441     int Elt     = N->getConstantOperandVal(0);
1442     int EltSize = N->getConstantOperandVal(1);
1443     unsigned Opc1, Opc2, Opc3;
1444     EVT VT;
1445
1446     if (EltSize == 1) {
1447       Opc1 = PPC::VSPLTISB;
1448       Opc2 = PPC::VADDUBM;
1449       Opc3 = PPC::VSUBUBM;
1450       VT = MVT::v16i8;
1451     } else if (EltSize == 2) {
1452       Opc1 = PPC::VSPLTISH;
1453       Opc2 = PPC::VADDUHM;
1454       Opc3 = PPC::VSUBUHM;
1455       VT = MVT::v8i16;
1456     } else {
1457       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1458       Opc1 = PPC::VSPLTISW;
1459       Opc2 = PPC::VADDUWM;
1460       Opc3 = PPC::VSUBUWM;
1461       VT = MVT::v4i32;
1462     }
1463
1464     if ((Elt & 1) == 0) {
1465       // Elt is even, in the range [-32,-18] + [16,30].
1466       //
1467       // Convert: VADD_SPLAT elt, size
1468       // Into:    tmp = VSPLTIS[BHW] elt
1469       //          VADDU[BHW]M tmp, tmp
1470       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1471       SDValue EltVal = getI32Imm(Elt >> 1);
1472       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1473       SDValue TmpVal = SDValue(Tmp, 0);
1474       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1475
1476     } else if (Elt > 0) {
1477       // Elt is odd and positive, in the range [17,31].
1478       //
1479       // Convert: VADD_SPLAT elt, size
1480       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1481       //          tmp2 = VSPLTIS[BHW] -16
1482       //          VSUBU[BHW]M tmp1, tmp2
1483       SDValue EltVal = getI32Imm(Elt - 16);
1484       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1485       EltVal = getI32Imm(-16);
1486       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1487       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1488                                     SDValue(Tmp2, 0));
1489
1490     } else {
1491       // Elt is odd and negative, in the range [-31,-17].
1492       //
1493       // Convert: VADD_SPLAT elt, size
1494       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1495       //          tmp2 = VSPLTIS[BHW] -16
1496       //          VADDU[BHW]M tmp1, tmp2
1497       SDValue EltVal = getI32Imm(Elt + 16);
1498       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1499       EltVal = getI32Imm(-16);
1500       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1501       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1502                                     SDValue(Tmp2, 0));
1503     }
1504   }
1505   }
1506
1507   return SelectCode(N);
1508 }
1509
1510 /// PostprocessISelDAG - Perform some late peephole optimizations
1511 /// on the DAG representation.
1512 void PPCDAGToDAGISel::PostprocessISelDAG() {
1513
1514   // Skip peepholes at -O0.
1515   if (TM.getOptLevel() == CodeGenOpt::None)
1516     return;
1517
1518   PeepholePPC64();
1519   PeepholdCROps();
1520 }
1521
1522 // Check if all users of this node will become isel where the second operand
1523 // is the constant zero. If this is so, and if we can negate the condition,
1524 // then we can flip the true and false operands. This will allow the zero to
1525 // be folded with the isel so that we don't need to materialize a register
1526 // containing zero.
1527 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
1528   // If we're not using isel, then this does not matter.
1529   if (!PPCSubTarget.hasISEL())
1530     return false;
1531
1532   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1533        UI != UE; ++UI) {
1534     SDNode *User = *UI;
1535     if (!User->isMachineOpcode())
1536       return false;
1537     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
1538         User->getMachineOpcode() != PPC::SELECT_I8)
1539       return false;
1540
1541     SDNode *Op2 = User->getOperand(2).getNode();
1542     if (!Op2->isMachineOpcode())
1543       return false;
1544
1545     if (Op2->getMachineOpcode() != PPC::LI &&
1546         Op2->getMachineOpcode() != PPC::LI8)
1547       return false;
1548
1549     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
1550     if (!C)
1551       return false;
1552
1553     if (!C->isNullValue())
1554       return false;
1555   }
1556
1557   return true;
1558 }
1559
1560 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
1561   SmallVector<SDNode *, 4> ToReplace;
1562   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1563        UI != UE; ++UI) {
1564     SDNode *User = *UI;
1565     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
1566             User->getMachineOpcode() == PPC::SELECT_I8) &&
1567            "Must have all select users");
1568     ToReplace.push_back(User);
1569   }
1570
1571   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
1572        UE = ToReplace.end(); UI != UE; ++UI) {
1573     SDNode *User = *UI;
1574     SDNode *ResNode =
1575       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
1576                              User->getValueType(0), User->getOperand(0),
1577                              User->getOperand(2),
1578                              User->getOperand(1));
1579
1580       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1581       DEBUG(User->dump(CurDAG));
1582       DEBUG(dbgs() << "\nNew: ");
1583       DEBUG(ResNode->dump(CurDAG));
1584       DEBUG(dbgs() << "\n");
1585
1586       ReplaceUses(User, ResNode);
1587   }
1588 }
1589
1590 void PPCDAGToDAGISel::PeepholdCROps() {
1591   bool IsModified;
1592   do {
1593     IsModified = false;
1594     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1595          E = CurDAG->allnodes_end(); I != E; ++I) {
1596       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1597       if (!MachineNode || MachineNode->use_empty())
1598         continue;
1599       SDNode *ResNode = MachineNode;
1600
1601       bool Op1Set   = false, Op1Unset = false,
1602            Op1Not   = false,
1603            Op2Set   = false, Op2Unset = false,
1604            Op2Not   = false;
1605
1606       unsigned Opcode = MachineNode->getMachineOpcode();
1607       switch (Opcode) {
1608       default: break;
1609       case PPC::CRAND:
1610       case PPC::CRNAND:
1611       case PPC::CROR:
1612       case PPC::CRXOR:
1613       case PPC::CRNOR:
1614       case PPC::CREQV:
1615       case PPC::CRANDC:
1616       case PPC::CRORC: {
1617         SDValue Op = MachineNode->getOperand(1);
1618         if (Op.isMachineOpcode()) {
1619           if (Op.getMachineOpcode() == PPC::CRSET)
1620             Op2Set = true;
1621           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1622             Op2Unset = true;
1623           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1624                    Op.getOperand(0) == Op.getOperand(1))
1625             Op2Not = true;
1626         }
1627         }  // fallthrough
1628       case PPC::BC:
1629       case PPC::BCn:
1630       case PPC::SELECT_I4:
1631       case PPC::SELECT_I8:
1632       case PPC::SELECT_F4:
1633       case PPC::SELECT_F8:
1634       case PPC::SELECT_VRRC: {
1635         SDValue Op = MachineNode->getOperand(0);
1636         if (Op.isMachineOpcode()) {
1637           if (Op.getMachineOpcode() == PPC::CRSET)
1638             Op1Set = true;
1639           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1640             Op1Unset = true;
1641           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1642                    Op.getOperand(0) == Op.getOperand(1))
1643             Op1Not = true;
1644         }
1645         }
1646         break;
1647       }
1648
1649       bool SelectSwap = false;
1650       switch (Opcode) {
1651       default: break;
1652       case PPC::CRAND:
1653         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1654           // x & x = x
1655           ResNode = MachineNode->getOperand(0).getNode();
1656         else if (Op1Set)
1657           // 1 & y = y
1658           ResNode = MachineNode->getOperand(1).getNode();
1659         else if (Op2Set)
1660           // x & 1 = x
1661           ResNode = MachineNode->getOperand(0).getNode();
1662         else if (Op1Unset || Op2Unset)
1663           // x & 0 = 0 & y = 0
1664           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1665                                            MVT::i1);
1666         else if (Op1Not)
1667           // ~x & y = andc(y, x)
1668           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1669                                            MVT::i1, MachineNode->getOperand(1),
1670                                            MachineNode->getOperand(0).
1671                                              getOperand(0));
1672         else if (Op2Not)
1673           // x & ~y = andc(x, y)
1674           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1675                                            MVT::i1, MachineNode->getOperand(0),
1676                                            MachineNode->getOperand(1).
1677                                              getOperand(0));
1678         else if (AllUsersSelectZero(MachineNode))
1679           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1680                                            MVT::i1, MachineNode->getOperand(0),
1681                                            MachineNode->getOperand(1)),
1682           SelectSwap = true;
1683         break;
1684       case PPC::CRNAND:
1685         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1686           // nand(x, x) -> nor(x, x)
1687           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1688                                            MVT::i1, MachineNode->getOperand(0),
1689                                            MachineNode->getOperand(0));
1690         else if (Op1Set)
1691           // nand(1, y) -> nor(y, y)
1692           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1693                                            MVT::i1, MachineNode->getOperand(1),
1694                                            MachineNode->getOperand(1));
1695         else if (Op2Set)
1696           // nand(x, 1) -> nor(x, x)
1697           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1698                                            MVT::i1, MachineNode->getOperand(0),
1699                                            MachineNode->getOperand(0));
1700         else if (Op1Unset || Op2Unset)
1701           // nand(x, 0) = nand(0, y) = 1
1702           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1703                                            MVT::i1);
1704         else if (Op1Not)
1705           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
1706           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1707                                            MVT::i1, MachineNode->getOperand(0).
1708                                                       getOperand(0),
1709                                            MachineNode->getOperand(1));
1710         else if (Op2Not)
1711           // nand(x, ~y) = ~x | y = orc(y, x)
1712           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1713                                            MVT::i1, MachineNode->getOperand(1).
1714                                                       getOperand(0),
1715                                            MachineNode->getOperand(0));
1716         else if (AllUsersSelectZero(MachineNode))
1717           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1718                                            MVT::i1, MachineNode->getOperand(0),
1719                                            MachineNode->getOperand(1)),
1720           SelectSwap = true;
1721         break;
1722       case PPC::CROR:
1723         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1724           // x | x = x
1725           ResNode = MachineNode->getOperand(0).getNode();
1726         else if (Op1Set || Op2Set)
1727           // x | 1 = 1 | y = 1
1728           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1729                                            MVT::i1);
1730         else if (Op1Unset)
1731           // 0 | y = y
1732           ResNode = MachineNode->getOperand(1).getNode();
1733         else if (Op2Unset)
1734           // x | 0 = x
1735           ResNode = MachineNode->getOperand(0).getNode();
1736         else if (Op1Not)
1737           // ~x | y = orc(y, x)
1738           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1739                                            MVT::i1, MachineNode->getOperand(1),
1740                                            MachineNode->getOperand(0).
1741                                              getOperand(0));
1742         else if (Op2Not)
1743           // x | ~y = orc(x, y)
1744           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1745                                            MVT::i1, MachineNode->getOperand(0),
1746                                            MachineNode->getOperand(1).
1747                                              getOperand(0));
1748         else if (AllUsersSelectZero(MachineNode))
1749           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1750                                            MVT::i1, MachineNode->getOperand(0),
1751                                            MachineNode->getOperand(1)),
1752           SelectSwap = true;
1753         break;
1754       case PPC::CRXOR:
1755         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1756           // xor(x, x) = 0
1757           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1758                                            MVT::i1);
1759         else if (Op1Set)
1760           // xor(1, y) -> nor(y, y)
1761           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1762                                            MVT::i1, MachineNode->getOperand(1),
1763                                            MachineNode->getOperand(1));
1764         else if (Op2Set)
1765           // xor(x, 1) -> nor(x, x)
1766           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1767                                            MVT::i1, MachineNode->getOperand(0),
1768                                            MachineNode->getOperand(0));
1769         else if (Op1Unset)
1770           // xor(0, y) = y
1771           ResNode = MachineNode->getOperand(1).getNode();
1772         else if (Op2Unset)
1773           // xor(x, 0) = x
1774           ResNode = MachineNode->getOperand(0).getNode();
1775         else if (Op1Not)
1776           // xor(~x, y) = eqv(x, y)
1777           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1778                                            MVT::i1, MachineNode->getOperand(0).
1779                                                       getOperand(0),
1780                                            MachineNode->getOperand(1));
1781         else if (Op2Not)
1782           // xor(x, ~y) = eqv(x, y)
1783           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1784                                            MVT::i1, MachineNode->getOperand(0),
1785                                            MachineNode->getOperand(1).
1786                                              getOperand(0));
1787         else if (AllUsersSelectZero(MachineNode))
1788           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1789                                            MVT::i1, MachineNode->getOperand(0),
1790                                            MachineNode->getOperand(1)),
1791           SelectSwap = true;
1792         break;
1793       case PPC::CRNOR:
1794         if (Op1Set || Op2Set)
1795           // nor(1, y) -> 0
1796           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1797                                            MVT::i1);
1798         else if (Op1Unset)
1799           // nor(0, y) = ~y -> nor(y, y)
1800           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1801                                            MVT::i1, MachineNode->getOperand(1),
1802                                            MachineNode->getOperand(1));
1803         else if (Op2Unset)
1804           // nor(x, 0) = ~x
1805           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1806                                            MVT::i1, MachineNode->getOperand(0),
1807                                            MachineNode->getOperand(0));
1808         else if (Op1Not)
1809           // nor(~x, y) = andc(x, y)
1810           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1811                                            MVT::i1, MachineNode->getOperand(0).
1812                                                       getOperand(0),
1813                                            MachineNode->getOperand(1));
1814         else if (Op2Not)
1815           // nor(x, ~y) = andc(y, x)
1816           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1817                                            MVT::i1, MachineNode->getOperand(1).
1818                                                       getOperand(0),
1819                                            MachineNode->getOperand(0));
1820         else if (AllUsersSelectZero(MachineNode))
1821           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1822                                            MVT::i1, MachineNode->getOperand(0),
1823                                            MachineNode->getOperand(1)),
1824           SelectSwap = true;
1825         break;
1826       case PPC::CREQV:
1827         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1828           // eqv(x, x) = 1
1829           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1830                                            MVT::i1);
1831         else if (Op1Set)
1832           // eqv(1, y) = y
1833           ResNode = MachineNode->getOperand(1).getNode();
1834         else if (Op2Set)
1835           // eqv(x, 1) = x
1836           ResNode = MachineNode->getOperand(0).getNode();
1837         else if (Op1Unset)
1838           // eqv(0, y) = ~y -> nor(y, y)
1839           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1840                                            MVT::i1, MachineNode->getOperand(1),
1841                                            MachineNode->getOperand(1));
1842         else if (Op2Unset)
1843           // eqv(x, 0) = ~x
1844           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1845                                            MVT::i1, MachineNode->getOperand(0),
1846                                            MachineNode->getOperand(0));
1847         else if (Op1Not)
1848           // eqv(~x, y) = xor(x, y)
1849           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1850                                            MVT::i1, MachineNode->getOperand(0).
1851                                                       getOperand(0),
1852                                            MachineNode->getOperand(1));
1853         else if (Op2Not)
1854           // eqv(x, ~y) = xor(x, y)
1855           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1856                                            MVT::i1, MachineNode->getOperand(0),
1857                                            MachineNode->getOperand(1).
1858                                              getOperand(0));
1859         else if (AllUsersSelectZero(MachineNode))
1860           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1861                                            MVT::i1, MachineNode->getOperand(0),
1862                                            MachineNode->getOperand(1)),
1863           SelectSwap = true;
1864         break;
1865       case PPC::CRANDC:
1866         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1867           // andc(x, x) = 0
1868           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1869                                            MVT::i1);
1870         else if (Op1Set)
1871           // andc(1, y) = ~y
1872           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1873                                            MVT::i1, MachineNode->getOperand(1),
1874                                            MachineNode->getOperand(1));
1875         else if (Op1Unset || Op2Set)
1876           // andc(0, y) = andc(x, 1) = 0
1877           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1878                                            MVT::i1);
1879         else if (Op2Unset)
1880           // andc(x, 0) = x
1881           ResNode = MachineNode->getOperand(0).getNode();
1882         else if (Op1Not)
1883           // andc(~x, y) = ~(x | y) = nor(x, y)
1884           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1885                                            MVT::i1, MachineNode->getOperand(0).
1886                                                       getOperand(0),
1887                                            MachineNode->getOperand(1));
1888         else if (Op2Not)
1889           // andc(x, ~y) = x & y
1890           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1891                                            MVT::i1, MachineNode->getOperand(0),
1892                                            MachineNode->getOperand(1).
1893                                              getOperand(0));
1894         else if (AllUsersSelectZero(MachineNode))
1895           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1896                                            MVT::i1, MachineNode->getOperand(1),
1897                                            MachineNode->getOperand(0)),
1898           SelectSwap = true;
1899         break;
1900       case PPC::CRORC:
1901         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1902           // orc(x, x) = 1
1903           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1904                                            MVT::i1);
1905         else if (Op1Set || Op2Unset)
1906           // orc(1, y) = orc(x, 0) = 1
1907           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1908                                            MVT::i1);
1909         else if (Op2Set)
1910           // orc(x, 1) = x
1911           ResNode = MachineNode->getOperand(0).getNode();
1912         else if (Op1Unset)
1913           // orc(0, y) = ~y
1914           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1915                                            MVT::i1, MachineNode->getOperand(1),
1916                                            MachineNode->getOperand(1));
1917         else if (Op1Not)
1918           // orc(~x, y) = ~(x & y) = nand(x, y)
1919           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1920                                            MVT::i1, MachineNode->getOperand(0).
1921                                                       getOperand(0),
1922                                            MachineNode->getOperand(1));
1923         else if (Op2Not)
1924           // orc(x, ~y) = x | y
1925           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1926                                            MVT::i1, MachineNode->getOperand(0),
1927                                            MachineNode->getOperand(1).
1928                                              getOperand(0));
1929         else if (AllUsersSelectZero(MachineNode))
1930           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1931                                            MVT::i1, MachineNode->getOperand(1),
1932                                            MachineNode->getOperand(0)),
1933           SelectSwap = true;
1934         break;
1935       case PPC::SELECT_I4:
1936       case PPC::SELECT_I8:
1937       case PPC::SELECT_F4:
1938       case PPC::SELECT_F8:
1939       case PPC::SELECT_VRRC:
1940         if (Op1Set)
1941           ResNode = MachineNode->getOperand(1).getNode();
1942         else if (Op1Unset)
1943           ResNode = MachineNode->getOperand(2).getNode();
1944         else if (Op1Not)
1945           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
1946                                            SDLoc(MachineNode),
1947                                            MachineNode->getValueType(0),
1948                                            MachineNode->getOperand(0).
1949                                              getOperand(0),
1950                                            MachineNode->getOperand(2),
1951                                            MachineNode->getOperand(1));
1952         break;
1953       case PPC::BC:
1954       case PPC::BCn:
1955         if (Op1Not)
1956           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
1957                                                                PPC::BC,
1958                                            SDLoc(MachineNode),
1959                                            MVT::Other,
1960                                            MachineNode->getOperand(0).
1961                                              getOperand(0),
1962                                            MachineNode->getOperand(1),
1963                                            MachineNode->getOperand(2));
1964         // FIXME: Handle Op1Set, Op1Unset here too.
1965         break;
1966       }
1967
1968       // If we're inverting this node because it is used only by selects that
1969       // we'd like to swap, then swap the selects before the node replacement.
1970       if (SelectSwap)
1971         SwapAllSelectUsers(MachineNode);
1972
1973       if (ResNode != MachineNode) {
1974         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1975         DEBUG(MachineNode->dump(CurDAG));
1976         DEBUG(dbgs() << "\nNew: ");
1977         DEBUG(ResNode->dump(CurDAG));
1978         DEBUG(dbgs() << "\n");
1979
1980         ReplaceUses(MachineNode, ResNode);
1981         IsModified = true;
1982       }
1983     }
1984     if (IsModified)
1985       CurDAG->RemoveDeadNodes();
1986   } while (IsModified);
1987 }
1988
1989 void PPCDAGToDAGISel::PeepholePPC64() {
1990   // These optimizations are currently supported only for 64-bit SVR4.
1991   if (PPCSubTarget.isDarwin() || !PPCSubTarget.isPPC64())
1992     return;
1993
1994   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
1995   ++Position;
1996
1997   while (Position != CurDAG->allnodes_begin()) {
1998     SDNode *N = --Position;
1999     // Skip dead nodes and any non-machine opcodes.
2000     if (N->use_empty() || !N->isMachineOpcode())
2001       continue;
2002
2003     unsigned FirstOp;
2004     unsigned StorageOpcode = N->getMachineOpcode();
2005
2006     switch (StorageOpcode) {
2007     default: continue;
2008
2009     case PPC::LBZ:
2010     case PPC::LBZ8:
2011     case PPC::LD:
2012     case PPC::LFD:
2013     case PPC::LFS:
2014     case PPC::LHA:
2015     case PPC::LHA8:
2016     case PPC::LHZ:
2017     case PPC::LHZ8:
2018     case PPC::LWA:
2019     case PPC::LWZ:
2020     case PPC::LWZ8:
2021       FirstOp = 0;
2022       break;
2023
2024     case PPC::STB:
2025     case PPC::STB8:
2026     case PPC::STD:
2027     case PPC::STFD:
2028     case PPC::STFS:
2029     case PPC::STH:
2030     case PPC::STH8:
2031     case PPC::STW:
2032     case PPC::STW8:
2033       FirstOp = 1;
2034       break;
2035     }
2036
2037     // If this is a load or store with a zero offset, we may be able to
2038     // fold an add-immediate into the memory operation.
2039     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
2040         N->getConstantOperandVal(FirstOp) != 0)
2041       continue;
2042
2043     SDValue Base = N->getOperand(FirstOp + 1);
2044     if (!Base.isMachineOpcode())
2045       continue;
2046
2047     unsigned Flags = 0;
2048     bool ReplaceFlags = true;
2049
2050     // When the feeding operation is an add-immediate of some sort,
2051     // determine whether we need to add relocation information to the
2052     // target flags on the immediate operand when we fold it into the
2053     // load instruction.
2054     //
2055     // For something like ADDItocL, the relocation information is
2056     // inferred from the opcode; when we process it in the AsmPrinter,
2057     // we add the necessary relocation there.  A load, though, can receive
2058     // relocation from various flavors of ADDIxxx, so we need to carry
2059     // the relocation information in the target flags.
2060     switch (Base.getMachineOpcode()) {
2061     default: continue;
2062
2063     case PPC::ADDI8:
2064     case PPC::ADDI:
2065       // In some cases (such as TLS) the relocation information
2066       // is already in place on the operand, so copying the operand
2067       // is sufficient.
2068       ReplaceFlags = false;
2069       // For these cases, the immediate may not be divisible by 4, in
2070       // which case the fold is illegal for DS-form instructions.  (The
2071       // other cases provide aligned addresses and are always safe.)
2072       if ((StorageOpcode == PPC::LWA ||
2073            StorageOpcode == PPC::LD  ||
2074            StorageOpcode == PPC::STD) &&
2075           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
2076            Base.getConstantOperandVal(1) % 4 != 0))
2077         continue;
2078       break;
2079     case PPC::ADDIdtprelL:
2080       Flags = PPCII::MO_DTPREL_LO;
2081       break;
2082     case PPC::ADDItlsldL:
2083       Flags = PPCII::MO_TLSLD_LO;
2084       break;
2085     case PPC::ADDItocL:
2086       Flags = PPCII::MO_TOC_LO;
2087       break;
2088     }
2089
2090     // We found an opportunity.  Reverse the operands from the add
2091     // immediate and substitute them into the load or store.  If
2092     // needed, update the target flags for the immediate operand to
2093     // reflect the necessary relocation information.
2094     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2095     DEBUG(Base->dump(CurDAG));
2096     DEBUG(dbgs() << "\nN: ");
2097     DEBUG(N->dump(CurDAG));
2098     DEBUG(dbgs() << "\n");
2099
2100     SDValue ImmOpnd = Base.getOperand(1);
2101
2102     // If the relocation information isn't already present on the
2103     // immediate operand, add it now.
2104     if (ReplaceFlags) {
2105       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
2106         SDLoc dl(GA);
2107         const GlobalValue *GV = GA->getGlobal();
2108         // We can't perform this optimization for data whose alignment
2109         // is insufficient for the instruction encoding.
2110         if (GV->getAlignment() < 4 &&
2111             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
2112              StorageOpcode == PPC::LWA)) {
2113           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
2114           continue;
2115         }
2116         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
2117       } else if (ConstantPoolSDNode *CP =
2118                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
2119         const Constant *C = CP->getConstVal();
2120         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
2121                                                 CP->getAlignment(),
2122                                                 0, Flags);
2123       }
2124     }
2125
2126     if (FirstOp == 1) // Store
2127       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
2128                                        Base.getOperand(0), N->getOperand(3));
2129     else // Load
2130       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
2131                                        N->getOperand(2));
2132
2133     // The add-immediate may now be dead, in which case remove it.
2134     if (Base.getNode()->use_empty())
2135       CurDAG->RemoveDeadNode(Base.getNode());
2136   }
2137 }
2138
2139
2140 /// createPPCISelDag - This pass converts a legalized DAG into a
2141 /// PowerPC-specific DAG, ready for instruction scheduling.
2142 ///
2143 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
2144   return new PPCDAGToDAGISel(TM);
2145 }
2146
2147 static void initializePassOnce(PassRegistry &Registry) {
2148   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
2149   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID, 0,
2150                               false, false);
2151   Registry.registerPass(*PI, true);
2152 }
2153
2154 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
2155   CALL_ONCE_INITIALIZATION(initializePassOnce);
2156 }
2157