Don't match 64-bit bitfield inserts into rlwimi's. todo add rldimi. :)
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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 "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include <iostream>
32 #include <set>
33 using namespace llvm;
34
35 namespace {
36   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
37     
38   //===--------------------------------------------------------------------===//
39   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
40   /// instructions for SelectionDAG operations.
41   ///
42   class PPCDAGToDAGISel : public SelectionDAGISel {
43     PPCTargetMachine &TM;
44     PPCTargetLowering PPCLowering;
45     unsigned GlobalBaseReg;
46   public:
47     PPCDAGToDAGISel(PPCTargetMachine &tm)
48       : SelectionDAGISel(PPCLowering), TM(tm),
49         PPCLowering(*TM.getTargetLowering()) {}
50     
51     virtual bool runOnFunction(Function &Fn) {
52       // Make sure we re-emit a set of the global base reg if necessary
53       GlobalBaseReg = 0;
54       SelectionDAGISel::runOnFunction(Fn);
55       
56       InsertVRSaveCode(Fn);
57       return true;
58     }
59    
60     /// getI32Imm - Return a target constant with the specified value, of type
61     /// i32.
62     inline SDOperand getI32Imm(unsigned Imm) {
63       return CurDAG->getTargetConstant(Imm, MVT::i32);
64     }
65
66     /// getI64Imm - Return a target constant with the specified value, of type
67     /// i64.
68     inline SDOperand getI64Imm(uint64_t Imm) {
69       return CurDAG->getTargetConstant(Imm, MVT::i64);
70     }
71     
72     /// getSmallIPtrImm - Return a target constant of pointer type.
73     inline SDOperand getSmallIPtrImm(unsigned Imm) {
74       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
75     }
76     
77     
78     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
79     /// base register.  Return the virtual register that holds this value.
80     SDOperand getGlobalBaseReg();
81     
82     // Select - Convert the specified operand from a target-independent to a
83     // target-specific node if it hasn't already been changed.
84     void Select(SDOperand &Result, SDOperand Op);
85     
86     SDNode *SelectBitfieldInsert(SDNode *N);
87
88     /// SelectCC - Select a comparison of the specified values with the
89     /// specified condition code, returning the CR# of the expression.
90     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
91
92     /// SelectAddrImm - Returns true if the address N can be represented by
93     /// a base register plus a signed 16-bit displacement [r+imm].
94     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
95       
96     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
97     /// represented as an indexed [r+r] operation.  Returns false if it can
98     /// be represented by [r+imm], which are preferred.
99     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
100     
101     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
102     /// represented as an indexed [r+r] operation.
103     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
104
105     /// SelectAddrImmShift - Returns true if the address N can be represented by
106     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
107     /// for use by STD and friends.
108     bool SelectAddrImmShift(SDOperand N, SDOperand &Disp, SDOperand &Base);
109     
110     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
111     /// inline asm expressions.
112     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
113                                               char ConstraintCode,
114                                               std::vector<SDOperand> &OutOps,
115                                               SelectionDAG &DAG) {
116       SDOperand Op0, Op1;
117       switch (ConstraintCode) {
118       default: return true;
119       case 'm':   // memory
120         if (!SelectAddrIdx(Op, Op0, Op1))
121           SelectAddrImm(Op, Op0, Op1);
122         break;
123       case 'o':   // offsetable
124         if (!SelectAddrImm(Op, Op0, Op1)) {
125           Select(Op0, Op);     // r+0.
126           Op1 = getSmallIPtrImm(0);
127         }
128         break;
129       case 'v':   // not offsetable
130         SelectAddrIdxOnly(Op, Op0, Op1);
131         break;
132       }
133       
134       OutOps.push_back(Op0);
135       OutOps.push_back(Op1);
136       return false;
137     }
138     
139     SDOperand BuildSDIVSequence(SDNode *N);
140     SDOperand BuildUDIVSequence(SDNode *N);
141     
142     /// InstructionSelectBasicBlock - This callback is invoked by
143     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
144     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
145     
146     void InsertVRSaveCode(Function &Fn);
147
148     virtual const char *getPassName() const {
149       return "PowerPC DAG->DAG Pattern Instruction Selection";
150     } 
151     
152     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
153     /// this target when scheduling the DAG.
154     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
155       // Should use subtarget info to pick the right hazard recognizer.  For
156       // now, always return a PPC970 recognizer.
157       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
158       assert(II && "No InstrInfo?");
159       return new PPCHazardRecognizer970(*II); 
160     }
161
162 // Include the pieces autogenerated from the target description.
163 #include "PPCGenDAGISel.inc"
164     
165 private:
166     SDOperand SelectSETCC(SDOperand Op);
167     void MySelect_PPCbctrl(SDOperand &Result, SDOperand N);
168     void MySelect_PPCcall(SDOperand &Result, SDOperand N);
169   };
170 }
171
172 /// InstructionSelectBasicBlock - This callback is invoked by
173 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
174 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
175   DEBUG(BB->dump());
176   
177   // The selection process is inherently a bottom-up recursive process (users
178   // select their uses before themselves).  Given infinite stack space, we
179   // could just start selecting on the root and traverse the whole graph.  In
180   // practice however, this causes us to run out of stack space on large basic
181   // blocks.  To avoid this problem, select the entry node, then all its uses,
182   // iteratively instead of recursively.
183   std::vector<SDOperand> Worklist;
184   Worklist.push_back(DAG.getEntryNode());
185   
186   // Note that we can do this in the PPC target (scanning forward across token
187   // chain edges) because no nodes ever get folded across these edges.  On a
188   // target like X86 which supports load/modify/store operations, this would
189   // have to be more careful.
190   while (!Worklist.empty()) {
191     SDOperand Node = Worklist.back();
192     Worklist.pop_back();
193     
194     // Chose from the least deep of the top two nodes.
195     if (!Worklist.empty() &&
196         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
197       std::swap(Worklist.back(), Node);
198     
199     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
200          Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
201         CodeGenMap.count(Node)) continue;
202     
203     for (SDNode::use_iterator UI = Node.Val->use_begin(),
204          E = Node.Val->use_end(); UI != E; ++UI) {
205       // Scan the values.  If this use has a value that is a token chain, add it
206       // to the worklist.
207       SDNode *User = *UI;
208       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
209         if (User->getValueType(i) == MVT::Other) {
210           Worklist.push_back(SDOperand(User, i));
211           break; 
212         }
213     }
214
215     // Finally, legalize this node.
216     SDOperand Dummy;
217     Select(Dummy, Node);
218   }
219     
220   // Select target instructions for the DAG.
221   DAG.setRoot(SelectRoot(DAG.getRoot()));
222   assert(InFlightSet.empty() && "ISel InFlightSet has not been emptied!");
223   CodeGenMap.clear();
224   HandleMap.clear();
225   ReplaceMap.clear();
226   DAG.RemoveDeadNodes();
227   
228   // Emit machine code to BB.
229   ScheduleAndEmitDAG(DAG);
230 }
231
232 /// InsertVRSaveCode - Once the entire function has been instruction selected,
233 /// all virtual registers are created and all machine instructions are built,
234 /// check to see if we need to save/restore VRSAVE.  If so, do it.
235 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
236   // Check to see if this function uses vector registers, which means we have to
237   // save and restore the VRSAVE register and update it with the regs we use.  
238   //
239   // In this case, there will be virtual registers of vector type type created
240   // by the scheduler.  Detect them now.
241   MachineFunction &Fn = MachineFunction::get(&F);
242   SSARegMap *RegMap = Fn.getSSARegMap();
243   bool HasVectorVReg = false;
244   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
245        e = RegMap->getLastVirtReg()+1; i != e; ++i)
246     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
247       HasVectorVReg = true;
248       break;
249     }
250   if (!HasVectorVReg) return;  // nothing to do.
251       
252   // If we have a vector register, we want to emit code into the entry and exit
253   // blocks to save and restore the VRSAVE register.  We do this here (instead
254   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
255   //
256   // 1. This (trivially) reduces the load on the register allocator, by not
257   //    having to represent the live range of the VRSAVE register.
258   // 2. This (more significantly) allows us to create a temporary virtual
259   //    register to hold the saved VRSAVE value, allowing this temporary to be
260   //    register allocated, instead of forcing it to be spilled to the stack.
261
262   // Create two vregs - one to hold the VRSAVE register that is live-in to the
263   // function and one for the value after having bits or'd into it.
264   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
265   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
266   
267   MachineBasicBlock &EntryBB = *Fn.begin();
268   // Emit the following code into the entry block:
269   // InVRSAVE = MFVRSAVE
270   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
271   // MTVRSAVE UpdatedVRSAVE
272   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
273   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
274   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
275   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
276   
277   // Find all return blocks, outputting a restore in each epilog.
278   const TargetInstrInfo &TII = *TM.getInstrInfo();
279   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
280     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
281       IP = BB->end(); --IP;
282       
283       // Skip over all terminator instructions, which are part of the return
284       // sequence.
285       MachineBasicBlock::iterator I2 = IP;
286       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
287         IP = I2;
288       
289       // Emit: MTVRSAVE InVRSave
290       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
291     }        
292   }
293 }
294
295
296 /// getGlobalBaseReg - Output the instructions required to put the
297 /// base address to use for accessing globals into a register.
298 ///
299 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
300   if (!GlobalBaseReg) {
301     // Insert the set of GlobalBaseReg into the first MBB of the function
302     MachineBasicBlock &FirstMBB = BB->getParent()->front();
303     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
304     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
305
306     if (PPCLowering.getPointerTy() == MVT::i32)
307       GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
308     else
309       GlobalBaseReg = RegMap->createVirtualRegister(PPC::G8RCRegisterClass);
310     
311     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
312     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
313   }
314   return CurDAG->getRegister(GlobalBaseReg, PPCLowering.getPointerTy());
315 }
316
317 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
318 /// or 64-bit immediate, and if the value can be accurately represented as a
319 /// sign extension from a 16-bit value.  If so, this returns true and the
320 /// immediate.
321 static bool isIntS16Immediate(SDNode *N, short &Imm) {
322   if (N->getOpcode() != ISD::Constant)
323     return false;
324
325   Imm = (short)cast<ConstantSDNode>(N)->getValue();
326   if (N->getValueType(0) == MVT::i32)
327     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
328   else
329     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
330 }
331
332 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
333   return isIntS16Immediate(Op.Val, Imm);
334 }
335
336
337 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
338 /// operand. If so Imm will receive the 32-bit value.
339 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
340   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
341     Imm = cast<ConstantSDNode>(N)->getValue();
342     return true;
343   }
344   return false;
345 }
346
347 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
348 /// operand.  If so Imm will receive the 64-bit value.
349 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
350   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
351     Imm = cast<ConstantSDNode>(N)->getValue();
352     return true;
353   }
354   return false;
355 }
356
357 // isInt32Immediate - This method tests to see if a constant operand.
358 // If so Imm will receive the 32 bit value.
359 static bool isInt32Immediate(SDOperand N, unsigned &Imm) {
360   return isInt32Immediate(N.Val, Imm);
361 }
362
363
364 // isOpcWithIntImmediate - This method tests to see if the node is a specific
365 // opcode and that it has a immediate integer right operand.
366 // If so Imm will receive the 32 bit value.
367 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
368   return N->getOpcode() == Opc && isInt32Immediate(N->getOperand(1).Val, Imm);
369 }
370
371
372 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
373 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
374 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
375 // not, since all 1s are not contiguous.
376 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
377   if (isShiftedMask_32(Val)) {
378     // look for the first non-zero bit
379     MB = CountLeadingZeros_32(Val);
380     // look for the first zero bit after the run of ones
381     ME = CountLeadingZeros_32((Val - 1) ^ Val);
382     return true;
383   } else {
384     Val = ~Val; // invert mask
385     if (isShiftedMask_32(Val)) {
386       // effectively look for the first zero bit
387       ME = CountLeadingZeros_32(Val) - 1;
388       // effectively look for the first one bit after the run of zeros
389       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
390       return true;
391     }
392   }
393   // no run present
394   return false;
395 }
396
397 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
398 // and mask opcode and mask operation.
399 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
400                             unsigned &SH, unsigned &MB, unsigned &ME) {
401   // Don't even go down this path for i64, since different logic will be
402   // necessary for rldicl/rldicr/rldimi.
403   if (N->getValueType(0) != MVT::i32)
404     return false;
405
406   unsigned Shift  = 32;
407   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
408   unsigned Opcode = N->getOpcode();
409   if (N->getNumOperands() != 2 ||
410       !isInt32Immediate(N->getOperand(1).Val, Shift) || (Shift > 31))
411     return false;
412   
413   if (Opcode == ISD::SHL) {
414     // apply shift left to mask if it comes first
415     if (IsShiftMask) Mask = Mask << Shift;
416     // determine which bits are made indeterminant by shift
417     Indeterminant = ~(0xFFFFFFFFu << Shift);
418   } else if (Opcode == ISD::SRL) { 
419     // apply shift right to mask if it comes first
420     if (IsShiftMask) Mask = Mask >> Shift;
421     // determine which bits are made indeterminant by shift
422     Indeterminant = ~(0xFFFFFFFFu >> Shift);
423     // adjust for the left rotate
424     Shift = 32 - Shift;
425   } else {
426     return false;
427   }
428   
429   // if the mask doesn't intersect any Indeterminant bits
430   if (Mask && !(Mask & Indeterminant)) {
431     SH = Shift & 31;
432     // make sure the mask is still a mask (wrap arounds may not be)
433     return isRunOfOnes(Mask, MB, ME);
434   }
435   return false;
436 }
437
438 /// SelectBitfieldInsert - turn an or of two masked values into
439 /// the rotate left word immediate then mask insert (rlwimi) instruction.
440 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
441   SDOperand Op0 = N->getOperand(0);
442   SDOperand Op1 = N->getOperand(1);
443   
444   uint64_t LKZ, LKO, RKZ, RKO;
445   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
446   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
447   
448   unsigned TargetMask = LKZ;
449   unsigned InsertMask = RKZ;
450   
451   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
452     unsigned Op0Opc = Op0.getOpcode();
453     unsigned Op1Opc = Op1.getOpcode();
454     unsigned Value, SH = 0;
455     TargetMask = ~TargetMask;
456     InsertMask = ~InsertMask;
457
458     // If the LHS has a foldable shift and the RHS does not, then swap it to the
459     // RHS so that we can fold the shift into the insert.
460     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
461       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
462           Op0.getOperand(0).getOpcode() == ISD::SRL) {
463         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
464             Op1.getOperand(0).getOpcode() != ISD::SRL) {
465           std::swap(Op0, Op1);
466           std::swap(Op0Opc, Op1Opc);
467           std::swap(TargetMask, InsertMask);
468         }
469       }
470     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
471       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
472           Op1.getOperand(0).getOpcode() != ISD::SRL) {
473         std::swap(Op0, Op1);
474         std::swap(Op0Opc, Op1Opc);
475         std::swap(TargetMask, InsertMask);
476       }
477     }
478     
479     unsigned MB, ME;
480     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
481       SDOperand Tmp1, Tmp2, Tmp3;
482       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
483
484       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
485           isInt32Immediate(Op1.getOperand(1), Value)) {
486         Op1 = Op1.getOperand(0);
487         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
488       }
489       if (Op1Opc == ISD::AND) {
490         unsigned SHOpc = Op1.getOperand(0).getOpcode();
491         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
492             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
493           Op1 = Op1.getOperand(0).getOperand(0);
494           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
495         } else {
496           Op1 = Op1.getOperand(0);
497         }
498       }
499       
500       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
501       Select(Tmp1, Tmp3);
502       Select(Tmp2, Op1);
503       SH &= 31;
504       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
505                                    getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
506     }
507   }
508   return 0;
509 }
510
511 /// SelectAddrImm - Returns true if the address N can be represented by
512 /// a base register plus a signed 16-bit displacement [r+imm].
513 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
514                                     SDOperand &Base) {
515   // If this can be more profitably realized as r+r, fail.
516   if (SelectAddrIdx(N, Disp, Base))
517     return false;
518
519   if (N.getOpcode() == ISD::ADD) {
520     short imm = 0;
521     if (isIntS16Immediate(N.getOperand(1), imm)) {
522       Disp = getI32Imm((int)imm & 0xFFFF);
523       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
524         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
525       } else {
526         Base = N.getOperand(0);
527       }
528       return true; // [r+i]
529     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
530       // Match LOAD (ADD (X, Lo(G))).
531       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
532              && "Cannot handle constant offsets yet!");
533       Disp = N.getOperand(1).getOperand(0);  // The global address.
534       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
535              Disp.getOpcode() == ISD::TargetConstantPool ||
536              Disp.getOpcode() == ISD::TargetJumpTable);
537       Base = N.getOperand(0);
538       return true;  // [&g+r]
539     }
540   } else if (N.getOpcode() == ISD::OR) {
541     short imm = 0;
542     if (isIntS16Immediate(N.getOperand(1), imm)) {
543       // If this is an or of disjoint bitfields, we can codegen this as an add
544       // (for better address arithmetic) if the LHS and RHS of the OR are
545       // provably disjoint.
546       uint64_t LHSKnownZero, LHSKnownOne;
547       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
548                                     LHSKnownZero, LHSKnownOne);
549       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
550         // If all of the bits are known zero on the LHS or RHS, the add won't
551         // carry.
552         Base = N.getOperand(0);
553         Disp = getI32Imm((int)imm & 0xFFFF);
554         return true;
555       }
556     }
557   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
558     // Loading from a constant address.
559
560     // If this address fits entirely in a 16-bit sext immediate field, codegen
561     // this as "d, 0"
562     short Imm;
563     if (isIntS16Immediate(CN, Imm)) {
564       Disp = CurDAG->getTargetConstant(Imm, CN->getValueType(0));
565       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
566       return true;
567     }
568
569     // FIXME: Handle small sext constant offsets in PPC64 mode also!
570     if (CN->getValueType(0) == MVT::i32) {
571       int Addr = (int)CN->getValue();
572     
573       // Otherwise, break this down into an LIS + disp.
574       Disp = getI32Imm((short)Addr);
575       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
576       return true;
577     }
578   }
579   
580   Disp = getSmallIPtrImm(0);
581   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
582     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
583   else
584     Base = N;
585   return true;      // [r+0]
586 }
587
588 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
589 /// represented as an indexed [r+r] operation.  Returns false if it can
590 /// be represented by [r+imm], which are preferred.
591 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
592                                     SDOperand &Index) {
593   short imm = 0;
594   if (N.getOpcode() == ISD::ADD) {
595     if (isIntS16Immediate(N.getOperand(1), imm))
596       return false;    // r+i
597     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
598       return false;    // r+i
599     
600     Base = N.getOperand(0);
601     Index = N.getOperand(1);
602     return true;
603   } else if (N.getOpcode() == ISD::OR) {
604     if (isIntS16Immediate(N.getOperand(1), imm))
605       return false;    // r+i can fold it if we can.
606     
607     // If this is an or of disjoint bitfields, we can codegen this as an add
608     // (for better address arithmetic) if the LHS and RHS of the OR are provably
609     // disjoint.
610     uint64_t LHSKnownZero, LHSKnownOne;
611     uint64_t RHSKnownZero, RHSKnownOne;
612     PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
613                                   LHSKnownZero, LHSKnownOne);
614     
615     if (LHSKnownZero) {
616       PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
617                                     RHSKnownZero, RHSKnownOne);
618       // If all of the bits are known zero on the LHS or RHS, the add won't
619       // carry.
620       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
621         Base = N.getOperand(0);
622         Index = N.getOperand(1);
623         return true;
624       }
625     }
626   }
627   
628   return false;
629 }
630
631 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
632 /// represented as an indexed [r+r] operation.
633 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
634                                         SDOperand &Index) {
635   // Check to see if we can easily represent this as an [r+r] address.  This
636   // will fail if it thinks that the address is more profitably represented as
637   // reg+imm, e.g. where imm = 0.
638   if (SelectAddrIdx(N, Base, Index))
639     return true;
640   
641   // If the operand is an addition, always emit this as [r+r], since this is
642   // better (for code size, and execution, as the memop does the add for free)
643   // than emitting an explicit add.
644   if (N.getOpcode() == ISD::ADD) {
645     Base = N.getOperand(0);
646     Index = N.getOperand(1);
647     return true;
648   }
649   
650   // Otherwise, do it the hard way, using R0 as the base register.
651   Base = CurDAG->getRegister(PPC::R0, N.getValueType());
652   Index = N;
653   return true;
654 }
655
656 /// SelectAddrImmShift - Returns true if the address N can be represented by
657 /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
658 /// for use by STD and friends.
659 bool PPCDAGToDAGISel::SelectAddrImmShift(SDOperand N, SDOperand &Disp, 
660                                          SDOperand &Base) {
661   // If this can be more profitably realized as r+r, fail.
662   if (SelectAddrIdx(N, Disp, Base))
663     return false;
664   
665   if (N.getOpcode() == ISD::ADD) {
666     short imm = 0;
667     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
668       Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
669       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
670         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
671       } else {
672         Base = N.getOperand(0);
673       }
674       return true; // [r+i]
675     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
676       // Match LOAD (ADD (X, Lo(G))).
677       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
678              && "Cannot handle constant offsets yet!");
679       Disp = N.getOperand(1).getOperand(0);  // The global address.
680       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
681              Disp.getOpcode() == ISD::TargetConstantPool ||
682              Disp.getOpcode() == ISD::TargetJumpTable);
683       Base = N.getOperand(0);
684       return true;  // [&g+r]
685     }
686   } else if (N.getOpcode() == ISD::OR) {
687     short imm = 0;
688     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
689       // If this is an or of disjoint bitfields, we can codegen this as an add
690       // (for better address arithmetic) if the LHS and RHS of the OR are
691       // provably disjoint.
692       uint64_t LHSKnownZero, LHSKnownOne;
693       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
694                                     LHSKnownZero, LHSKnownOne);
695       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
696         // If all of the bits are known zero on the LHS or RHS, the add won't
697         // carry.
698         Base = N.getOperand(0);
699         Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
700         return true;
701       }
702     }
703   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
704     // Loading from a constant address.
705     
706     // If this address fits entirely in a 14-bit sext immediate field, codegen
707     // this as "d, 0"
708     short Imm;
709     if (isIntS16Immediate(CN, Imm)) {
710       Disp = getSmallIPtrImm((unsigned short)Imm >> 2);
711       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
712       return true;
713     }
714     
715     // FIXME: Handle small sext constant offsets in PPC64 mode also!
716     if (CN->getValueType(0) == MVT::i32) {
717       int Addr = (int)CN->getValue();
718       
719       // Otherwise, break this down into an LIS + disp.
720       Disp = getI32Imm((short)Addr >> 2);
721       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
722       return true;
723     }
724   }
725   
726   Disp = getSmallIPtrImm(0);
727   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
728     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
729   else
730     Base = N;
731   return true;      // [r+0]
732 }
733
734
735 /// SelectCC - Select a comparison of the specified values with the specified
736 /// condition code, returning the CR# of the expression.
737 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
738                                     ISD::CondCode CC) {
739   // Always select the LHS.
740   Select(LHS, LHS);
741   unsigned Opc;
742   
743   if (LHS.getValueType() == MVT::i32) {
744     unsigned Imm;
745     if (ISD::isUnsignedIntSetCC(CC)) {
746       if (isInt32Immediate(RHS, Imm) && isUInt16(Imm))
747         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
748                                                getI32Imm(Imm & 0xFFFF)), 0);
749       Opc = PPC::CMPLW;
750     } else {
751       short SImm;
752       if (isIntS16Immediate(RHS, SImm))
753         return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
754                                                getI32Imm((int)SImm & 0xFFFF)),
755                          0);
756       Opc = PPC::CMPW;
757     }
758   } else if (LHS.getValueType() == MVT::i64) {
759     uint64_t Imm;
760     if (ISD::isUnsignedIntSetCC(CC)) {
761       if (isInt64Immediate(RHS.Val, Imm) && isUInt16(Imm))
762         return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
763                                                getI64Imm(Imm & 0xFFFF)), 0);
764       Opc = PPC::CMPLD;
765     } else {
766       short SImm;
767       if (isIntS16Immediate(RHS, SImm))
768         return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
769                                                getI64Imm((int)SImm & 0xFFFF)),
770                          0);
771       Opc = PPC::CMPD;
772     }
773   } else if (LHS.getValueType() == MVT::f32) {
774     Opc = PPC::FCMPUS;
775   } else {
776     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
777     Opc = PPC::FCMPUD;
778   }
779   Select(RHS, RHS);
780   return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0);
781 }
782
783 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
784 /// to Condition.
785 static unsigned getBCCForSetCC(ISD::CondCode CC) {
786   switch (CC) {
787   default: assert(0 && "Unknown condition!"); abort();
788   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
789   case ISD::SETUEQ:
790   case ISD::SETEQ:  return PPC::BEQ;
791   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
792   case ISD::SETUNE:
793   case ISD::SETNE:  return PPC::BNE;
794   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
795   case ISD::SETULT:
796   case ISD::SETLT:  return PPC::BLT;
797   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
798   case ISD::SETULE:
799   case ISD::SETLE:  return PPC::BLE;
800   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
801   case ISD::SETUGT:
802   case ISD::SETGT:  return PPC::BGT;
803   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
804   case ISD::SETUGE:
805   case ISD::SETGE:  return PPC::BGE;
806     
807   case ISD::SETO:   return PPC::BUN;
808   case ISD::SETUO:  return PPC::BNU;
809   }
810   return 0;
811 }
812
813 /// getCRIdxForSetCC - Return the index of the condition register field
814 /// associated with the SetCC condition, and whether or not the field is
815 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
816 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
817   switch (CC) {
818   default: assert(0 && "Unknown condition!"); abort();
819   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
820   case ISD::SETULT:
821   case ISD::SETLT:  Inv = false;  return 0;
822   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
823   case ISD::SETUGE:
824   case ISD::SETGE:  Inv = true;   return 0;
825   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
826   case ISD::SETUGT:
827   case ISD::SETGT:  Inv = false;  return 1;
828   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
829   case ISD::SETULE:
830   case ISD::SETLE:  Inv = true;   return 1;
831   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
832   case ISD::SETUEQ:
833   case ISD::SETEQ:  Inv = false;  return 2;
834   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
835   case ISD::SETUNE:
836   case ISD::SETNE:  Inv = true;   return 2;
837   case ISD::SETO:   Inv = true;   return 3;
838   case ISD::SETUO:  Inv = false;  return 3;
839   }
840   return 0;
841 }
842
843 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
844   SDNode *N = Op.Val;
845   unsigned Imm;
846   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
847   if (isInt32Immediate(N->getOperand(1), Imm)) {
848     // We can codegen setcc op, imm very efficiently compared to a brcond.
849     // Check for those cases here.
850     // setcc op, 0
851     if (Imm == 0) {
852       SDOperand Op;
853       Select(Op, N->getOperand(0));
854       switch (CC) {
855       default: break;
856       case ISD::SETEQ:
857         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
858         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
859                                     getI32Imm(5), getI32Imm(31));
860       case ISD::SETNE: {
861         SDOperand AD =
862           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
863                                           Op, getI32Imm(~0U)), 0);
864         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
865                                     AD.getValue(1));
866       }
867       case ISD::SETLT:
868         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
869                                     getI32Imm(31), getI32Imm(31));
870       case ISD::SETGT: {
871         SDOperand T =
872           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
873         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
874         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
875                                     getI32Imm(31), getI32Imm(31));
876       }
877       }
878     } else if (Imm == ~0U) {        // setcc op, -1
879       SDOperand Op;
880       Select(Op, N->getOperand(0));
881       switch (CC) {
882       default: break;
883       case ISD::SETEQ:
884         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
885                                              Op, getI32Imm(1)), 0);
886         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
887                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
888                                                               getI32Imm(0)), 0),
889                                     Op.getValue(1));
890       case ISD::SETNE: {
891         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
892         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
893                                            Op, getI32Imm(~0U));
894         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
895                                     Op, SDOperand(AD, 1));
896       }
897       case ISD::SETLT: {
898         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
899                                                        getI32Imm(1)), 0);
900         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
901                                                        Op), 0);
902         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
903                                     getI32Imm(31), getI32Imm(31));
904       }
905       case ISD::SETGT:
906         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
907                                              getI32Imm(1), getI32Imm(31),
908                                              getI32Imm(31)), 0);
909         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
910       }
911     }
912   }
913   
914   bool Inv;
915   unsigned Idx = getCRIdxForSetCC(CC, Inv);
916   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
917   SDOperand IntCR;
918   
919   // Force the ccreg into CR7.
920   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
921   
922   SDOperand InFlag(0, 0);  // Null incoming flag value.
923   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
924                                InFlag).getValue(1);
925   
926   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
927     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
928                                             CCReg), 0);
929   else
930     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
931   
932   if (!Inv) {
933     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
934                                 getI32Imm((32-(3-Idx)) & 31),
935                                 getI32Imm(31), getI32Imm(31));
936   } else {
937     SDOperand Tmp =
938       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
939                                       getI32Imm((32-(3-Idx)) & 31),
940                                       getI32Imm(31),getI32Imm(31)), 0);
941     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
942   }
943 }
944
945
946 // Select - Convert the specified operand from a target-independent to a
947 // target-specific node if it hasn't already been changed.
948 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
949   SDNode *N = Op.Val;
950   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
951       N->getOpcode() < PPCISD::FIRST_NUMBER) {
952     Result = Op;
953     return;   // Already selected.
954   }
955
956   // If this has already been converted, use it.
957   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
958   if (CGMI != CodeGenMap.end()) {
959     Result = CGMI->second;
960     return;
961   }
962   
963   switch (N->getOpcode()) {
964   default: break;
965   case ISD::SETCC:
966     Result = SelectSETCC(Op);
967     return;
968   case PPCISD::GlobalBaseReg:
969     Result = getGlobalBaseReg();
970     return;
971     
972   case ISD::FrameIndex: {
973     int FI = cast<FrameIndexSDNode>(N)->getIndex();
974     SDOperand TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
975     unsigned Opc = Op.getValueType() == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
976     if (N->hasOneUse()) {
977       Result = CurDAG->SelectNodeTo(N, Opc, Op.getValueType(), TFI,
978                                     getSmallIPtrImm(0));
979       return;
980     }
981     Result = CodeGenMap[Op] = 
982       SDOperand(CurDAG->getTargetNode(Opc, Op.getValueType(), TFI,
983                                       getSmallIPtrImm(0)), 0);
984     return;
985   }
986
987   case PPCISD::MFCR: {
988     SDOperand InFlag;
989     Select(InFlag, N->getOperand(1));
990     // Use MFOCRF if supported.
991     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
992       Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
993                                                N->getOperand(0), InFlag), 0);
994     else
995       Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0);
996     CodeGenMap[Op] = Result;
997     return;
998   }
999     
1000   case ISD::SDIV: {
1001     // FIXME: since this depends on the setting of the carry flag from the srawi
1002     //        we should really be making notes about that for the scheduler.
1003     // FIXME: It sure would be nice if we could cheaply recognize the 
1004     //        srl/add/sra pattern the dag combiner will generate for this as
1005     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1006     unsigned Imm;
1007     if (isInt32Immediate(N->getOperand(1), Imm)) {
1008       SDOperand N0;
1009       Select(N0, N->getOperand(0));
1010       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1011         SDNode *Op =
1012           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
1013                                 N0, getI32Imm(Log2_32(Imm)));
1014         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
1015                                       SDOperand(Op, 0), SDOperand(Op, 1));
1016       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1017         SDNode *Op =
1018           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
1019                                 N0, getI32Imm(Log2_32(-Imm)));
1020         SDOperand PT =
1021           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
1022                                           SDOperand(Op, 0), SDOperand(Op, 1)),
1023                     0);
1024         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1025       }
1026       return;
1027     }
1028     
1029     // Other cases are autogenerated.
1030     break;
1031   }
1032   case ISD::AND: {
1033     unsigned Imm, Imm2;
1034     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1035     // with a mask, emit rlwinm
1036     if (isInt32Immediate(N->getOperand(1), Imm) &&
1037         (isShiftedMask_32(Imm) || isShiftedMask_32(~Imm))) {
1038       SDOperand Val;
1039       unsigned SH, MB, ME;
1040       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
1041         Select(Val, N->getOperand(0).getOperand(0));
1042       } else if (Imm == 0) {
1043         // AND X, 0 -> 0, not "rlwinm 32".
1044         Select(Result, N->getOperand(1));
1045         return ;
1046       } else {        
1047         Select(Val, N->getOperand(0));
1048         isRunOfOnes(Imm, MB, ME);
1049         SH = 0;
1050       }
1051       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
1052                                     getI32Imm(SH), getI32Imm(MB),
1053                                     getI32Imm(ME));
1054       return;
1055     }
1056     // ISD::OR doesn't get all the bitfield insertion fun.
1057     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1058     if (isInt32Immediate(N->getOperand(1), Imm) && 
1059         N->getOperand(0).getOpcode() == ISD::OR &&
1060         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1061       unsigned MB, ME;
1062       Imm = ~(Imm^Imm2);
1063       if (isRunOfOnes(Imm, MB, ME)) {
1064         SDOperand Tmp1, Tmp2;
1065         Select(Tmp1, N->getOperand(0).getOperand(0));
1066         Select(Tmp2, N->getOperand(0).getOperand(1));
1067         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1068                                                  Tmp1, Tmp2,
1069                                                  getI32Imm(0), getI32Imm(MB),
1070                                                  getI32Imm(ME)), 0);
1071         return;
1072       }
1073     }
1074     
1075     // Other cases are autogenerated.
1076     break;
1077   }
1078   case ISD::OR:
1079     if (N->getValueType(0) == MVT::i32)
1080       if (SDNode *I = SelectBitfieldInsert(N)) {
1081         Result = CodeGenMap[Op] = SDOperand(I, 0);
1082         return;
1083       }
1084       
1085     // Other cases are autogenerated.
1086     break;
1087   case ISD::SHL: {
1088     unsigned Imm, SH, MB, ME;
1089     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1090         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1091       SDOperand Val;
1092       Select(Val, N->getOperand(0).getOperand(0));
1093       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1094                                     Val, getI32Imm(SH), getI32Imm(MB),
1095                                     getI32Imm(ME));
1096       return;
1097     }
1098     
1099     // Other cases are autogenerated.
1100     break;
1101   }
1102   case ISD::SRL: {
1103     unsigned Imm, SH, MB, ME;
1104     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1105         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1106       SDOperand Val;
1107       Select(Val, N->getOperand(0).getOperand(0));
1108       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1109                                     Val, getI32Imm(SH), getI32Imm(MB),
1110                                     getI32Imm(ME));
1111       return;
1112     }
1113     
1114     // Other cases are autogenerated.
1115     break;
1116   }
1117   case ISD::SELECT_CC: {
1118     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1119     
1120     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1121     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1122       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1123         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1124           if (N1C->isNullValue() && N3C->isNullValue() &&
1125               N2C->getValue() == 1ULL && CC == ISD::SETNE &&
1126               // FIXME: Implement this optzn for PPC64.
1127               N->getValueType(0) == MVT::i32) {
1128             SDOperand LHS;
1129             Select(LHS, N->getOperand(0));
1130             SDNode *Tmp =
1131               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1132                                     LHS, getI32Imm(~0U));
1133             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1134                                           SDOperand(Tmp, 0), LHS,
1135                                           SDOperand(Tmp, 1));
1136             return;
1137           }
1138
1139     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1140     unsigned BROpc = getBCCForSetCC(CC);
1141
1142     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1143     unsigned SelectCCOp;
1144     if (N->getValueType(0) == MVT::i32)
1145       SelectCCOp = PPC::SELECT_CC_I4;
1146     else if (N->getValueType(0) == MVT::i64)
1147       SelectCCOp = PPC::SELECT_CC_I8;
1148     else if (N->getValueType(0) == MVT::f32)
1149       SelectCCOp = PPC::SELECT_CC_F4;
1150     else if (N->getValueType(0) == MVT::f64)
1151       SelectCCOp = PPC::SELECT_CC_F8;
1152     else
1153       SelectCCOp = PPC::SELECT_CC_VRRC;
1154
1155     SDOperand N2, N3;
1156     Select(N2, N->getOperand(2));
1157     Select(N3, N->getOperand(3));
1158     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1159                                   N2, N3, getI32Imm(BROpc));
1160     return;
1161   }
1162   case ISD::BR_CC: {
1163     SDOperand Chain;
1164     Select(Chain, N->getOperand(0));
1165     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1166     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1167     Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, 
1168                                   CondCode, getI32Imm(getBCCForSetCC(CC)), 
1169                                   N->getOperand(4), Chain);
1170     return;
1171   }
1172   case ISD::BRIND: {
1173     // FIXME: Should custom lower this.
1174     SDOperand Chain, Target;
1175     Select(Chain, N->getOperand(0));
1176     Select(Target,N->getOperand(1));
1177     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1178     Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target,
1179                                             Chain), 0);
1180     Result = CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1181     return;
1182   }
1183   // FIXME: These are manually selected because tblgen isn't handling varargs
1184   // nodes correctly.
1185   case PPCISD::BCTRL:            MySelect_PPCbctrl(Result, Op); return;
1186   case PPCISD::CALL:             MySelect_PPCcall(Result, Op); return;
1187   }
1188   
1189   SelectCode(Result, Op);
1190 }
1191
1192
1193 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1194 // correctly.
1195 void PPCDAGToDAGISel::MySelect_PPCbctrl(SDOperand &Result, SDOperand N) {
1196   SDOperand Chain(0, 0);
1197   SDOperand InFlag(0, 0);
1198   SDNode *ResNode;
1199   
1200   bool hasFlag =
1201     N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1202
1203   std::vector<SDOperand> Ops;
1204   // Push varargs arguments, including optional flag.
1205   for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1206     Select(Chain, N.getOperand(i));
1207     Ops.push_back(Chain);
1208   }
1209
1210   Select(Chain, N.getOperand(0));
1211   Ops.push_back(Chain);
1212
1213   if (hasFlag) {
1214     Select(Chain, N.getOperand(N.getNumOperands()-1));
1215     Ops.push_back(Chain);
1216   }
1217   
1218   ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag, Ops);
1219   Chain = SDOperand(ResNode, 0);
1220   InFlag = SDOperand(ResNode, 1);
1221   SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1222                                    Chain.ResNo);
1223   SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val,
1224                                    InFlag.ResNo);
1225   Result = SDOperand(ResNode, N.ResNo);
1226   return;
1227 }
1228
1229 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1230 // correctly.
1231 void PPCDAGToDAGISel::MySelect_PPCcall(SDOperand &Result, SDOperand N) {
1232   SDOperand Chain(0, 0);
1233   SDOperand InFlag(0, 0);
1234   SDOperand N1(0, 0);
1235   SDOperand Tmp0(0, 0);
1236   SDNode *ResNode;
1237   Chain = N.getOperand(0);
1238   N1 = N.getOperand(1);
1239   
1240   // Pattern: (PPCcall:void (imm:i32):$func)
1241   // Emits: (BLA:void (imm:i32):$func)
1242   // Pattern complexity = 4  cost = 1
1243   if (N1.getOpcode() == ISD::Constant) {
1244     unsigned Tmp0C = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1245     
1246     std::vector<SDOperand> Ops;
1247     Ops.push_back(CurDAG->getTargetConstant(Tmp0C, MVT::i32));
1248
1249     bool hasFlag =
1250       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1251     
1252     // Push varargs arguments, not including optional flag.
1253     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1254       Select(Chain, N.getOperand(i));
1255       Ops.push_back(Chain);
1256     }
1257     Select(Chain, N.getOperand(0));
1258     Ops.push_back(Chain);
1259     if (hasFlag) {
1260       Select(Chain, N.getOperand(N.getNumOperands()-1));
1261       Ops.push_back(Chain);
1262     }
1263     ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag, Ops);
1264     
1265     Chain = SDOperand(ResNode, 0);
1266     InFlag = SDOperand(ResNode, 1);
1267     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, 
1268                                      Chain.ResNo);
1269     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, 
1270                                      InFlag.ResNo);
1271     Result = SDOperand(ResNode, N.ResNo);
1272     return;
1273   }
1274   
1275   // Pattern: (PPCcall:void (tglobaladdr:i32):$dst)
1276   // Emits: (BL:void (tglobaladdr:i32):$dst)
1277   // Pattern complexity = 4  cost = 1
1278   if (N1.getOpcode() == ISD::TargetGlobalAddress) {
1279     std::vector<SDOperand> Ops;
1280     Ops.push_back(N1);
1281     
1282     bool hasFlag =
1283       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1284
1285     // Push varargs arguments, not including optional flag.
1286     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1287       Select(Chain, N.getOperand(i));
1288       Ops.push_back(Chain);
1289     }
1290     Select(Chain, N.getOperand(0));
1291     Ops.push_back(Chain);
1292     if (hasFlag) {
1293       Select(Chain, N.getOperand(N.getNumOperands()-1));
1294       Ops.push_back(Chain);
1295     }
1296     
1297     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops);
1298     
1299     Chain = SDOperand(ResNode, 0);
1300     InFlag = SDOperand(ResNode, 1);
1301     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1302                                      Chain.ResNo);
1303     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, 
1304                                      InFlag.ResNo);
1305     Result = SDOperand(ResNode, N.ResNo);
1306     return;
1307   }
1308   
1309   // Pattern: (PPCcall:void (texternalsym:i32):$dst)
1310   // Emits: (BL:void (texternalsym:i32):$dst)
1311   // Pattern complexity = 4  cost = 1
1312   if (N1.getOpcode() == ISD::TargetExternalSymbol) {
1313     std::vector<SDOperand> Ops;
1314     Ops.push_back(N1);
1315     
1316     bool hasFlag =
1317       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1318
1319     // Push varargs arguments, not including optional flag.
1320     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1321       Select(Chain, N.getOperand(i));
1322       Ops.push_back(Chain);
1323     }
1324     Select(Chain, N.getOperand(0));
1325     Ops.push_back(Chain);
1326     if (hasFlag) {
1327       Select(Chain, N.getOperand(N.getNumOperands()-1));
1328       Ops.push_back(Chain);
1329     }
1330     
1331     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops);
1332
1333     Chain = SDOperand(ResNode, 0);
1334     InFlag = SDOperand(ResNode, 1);
1335     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1336                                      Chain.ResNo);
1337     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val,
1338                                      InFlag.ResNo);
1339     Result = SDOperand(ResNode, N.ResNo);
1340     return;
1341   }
1342   std::cerr << "Cannot yet select: ";
1343   N.Val->dump(CurDAG);
1344   std::cerr << '\n';
1345   abort();
1346 }
1347
1348
1349 /// createPPCISelDag - This pass converts a legalized DAG into a 
1350 /// PowerPC-specific DAG, ready for instruction scheduling.
1351 ///
1352 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1353   return new PPCDAGToDAGISel(TM);
1354 }
1355