1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define DEBUG_TYPE "ppc-codegen"
16 #include "PPC.h"
17 #include "MCTargetDesc/PPCPredicates.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37 
38 namespace llvm {
39   void initializePPCDAGToDAGISelPass(PassRegistry&);
40 }
41 
42 namespace {
43   //===--------------------------------------------------------------------===//
44   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
45   /// instructions for SelectionDAG operations.
46   ///
47   class PPCDAGToDAGISel : public SelectionDAGISel {
48     const PPCTargetMachine &TM;
49     const PPCTargetLowering &PPCLowering;
50     const PPCSubtarget &PPCSubTarget;
51     unsigned GlobalBaseReg;
52   public:
53     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
54       : SelectionDAGISel(tm), TM(tm),
55         PPCLowering(*TM.getTargetLowering()),
56         PPCSubTarget(*TM.getSubtargetImpl()) {
57       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
58     }
59 
60     virtual bool runOnMachineFunction(MachineFunction &MF) {
61       // Make sure we re-emit a set of the global base reg if necessary
62       GlobalBaseReg = 0;
63       SelectionDAGISel::runOnMachineFunction(MF);
64 
65       if (!PPCSubTarget.isSVR4ABI())
66         InsertVRSaveCode(MF);
67 
68       return true;
69     }
70 
71     virtual void PostprocessISelDAG();
72 
73     /// getI32Imm - Return a target constant with the specified value, of type
74     /// i32.
75     inline SDValue getI32Imm(unsigned Imm) {
76       return CurDAG->getTargetConstant(Imm, MVT::i32);
77     }
78 
79     /// getI64Imm - Return a target constant with the specified value, of type
80     /// i64.
81     inline SDValue getI64Imm(uint64_t Imm) {
82       return CurDAG->getTargetConstant(Imm, MVT::i64);
83     }
84 
85     /// getSmallIPtrImm - Return a target constant of pointer type.
86     inline SDValue getSmallIPtrImm(unsigned Imm) {
87       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
88     }
89 
90     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
91     /// with any number of 0s on either side.  The 1s are allowed to wrap from
92     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
93     /// 0x0F0F0000 is not, since all 1s are not contiguous.
94     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
95 
96 
97     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
98     /// rotate and mask opcode and mask operation.
99     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
100                                 unsigned &SH, unsigned &MB, unsigned &ME);
101 
102     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
103     /// base register.  Return the virtual register that holds this value.
104     SDNode *getGlobalBaseReg();
105 
106     // Select - Convert the specified operand from a target-independent to a
107     // target-specific node if it hasn't already been changed.
108     SDNode *Select(SDNode *N);
109 
110     SDNode *SelectBitfieldInsert(SDNode *N);
111 
112     /// SelectCC - Select a comparison of the specified values with the
113     /// specified condition code, returning the CR# of the expression.
114     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
115 
116     /// SelectAddrImm - Returns true if the address N can be represented by
117     /// a base register plus a signed 16-bit displacement [r+imm].
118     bool SelectAddrImm(SDValue N, SDValue &Disp,
119                        SDValue &Base) {
120       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
121     }
122 
123     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
124     /// immediate field.  Note that the operand at this point is already the
125     /// result of a prior SelectAddressRegImm call.
126     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
127       if (N.getOpcode() == ISD::TargetConstant ||
128           N.getOpcode() == ISD::TargetGlobalAddress) {
129         Out = N;
130         return true;
131       }
132 
133       return false;
134     }
135 
136     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
137     /// represented as an indexed [r+r] operation.  Returns false if it can
138     /// be represented by [r+imm], which are preferred.
139     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
140       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
141     }
142 
143     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
144     /// represented as an indexed [r+r] operation.
145     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
146       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
147     }
148 
149     /// SelectAddrImmX4 - Returns true if the address N can be represented by
150     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
151     /// Suitable for use by STD and friends.
152     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
153       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
154     }
155 
156     // Select an address into a single register.
157     bool SelectAddr(SDValue N, SDValue &Base) {
158       Base = N;
159       return true;
160     }
161 
162     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
163     /// inline asm expressions.  It is always correct to compute the value into
164     /// a register.  The case of adding a (possibly relocatable) constant to a
165     /// register can be improved, but it is wrong to substitute Reg+Reg for
166     /// Reg in an asm, because the load or store opcode would have to change.
167    virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
168                                               char ConstraintCode,
169                                               std::vector<SDValue> &OutOps) {
170       OutOps.push_back(Op);
171       return false;
172     }
173 
174     void InsertVRSaveCode(MachineFunction &MF);
175 
176     virtual const char *getPassName() const {
177       return "PowerPC DAG->DAG Pattern Instruction Selection";
178     }
179 
180 // Include the pieces autogenerated from the target description.
181 #include "PPCGenDAGISel.inc"
182 
183 private:
184     SDNode *SelectSETCC(SDNode *N);
185   };
186 }
187 
188 /// InsertVRSaveCode - Once the entire function has been instruction selected,
189 /// all virtual registers are created and all machine instructions are built,
190 /// check to see if we need to save/restore VRSAVE.  If so, do it.
191 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
192   // Check to see if this function uses vector registers, which means we have to
193   // save and restore the VRSAVE register and update it with the regs we use.
194   //
195   // In this case, there will be virtual registers of vector type created
196   // by the scheduler.  Detect them now.
197   bool HasVectorVReg = false;
198   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
199     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
200     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
201       HasVectorVReg = true;
202       break;
203     }
204   }
205   if (!HasVectorVReg) return;  // nothing to do.
206 
207   // If we have a vector register, we want to emit code into the entry and exit
208   // blocks to save and restore the VRSAVE register.  We do this here (instead
209   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
210   //
211   // 1. This (trivially) reduces the load on the register allocator, by not
212   //    having to represent the live range of the VRSAVE register.
213   // 2. This (more significantly) allows us to create a temporary virtual
214   //    register to hold the saved VRSAVE value, allowing this temporary to be
215   //    register allocated, instead of forcing it to be spilled to the stack.
216 
217   // Create two vregs - one to hold the VRSAVE register that is live-in to the
218   // function and one for the value after having bits or'd into it.
219   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
220   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
221 
222   const TargetInstrInfo &TII = *TM.getInstrInfo();
223   MachineBasicBlock &EntryBB = *Fn.begin();
224   DebugLoc dl;
225   // Emit the following code into the entry block:
226   // InVRSAVE = MFVRSAVE
227   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
228   // MTVRSAVE UpdatedVRSAVE
229   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
230   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
231   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
232           UpdatedVRSAVE).addReg(InVRSAVE);
233   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
234 
235   // Find all return blocks, outputting a restore in each epilog.
236   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
237     if (!BB->empty() && BB->back().isReturn()) {
238       IP = BB->end(); --IP;
239 
240       // Skip over all terminator instructions, which are part of the return
241       // sequence.
242       MachineBasicBlock::iterator I2 = IP;
243       while (I2 != BB->begin() && (--I2)->isTerminator())
244         IP = I2;
245 
246       // Emit: MTVRSAVE InVRSave
247       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
248     }
249   }
250 }
251 
252 
253 /// getGlobalBaseReg - Output the instructions required to put the
254 /// base address to use for accessing globals into a register.
255 ///
256 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
257   if (!GlobalBaseReg) {
258     const TargetInstrInfo &TII = *TM.getInstrInfo();
259     // Insert the set of GlobalBaseReg into the first MBB of the function
260     MachineBasicBlock &FirstMBB = MF->front();
261     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
262     DebugLoc dl;
263 
264     if (PPCLowering.getPointerTy() == MVT::i32) {
265       if (PPCSubTarget.isTargetELF())
266         GlobalBaseReg = PPC::R30;
267       else
268         GlobalBaseReg =
269           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
270       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
271       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
272       if (PPCSubTarget.isTargetELF()) {
273         unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
274         BuildMI(FirstMBB, MBBI, dl,
275                 TII.get(PPC::GetGBRO), TempReg).addReg(GlobalBaseReg);
276         BuildMI(FirstMBB, MBBI, dl,
277                 TII.get(PPC::UpdateGBR)).addReg(GlobalBaseReg).addReg(TempReg);
278         MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
279       }
280     } else {
281       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
282       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
283       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
284     }
285   }
286   return CurDAG->getRegister(GlobalBaseReg,
287                              PPCLowering.getPointerTy()).getNode();
288 }
289 
290 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
291 /// or 64-bit immediate, and if the value can be accurately represented as a
292 /// sign extension from a 16-bit value.  If so, this returns true and the
293 /// immediate.
294 static bool isIntS16Immediate(SDNode *N, short &Imm) {
295   if (N->getOpcode() != ISD::Constant)
296     return false;
297 
298   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
299   if (N->getValueType(0) == MVT::i32)
300     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
301   else
302     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
303 }
304 
305 static bool isIntS16Immediate(SDValue Op, short &Imm) {
306   return isIntS16Immediate(Op.getNode(), Imm);
307 }
308 
309 
310 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
311 /// operand. If so Imm will receive the 32-bit value.
312 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
313   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
314     Imm = cast<ConstantSDNode>(N)->getZExtValue();
315     return true;
316   }
317   return false;
318 }
319 
320 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
321 /// operand.  If so Imm will receive the 64-bit value.
322 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
323   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
324     Imm = cast<ConstantSDNode>(N)->getZExtValue();
325     return true;
326   }
327   return false;
328 }
329 
330 // isInt32Immediate - This method tests to see if a constant operand.
331 // If so Imm will receive the 32 bit value.
332 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
333   return isInt32Immediate(N.getNode(), Imm);
334 }
335 
336 
337 // isOpcWithIntImmediate - This method tests to see if the node is a specific
338 // opcode and that it has a immediate integer right operand.
339 // If so Imm will receive the 32 bit value.
340 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
341   return N->getOpcode() == Opc
342          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
343 }
344 
345 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
346   if (!Val)
347     return false;
348 
349   if (isShiftedMask_32(Val)) {
350     // look for the first non-zero bit
351     MB = countLeadingZeros(Val);
352     // look for the first zero bit after the run of ones
353     ME = countLeadingZeros((Val - 1) ^ Val);
354     return true;
355   } else {
356     Val = ~Val; // invert mask
357     if (isShiftedMask_32(Val)) {
358       // effectively look for the first zero bit
359       ME = countLeadingZeros(Val) - 1;
360       // effectively look for the first one bit after the run of zeros
361       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
362       return true;
363     }
364   }
365   // no run present
366   return false;
367 }
368 
369 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
370                                       bool isShiftMask, unsigned &SH,
371                                       unsigned &MB, unsigned &ME) {
372   // Don't even go down this path for i64, since different logic will be
373   // necessary for rldicl/rldicr/rldimi.
374   if (N->getValueType(0) != MVT::i32)
375     return false;
376 
377   unsigned Shift  = 32;
378   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
379   unsigned Opcode = N->getOpcode();
380   if (N->getNumOperands() != 2 ||
381       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
382     return false;
383 
384   if (Opcode == ISD::SHL) {
385     // apply shift left to mask if it comes first
386     if (isShiftMask) Mask = Mask << Shift;
387     // determine which bits are made indeterminant by shift
388     Indeterminant = ~(0xFFFFFFFFu << Shift);
389   } else if (Opcode == ISD::SRL) {
390     // apply shift right to mask if it comes first
391     if (isShiftMask) Mask = Mask >> Shift;
392     // determine which bits are made indeterminant by shift
393     Indeterminant = ~(0xFFFFFFFFu >> Shift);
394     // adjust for the left rotate
395     Shift = 32 - Shift;
396   } else if (Opcode == ISD::ROTL) {
397     Indeterminant = 0;
398   } else {
399     return false;
400   }
401 
402   // if the mask doesn't intersect any Indeterminant bits
403   if (Mask && !(Mask & Indeterminant)) {
404     SH = Shift & 31;
405     // make sure the mask is still a mask (wrap arounds may not be)
406     return isRunOfOnes(Mask, MB, ME);
407   }
408   return false;
409 }
410 
411 /// SelectBitfieldInsert - turn an or of two masked values into
412 /// the rotate left word immediate then mask insert (rlwimi) instruction.
413 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
414   SDValue Op0 = N->getOperand(0);
415   SDValue Op1 = N->getOperand(1);
416   SDLoc dl(N);
417 
418   APInt LKZ, LKO, RKZ, RKO;
419   CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
420   CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
421 
422   unsigned TargetMask = LKZ.getZExtValue();
423   unsigned InsertMask = RKZ.getZExtValue();
424 
425   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
426     unsigned Op0Opc = Op0.getOpcode();
427     unsigned Op1Opc = Op1.getOpcode();
428     unsigned Value, SH = 0;
429     TargetMask = ~TargetMask;
430     InsertMask = ~InsertMask;
431 
432     // If the LHS has a foldable shift and the RHS does not, then swap it to the
433     // RHS so that we can fold the shift into the insert.
434     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
435       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
436           Op0.getOperand(0).getOpcode() == ISD::SRL) {
437         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
438             Op1.getOperand(0).getOpcode() != ISD::SRL) {
439           std::swap(Op0, Op1);
440           std::swap(Op0Opc, Op1Opc);
441           std::swap(TargetMask, InsertMask);
442         }
443       }
444     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
445       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
446           Op1.getOperand(0).getOpcode() != ISD::SRL) {
447         std::swap(Op0, Op1);
448         std::swap(Op0Opc, Op1Opc);
449         std::swap(TargetMask, InsertMask);
450       }
451     }
452 
453     unsigned MB, ME;
454     if (isRunOfOnes(InsertMask, MB, ME)) {
455       SDValue Tmp1, Tmp2;
456 
457       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
458           isInt32Immediate(Op1.getOperand(1), Value)) {
459         Op1 = Op1.getOperand(0);
460         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
461       }
462       if (Op1Opc == ISD::AND) {
463         unsigned SHOpc = Op1.getOperand(0).getOpcode();
464         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
465             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
466 	  // Note that Value must be in range here (less than 32) because
467 	  // otherwise there would not be any bits set in InsertMask.
468           Op1 = Op1.getOperand(0).getOperand(0);
469           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
470         }
471       }
472 
473       SH &= 31;
474       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
475                           getI32Imm(ME) };
476       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
477     }
478   }
479   return 0;
480 }
481 
482 /// SelectCC - Select a comparison of the specified values with the specified
483 /// condition code, returning the CR# of the expression.
484 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
485                                     ISD::CondCode CC, SDLoc dl) {
486   // Always select the LHS.
487   unsigned Opc;
488 
489   if (LHS.getValueType() == MVT::i32) {
490     unsigned Imm;
491     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
492       if (isInt32Immediate(RHS, Imm)) {
493         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
494         if (isUInt<16>(Imm))
495           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
496                                                 getI32Imm(Imm & 0xFFFF)), 0);
497         // If this is a 16-bit signed immediate, fold it.
498         if (isInt<16>((int)Imm))
499           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
500                                                 getI32Imm(Imm & 0xFFFF)), 0);
501 
502         // For non-equality comparisons, the default code would materialize the
503         // constant, then compare against it, like this:
504         //   lis r2, 4660
505         //   ori r2, r2, 22136
506         //   cmpw cr0, r3, r2
507         // Since we are just comparing for equality, we can emit this instead:
508         //   xoris r0,r3,0x1234
509         //   cmplwi cr0,r0,0x5678
510         //   beq cr0,L6
511         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
512                                            getI32Imm(Imm >> 16)), 0);
513         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
514                                               getI32Imm(Imm & 0xFFFF)), 0);
515       }
516       Opc = PPC::CMPLW;
517     } else if (ISD::isUnsignedIntSetCC(CC)) {
518       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
519         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
520                                               getI32Imm(Imm & 0xFFFF)), 0);
521       Opc = PPC::CMPLW;
522     } else {
523       short SImm;
524       if (isIntS16Immediate(RHS, SImm))
525         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
526                                               getI32Imm((int)SImm & 0xFFFF)),
527                          0);
528       Opc = PPC::CMPW;
529     }
530   } else if (LHS.getValueType() == MVT::i64) {
531     uint64_t Imm;
532     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
533       if (isInt64Immediate(RHS.getNode(), Imm)) {
534         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
535         if (isUInt<16>(Imm))
536           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
537                                                 getI32Imm(Imm & 0xFFFF)), 0);
538         // If this is a 16-bit signed immediate, fold it.
539         if (isInt<16>(Imm))
540           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
541                                                 getI32Imm(Imm & 0xFFFF)), 0);
542 
543         // For non-equality comparisons, the default code would materialize the
544         // constant, then compare against it, like this:
545         //   lis r2, 4660
546         //   ori r2, r2, 22136
547         //   cmpd cr0, r3, r2
548         // Since we are just comparing for equality, we can emit this instead:
549         //   xoris r0,r3,0x1234
550         //   cmpldi cr0,r0,0x5678
551         //   beq cr0,L6
552         if (isUInt<32>(Imm)) {
553           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
554                                              getI64Imm(Imm >> 16)), 0);
555           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
556                                                 getI64Imm(Imm & 0xFFFF)), 0);
557         }
558       }
559       Opc = PPC::CMPLD;
560     } else if (ISD::isUnsignedIntSetCC(CC)) {
561       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
562         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
563                                               getI64Imm(Imm & 0xFFFF)), 0);
564       Opc = PPC::CMPLD;
565     } else {
566       short SImm;
567       if (isIntS16Immediate(RHS, SImm))
568         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
569                                               getI64Imm(SImm & 0xFFFF)),
570                          0);
571       Opc = PPC::CMPD;
572     }
573   } else if (LHS.getValueType() == MVT::f32) {
574     Opc = PPC::FCMPUS;
575   } else {
576     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
577     Opc = PPC::FCMPUD;
578   }
579   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
580 }
581 
582 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
583   switch (CC) {
584   case ISD::SETUEQ:
585   case ISD::SETONE:
586   case ISD::SETOLE:
587   case ISD::SETOGE:
588     llvm_unreachable("Should be lowered by legalize!");
589   default: llvm_unreachable("Unknown condition!");
590   case ISD::SETOEQ:
591   case ISD::SETEQ:  return PPC::PRED_EQ;
592   case ISD::SETUNE:
593   case ISD::SETNE:  return PPC::PRED_NE;
594   case ISD::SETOLT:
595   case ISD::SETLT:  return PPC::PRED_LT;
596   case ISD::SETULE:
597   case ISD::SETLE:  return PPC::PRED_LE;
598   case ISD::SETOGT:
599   case ISD::SETGT:  return PPC::PRED_GT;
600   case ISD::SETUGE:
601   case ISD::SETGE:  return PPC::PRED_GE;
602   case ISD::SETO:   return PPC::PRED_NU;
603   case ISD::SETUO:  return PPC::PRED_UN;
604     // These two are invalid for floating point.  Assume we have int.
605   case ISD::SETULT: return PPC::PRED_LT;
606   case ISD::SETUGT: return PPC::PRED_GT;
607   }
608 }
609 
610 /// getCRIdxForSetCC - Return the index of the condition register field
611 /// associated with the SetCC condition, and whether or not the field is
612 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
613 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
614   Invert = false;
615   switch (CC) {
616   default: llvm_unreachable("Unknown condition!");
617   case ISD::SETOLT:
618   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
619   case ISD::SETOGT:
620   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
621   case ISD::SETOEQ:
622   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
623   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
624   case ISD::SETUGE:
625   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
626   case ISD::SETULE:
627   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
628   case ISD::SETUNE:
629   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
630   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
631   case ISD::SETUEQ:
632   case ISD::SETOGE:
633   case ISD::SETOLE:
634   case ISD::SETONE:
635     llvm_unreachable("Invalid branch code: should be expanded by legalize");
636   // These are invalid for floating point.  Assume integer.
637   case ISD::SETULT: return 0;
638   case ISD::SETUGT: return 1;
639   }
640 }
641 
642 // getVCmpInst: return the vector compare instruction for the specified
643 // vector type and condition code. Since this is for altivec specific code,
644 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
645 static unsigned int getVCmpInst(MVT::SimpleValueType VecVT, ISD::CondCode CC) {
646   switch (CC) {
647     case ISD::SETEQ:
648     case ISD::SETUEQ:
649     case ISD::SETNE:
650     case ISD::SETUNE:
651       if (VecVT == MVT::v16i8)
652         return PPC::VCMPEQUB;
653       else if (VecVT == MVT::v8i16)
654         return PPC::VCMPEQUH;
655       else if (VecVT == MVT::v4i32)
656         return PPC::VCMPEQUW;
657       // v4f32 != v4f32 could be translate to unordered not equal
658       else if (VecVT == MVT::v4f32)
659         return PPC::VCMPEQFP;
660       break;
661     case ISD::SETLT:
662     case ISD::SETGT:
663     case ISD::SETLE:
664     case ISD::SETGE:
665       if (VecVT == MVT::v16i8)
666         return PPC::VCMPGTSB;
667       else if (VecVT == MVT::v8i16)
668         return PPC::VCMPGTSH;
669       else if (VecVT == MVT::v4i32)
670         return PPC::VCMPGTSW;
671       else if (VecVT == MVT::v4f32)
672         return PPC::VCMPGTFP;
673       break;
674     case ISD::SETULT:
675     case ISD::SETUGT:
676     case ISD::SETUGE:
677     case ISD::SETULE:
678       if (VecVT == MVT::v16i8)
679         return PPC::VCMPGTUB;
680       else if (VecVT == MVT::v8i16)
681         return PPC::VCMPGTUH;
682       else if (VecVT == MVT::v4i32)
683         return PPC::VCMPGTUW;
684       break;
685     case ISD::SETOEQ:
686       if (VecVT == MVT::v4f32)
687         return PPC::VCMPEQFP;
688       break;
689     case ISD::SETOLT:
690     case ISD::SETOGT:
691     case ISD::SETOLE:
692       if (VecVT == MVT::v4f32)
693         return PPC::VCMPGTFP;
694       break;
695     case ISD::SETOGE:
696       if (VecVT == MVT::v4f32)
697         return PPC::VCMPGEFP;
698       break;
699     default:
700       break;
701   }
702   llvm_unreachable("Invalid integer vector compare condition");
703 }
704 
705 // getVCmpEQInst: return the equal compare instruction for the specified vector
706 // type. Since this is for altivec specific code, only support the altivec
707 // types (v16i8, v8i16, v4i32, and v4f32).
708 static unsigned int getVCmpEQInst(MVT::SimpleValueType VecVT) {
709   switch (VecVT) {
710     case MVT::v16i8:
711       return PPC::VCMPEQUB;
712     case MVT::v8i16:
713       return PPC::VCMPEQUH;
714     case MVT::v4i32:
715       return PPC::VCMPEQUW;
716     case MVT::v4f32:
717       return PPC::VCMPEQFP;
718     default:
719       llvm_unreachable("Invalid integer vector compare condition");
720   }
721 }
722 
723 
724 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
725   SDLoc dl(N);
726   unsigned Imm;
727   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
728   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
729   bool isPPC64 = (PtrVT == MVT::i64);
730 
731   if (isInt32Immediate(N->getOperand(1), Imm)) {
732     // We can codegen setcc op, imm very efficiently compared to a brcond.
733     // Check for those cases here.
734     // setcc op, 0
735     if (Imm == 0) {
736       SDValue Op = N->getOperand(0);
737       switch (CC) {
738       default: break;
739       case ISD::SETEQ: {
740         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
741         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
742         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
743       }
744       case ISD::SETNE: {
745         if (isPPC64) break;
746         SDValue AD =
747           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
748                                          Op, getI32Imm(~0U)), 0);
749         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
750                                     AD.getValue(1));
751       }
752       case ISD::SETLT: {
753         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
754         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
755       }
756       case ISD::SETGT: {
757         SDValue T =
758           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
759         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
760         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
761         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
762       }
763       }
764     } else if (Imm == ~0U) {        // setcc op, -1
765       SDValue Op = N->getOperand(0);
766       switch (CC) {
767       default: break;
768       case ISD::SETEQ:
769         if (isPPC64) break;
770         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
771                                             Op, getI32Imm(1)), 0);
772         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
773                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
774                                                              MVT::i32,
775                                                              getI32Imm(0)), 0),
776                                       Op.getValue(1));
777       case ISD::SETNE: {
778         if (isPPC64) break;
779         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
780         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
781                                             Op, getI32Imm(~0U));
782         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
783                                     Op, SDValue(AD, 1));
784       }
785       case ISD::SETLT: {
786         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
787                                                     getI32Imm(1)), 0);
788         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
789                                                     Op), 0);
790         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
791         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
792       }
793       case ISD::SETGT: {
794         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
795         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
796                      0);
797         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
798                                     getI32Imm(1));
799       }
800       }
801     }
802   }
803 
804   SDValue LHS = N->getOperand(0);
805   SDValue RHS = N->getOperand(1);
806 
807   // Altivec Vector compare instructions do not set any CR register by default and
808   // vector compare operations return the same type as the operands.
809   if (LHS.getValueType().isVector()) {
810     EVT VecVT = LHS.getValueType();
811     MVT::SimpleValueType VT = VecVT.getSimpleVT().SimpleTy;
812     unsigned int VCmpInst = getVCmpInst(VT, CC);
813 
814     switch (CC) {
815       case ISD::SETEQ:
816       case ISD::SETOEQ:
817       case ISD::SETUEQ:
818         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
819       case ISD::SETNE:
820       case ISD::SETONE:
821       case ISD::SETUNE: {
822         SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
823         return CurDAG->SelectNodeTo(N, PPC::VNOR, VecVT, VCmp, VCmp);
824       }
825       case ISD::SETLT:
826       case ISD::SETOLT:
827       case ISD::SETULT:
828         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, RHS, LHS);
829       case ISD::SETGT:
830       case ISD::SETOGT:
831       case ISD::SETUGT:
832         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
833       case ISD::SETGE:
834       case ISD::SETOGE:
835       case ISD::SETUGE: {
836         // Small optimization: Altivec provides a 'Vector Compare Greater Than
837         // or Equal To' instruction (vcmpgefp), so in this case there is no
838         // need for extra logic for the equal compare.
839         if (VecVT.getSimpleVT().isFloatingPoint()) {
840           return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
841         } else {
842           SDValue VCmpGT(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
843           unsigned int VCmpEQInst = getVCmpEQInst(VT);
844           SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
845           return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpGT, VCmpEQ);
846         }
847       }
848       case ISD::SETLE:
849       case ISD::SETOLE:
850       case ISD::SETULE: {
851         SDValue VCmpLE(CurDAG->getMachineNode(VCmpInst, dl, VecVT, RHS, LHS), 0);
852         unsigned int VCmpEQInst = getVCmpEQInst(VT);
853         SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
854         return CurDAG->SelectNodeTo(N, PPC::VOR, VecVT, VCmpLE, VCmpEQ);
855       }
856       default:
857         llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
858     }
859   }
860 
861   bool Inv;
862   unsigned Idx = getCRIdxForSetCC(CC, Inv);
863   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
864   SDValue IntCR;
865 
866   // Force the ccreg into CR7.
867   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
868 
869   SDValue InFlag(0, 0);  // Null incoming flag value.
870   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
871                                InFlag).getValue(1);
872 
873   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
874                                          CCReg), 0);
875 
876   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
877                       getI32Imm(31), getI32Imm(31) };
878   if (!Inv)
879     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
880 
881   // Get the specified bit.
882   SDValue Tmp =
883     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
884   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
885 }
886 
887 
888 // Select - Convert the specified operand from a target-independent to a
889 // target-specific node if it hasn't already been changed.
890 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
891   SDLoc dl(N);
892   if (N->isMachineOpcode()) {
893     N->setNodeId(-1);
894     return NULL;   // Already selected.
895   }
896 
897   switch (N->getOpcode()) {
898   default: break;
899 
900   case ISD::Constant: {
901     if (N->getValueType(0) == MVT::i64) {
902       // Get 64 bit value.
903       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
904       // Assume no remaining bits.
905       unsigned Remainder = 0;
906       // Assume no shift required.
907       unsigned Shift = 0;
908 
909       // If it can't be represented as a 32 bit value.
910       if (!isInt<32>(Imm)) {
911         Shift = countTrailingZeros<uint64_t>(Imm);
912         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
913 
914         // If the shifted value fits 32 bits.
915         if (isInt<32>(ImmSh)) {
916           // Go with the shifted value.
917           Imm = ImmSh;
918         } else {
919           // Still stuck with a 64 bit value.
920           Remainder = Imm;
921           Shift = 32;
922           Imm >>= 32;
923         }
924       }
925 
926       // Intermediate operand.
927       SDNode *Result;
928 
929       // Handle first 32 bits.
930       unsigned Lo = Imm & 0xFFFF;
931       unsigned Hi = (Imm >> 16) & 0xFFFF;
932 
933       // Simple value.
934       if (isInt<16>(Imm)) {
935        // Just the Lo bits.
936         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
937       } else if (Lo) {
938         // Handle the Hi bits.
939         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
940         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
941         // And Lo bits.
942         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
943                                         SDValue(Result, 0), getI32Imm(Lo));
944       } else {
945        // Just the Hi bits.
946         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
947       }
948 
949       // If no shift, we're done.
950       if (!Shift) return Result;
951 
952       // Shift for next step if the upper 32-bits were not zero.
953       if (Imm) {
954         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
955                                         SDValue(Result, 0),
956                                         getI32Imm(Shift),
957                                         getI32Imm(63 - Shift));
958       }
959 
960       // Add in the last bits as required.
961       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
962         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
963                                         SDValue(Result, 0), getI32Imm(Hi));
964       }
965       if ((Lo = Remainder & 0xFFFF)) {
966         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
967                                         SDValue(Result, 0), getI32Imm(Lo));
968       }
969 
970       return Result;
971     }
972     break;
973   }
974 
975   case ISD::SETCC:
976     return SelectSETCC(N);
977   case PPCISD::GlobalBaseReg:
978     return getGlobalBaseReg();
979 
980   case ISD::FrameIndex: {
981     int FI = cast<FrameIndexSDNode>(N)->getIndex();
982     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
983     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
984     if (N->hasOneUse())
985       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
986                                   getSmallIPtrImm(0));
987     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
988                                   getSmallIPtrImm(0));
989   }
990 
991   case PPCISD::MFOCRF: {
992     SDValue InFlag = N->getOperand(1);
993     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
994                                   N->getOperand(0), InFlag);
995   }
996 
997   case ISD::SDIV: {
998     // FIXME: since this depends on the setting of the carry flag from the srawi
999     //        we should really be making notes about that for the scheduler.
1000     // FIXME: It sure would be nice if we could cheaply recognize the
1001     //        srl/add/sra pattern the dag combiner will generate for this as
1002     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1003     unsigned Imm;
1004     if (isInt32Immediate(N->getOperand(1), Imm)) {
1005       SDValue N0 = N->getOperand(0);
1006       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1007         SDNode *Op =
1008           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1009                                  N0, getI32Imm(Log2_32(Imm)));
1010         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1011                                     SDValue(Op, 0), SDValue(Op, 1));
1012       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1013         SDNode *Op =
1014           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1015                                  N0, getI32Imm(Log2_32(-Imm)));
1016         SDValue PT =
1017           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
1018                                          SDValue(Op, 0), SDValue(Op, 1)),
1019                     0);
1020         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1021       }
1022     }
1023 
1024     // Other cases are autogenerated.
1025     break;
1026   }
1027 
1028   case ISD::LOAD: {
1029     // Handle preincrement loads.
1030     LoadSDNode *LD = cast<LoadSDNode>(N);
1031     EVT LoadedVT = LD->getMemoryVT();
1032 
1033     // Normal loads are handled by code generated from the .td file.
1034     if (LD->getAddressingMode() != ISD::PRE_INC)
1035       break;
1036 
1037     SDValue Offset = LD->getOffset();
1038     if (Offset.getOpcode() == ISD::TargetConstant ||
1039         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1040 
1041       unsigned Opcode;
1042       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1043       if (LD->getValueType(0) != MVT::i64) {
1044         // Handle PPC32 integer and normal FP loads.
1045         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1046         switch (LoadedVT.getSimpleVT().SimpleTy) {
1047           default: llvm_unreachable("Invalid PPC load type!");
1048           case MVT::f64: Opcode = PPC::LFDU; break;
1049           case MVT::f32: Opcode = PPC::LFSU; break;
1050           case MVT::i32: Opcode = PPC::LWZU; break;
1051           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1052           case MVT::i1:
1053           case MVT::i8:  Opcode = PPC::LBZU; break;
1054         }
1055       } else {
1056         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1057         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1058         switch (LoadedVT.getSimpleVT().SimpleTy) {
1059           default: llvm_unreachable("Invalid PPC load type!");
1060           case MVT::i64: Opcode = PPC::LDU; break;
1061           case MVT::i32: Opcode = PPC::LWZU8; break;
1062           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1063           case MVT::i1:
1064           case MVT::i8:  Opcode = PPC::LBZU8; break;
1065         }
1066       }
1067 
1068       SDValue Chain = LD->getChain();
1069       SDValue Base = LD->getBasePtr();
1070       SDValue Ops[] = { Offset, Base, Chain };
1071       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1072                                     PPCLowering.getPointerTy(),
1073                                     MVT::Other, Ops);
1074     } else {
1075       unsigned Opcode;
1076       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1077       if (LD->getValueType(0) != MVT::i64) {
1078         // Handle PPC32 integer and normal FP loads.
1079         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1080         switch (LoadedVT.getSimpleVT().SimpleTy) {
1081           default: llvm_unreachable("Invalid PPC load type!");
1082           case MVT::f64: Opcode = PPC::LFDUX; break;
1083           case MVT::f32: Opcode = PPC::LFSUX; break;
1084           case MVT::i32: Opcode = PPC::LWZUX; break;
1085           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1086           case MVT::i1:
1087           case MVT::i8:  Opcode = PPC::LBZUX; break;
1088         }
1089       } else {
1090         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1091         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1092                "Invalid sext update load");
1093         switch (LoadedVT.getSimpleVT().SimpleTy) {
1094           default: llvm_unreachable("Invalid PPC load type!");
1095           case MVT::i64: Opcode = PPC::LDUX; break;
1096           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1097           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1098           case MVT::i1:
1099           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1100         }
1101       }
1102 
1103       SDValue Chain = LD->getChain();
1104       SDValue Base = LD->getBasePtr();
1105       SDValue Ops[] = { Base, Offset, Chain };
1106       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1107                                     PPCLowering.getPointerTy(),
1108                                     MVT::Other, Ops);
1109     }
1110   }
1111 
1112   case ISD::AND: {
1113     unsigned Imm, Imm2, SH, MB, ME;
1114     uint64_t Imm64;
1115 
1116     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1117     // with a mask, emit rlwinm
1118     if (isInt32Immediate(N->getOperand(1), Imm) &&
1119         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1120       SDValue Val = N->getOperand(0).getOperand(0);
1121       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1122       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1123     }
1124     // If this is just a masked value where the input is not handled above, and
1125     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1126     if (isInt32Immediate(N->getOperand(1), Imm) &&
1127         isRunOfOnes(Imm, MB, ME) &&
1128         N->getOperand(0).getOpcode() != ISD::ROTL) {
1129       SDValue Val = N->getOperand(0);
1130       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1131       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1132     }
1133     // If this is a 64-bit zero-extension mask, emit rldicl.
1134     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1135         isMask_64(Imm64)) {
1136       SDValue Val = N->getOperand(0);
1137       MB = 64 - CountTrailingOnes_64(Imm64);
1138       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB) };
1139       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1140     }
1141     // AND X, 0 -> 0, not "rlwinm 32".
1142     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1143       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1144       return NULL;
1145     }
1146     // ISD::OR doesn't get all the bitfield insertion fun.
1147     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1148     if (isInt32Immediate(N->getOperand(1), Imm) &&
1149         N->getOperand(0).getOpcode() == ISD::OR &&
1150         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1151       unsigned MB, ME;
1152       Imm = ~(Imm^Imm2);
1153       if (isRunOfOnes(Imm, MB, ME)) {
1154         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1155                             N->getOperand(0).getOperand(1),
1156                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1157         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1158       }
1159     }
1160 
1161     // Other cases are autogenerated.
1162     break;
1163   }
1164   case ISD::OR:
1165     if (N->getValueType(0) == MVT::i32)
1166       if (SDNode *I = SelectBitfieldInsert(N))
1167         return I;
1168 
1169     // Other cases are autogenerated.
1170     break;
1171   case ISD::SHL: {
1172     unsigned Imm, SH, MB, ME;
1173     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1174         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1175       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1176                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1177       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1178     }
1179 
1180     // Other cases are autogenerated.
1181     break;
1182   }
1183   case ISD::SRL: {
1184     unsigned Imm, SH, MB, ME;
1185     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1186         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1187       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1188                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1189       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1190     }
1191 
1192     // Other cases are autogenerated.
1193     break;
1194   }
1195   case ISD::SELECT_CC: {
1196     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1197     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1198     bool isPPC64 = (PtrVT == MVT::i64);
1199 
1200     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1201     if (!isPPC64)
1202       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1203         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1204           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1205             if (N1C->isNullValue() && N3C->isNullValue() &&
1206                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1207                 // FIXME: Implement this optzn for PPC64.
1208                 N->getValueType(0) == MVT::i32) {
1209               SDNode *Tmp =
1210                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1211                                        N->getOperand(0), getI32Imm(~0U));
1212               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1213                                           SDValue(Tmp, 0), N->getOperand(0),
1214                                           SDValue(Tmp, 1));
1215             }
1216 
1217     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1218     unsigned BROpc = getPredicateForSetCC(CC);
1219 
1220     unsigned SelectCCOp;
1221     if (N->getValueType(0) == MVT::i32)
1222       SelectCCOp = PPC::SELECT_CC_I4;
1223     else if (N->getValueType(0) == MVT::i64)
1224       SelectCCOp = PPC::SELECT_CC_I8;
1225     else if (N->getValueType(0) == MVT::f32)
1226       SelectCCOp = PPC::SELECT_CC_F4;
1227     else if (N->getValueType(0) == MVT::f64)
1228       SelectCCOp = PPC::SELECT_CC_F8;
1229     else
1230       SelectCCOp = PPC::SELECT_CC_VRRC;
1231 
1232     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1233                         getI32Imm(BROpc) };
1234     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1235   }
1236   case PPCISD::BDNZ:
1237   case PPCISD::BDZ: {
1238     bool IsPPC64 = PPCSubTarget.isPPC64();
1239     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1240     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1241                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1242                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1243                                 MVT::Other, Ops, 2);
1244   }
1245   case PPCISD::COND_BRANCH: {
1246     // Op #0 is the Chain.
1247     // Op #1 is the PPC::PRED_* number.
1248     // Op #2 is the CR#
1249     // Op #3 is the Dest MBB
1250     // Op #4 is the Flag.
1251     // Prevent PPC::PRED_* from being selected into LI.
1252     SDValue Pred =
1253       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1254     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1255       N->getOperand(0), N->getOperand(4) };
1256     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1257   }
1258   case ISD::BR_CC: {
1259     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1260     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1261     SDValue Ops[] = { getI32Imm(getPredicateForSetCC(CC)), CondCode,
1262                         N->getOperand(4), N->getOperand(0) };
1263     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1264   }
1265   case ISD::BRIND: {
1266     // FIXME: Should custom lower this.
1267     SDValue Chain = N->getOperand(0);
1268     SDValue Target = N->getOperand(1);
1269     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1270     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1271     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1272                                            Chain), 0);
1273     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1274   }
1275   case PPCISD::TOC_ENTRY: {
1276     if (PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64()) {
1277       SDValue GA = N->getOperand(0);
1278       return CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
1279                                     N->getOperand(1));
1280        }
1281     assert (PPCSubTarget.isPPC64() &&
1282             "Only supported for 64-bit ABI and 32-bit SVR4");
1283 
1284     // For medium and large code model, we generate two instructions as
1285     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1286     // selecting one of LDtoc, LDtocJTI, and LDtocCPT.
1287     CodeModel::Model CModel = TM.getCodeModel();
1288     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1289       break;
1290 
1291     // The first source operand is a TargetGlobalAddress or a
1292     // TargetJumpTable.  If it is an externally defined symbol, a symbol
1293     // with common linkage, a function address, or a jump table address,
1294     // or if we are generating code for large code model, we generate:
1295     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1296     // Otherwise we generate:
1297     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1298     SDValue GA = N->getOperand(0);
1299     SDValue TOCbase = N->getOperand(1);
1300     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1301                                         TOCbase, GA);
1302 
1303     if (isa<JumpTableSDNode>(GA) || CModel == CodeModel::Large)
1304       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1305                                     SDValue(Tmp, 0));
1306 
1307     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1308       const GlobalValue *GValue = G->getGlobal();
1309       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
1310       const GlobalValue *RealGValue = GAlias ?
1311         GAlias->resolveAliasedGlobal(false) : GValue;
1312       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
1313       assert((GVar || isa<Function>(RealGValue)) &&
1314              "Unexpected global value subclass!");
1315 
1316       // An external variable is one without an initializer.  For these,
1317       // for variables with common linkage, and for Functions, generate
1318       // the LDtocL form.
1319       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
1320           RealGValue->hasAvailableExternallyLinkage())
1321         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1322                                       SDValue(Tmp, 0));
1323     }
1324 
1325     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1326                                   SDValue(Tmp, 0), GA);
1327   }
1328   case PPCISD::PPC32_PICGOT: {
1329     // Generate a PIC-safe GOT reference.
1330     assert(!PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI() &&
1331       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
1332     return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering.getPointerTy(),  MVT::i32);
1333   }
1334   case PPCISD::VADD_SPLAT: {
1335     // This expands into one of three sequences, depending on whether
1336     // the first operand is odd or even, positive or negative.
1337     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1338            isa<ConstantSDNode>(N->getOperand(1)) &&
1339            "Invalid operand on VADD_SPLAT!");
1340 
1341     int Elt     = N->getConstantOperandVal(0);
1342     int EltSize = N->getConstantOperandVal(1);
1343     unsigned Opc1, Opc2, Opc3;
1344     EVT VT;
1345 
1346     if (EltSize == 1) {
1347       Opc1 = PPC::VSPLTISB;
1348       Opc2 = PPC::VADDUBM;
1349       Opc3 = PPC::VSUBUBM;
1350       VT = MVT::v16i8;
1351     } else if (EltSize == 2) {
1352       Opc1 = PPC::VSPLTISH;
1353       Opc2 = PPC::VADDUHM;
1354       Opc3 = PPC::VSUBUHM;
1355       VT = MVT::v8i16;
1356     } else {
1357       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1358       Opc1 = PPC::VSPLTISW;
1359       Opc2 = PPC::VADDUWM;
1360       Opc3 = PPC::VSUBUWM;
1361       VT = MVT::v4i32;
1362     }
1363 
1364     if ((Elt & 1) == 0) {
1365       // Elt is even, in the range [-32,-18] + [16,30].
1366       //
1367       // Convert: VADD_SPLAT elt, size
1368       // Into:    tmp = VSPLTIS[BHW] elt
1369       //          VADDU[BHW]M tmp, tmp
1370       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1371       SDValue EltVal = getI32Imm(Elt >> 1);
1372       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1373       SDValue TmpVal = SDValue(Tmp, 0);
1374       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1375 
1376     } else if (Elt > 0) {
1377       // Elt is odd and positive, in the range [17,31].
1378       //
1379       // Convert: VADD_SPLAT elt, size
1380       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1381       //          tmp2 = VSPLTIS[BHW] -16
1382       //          VSUBU[BHW]M tmp1, tmp2
1383       SDValue EltVal = getI32Imm(Elt - 16);
1384       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1385       EltVal = getI32Imm(-16);
1386       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1387       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1388                                     SDValue(Tmp2, 0));
1389 
1390     } else {
1391       // Elt is odd and negative, in the range [-31,-17].
1392       //
1393       // Convert: VADD_SPLAT elt, size
1394       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1395       //          tmp2 = VSPLTIS[BHW] -16
1396       //          VADDU[BHW]M tmp1, tmp2
1397       SDValue EltVal = getI32Imm(Elt + 16);
1398       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1399       EltVal = getI32Imm(-16);
1400       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1401       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1402                                     SDValue(Tmp2, 0));
1403     }
1404   }
1405   }
1406 
1407   return SelectCode(N);
1408 }
1409 
1410 /// PostProcessISelDAG - Perform some late peephole optimizations
1411 /// on the DAG representation.
1412 void PPCDAGToDAGISel::PostprocessISelDAG() {
1413 
1414   // Skip peepholes at -O0.
1415   if (TM.getOptLevel() == CodeGenOpt::None)
1416     return;
1417 
1418   // These optimizations are currently supported only for 64-bit SVR4.
1419   if (PPCSubTarget.isDarwin() || !PPCSubTarget.isPPC64())
1420     return;
1421 
1422   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
1423   ++Position;
1424 
1425   while (Position != CurDAG->allnodes_begin()) {
1426     SDNode *N = --Position;
1427     // Skip dead nodes and any non-machine opcodes.
1428     if (N->use_empty() || !N->isMachineOpcode())
1429       continue;
1430 
1431     unsigned FirstOp;
1432     unsigned StorageOpcode = N->getMachineOpcode();
1433 
1434     switch (StorageOpcode) {
1435     default: continue;
1436 
1437     case PPC::LBZ:
1438     case PPC::LBZ8:
1439     case PPC::LD:
1440     case PPC::LFD:
1441     case PPC::LFS:
1442     case PPC::LHA:
1443     case PPC::LHA8:
1444     case PPC::LHZ:
1445     case PPC::LHZ8:
1446     case PPC::LWA:
1447     case PPC::LWZ:
1448     case PPC::LWZ8:
1449       FirstOp = 0;
1450       break;
1451 
1452     case PPC::STB:
1453     case PPC::STB8:
1454     case PPC::STD:
1455     case PPC::STFD:
1456     case PPC::STFS:
1457     case PPC::STH:
1458     case PPC::STH8:
1459     case PPC::STW:
1460     case PPC::STW8:
1461       FirstOp = 1;
1462       break;
1463     }
1464 
1465     // If this is a load or store with a zero offset, we may be able to
1466     // fold an add-immediate into the memory operation.
1467     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
1468         N->getConstantOperandVal(FirstOp) != 0)
1469       continue;
1470 
1471     SDValue Base = N->getOperand(FirstOp + 1);
1472     if (!Base.isMachineOpcode())
1473       continue;
1474 
1475     unsigned Flags = 0;
1476     bool ReplaceFlags = true;
1477 
1478     // When the feeding operation is an add-immediate of some sort,
1479     // determine whether we need to add relocation information to the
1480     // target flags on the immediate operand when we fold it into the
1481     // load instruction.
1482     //
1483     // For something like ADDItocL, the relocation information is
1484     // inferred from the opcode; when we process it in the AsmPrinter,
1485     // we add the necessary relocation there.  A load, though, can receive
1486     // relocation from various flavors of ADDIxxx, so we need to carry
1487     // the relocation information in the target flags.
1488     switch (Base.getMachineOpcode()) {
1489     default: continue;
1490 
1491     case PPC::ADDI8:
1492     case PPC::ADDI:
1493       // In some cases (such as TLS) the relocation information
1494       // is already in place on the operand, so copying the operand
1495       // is sufficient.
1496       ReplaceFlags = false;
1497       // For these cases, the immediate may not be divisible by 4, in
1498       // which case the fold is illegal for DS-form instructions.  (The
1499       // other cases provide aligned addresses and are always safe.)
1500       if ((StorageOpcode == PPC::LWA ||
1501            StorageOpcode == PPC::LD  ||
1502            StorageOpcode == PPC::STD) &&
1503           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
1504            Base.getConstantOperandVal(1) % 4 != 0))
1505         continue;
1506       break;
1507     case PPC::ADDIdtprelL:
1508       Flags = PPCII::MO_DTPREL_LO;
1509       break;
1510     case PPC::ADDItlsldL:
1511       Flags = PPCII::MO_TLSLD_LO;
1512       break;
1513     case PPC::ADDItocL:
1514       Flags = PPCII::MO_TOC_LO;
1515       break;
1516     }
1517 
1518     // We found an opportunity.  Reverse the operands from the add
1519     // immediate and substitute them into the load or store.  If
1520     // needed, update the target flags for the immediate operand to
1521     // reflect the necessary relocation information.
1522     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
1523     DEBUG(Base->dump(CurDAG));
1524     DEBUG(dbgs() << "\nN: ");
1525     DEBUG(N->dump(CurDAG));
1526     DEBUG(dbgs() << "\n");
1527 
1528     SDValue ImmOpnd = Base.getOperand(1);
1529 
1530     // If the relocation information isn't already present on the
1531     // immediate operand, add it now.
1532     if (ReplaceFlags) {
1533       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
1534         SDLoc dl(GA);
1535         const GlobalValue *GV = GA->getGlobal();
1536         // We can't perform this optimization for data whose alignment
1537         // is insufficient for the instruction encoding.
1538         if (GV->getAlignment() < 4 &&
1539             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
1540              StorageOpcode == PPC::LWA)) {
1541           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
1542           continue;
1543         }
1544         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
1545       } else if (ConstantPoolSDNode *CP =
1546                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
1547         const Constant *C = CP->getConstVal();
1548         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
1549                                                 CP->getAlignment(),
1550                                                 0, Flags);
1551       }
1552     }
1553 
1554     if (FirstOp == 1) // Store
1555       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
1556                                        Base.getOperand(0), N->getOperand(3));
1557     else // Load
1558       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
1559                                        N->getOperand(2));
1560 
1561     // The add-immediate may now be dead, in which case remove it.
1562     if (Base.getNode()->use_empty())
1563       CurDAG->RemoveDeadNode(Base.getNode());
1564   }
1565 }
1566 
1567 
1568 /// createPPCISelDag - This pass converts a legalized DAG into a
1569 /// PowerPC-specific DAG, ready for instruction scheduling.
1570 ///
1571 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1572   return new PPCDAGToDAGISel(TM);
1573 }
1574 
1575 static void initializePassOnce(PassRegistry &Registry) {
1576   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
1577   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID, 0,
1578                               false, false);
1579   Registry.registerPass(*PI, true);
1580 }
1581 
1582 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
1583   CALL_ONCE_INITIALIZATION(initializePassOnce);
1584 }
1585 
1586