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