Update to use the new MathExtras.h support for log2 computation.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelPattern.cpp
1 //===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman 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 32 bit PowerPC.
11 // Magic number generation for integer divide from the PowerPC Compiler Writer's
12 // Guide, section 3.2.3.5
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "PowerPC.h"
17 #include "PowerPCInstrBuilder.h"
18 #include "PowerPCInstrInfo.h"
19 #include "PPC32TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include <set>
35 #include <algorithm>
36 using namespace llvm;
37
38
39 // IsRunOfOnes - returns true if Val consists of one contiguous run of 1's with
40 // any number of 0's on either side.  the 1's are allowed to wrap from LSB to
41 // MSB.  so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
42 // not, since all 1's are not contiguous.
43 static bool IsRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
44   if (isShiftedMask_32(Val)) {
45     // look for the first non-zero bit
46     MB = CountLeadingZeros_32(Val);
47     // look for the first zero bit after the run of ones
48     ME = CountLeadingZeros_32((Val - 1) ^ Val);
49     return true;
50   } else if (isShiftedMask_32(Val = ~Val)) { // invert mask
51     // effectively look for the first zero bit
52     ME = CountLeadingZeros_32(Val) - 1;
53     // effectively look for the first one bit after the run of zeros
54     MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
55     return true;
56   }
57   // no run present
58   return false;
59 }
60
61 //===----------------------------------------------------------------------===//
62 //  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
63 namespace {
64   class PPC32TargetLowering : public TargetLowering {
65     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
66     int ReturnAddrIndex;              // FrameIndex for return slot.
67   public:
68     PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
69       // Fold away setcc operations if possible.
70       setSetCCIsExpensive();
71
72       // Set up the register classes.
73       addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
74       addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
75       addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
76
77       // PowerPC has no intrinsics for these particular operations
78       setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
79       setOperationAction(ISD::MEMSET, MVT::Other, Expand);
80       setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
81
82       // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83       setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
84       setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
85
86       // PowerPC has no SREM/UREM instructions
87       setOperationAction(ISD::SREM, MVT::i32, Expand);
88       setOperationAction(ISD::UREM, MVT::i32, Expand);
89
90       // We don't support sin/cos/sqrt/fmod
91       setOperationAction(ISD::FSIN , MVT::f64, Expand);
92       setOperationAction(ISD::FCOS , MVT::f64, Expand);
93       setOperationAction(ISD::SREM , MVT::f64, Expand);
94       setOperationAction(ISD::FSIN , MVT::f32, Expand);
95       setOperationAction(ISD::FCOS , MVT::f32, Expand);
96       setOperationAction(ISD::SREM , MVT::f32, Expand);
97
98       // If we're enabling GP optimizations, use hardware square root
99       if (!GPOPT) {
100         setOperationAction(ISD::FSQRT, MVT::f64, Expand);
101         setOperationAction(ISD::FSQRT, MVT::f32, Expand);
102       }
103
104       //PowerPC does not have CTPOP or CTTZ
105       setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
106       setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
107
108       setSetCCResultContents(ZeroOrOneSetCCResult);
109       addLegalFPImmediate(+0.0); // Necessary for FSEL
110       addLegalFPImmediate(-0.0); //
111
112       computeRegisterProperties();
113     }
114
115     /// LowerArguments - This hook must be implemented to indicate how we should
116     /// lower the arguments for the specified function, into the specified DAG.
117     virtual std::vector<SDOperand>
118     LowerArguments(Function &F, SelectionDAG &DAG);
119
120     /// LowerCallTo - This hook lowers an abstract call to a function into an
121     /// actual call.
122     virtual std::pair<SDOperand, SDOperand>
123     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
124                 bool isTailCall, SDOperand Callee, ArgListTy &Args,
125                 SelectionDAG &DAG);
126
127     virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
128                                    Value *VAListV, SelectionDAG &DAG);
129
130     virtual std::pair<SDOperand,SDOperand>
131       LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
132                  const Type *ArgTy, SelectionDAG &DAG);
133
134     virtual std::pair<SDOperand, SDOperand>
135     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
136                             SelectionDAG &DAG);
137   };
138 }
139
140
141 std::vector<SDOperand>
142 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
143   //
144   // add beautiful description of PPC stack frame format, or at least some docs
145   //
146   MachineFunction &MF = DAG.getMachineFunction();
147   MachineFrameInfo *MFI = MF.getFrameInfo();
148   MachineBasicBlock& BB = MF.front();
149   std::vector<SDOperand> ArgValues;
150
151   // Due to the rather complicated nature of the PowerPC ABI, rather than a
152   // fixed size array of physical args, for the sake of simplicity let the STL
153   // handle tracking them for us.
154   std::vector<unsigned> argVR, argPR, argOp;
155   unsigned ArgOffset = 24;
156   unsigned GPR_remaining = 8;
157   unsigned FPR_remaining = 13;
158   unsigned GPR_idx = 0, FPR_idx = 0;
159   static const unsigned GPR[] = {
160     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
161     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
162   };
163   static const unsigned FPR[] = {
164     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
165     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
166   };
167
168   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
169   // the arguments start at offset 24, although they are likely to be passed
170   // in registers.
171   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
172     SDOperand newroot, argt;
173     unsigned ObjSize;
174     bool needsLoad = false;
175     bool ArgLive = !I->use_empty();
176     MVT::ValueType ObjectVT = getValueType(I->getType());
177
178     switch (ObjectVT) {
179     default: assert(0 && "Unhandled argument type!");
180     case MVT::i1:
181     case MVT::i8:
182     case MVT::i16:
183     case MVT::i32:
184       ObjSize = 4;
185       if (!ArgLive) break;
186       if (GPR_remaining > 0) {
187         MF.addLiveIn(GPR[GPR_idx]);
188         argt = newroot = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32,
189                                             DAG.getRoot());
190         if (ObjectVT != MVT::i32)
191           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
192       } else {
193         needsLoad = true;
194       }
195       break;
196       case MVT::i64: ObjSize = 8;
197       if (!ArgLive) break;
198       if (GPR_remaining > 0) {
199         SDOperand argHi, argLo;
200         MF.addLiveIn(GPR[GPR_idx]);
201         argHi = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
202         // If we have two or more remaining argument registers, then both halves
203         // of the i64 can be sourced from there.  Otherwise, the lower half will
204         // have to come off the stack.  This can happen when an i64 is preceded
205         // by 28 bytes of arguments.
206         if (GPR_remaining > 1) {
207           MF.addLiveIn(GPR[GPR_idx+1]);
208           argLo = DAG.getCopyFromReg(GPR[GPR_idx+1], MVT::i32, argHi);
209         } else {
210           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
211           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
212           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
213                               DAG.getSrcValue(NULL));
214         }
215         // Build the outgoing arg thingy
216         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
217         newroot = argLo;
218       } else {
219         needsLoad = true;
220       }
221       break;
222       case MVT::f32:
223       case MVT::f64:
224       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
225       if (!ArgLive) break;
226       if (FPR_remaining > 0) {
227         MF.addLiveIn(FPR[FPR_idx]);
228         argt = newroot = DAG.getCopyFromReg(FPR[FPR_idx], ObjectVT,
229                                             DAG.getRoot());
230         --FPR_remaining;
231         ++FPR_idx;
232       } else {
233         needsLoad = true;
234       }
235       break;
236     }
237
238     // We need to load the argument to a virtual register if we determined above
239     // that we ran out of physical registers of the appropriate type
240     if (needsLoad) {
241       unsigned SubregOffset = 0;
242       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
243       if (ObjectVT == MVT::i16) SubregOffset = 2;
244       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
245       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
246       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
247                         DAG.getConstant(SubregOffset, MVT::i32));
248       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
249                                    DAG.getSrcValue(NULL));
250     }
251
252     // Every 4 bytes of argument space consumes one of the GPRs available for
253     // argument passing.
254     if (GPR_remaining > 0) {
255       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
256       GPR_remaining -= delta;
257       GPR_idx += delta;
258     }
259     ArgOffset += ObjSize;
260     if (newroot.Val)
261       DAG.setRoot(newroot.getValue(1));
262
263     ArgValues.push_back(argt);
264   }
265
266   // If the function takes variable number of arguments, make a frame index for
267   // the start of the first vararg value... for expansion of llvm.va_start.
268   if (F.isVarArg()) {
269     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
270     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
271     // If this function is vararg, store any remaining integer argument regs
272     // to their spots on the stack so that they may be loaded by deferencing the
273     // result of va_next.
274     std::vector<SDOperand> MemOps;
275     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
276       MF.addLiveIn(GPR[GPR_idx]);
277       SDOperand Val = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
278       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
279                                     Val, FIN, DAG.getSrcValue(NULL));
280       MemOps.push_back(Store);
281       // Increment the address by four for the next argument to store
282       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
283       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
284     }
285     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
286   }
287
288   // Finally, inform the code generator which regs we return values in.
289   switch (getValueType(F.getReturnType())) {
290   default: assert(0 && "Unknown type!");
291   case MVT::isVoid: break;
292   case MVT::i1:
293   case MVT::i8:
294   case MVT::i16:
295   case MVT::i32:
296     MF.addLiveOut(PPC::R3);
297     break;
298   case MVT::i64:
299     MF.addLiveOut(PPC::R3);
300     MF.addLiveOut(PPC::R4);
301     break;
302   case MVT::f32:
303   case MVT::f64:
304     MF.addLiveOut(PPC::F1);
305     break;
306   }
307
308   return ArgValues;
309 }
310
311 std::pair<SDOperand, SDOperand>
312 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
313                                  const Type *RetTy, bool isVarArg,
314                                  unsigned CallingConv, bool isTailCall,
315                                  SDOperand Callee, ArgListTy &Args,
316                                  SelectionDAG &DAG) {
317   // args_to_use will accumulate outgoing args for the ISD::CALL case in
318   // SelectExpr to use to put the arguments in the appropriate registers.
319   std::vector<SDOperand> args_to_use;
320
321   // Count how many bytes are to be pushed on the stack, including the linkage
322   // area, and parameter passing area.
323   unsigned NumBytes = 24;
324
325   if (Args.empty()) {
326     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
327                         DAG.getConstant(NumBytes, getPointerTy()));
328   } else {
329     for (unsigned i = 0, e = Args.size(); i != e; ++i)
330       switch (getValueType(Args[i].second)) {
331       default: assert(0 && "Unknown value type!");
332       case MVT::i1:
333       case MVT::i8:
334       case MVT::i16:
335       case MVT::i32:
336       case MVT::f32:
337         NumBytes += 4;
338         break;
339       case MVT::i64:
340       case MVT::f64:
341         NumBytes += 8;
342         break;
343       }
344
345     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
346     // plus 32 bytes of argument space in case any called code gets funky on us.
347     // (Required by ABI to support var arg)
348     if (NumBytes < 56) NumBytes = 56;
349
350     // Adjust the stack pointer for the new arguments...
351     // These operations are automatically eliminated by the prolog/epilog pass
352     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
353                         DAG.getConstant(NumBytes, getPointerTy()));
354
355     // Set up a copy of the stack pointer for use loading and storing any
356     // arguments that may not fit in the registers available for argument
357     // passing.
358     SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
359                                             DAG.getEntryNode());
360
361     // Figure out which arguments are going to go in registers, and which in
362     // memory.  Also, if this is a vararg function, floating point operations
363     // must be stored to our stack, and loaded into integer regs as well, if
364     // any integer regs are available for argument passing.
365     unsigned ArgOffset = 24;
366     unsigned GPR_remaining = 8;
367     unsigned FPR_remaining = 13;
368
369     std::vector<SDOperand> MemOps;
370     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
371       // PtrOff will be used to store the current argument to the stack if a
372       // register cannot be found for it.
373       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
374       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
375       MVT::ValueType ArgVT = getValueType(Args[i].second);
376
377       switch (ArgVT) {
378       default: assert(0 && "Unexpected ValueType for argument!");
379       case MVT::i1:
380       case MVT::i8:
381       case MVT::i16:
382         // Promote the integer to 32 bits.  If the input type is signed use a
383         // sign extend, otherwise use a zero extend.
384         if (Args[i].second->isSigned())
385           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
386         else
387           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
388         // FALL THROUGH
389       case MVT::i32:
390         if (GPR_remaining > 0) {
391           args_to_use.push_back(Args[i].first);
392           --GPR_remaining;
393         } else {
394           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
395                                        Args[i].first, PtrOff,
396                                        DAG.getSrcValue(NULL)));
397         }
398         ArgOffset += 4;
399         break;
400       case MVT::i64:
401         // If we have one free GPR left, we can place the upper half of the i64
402         // in it, and store the other half to the stack.  If we have two or more
403         // free GPRs, then we can pass both halves of the i64 in registers.
404         if (GPR_remaining > 0) {
405           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
406             Args[i].first, DAG.getConstant(1, MVT::i32));
407           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
408             Args[i].first, DAG.getConstant(0, MVT::i32));
409           args_to_use.push_back(Hi);
410           --GPR_remaining;
411           if (GPR_remaining > 0) {
412             args_to_use.push_back(Lo);
413             --GPR_remaining;
414           } else {
415             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
416             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
417             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
418                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
419           }
420         } else {
421           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
422                                        Args[i].first, PtrOff,
423                                        DAG.getSrcValue(NULL)));
424         }
425         ArgOffset += 8;
426         break;
427       case MVT::f32:
428       case MVT::f64:
429         if (FPR_remaining > 0) {
430           args_to_use.push_back(Args[i].first);
431           --FPR_remaining;
432           if (isVarArg) {
433             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
434                                           Args[i].first, PtrOff,
435                                           DAG.getSrcValue(NULL));
436             MemOps.push_back(Store);
437             // Float varargs are always shadowed in available integer registers
438             if (GPR_remaining > 0) {
439               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
440                                            DAG.getSrcValue(NULL));
441               MemOps.push_back(Load);
442               args_to_use.push_back(Load);
443               --GPR_remaining;
444             }
445             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
446               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
447               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
448               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
449                                            DAG.getSrcValue(NULL));
450               MemOps.push_back(Load);
451               args_to_use.push_back(Load);
452               --GPR_remaining;
453             }
454           } else {
455             // If we have any FPRs remaining, we may also have GPRs remaining.
456             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
457             // GPRs.
458             if (GPR_remaining > 0) {
459               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
460               --GPR_remaining;
461             }
462             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
463               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
464               --GPR_remaining;
465             }
466           }
467         } else {
468           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
469                                        Args[i].first, PtrOff,
470                                        DAG.getSrcValue(NULL)));
471         }
472         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
473         break;
474       }
475     }
476     if (!MemOps.empty())
477       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
478   }
479
480   std::vector<MVT::ValueType> RetVals;
481   MVT::ValueType RetTyVT = getValueType(RetTy);
482   if (RetTyVT != MVT::isVoid)
483     RetVals.push_back(RetTyVT);
484   RetVals.push_back(MVT::Other);
485
486   SDOperand TheCall = SDOperand(DAG.getCall(RetVals,
487                                             Chain, Callee, args_to_use), 0);
488   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
489   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
490                       DAG.getConstant(NumBytes, getPointerTy()));
491   return std::make_pair(TheCall, Chain);
492 }
493
494 SDOperand PPC32TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
495                                             Value *VAListV, SelectionDAG &DAG) {
496   // vastart just stores the address of the VarArgsFrameIndex slot into the
497   // memory location argument.
498   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
499   return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
500                      DAG.getSrcValue(VAListV));
501 }
502
503 std::pair<SDOperand,SDOperand>
504 PPC32TargetLowering::LowerVAArg(SDOperand Chain,
505                                 SDOperand VAListP, Value *VAListV,
506                                 const Type *ArgTy, SelectionDAG &DAG) {
507   MVT::ValueType ArgVT = getValueType(ArgTy);
508
509   SDOperand VAList =
510     DAG.getLoad(MVT::i32, Chain, VAListP, DAG.getSrcValue(VAListV));
511   SDOperand Result = DAG.getLoad(ArgVT, Chain, VAList, DAG.getSrcValue(NULL));
512   unsigned Amt;
513   if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
514     Amt = 4;
515   else {
516     assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
517            "Other types should have been promoted for varargs!");
518     Amt = 8;
519   }
520   VAList = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
521                       DAG.getConstant(Amt, VAList.getValueType()));
522   Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
523                       VAList, VAListP, DAG.getSrcValue(VAListV));
524   return std::make_pair(Result, Chain);
525 }
526
527
528 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
529 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
530                         SelectionDAG &DAG) {
531   assert(0 && "LowerFrameReturnAddress unimplemented");
532   abort();
533 }
534
535 namespace {
536 Statistic<>Recorded("ppc-codegen", "Number of recording ops emitted");
537 Statistic<>FusedFP("ppc-codegen", "Number of fused fp operations");
538 Statistic<>FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
539 //===--------------------------------------------------------------------===//
540 /// ISel - PPC32 specific code to select PPC32 machine instructions for
541 /// SelectionDAG operations.
542 //===--------------------------------------------------------------------===//
543 class ISel : public SelectionDAGISel {
544   PPC32TargetLowering PPC32Lowering;
545   SelectionDAG *ISelDAG;  // Hack to support us having a dag->dag transform
546                           // for sdiv and udiv until it is put into the future
547                           // dag combiner.
548
549   /// ExprMap - As shared expressions are codegen'd, we keep track of which
550   /// vreg the value is produced in, so we only emit one copy of each compiled
551   /// tree.
552   std::map<SDOperand, unsigned> ExprMap;
553
554   unsigned GlobalBaseReg;
555   bool GlobalBaseInitialized;
556   bool RecordSuccess;
557 public:
558   ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM),
559                             ISelDAG(0) {}
560
561   /// runOnFunction - Override this function in order to reset our per-function
562   /// variables.
563   virtual bool runOnFunction(Function &Fn) {
564     // Make sure we re-emit a set of the global base reg if necessary
565     GlobalBaseInitialized = false;
566     return SelectionDAGISel::runOnFunction(Fn);
567   }
568
569   /// InstructionSelectBasicBlock - This callback is invoked by
570   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
571   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
572     DEBUG(BB->dump());
573     // Codegen the basic block.
574     ISelDAG = &DAG;
575     Select(DAG.getRoot());
576
577     // Clear state used for selection.
578     ExprMap.clear();
579     ISelDAG = 0;
580   }
581
582   // dag -> dag expanders for integer divide by constant
583   SDOperand BuildSDIVSequence(SDOperand N);
584   SDOperand BuildUDIVSequence(SDOperand N);
585
586   unsigned getGlobalBaseReg();
587   unsigned getConstDouble(double floatVal, unsigned Result);
588   void MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result);
589   bool SelectBitfieldInsert(SDOperand OR, unsigned Result);
590   unsigned FoldIfWideZeroExtend(SDOperand N);
591   unsigned SelectCC(SDOperand CC, unsigned &Opc, bool &Inv, unsigned &Idx);
592   unsigned SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv, unsigned &Idx);
593   unsigned SelectExpr(SDOperand N, bool Recording=false);
594   void Select(SDOperand N);
595
596   unsigned SelectAddr(SDOperand N, unsigned& Reg, int& offset);
597   void SelectBranchCC(SDOperand N);
598   
599   virtual const char *getPassName() const {
600     return "PowerPC Pattern Instruction Selection";
601   } 
602 };
603
604 /// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
605 /// returns zero when the input is not exactly a power of two.
606 static unsigned ExactLog2(unsigned Val) {
607   if (Val == 0 || (Val & (Val-1))) return 0;
608   unsigned Count = 0;
609   while (Val != 1) {
610     Val >>= 1;
611     ++Count;
612   }
613   return Count;
614 }
615
616 // IsRunOfOnes - returns true if Val consists of one contiguous run of 1's with
617 // any number of 0's on either side.  the 1's are allowed to wrap from LSB to
618 // MSB.  so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
619 // not, since all 1's are not contiguous.
620 static bool IsRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
621   bool isRun = true;
622   MB = 0;
623   ME = 0;
624
625   // look for first set bit
626   int i = 0;
627   for (; i < 32; i++) {
628     if ((Val & (1 << (31 - i))) != 0) {
629       MB = i;
630       ME = i;
631       break;
632     }
633   }
634
635   // look for last set bit
636   for (; i < 32; i++) {
637     if ((Val & (1 << (31 - i))) == 0)
638       break;
639     ME = i;
640   }
641
642   // look for next set bit
643   for (; i < 32; i++) {
644     if ((Val & (1 << (31 - i))) != 0)
645       break;
646   }
647
648   // if we exhausted all the bits, we found a match at this point for 0*1*0*
649   if (i == 32)
650     return true;
651
652   // since we just encountered more 1's, if it doesn't wrap around to the
653   // most significant bit of the word, then we did not find a match to 1*0*1* so
654   // exit.
655   if (MB != 0)
656     return false;
657
658   // look for last set bit
659   for (MB = i; i < 32; i++) {
660     if ((Val & (1 << (31 - i))) == 0)
661       break;
662   }
663
664   // if we exhausted all the bits, then we found a match for 1*0*1*, otherwise,
665   // the value is not a run of ones.
666   if (i == 32)
667     return true;
668   return false;
669 }
670
671 /// getImmediateForOpcode - This method returns a value indicating whether
672 /// the ConstantSDNode N can be used as an immediate to Opcode.  The return
673 /// values are either 0, 1 or 2.  0 indicates that either N is not a
674 /// ConstantSDNode, or is not suitable for use by that opcode.
675 /// Return value codes for turning into an enum someday:
676 /// 1: constant may be used in normal immediate form.
677 /// 2: constant may be used in shifted immediate form.
678 /// 3: log base 2 of the constant may be used.
679 /// 4: constant is suitable for integer division conversion
680 /// 5: constant is a bitfield mask
681 ///
682 static unsigned getImmediateForOpcode(SDOperand N, unsigned Opcode,
683                                       unsigned& Imm, bool U = false) {
684   if (N.getOpcode() != ISD::Constant) return 0;
685
686   int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
687
688   switch(Opcode) {
689   default: return 0;
690   case ISD::ADD:
691     if (isInt16(v))             { Imm = v & 0xFFFF; return 1; }
692     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
693     break;
694   case ISD::AND: {
695     unsigned MB, ME;
696     if (IsRunOfOnes(v, MB, ME)) { Imm = MB << 16 | ME & 0xFFFF; return 5; }
697     if (isUInt16(v))            { Imm = v & 0xFFFF; return 1; }
698     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
699     break;
700   }
701   case ISD::XOR:
702   case ISD::OR:
703     if (isUInt16(v))            { Imm = v & 0xFFFF; return 1; }
704     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
705     break;
706   case ISD::MUL:
707     if (isInt16(v))             { Imm = v & 0xFFFF; return 1; }
708     break;
709   case ISD::SUB:
710     // handle subtract-from separately from subtract, since subi is really addi
711     if (U && isInt16(v))        { Imm = v    & 0xFFFF; return 1; }
712     if (!U && isInt16(-v))      { Imm = (-v) & 0xFFFF; return 1; }
713     break;
714   case ISD::SETCC:
715     if (U && isUInt16(v))       { Imm = v & 0xFFFF; return 1; }
716     if (!U && isInt16(v))       { Imm = v & 0xFFFF; return 1; }
717     break;
718   case ISD::SDIV:
719     if (isPowerOf2_32(v))       { Imm = Log2_32(v); return 3; }
720     if (isPowerOf2_32(-v))      { Imm = Log2_32(-v); return 3; }
721     if (v <= -2 || v >= 2) { return 4; }
722     break;
723   case ISD::UDIV:
724     if (v > 1) { return 4; }
725     break;
726   }
727   return 0;
728 }
729
730 /// NodeHasRecordingVariant - If SelectExpr can always produce code for
731 /// NodeOpcode that also sets CR0 as a side effect, return true.  Otherwise,
732 /// return false.
733 static bool NodeHasRecordingVariant(unsigned NodeOpcode) {
734   switch(NodeOpcode) {
735   default: return false;
736   case ISD::AND:
737   case ISD::OR:
738     return true;
739   }
740 }
741
742 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
743 /// to Condition.  If the Condition is unordered or unsigned, the bool argument
744 /// U is set to true, otherwise it is set to false.
745 static unsigned getBCCForSetCC(unsigned Condition, bool& U) {
746   U = false;
747   switch (Condition) {
748   default: assert(0 && "Unknown condition!"); abort();
749   case ISD::SETEQ:  return PPC::BEQ;
750   case ISD::SETNE:  return PPC::BNE;
751   case ISD::SETULT: U = true;
752   case ISD::SETLT:  return PPC::BLT;
753   case ISD::SETULE: U = true;
754   case ISD::SETLE:  return PPC::BLE;
755   case ISD::SETUGT: U = true;
756   case ISD::SETGT:  return PPC::BGT;
757   case ISD::SETUGE: U = true;
758   case ISD::SETGE:  return PPC::BGE;
759   }
760   return 0;
761 }
762
763 /// getCROpForOp - Return the condition register opcode (or inverted opcode)
764 /// associated with the SelectionDAG opcode.
765 static unsigned getCROpForSetCC(unsigned Opcode, bool Inv1, bool Inv2) {
766   switch (Opcode) {
767   default: assert(0 && "Unknown opcode!"); abort();
768   case ISD::AND:
769     if (Inv1 && Inv2) return PPC::CRNOR; // De Morgan's Law
770     if (!Inv1 && !Inv2) return PPC::CRAND;
771     if (Inv1 ^ Inv2) return PPC::CRANDC;
772   case ISD::OR:
773     if (Inv1 && Inv2) return PPC::CRNAND; // De Morgan's Law
774     if (!Inv1 && !Inv2) return PPC::CROR;
775     if (Inv1 ^ Inv2) return PPC::CRORC;
776   }
777   return 0;
778 }
779
780 /// getCRIdxForSetCC - Return the index of the condition register field
781 /// associated with the SetCC condition, and whether or not the field is
782 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
783 static unsigned getCRIdxForSetCC(unsigned Condition, bool& Inv) {
784   switch (Condition) {
785   default: assert(0 && "Unknown condition!"); abort();
786   case ISD::SETULT:
787   case ISD::SETLT:  Inv = false;  return 0;
788   case ISD::SETUGE:
789   case ISD::SETGE:  Inv = true;   return 0;
790   case ISD::SETUGT:
791   case ISD::SETGT:  Inv = false;  return 1;
792   case ISD::SETULE:
793   case ISD::SETLE:  Inv = true;   return 1;
794   case ISD::SETEQ:  Inv = false;  return 2;
795   case ISD::SETNE:  Inv = true;   return 2;
796   }
797   return 0;
798 }
799
800 /// IndexedOpForOp - Return the indexed variant for each of the PowerPC load
801 /// and store immediate instructions.
802 static unsigned IndexedOpForOp(unsigned Opcode) {
803   switch(Opcode) {
804   default: assert(0 && "Unknown opcode!"); abort();
805   case PPC::LBZ: return PPC::LBZX;  case PPC::STB: return PPC::STBX;
806   case PPC::LHZ: return PPC::LHZX;  case PPC::STH: return PPC::STHX;
807   case PPC::LHA: return PPC::LHAX;  case PPC::STW: return PPC::STWX;
808   case PPC::LWZ: return PPC::LWZX;  case PPC::STFS: return PPC::STFSX;
809   case PPC::LFS: return PPC::LFSX;  case PPC::STFD: return PPC::STFDX;
810   case PPC::LFD: return PPC::LFDX;
811   }
812   return 0;
813 }
814
815 // Structure used to return the necessary information to codegen an SDIV as
816 // a multiply.
817 struct ms {
818   int m; // magic number
819   int s; // shift amount
820 };
821
822 struct mu {
823   unsigned int m; // magic number
824   int a;          // add indicator
825   int s;          // shift amount
826 };
827
828 /// magic - calculate the magic numbers required to codegen an integer sdiv as
829 /// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
830 /// or -1.
831 static struct ms magic(int d) {
832   int p;
833   unsigned int ad, anc, delta, q1, r1, q2, r2, t;
834   const unsigned int two31 = 0x80000000U;
835   struct ms mag;
836
837   ad = abs(d);
838   t = two31 + ((unsigned int)d >> 31);
839   anc = t - 1 - t%ad;   // absolute value of nc
840   p = 31;               // initialize p
841   q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
842   r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
843   q2 = two31/ad;        // initialize q2 = 2p/abs(d)
844   r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
845   do {
846     p = p + 1;
847     q1 = 2*q1;        // update q1 = 2p/abs(nc)
848     r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
849     if (r1 >= anc) {  // must be unsigned comparison
850       q1 = q1 + 1;
851       r1 = r1 - anc;
852     }
853     q2 = 2*q2;        // update q2 = 2p/abs(d)
854     r2 = 2*r2;        // update r2 = rem(2p/abs(d))
855     if (r2 >= ad) {   // must be unsigned comparison
856       q2 = q2 + 1;
857       r2 = r2 - ad;
858     }
859     delta = ad - r2;
860   } while (q1 < delta || (q1 == delta && r1 == 0));
861
862   mag.m = q2 + 1;
863   if (d < 0) mag.m = -mag.m; // resulting magic number
864   mag.s = p - 32;            // resulting shift
865   return mag;
866 }
867
868 /// magicu - calculate the magic numbers required to codegen an integer udiv as
869 /// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
870 static struct mu magicu(unsigned d)
871 {
872   int p;
873   unsigned int nc, delta, q1, r1, q2, r2;
874   struct mu magu;
875   magu.a = 0;               // initialize "add" indicator
876   nc = - 1 - (-d)%d;
877   p = 31;                   // initialize p
878   q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
879   r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
880   q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
881   r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
882   do {
883     p = p + 1;
884     if (r1 >= nc - r1 ) {
885       q1 = 2*q1 + 1;  // update q1
886       r1 = 2*r1 - nc; // update r1
887     }
888     else {
889       q1 = 2*q1; // update q1
890       r1 = 2*r1; // update r1
891     }
892     if (r2 + 1 >= d - r2) {
893       if (q2 >= 0x7FFFFFFF) magu.a = 1;
894       q2 = 2*q2 + 1;     // update q2
895       r2 = 2*r2 + 1 - d; // update r2
896     }
897     else {
898       if (q2 >= 0x80000000) magu.a = 1;
899       q2 = 2*q2;     // update q2
900       r2 = 2*r2 + 1; // update r2
901     }
902     delta = d - 1 - r2;
903   } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
904   magu.m = q2 + 1; // resulting magic number
905   magu.s = p - 32;  // resulting shift
906   return magu;
907 }
908 }
909
910 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
911 /// return a DAG expression to select that will generate the same value by
912 /// multiplying by a magic number.  See:
913 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
914 SDOperand ISel::BuildSDIVSequence(SDOperand N) {
915   int d = (int)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
916   ms magics = magic(d);
917   // Multiply the numerator (operand 0) by the magic value
918   SDOperand Q = ISelDAG->getNode(ISD::MULHS, MVT::i32, N.getOperand(0),
919                                  ISelDAG->getConstant(magics.m, MVT::i32));
920   // If d > 0 and m < 0, add the numerator
921   if (d > 0 && magics.m < 0)
922     Q = ISelDAG->getNode(ISD::ADD, MVT::i32, Q, N.getOperand(0));
923   // If d < 0 and m > 0, subtract the numerator.
924   if (d < 0 && magics.m > 0)
925     Q = ISelDAG->getNode(ISD::SUB, MVT::i32, Q, N.getOperand(0));
926   // Shift right algebraic if shift value is nonzero
927   if (magics.s > 0)
928     Q = ISelDAG->getNode(ISD::SRA, MVT::i32, Q,
929                          ISelDAG->getConstant(magics.s, MVT::i32));
930   // Extract the sign bit and add it to the quotient
931   SDOperand T =
932     ISelDAG->getNode(ISD::SRL, MVT::i32, Q, ISelDAG->getConstant(31, MVT::i32));
933   return ISelDAG->getNode(ISD::ADD, MVT::i32, Q, T);
934 }
935
936 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
937 /// return a DAG expression to select that will generate the same value by
938 /// multiplying by a magic number.  See:
939 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
940 SDOperand ISel::BuildUDIVSequence(SDOperand N) {
941   unsigned d =
942     (unsigned)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
943   mu magics = magicu(d);
944   // Multiply the numerator (operand 0) by the magic value
945   SDOperand Q = ISelDAG->getNode(ISD::MULHU, MVT::i32, N.getOperand(0),
946                                  ISelDAG->getConstant(magics.m, MVT::i32));
947   if (magics.a == 0) {
948     Q = ISelDAG->getNode(ISD::SRL, MVT::i32, Q,
949                          ISelDAG->getConstant(magics.s, MVT::i32));
950   } else {
951     SDOperand NPQ = ISelDAG->getNode(ISD::SUB, MVT::i32, N.getOperand(0), Q);
952     NPQ = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
953                            ISelDAG->getConstant(1, MVT::i32));
954     NPQ = ISelDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
955     Q = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
956                            ISelDAG->getConstant(magics.s-1, MVT::i32));
957   }
958   return Q;
959 }
960
961 /// getGlobalBaseReg - Output the instructions required to put the
962 /// base address to use for accessing globals into a register.
963 ///
964 unsigned ISel::getGlobalBaseReg() {
965   if (!GlobalBaseInitialized) {
966     // Insert the set of GlobalBaseReg into the first MBB of the function
967     MachineBasicBlock &FirstMBB = BB->getParent()->front();
968     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
969     GlobalBaseReg = MakeReg(MVT::i32);
970     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
971     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
972     GlobalBaseInitialized = true;
973   }
974   return GlobalBaseReg;
975 }
976
977 /// getConstDouble - Loads a floating point value into a register, via the
978 /// Constant Pool.  Optionally takes a register in which to load the value.
979 unsigned ISel::getConstDouble(double doubleVal, unsigned Result=0) {
980   unsigned Tmp1 = MakeReg(MVT::i32);
981   if (0 == Result) Result = MakeReg(MVT::f64);
982   MachineConstantPool *CP = BB->getParent()->getConstantPool();
983   ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, doubleVal);
984   unsigned CPI = CP->getConstantPoolIndex(CFP);
985   if (PICEnabled)
986     BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
987       .addConstantPoolIndex(CPI);
988   else
989     BuildMI(BB, PPC::LIS, 1, Tmp1).addConstantPoolIndex(CPI);
990   BuildMI(BB, PPC::LFD, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
991   return Result;
992 }
993
994 /// MoveCRtoGPR - Move CCReg[Idx] to the least significant bit of Result.  If
995 /// Inv is true, then invert the result.
996 void ISel::MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result){
997   unsigned IntCR = MakeReg(MVT::i32);
998   BuildMI(BB, PPC::MCRF, 1, PPC::CR7).addReg(CCReg);
999   BuildMI(BB, GPOPT ? PPC::MFOCRF : PPC::MFCR, 1, IntCR).addReg(PPC::CR7);
1000   if (Inv) {
1001     unsigned Tmp1 = MakeReg(MVT::i32);
1002     BuildMI(BB, PPC::RLWINM, 4, Tmp1).addReg(IntCR).addImm(32-(3-Idx))
1003       .addImm(31).addImm(31);
1004     BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(1);
1005   } else {
1006     BuildMI(BB, PPC::RLWINM, 4, Result).addReg(IntCR).addImm(32-(3-Idx))
1007       .addImm(31).addImm(31);
1008   }
1009 }
1010
1011 /// SelectBitfieldInsert - turn an or of two masked values into
1012 /// the rotate left word immediate then mask insert (rlwimi) instruction.
1013 /// Returns true on success, false if the caller still needs to select OR.
1014 ///
1015 /// Patterns matched:
1016 /// 1. or shl, and   5. or and, and
1017 /// 2. or and, shl   6. or shl, shr
1018 /// 3. or shr, and   7. or shr, shl
1019 /// 4. or and, shr
1020 bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
1021   bool IsRotate = false;
1022   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, Amount = 0;
1023
1024   SDOperand Op0 = OR.getOperand(0);
1025   SDOperand Op1 = OR.getOperand(1);
1026
1027   unsigned Op0Opc = Op0.getOpcode();
1028   unsigned Op1Opc = Op1.getOpcode();
1029
1030   // Verify that we have the correct opcodes
1031   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
1032     return false;
1033   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
1034     return false;
1035
1036   // Generate Mask value for Target
1037   if (ConstantSDNode *CN =
1038       dyn_cast<ConstantSDNode>(Op0.getOperand(1).Val)) {
1039     switch(Op0Opc) {
1040     case ISD::SHL: TgtMask <<= (unsigned)CN->getValue(); break;
1041     case ISD::SRL: TgtMask >>= (unsigned)CN->getValue(); break;
1042     case ISD::AND: TgtMask &= (unsigned)CN->getValue(); break;
1043     }
1044   } else {
1045     return false;
1046   }
1047
1048   // Generate Mask value for Insert
1049   if (ConstantSDNode *CN =
1050       dyn_cast<ConstantSDNode>(Op1.getOperand(1).Val)) {
1051     switch(Op1Opc) {
1052     case ISD::SHL:
1053       Amount = CN->getValue();
1054       InsMask <<= Amount;
1055       if (Op0Opc == ISD::SRL) IsRotate = true;
1056       break;
1057     case ISD::SRL:
1058       Amount = CN->getValue();
1059       InsMask >>= Amount;
1060       Amount = 32-Amount;
1061       if (Op0Opc == ISD::SHL) IsRotate = true;
1062       break;
1063     case ISD::AND:
1064       InsMask &= (unsigned)CN->getValue();
1065       break;
1066     }
1067   } else {
1068     return false;
1069   }
1070
1071   unsigned Tmp3 = 0;
1072
1073   // If both of the inputs are ANDs and one of them has a logical shift by
1074   // constant as its input, make that the inserted value so that we can combine
1075   // the shift into the rotate part of the rlwimi instruction
1076   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
1077     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
1078         Op1.getOperand(0).getOpcode() == ISD::SRL) {
1079       if (ConstantSDNode *CN =
1080           dyn_cast<ConstantSDNode>(Op1.getOperand(0).getOperand(1).Val)) {
1081         Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
1082           CN->getValue() : 32 - CN->getValue();
1083         Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
1084       }
1085     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
1086                Op0.getOperand(0).getOpcode() == ISD::SRL) {
1087       if (ConstantSDNode *CN =
1088           dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(1).Val)) {
1089         std::swap(Op0, Op1);
1090         std::swap(TgtMask, InsMask);
1091         Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
1092           CN->getValue() : 32 - CN->getValue();
1093         Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
1094       }
1095     }
1096   }
1097
1098   // Verify that the Target mask and Insert mask together form a full word mask
1099   // and that the Insert mask is a run of set bits (which implies both are runs
1100   // of set bits).  Given that, Select the arguments and generate the rlwimi
1101   // instruction.
1102   unsigned MB, ME;
1103   if (((TgtMask & InsMask) == 0) && IsRunOfOnes(InsMask, MB, ME)) {
1104     unsigned Tmp1, Tmp2;
1105     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
1106     // Check for rotlwi / rotrwi here, a special case of bitfield insert
1107     // where both bitfield halves are sourced from the same value.
1108     if (IsRotate && fullMask &&
1109         OR.getOperand(0).getOperand(0) == OR.getOperand(1).getOperand(0)) {
1110       Tmp1 = SelectExpr(OR.getOperand(0).getOperand(0));
1111       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Amount)
1112         .addImm(0).addImm(31);
1113       return true;
1114     }
1115     if (Op0Opc == ISD::AND && fullMask)
1116       Tmp1 = SelectExpr(Op0.getOperand(0));
1117     else
1118       Tmp1 = SelectExpr(Op0);
1119     Tmp2 = Tmp3 ? Tmp3 : SelectExpr(Op1.getOperand(0));
1120     BuildMI(BB, PPC::RLWIMI, 5, Result).addReg(Tmp1).addReg(Tmp2)
1121       .addImm(Amount).addImm(MB).addImm(ME);
1122     return true;
1123   }
1124   return false;
1125 }
1126
1127 /// FoldIfWideZeroExtend - 32 bit PowerPC implicit masks shift amounts to the
1128 /// low six bits.  If the shift amount is an ISD::AND node with a mask that is
1129 /// wider than the implicit mask, then we can get rid of the AND and let the
1130 /// shift do the mask.
1131 unsigned ISel::FoldIfWideZeroExtend(SDOperand N) {
1132   unsigned C;
1133   if (N.getOpcode() == ISD::AND &&
1134       5 == getImmediateForOpcode(N.getOperand(1), ISD::AND, C) && // isMask
1135       31 == (C & 0xFFFF) && // ME
1136       26 >= (C >> 16))      // MB
1137     return SelectExpr(N.getOperand(0));
1138   else
1139     return SelectExpr(N);
1140 }
1141
1142 unsigned ISel::SelectCC(SDOperand CC, unsigned& Opc, bool &Inv, unsigned& Idx) {
1143   unsigned Result, Tmp1, Tmp2;
1144   bool AlreadySelected = false;
1145   static const unsigned CompareOpcodes[] =
1146     { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };
1147
1148   // Allocate a condition register for this expression
1149   Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
1150
1151   // If the first operand to the select is a SETCC node, then we can fold it
1152   // into the branch that selects which value to return.
1153   if (SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(CC.Val)) {
1154     bool U;
1155     Opc = getBCCForSetCC(SetCC->getCondition(), U);
1156     Idx = getCRIdxForSetCC(SetCC->getCondition(), Inv);
1157
1158     // Pass the optional argument U to getImmediateForOpcode for SETCC,
1159     // so that it knows whether the SETCC immediate range is signed or not.
1160     if (1 == getImmediateForOpcode(SetCC->getOperand(1), ISD::SETCC,
1161                                    Tmp2, U)) {
1162       // For comparisons against zero, we can implicity set CR0 if a recording
1163       // variant (e.g. 'or.' instead of 'or') of the instruction that defines
1164       // operand zero of the SetCC node is available.
1165       if (0 == Tmp2 &&
1166           NodeHasRecordingVariant(SetCC->getOperand(0).getOpcode()) &&
1167           SetCC->getOperand(0).Val->hasOneUse()) {
1168         RecordSuccess = false;
1169         Tmp1 = SelectExpr(SetCC->getOperand(0), true);
1170         if (RecordSuccess) {
1171           ++Recorded;
1172           BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
1173           return Result;
1174         }
1175         AlreadySelected = true;
1176       }
1177       // If we could not implicitly set CR0, then emit a compare immediate
1178       // instead.
1179       if (!AlreadySelected) Tmp1 = SelectExpr(SetCC->getOperand(0));
1180       if (U)
1181         BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1182       else
1183         BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1184     } else {
1185       bool IsInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1186       unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
1187       Tmp1 = SelectExpr(SetCC->getOperand(0));
1188       Tmp2 = SelectExpr(SetCC->getOperand(1));
1189       BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1190     }
1191   } else {
1192     // If this isn't a SetCC, then select the value and compare it against zero,
1193     // treating it as if it were a boolean.
1194     Opc = PPC::BNE;
1195     Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
1196     Tmp1 = SelectExpr(CC);
1197     BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
1198   }
1199   return Result;
1200 }
1201
1202 unsigned ISel::SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv,
1203                             unsigned &Idx) {
1204   bool Inv0, Inv1;
1205   unsigned Idx0, Idx1, CROpc, Opc1, Tmp1, Tmp2;
1206
1207   // Allocate a condition register for this expression
1208   unsigned Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
1209
1210   // Check for the operations we support:
1211   switch(N.getOpcode()) {
1212   default:
1213     Opc = PPC::BNE;
1214     Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
1215     Tmp1 = SelectExpr(N);
1216     BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
1217     break;
1218   case ISD::OR:
1219   case ISD::AND:
1220     Tmp1 = SelectCCExpr(N.getOperand(0), Opc, Inv0, Idx0);
1221     Tmp2 = SelectCCExpr(N.getOperand(1), Opc1, Inv1, Idx1);
1222     CROpc = getCROpForSetCC(N.getOpcode(), Inv0, Inv1);
1223     if (Inv0 && !Inv1) {
1224       std::swap(Tmp1, Tmp2);
1225       std::swap(Idx0, Idx1);
1226       Opc = Opc1;
1227     }
1228     if (Inv0 && Inv1) Opc = PPC32InstrInfo::invertPPCBranchOpcode(Opc);
1229     BuildMI(BB, CROpc, 5, Result).addImm(Idx0).addReg(Tmp1).addImm(Idx0)
1230       .addReg(Tmp2).addImm(Idx1);
1231     Inv = false;
1232     Idx = Idx0;
1233     break;
1234   case ISD::SETCC:
1235     Tmp1 = SelectCC(N, Opc, Inv, Idx);
1236     Result = Tmp1;
1237     break;
1238   }
1239   return Result;
1240 }
1241
1242 /// Check to see if the load is a constant offset from a base register
1243 unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
1244 {
1245   unsigned imm = 0, opcode = N.getOpcode();
1246   if (N.getOpcode() == ISD::ADD) {
1247     bool isFrame = N.getOperand(0).getOpcode() == ISD::FrameIndex;
1248     if (1 == getImmediateForOpcode(N.getOperand(1), opcode, imm)) {
1249       offset = imm;
1250       if (isFrame) {
1251         ++FrameOff;
1252         Reg = cast<FrameIndexSDNode>(N.getOperand(0))->getIndex();
1253         return 1;
1254       } else {
1255         Reg = SelectExpr(N.getOperand(0));
1256         return 0;
1257       }
1258     } else {
1259       Reg = SelectExpr(N.getOperand(0));
1260       offset = SelectExpr(N.getOperand(1));
1261       return 2;
1262     }
1263   }
1264   Reg = SelectExpr(N);
1265   offset = 0;
1266   return 0;
1267 }
1268
1269 void ISel::SelectBranchCC(SDOperand N)
1270 {
1271   MachineBasicBlock *Dest =
1272     cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
1273
1274   bool Inv;
1275   unsigned Opc, CCReg, Idx;
1276   Select(N.getOperand(0));  //chain
1277   CCReg = SelectCC(N.getOperand(1), Opc, Inv, Idx);
1278
1279   // Iterate to the next basic block
1280   ilist<MachineBasicBlock>::iterator It = BB;
1281   ++It;
1282
1283   // If this is a two way branch, then grab the fallthrough basic block argument
1284   // and build a PowerPC branch pseudo-op, suitable for long branch conversion
1285   // if necessary by the branch selection pass.  Otherwise, emit a standard
1286   // conditional branch.
1287   if (N.getOpcode() == ISD::BRCONDTWOWAY) {
1288     MachineBasicBlock *Fallthrough =
1289       cast<BasicBlockSDNode>(N.getOperand(3))->getBasicBlock();
1290     if (Dest != It) {
1291       BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1292         .addMBB(Dest).addMBB(Fallthrough);
1293       if (Fallthrough != It)
1294         BuildMI(BB, PPC::B, 1).addMBB(Fallthrough);
1295     } else {
1296       if (Fallthrough != It) {
1297         Opc = PPC32InstrInfo::invertPPCBranchOpcode(Opc);
1298         BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1299           .addMBB(Fallthrough).addMBB(Dest);
1300       }
1301     }
1302   } else {
1303     // If the fallthrough path is off the end of the function, which would be
1304     // undefined behavior, set it to be the same as the current block because
1305     // we have nothing better to set it to, and leaving it alone will cause the
1306     // PowerPC Branch Selection pass to crash.
1307     if (It == BB->getParent()->end()) It = Dest;
1308     BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1309       .addMBB(Dest).addMBB(It);
1310   }
1311   return;
1312 }
1313
1314 unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
1315   unsigned Result;
1316   unsigned Tmp1, Tmp2, Tmp3;
1317   unsigned Opc = 0;
1318   unsigned opcode = N.getOpcode();
1319
1320   SDNode *Node = N.Val;
1321   MVT::ValueType DestType = N.getValueType();
1322
1323   if (Node->getOpcode() == ISD::CopyFromReg &&
1324       (MRegisterInfo::isVirtualRegister(cast<RegSDNode>(Node)->getReg()) ||
1325        cast<RegSDNode>(Node)->getReg() == PPC::R1))
1326     // Just use the specified register as our input.
1327     return cast<RegSDNode>(Node)->getReg();
1328
1329   unsigned &Reg = ExprMap[N];
1330   if (Reg) return Reg;
1331
1332   switch (N.getOpcode()) {
1333   default:
1334     Reg = Result = (N.getValueType() != MVT::Other) ?
1335                             MakeReg(N.getValueType()) : 1;
1336     break;
1337   case ISD::TAILCALL:
1338   case ISD::CALL:
1339     // If this is a call instruction, make sure to prepare ALL of the result
1340     // values as well as the chain.
1341     if (Node->getNumValues() == 1)
1342       Reg = Result = 1;  // Void call, just a chain.
1343     else {
1344       Result = MakeReg(Node->getValueType(0));
1345       ExprMap[N.getValue(0)] = Result;
1346       for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
1347         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1348       ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
1349     }
1350     break;
1351   case ISD::ADD_PARTS:
1352   case ISD::SUB_PARTS:
1353   case ISD::SHL_PARTS:
1354   case ISD::SRL_PARTS:
1355   case ISD::SRA_PARTS:
1356     Result = MakeReg(Node->getValueType(0));
1357     ExprMap[N.getValue(0)] = Result;
1358     for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
1359       ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1360     break;
1361   }
1362
1363   switch (opcode) {
1364   default:
1365     Node->dump();
1366     assert(0 && "Node not handled!\n");
1367   case ISD::UNDEF:
1368     BuildMI(BB, PPC::IMPLICIT_DEF, 0, Result);
1369     return Result;
1370   case ISD::DYNAMIC_STACKALLOC:
1371     // Generate both result values.  FIXME: Need a better commment here?
1372     if (Result != 1)
1373       ExprMap[N.getValue(1)] = 1;
1374     else
1375       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1376
1377     // FIXME: We are currently ignoring the requested alignment for handling
1378     // greater than the stack alignment.  This will need to be revisited at some
1379     // point.  Align = N.getOperand(2);
1380     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
1381         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
1382       std::cerr << "Cannot allocate stack object with greater alignment than"
1383                 << " the stack alignment yet!";
1384       abort();
1385     }
1386     Select(N.getOperand(0));
1387     Tmp1 = SelectExpr(N.getOperand(1));
1388     // Subtract size from stack pointer, thereby allocating some space.
1389     BuildMI(BB, PPC::SUBF, 2, PPC::R1).addReg(Tmp1).addReg(PPC::R1);
1390     // Put a pointer to the space into the result register by copying the SP
1391     BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R1).addReg(PPC::R1);
1392     return Result;
1393
1394   case ISD::ConstantPool:
1395     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
1396     Tmp2 = MakeReg(MVT::i32);
1397     if (PICEnabled)
1398       BuildMI(BB, PPC::ADDIS, 2, Tmp2).addReg(getGlobalBaseReg())
1399         .addConstantPoolIndex(Tmp1);
1400     else
1401       BuildMI(BB, PPC::LIS, 1, Tmp2).addConstantPoolIndex(Tmp1);
1402     BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp2).addConstantPoolIndex(Tmp1);
1403     return Result;
1404
1405   case ISD::FrameIndex:
1406     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
1407     addFrameReference(BuildMI(BB, PPC::ADDI, 2, Result), (int)Tmp1, 0, false);
1408     return Result;
1409
1410   case ISD::GlobalAddress: {
1411     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1412     Tmp1 = MakeReg(MVT::i32);
1413     if (PICEnabled)
1414       BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
1415         .addGlobalAddress(GV);
1416     else
1417       BuildMI(BB, PPC::LIS, 1, Tmp1).addGlobalAddress(GV);
1418     if (GV->hasWeakLinkage() || GV->isExternal()) {
1419       BuildMI(BB, PPC::LWZ, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
1420     } else {
1421       BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp1).addGlobalAddress(GV);
1422     }
1423     return Result;
1424   }
1425
1426   case ISD::LOAD:
1427   case ISD::EXTLOAD:
1428   case ISD::ZEXTLOAD:
1429   case ISD::SEXTLOAD: {
1430     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
1431       Node->getValueType(0) : cast<VTSDNode>(Node->getOperand(3))->getVT();
1432     bool sext = (ISD::SEXTLOAD == opcode);
1433
1434     // Make sure we generate both values.
1435     if (Result != 1)
1436       ExprMap[N.getValue(1)] = 1;   // Generate the token
1437     else
1438       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1439
1440     SDOperand Chain   = N.getOperand(0);
1441     SDOperand Address = N.getOperand(1);
1442     Select(Chain);
1443
1444     switch (TypeBeingLoaded) {
1445     default: Node->dump(); assert(0 && "Cannot load this type!");
1446     case MVT::i1:  Opc = PPC::LBZ; break;
1447     case MVT::i8:  Opc = PPC::LBZ; break;
1448     case MVT::i16: Opc = sext ? PPC::LHA : PPC::LHZ; break;
1449     case MVT::i32: Opc = PPC::LWZ; break;
1450     case MVT::f32: Opc = PPC::LFS; break;
1451     case MVT::f64: Opc = PPC::LFD; break;
1452     }
1453
1454     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
1455       Tmp1 = MakeReg(MVT::i32);
1456       int CPI = CP->getIndex();
1457       if (PICEnabled)
1458         BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
1459           .addConstantPoolIndex(CPI);
1460       else
1461         BuildMI(BB, PPC::LIS, 1, Tmp1).addConstantPoolIndex(CPI);
1462       BuildMI(BB, Opc, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
1463     } else if (Address.getOpcode() == ISD::FrameIndex) {
1464       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
1465       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
1466     } else if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Address)){
1467       GlobalValue *GV = GN->getGlobal();
1468       Tmp1 = MakeReg(MVT::i32);
1469       if (PICEnabled)
1470         BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
1471           .addGlobalAddress(GV);
1472       else
1473         BuildMI(BB, PPC::LIS, 1, Tmp1).addGlobalAddress(GV);
1474       if (GV->hasWeakLinkage() || GV->isExternal()) {
1475         Tmp2 = MakeReg(MVT::i32);
1476         BuildMI(BB, PPC::LWZ, 2, Tmp2).addGlobalAddress(GV).addReg(Tmp1);
1477         BuildMI(BB, Opc, 2, Result).addSImm(0).addReg(Tmp2);
1478       } else {
1479         BuildMI(BB, Opc, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
1480       }
1481     } else {
1482       int offset;
1483       switch(SelectAddr(Address, Tmp1, offset)) {
1484       default: assert(0 && "Unhandled return value from SelectAddr");
1485       case 0:   // imm offset, no frame, no index
1486         BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
1487         break;
1488       case 1:   // imm offset + frame index
1489         addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1, offset);
1490         break;
1491       case 2:   // base+index addressing
1492         Opc = IndexedOpForOp(Opc);
1493         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(offset);
1494         break;
1495       }
1496     }
1497     return Result;
1498   }
1499
1500   case ISD::TAILCALL:
1501   case ISD::CALL: {
1502     unsigned GPR_idx = 0, FPR_idx = 0;
1503     static const unsigned GPR[] = {
1504       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1505       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1506     };
1507     static const unsigned FPR[] = {
1508       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1509       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1510     };
1511
1512     // Lower the chain for this call.
1513     Select(N.getOperand(0));
1514     ExprMap[N.getValue(Node->getNumValues()-1)] = 1;
1515
1516     MachineInstr *CallMI;
1517     // Emit the correct call instruction based on the type of symbol called.
1518     if (GlobalAddressSDNode *GASD =
1519         dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
1520       CallMI = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(GASD->getGlobal(),
1521                                                            true);
1522     } else if (ExternalSymbolSDNode *ESSDN =
1523                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
1524       CallMI = BuildMI(PPC::CALLpcrel, 1).addExternalSymbol(ESSDN->getSymbol(),
1525                                                             true);
1526     } else {
1527       Tmp1 = SelectExpr(N.getOperand(1));
1528       BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Tmp1).addReg(Tmp1);
1529       BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1530       CallMI = BuildMI(PPC::CALLindirect, 3).addImm(20).addImm(0)
1531         .addReg(PPC::R12);
1532     }
1533
1534     // Load the register args to virtual regs
1535     std::vector<unsigned> ArgVR;
1536     for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
1537       ArgVR.push_back(SelectExpr(N.getOperand(i)));
1538
1539     // Copy the virtual registers into the appropriate argument register
1540     for(int i = 0, e = ArgVR.size(); i < e; ++i) {
1541       switch(N.getOperand(i+2).getValueType()) {
1542       default: Node->dump(); assert(0 && "Unknown value type for call");
1543       case MVT::i1:
1544       case MVT::i8:
1545       case MVT::i16:
1546       case MVT::i32:
1547         assert(GPR_idx < 8 && "Too many int args");
1548         if (N.getOperand(i+2).getOpcode() != ISD::UNDEF) {
1549           BuildMI(BB, PPC::OR,2,GPR[GPR_idx]).addReg(ArgVR[i]).addReg(ArgVR[i]);
1550           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1551         }
1552         ++GPR_idx;
1553         break;
1554       case MVT::f64:
1555       case MVT::f32:
1556         assert(FPR_idx < 13 && "Too many fp args");
1557         BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgVR[i]);
1558         CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1559         ++FPR_idx;
1560         break;
1561       }
1562     }
1563
1564     // Put the call instruction in the correct place in the MachineBasicBlock
1565     BB->push_back(CallMI);
1566
1567     switch (Node->getValueType(0)) {
1568     default: assert(0 && "Unknown value type for call result!");
1569     case MVT::Other: return 1;
1570     case MVT::i1:
1571     case MVT::i8:
1572     case MVT::i16:
1573     case MVT::i32:
1574       if (Node->getValueType(1) == MVT::i32) {
1575         BuildMI(BB, PPC::OR, 2, Result+1).addReg(PPC::R3).addReg(PPC::R3);
1576         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R4).addReg(PPC::R4);
1577       } else {
1578         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R3).addReg(PPC::R3);
1579       }
1580       break;
1581     case MVT::f32:
1582     case MVT::f64:
1583       BuildMI(BB, PPC::FMR, 1, Result).addReg(PPC::F1);
1584       break;
1585     }
1586     return Result+N.ResNo;
1587   }
1588
1589   case ISD::SIGN_EXTEND:
1590   case ISD::SIGN_EXTEND_INREG:
1591     Tmp1 = SelectExpr(N.getOperand(0));
1592     switch(cast<VTSDNode>(Node->getOperand(1))->getVT()) {
1593     default: Node->dump(); assert(0 && "Unhandled SIGN_EXTEND type"); break;
1594     case MVT::i16:
1595       BuildMI(BB, PPC::EXTSH, 1, Result).addReg(Tmp1);
1596       break;
1597     case MVT::i8:
1598       BuildMI(BB, PPC::EXTSB, 1, Result).addReg(Tmp1);
1599       break;
1600     case MVT::i1:
1601       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp1).addSImm(0);
1602       break;
1603     }
1604     return Result;
1605
1606   case ISD::CopyFromReg:
1607     DestType = N.getValue(0).getValueType();
1608     if (Result == 1)
1609       Result = ExprMap[N.getValue(0)] = MakeReg(DestType);
1610     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
1611     if (MVT::isInteger(DestType))
1612       BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1613     else
1614       BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
1615     return Result;
1616
1617   case ISD::SHL:
1618     Tmp1 = SelectExpr(N.getOperand(0));
1619     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1620       Tmp2 = CN->getValue() & 0x1F;
1621       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
1622         .addImm(31-Tmp2);
1623     } else {
1624       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1625       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1626     }
1627     return Result;
1628
1629   case ISD::SRL:
1630     Tmp1 = SelectExpr(N.getOperand(0));
1631     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1632       Tmp2 = CN->getValue() & 0x1F;
1633       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(32-Tmp2)
1634         .addImm(Tmp2).addImm(31);
1635     } else {
1636       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1637       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1638     }
1639     return Result;
1640
1641   case ISD::SRA:
1642     Tmp1 = SelectExpr(N.getOperand(0));
1643     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1644       Tmp2 = CN->getValue() & 0x1F;
1645       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1646     } else {
1647       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1648       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1649     }
1650     return Result;
1651
1652   case ISD::CTLZ:
1653     Tmp1 = SelectExpr(N.getOperand(0));
1654     BuildMI(BB, PPC::CNTLZW, 1, Result).addReg(Tmp1);
1655     return Result;
1656
1657   case ISD::ADD:
1658     if (!MVT::isInteger(DestType)) {
1659       if (!NoExcessFPPrecision && N.getOperand(0).getOpcode() == ISD::MUL &&
1660           N.getOperand(0).Val->hasOneUse()) {
1661         ++FusedFP; // Statistic
1662         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1663         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1664         Tmp3 = SelectExpr(N.getOperand(1));
1665         Opc = DestType == MVT::f64 ? PPC::FMADD : PPC::FMADDS;
1666         BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1667         return Result;
1668       }
1669       if (!NoExcessFPPrecision && N.getOperand(1).getOpcode() == ISD::MUL &&
1670           N.getOperand(1).Val->hasOneUse()) {
1671         ++FusedFP; // Statistic
1672         Tmp1 = SelectExpr(N.getOperand(1).getOperand(0));
1673         Tmp2 = SelectExpr(N.getOperand(1).getOperand(1));
1674         Tmp3 = SelectExpr(N.getOperand(0));
1675         Opc = DestType == MVT::f64 ? PPC::FMADD : PPC::FMADDS;
1676         BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1677         return Result;
1678       }
1679       Opc = DestType == MVT::f64 ? PPC::FADD : PPC::FADDS;
1680       Tmp1 = SelectExpr(N.getOperand(0));
1681       Tmp2 = SelectExpr(N.getOperand(1));
1682       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1683       return Result;
1684     }
1685     Tmp1 = SelectExpr(N.getOperand(0));
1686     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1687       default: assert(0 && "unhandled result code");
1688       case 0: // No immediate
1689         Tmp2 = SelectExpr(N.getOperand(1));
1690         BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1691         break;
1692       case 1: // Low immediate
1693         BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1694         break;
1695       case 2: // Shifted immediate
1696         BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1697         break;
1698     }
1699     return Result;
1700
1701   case ISD::AND:
1702     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1703       default: assert(0 && "unhandled result code");
1704       case 0: // No immediate
1705         // Check for andc: and, (xor a, -1), b
1706         if (N.getOperand(0).getOpcode() == ISD::XOR &&
1707           N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
1708         cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
1709           Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1710           Tmp2 = SelectExpr(N.getOperand(1));
1711           BuildMI(BB, PPC::ANDC, 2, Result).addReg(Tmp2).addReg(Tmp1);
1712           return Result;
1713         }
1714         // It wasn't and-with-complement, emit a regular and
1715         Tmp1 = SelectExpr(N.getOperand(0));
1716         Tmp2 = SelectExpr(N.getOperand(1));
1717         Opc = Recording ? PPC::ANDo : PPC::AND;
1718         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1719         break;
1720       case 1: // Low immediate
1721         Tmp1 = SelectExpr(N.getOperand(0));
1722         BuildMI(BB, PPC::ANDIo, 2, Result).addReg(Tmp1).addImm(Tmp2);
1723         break;
1724       case 2: // Shifted immediate
1725         Tmp1 = SelectExpr(N.getOperand(0));
1726         BuildMI(BB, PPC::ANDISo, 2, Result).addReg(Tmp1).addImm(Tmp2);
1727         break;
1728       case 5: // Bitfield mask
1729         Opc = Recording ? PPC::RLWINMo : PPC::RLWINM;
1730         Tmp3 = Tmp2 >> 16;  // MB
1731         Tmp2 &= 0xFFFF;     // ME
1732
1733         // FIXME: Catch SHL-AND in addition to SRL-AND in this block.
1734         if (N.getOperand(0).getOpcode() == ISD::SRL)
1735           if (ConstantSDNode *SA =
1736               dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
1737
1738             // We can fold the RLWINM and the SRL together if the mask is
1739             // clearing the top bits which are rotated around.
1740             unsigned RotAmt = 32-(SA->getValue() & 31);
1741             if (Tmp2 <= RotAmt) {
1742               Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1743               BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(RotAmt)
1744                 .addImm(Tmp3).addImm(Tmp2);
1745               break;
1746             }
1747           }
1748
1749         Tmp1 = SelectExpr(N.getOperand(0));
1750         BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(0)
1751           .addImm(Tmp3).addImm(Tmp2);
1752         break;
1753     }
1754     RecordSuccess = true;
1755     return Result;
1756
1757   case ISD::OR:
1758     if (SelectBitfieldInsert(N, Result))
1759       return Result;
1760     Tmp1 = SelectExpr(N.getOperand(0));
1761     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1762       default: assert(0 && "unhandled result code");
1763       case 0: // No immediate
1764         Tmp2 = SelectExpr(N.getOperand(1));
1765         Opc = Recording ? PPC::ORo : PPC::OR;
1766         RecordSuccess = true;
1767         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1768         break;
1769       case 1: // Low immediate
1770         BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1771         break;
1772       case 2: // Shifted immediate
1773         BuildMI(BB, PPC::ORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
1774         break;
1775     }
1776     return Result;
1777
1778   case ISD::XOR: {
1779     // Check for EQV: xor, (xor a, -1), b
1780     if (N.getOperand(0).getOpcode() == ISD::XOR &&
1781         N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
1782         cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
1783       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1784       Tmp2 = SelectExpr(N.getOperand(1));
1785       BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
1786       return Result;
1787     }
1788     // Check for NOT, NOR, EQV, and NAND: xor (copy, or, xor, and), -1
1789     if (N.getOperand(1).getOpcode() == ISD::Constant &&
1790         cast<ConstantSDNode>(N.getOperand(1))->isAllOnesValue()) {
1791       switch(N.getOperand(0).getOpcode()) {
1792       case ISD::OR:
1793         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1794         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1795         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1796         break;
1797       case ISD::AND:
1798         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1799         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1800         BuildMI(BB, PPC::NAND, 2, Result).addReg(Tmp1).addReg(Tmp2);
1801         break;
1802       case ISD::XOR:
1803         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1804         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1805         BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
1806         break;
1807       default:
1808         Tmp1 = SelectExpr(N.getOperand(0));
1809         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1810         break;
1811       }
1812       return Result;
1813     }
1814     Tmp1 = SelectExpr(N.getOperand(0));
1815     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1816       default: assert(0 && "unhandled result code");
1817       case 0: // No immediate
1818         Tmp2 = SelectExpr(N.getOperand(1));
1819         BuildMI(BB, PPC::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1820         break;
1821       case 1: // Low immediate
1822         BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1823         break;
1824       case 2: // Shifted immediate
1825         BuildMI(BB, PPC::XORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
1826         break;
1827     }
1828     return Result;
1829   }
1830
1831   case ISD::SUB:
1832     if (!MVT::isInteger(DestType)) {
1833       if (!NoExcessFPPrecision && N.getOperand(0).getOpcode() == ISD::MUL &&
1834           N.getOperand(0).Val->hasOneUse()) {
1835         ++FusedFP; // Statistic
1836         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1837         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1838         Tmp3 = SelectExpr(N.getOperand(1));
1839         Opc = DestType == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS;
1840         BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1841         return Result;
1842       }
1843       if (!NoExcessFPPrecision && N.getOperand(1).getOpcode() == ISD::MUL &&
1844           N.getOperand(1).Val->hasOneUse()) {
1845         ++FusedFP; // Statistic
1846         Tmp1 = SelectExpr(N.getOperand(1).getOperand(0));
1847         Tmp2 = SelectExpr(N.getOperand(1).getOperand(1));
1848         Tmp3 = SelectExpr(N.getOperand(0));
1849         Opc = DestType == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS;
1850         BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1851         return Result;
1852       }
1853       Opc = DestType == MVT::f64 ? PPC::FSUB : PPC::FSUBS;
1854       Tmp1 = SelectExpr(N.getOperand(0));
1855       Tmp2 = SelectExpr(N.getOperand(1));
1856       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1857       return Result;
1858     }
1859     if (1 == getImmediateForOpcode(N.getOperand(0), opcode, Tmp1, true)) {
1860       Tmp2 = SelectExpr(N.getOperand(1));
1861       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp2).addSImm(Tmp1);
1862     } else if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1863       Tmp1 = SelectExpr(N.getOperand(0));
1864       BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1865     } else {
1866       Tmp1 = SelectExpr(N.getOperand(0));
1867       Tmp2 = SelectExpr(N.getOperand(1));
1868       BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
1869     }
1870     return Result;
1871
1872   case ISD::MUL:
1873     Tmp1 = SelectExpr(N.getOperand(0));
1874     if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
1875       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1876     else {
1877       Tmp2 = SelectExpr(N.getOperand(1));
1878       switch (DestType) {
1879       default: assert(0 && "Unknown type to ISD::MUL"); break;
1880       case MVT::i32: Opc = PPC::MULLW; break;
1881       case MVT::f32: Opc = PPC::FMULS; break;
1882       case MVT::f64: Opc = PPC::FMUL; break;
1883       }
1884       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1885     }
1886     return Result;
1887
1888   case ISD::MULHS:
1889   case ISD::MULHU:
1890     Tmp1 = SelectExpr(N.getOperand(0));
1891     Tmp2 = SelectExpr(N.getOperand(1));
1892     Opc = (ISD::MULHU == opcode) ? PPC::MULHWU : PPC::MULHW;
1893     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1894     return Result;
1895
1896   case ISD::SDIV:
1897   case ISD::UDIV:
1898     switch (getImmediateForOpcode(N.getOperand(1), opcode, Tmp3)) {
1899     default: break;
1900     // If this is an sdiv by a power of two, we can use an srawi/addze pair.
1901     case 3:
1902       Tmp1 = MakeReg(MVT::i32);
1903       Tmp2 = SelectExpr(N.getOperand(0));
1904       if ((int)Tmp3 < 0) {
1905         unsigned Tmp4 = MakeReg(MVT::i32);
1906         BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(-Tmp3);
1907         BuildMI(BB, PPC::ADDZE, 1, Tmp4).addReg(Tmp1);
1908         BuildMI(BB, PPC::NEG, 1, Result).addReg(Tmp4);
1909       } else {
1910         BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(Tmp3);
1911         BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp1);
1912       }
1913       return Result;
1914     // If this is a divide by constant, we can emit code using some magic
1915     // constants to implement it as a multiply instead.
1916     case 4:
1917       ExprMap.erase(N);
1918       if (opcode == ISD::SDIV)
1919         return SelectExpr(BuildSDIVSequence(N));
1920       else
1921         return SelectExpr(BuildUDIVSequence(N));
1922     }
1923     Tmp1 = SelectExpr(N.getOperand(0));
1924     Tmp2 = SelectExpr(N.getOperand(1));
1925     switch (DestType) {
1926     default: assert(0 && "Unknown type to ISD::SDIV"); break;
1927     case MVT::i32: Opc = (ISD::UDIV == opcode) ? PPC::DIVWU : PPC::DIVW; break;
1928     case MVT::f32: Opc = PPC::FDIVS; break;
1929     case MVT::f64: Opc = PPC::FDIV; break;
1930     }
1931     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1932     return Result;
1933
1934   case ISD::ADD_PARTS:
1935   case ISD::SUB_PARTS: {
1936     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
1937            "Not an i64 add/sub!");
1938     // Emit all of the operands.
1939     std::vector<unsigned> InVals;
1940     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
1941       InVals.push_back(SelectExpr(N.getOperand(i)));
1942     if (N.getOpcode() == ISD::ADD_PARTS) {
1943       BuildMI(BB, PPC::ADDC, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1944       BuildMI(BB, PPC::ADDE, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
1945     } else {
1946       BuildMI(BB, PPC::SUBFC, 2, Result).addReg(InVals[2]).addReg(InVals[0]);
1947       BuildMI(BB, PPC::SUBFE, 2, Result+1).addReg(InVals[3]).addReg(InVals[1]);
1948     }
1949     return Result+N.ResNo;
1950   }
1951
1952   case ISD::SHL_PARTS:
1953   case ISD::SRA_PARTS:
1954   case ISD::SRL_PARTS: {
1955     assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
1956            "Not an i64 shift!");
1957     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
1958     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
1959     unsigned SHReg = FoldIfWideZeroExtend(N.getOperand(2));
1960     Tmp1 = MakeReg(MVT::i32);
1961     Tmp2 = MakeReg(MVT::i32);
1962     Tmp3 = MakeReg(MVT::i32);
1963     unsigned Tmp4 = MakeReg(MVT::i32);
1964     unsigned Tmp5 = MakeReg(MVT::i32);
1965     unsigned Tmp6 = MakeReg(MVT::i32);
1966     BuildMI(BB, PPC::SUBFIC, 2, Tmp1).addReg(SHReg).addSImm(32);
1967     if (ISD::SHL_PARTS == opcode) {
1968       BuildMI(BB, PPC::SLW, 2, Tmp2).addReg(ShiftOpHi).addReg(SHReg);
1969       BuildMI(BB, PPC::SRW, 2, Tmp3).addReg(ShiftOpLo).addReg(Tmp1);
1970       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1971       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
1972       BuildMI(BB, PPC::SLW, 2, Tmp6).addReg(ShiftOpLo).addReg(Tmp5);
1973       BuildMI(BB, PPC::OR, 2, Result+1).addReg(Tmp4).addReg(Tmp6);
1974       BuildMI(BB, PPC::SLW, 2, Result).addReg(ShiftOpLo).addReg(SHReg);
1975     } else if (ISD::SRL_PARTS == opcode) {
1976       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
1977       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
1978       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1979       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
1980       BuildMI(BB, PPC::SRW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
1981       BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp4).addReg(Tmp6);
1982       BuildMI(BB, PPC::SRW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
1983     } else {
1984       MachineBasicBlock *TmpMBB = new MachineBasicBlock(BB->getBasicBlock());
1985       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
1986       MachineBasicBlock *OldMBB = BB;
1987       MachineFunction *F = BB->getParent();
1988       ilist<MachineBasicBlock>::iterator It = BB; ++It;
1989       F->getBasicBlockList().insert(It, TmpMBB);
1990       F->getBasicBlockList().insert(It, PhiMBB);
1991       BB->addSuccessor(TmpMBB);
1992       BB->addSuccessor(PhiMBB);
1993       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
1994       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
1995       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1996       BuildMI(BB, PPC::ADDICo, 2, Tmp5).addReg(SHReg).addSImm(-32);
1997       BuildMI(BB, PPC::SRAW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
1998       BuildMI(BB, PPC::SRAW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
1999       BuildMI(BB, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2000       // Select correct least significant half if the shift amount > 32
2001       BB = TmpMBB;
2002       unsigned Tmp7 = MakeReg(MVT::i32);
2003       BuildMI(BB, PPC::OR, 2, Tmp7).addReg(Tmp6).addReg(Tmp6);
2004       TmpMBB->addSuccessor(PhiMBB);
2005       BB = PhiMBB;
2006       BuildMI(BB, PPC::PHI, 4, Result).addReg(Tmp4).addMBB(OldMBB)
2007         .addReg(Tmp7).addMBB(TmpMBB);
2008     }
2009     return Result+N.ResNo;
2010   }
2011
2012   case ISD::FP_TO_UINT:
2013   case ISD::FP_TO_SINT: {
2014     bool U = (ISD::FP_TO_UINT == opcode);
2015     Tmp1 = SelectExpr(N.getOperand(0));
2016     if (!U) {
2017       Tmp2 = MakeReg(MVT::f64);
2018       BuildMI(BB, PPC::FCTIWZ, 1, Tmp2).addReg(Tmp1);
2019       int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
2020       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(Tmp2), FrameIdx);
2021       addFrameReference(BuildMI(BB, PPC::LWZ, 2, Result), FrameIdx, 4);
2022       return Result;
2023     } else {
2024       unsigned Zero = getConstDouble(0.0);
2025       unsigned MaxInt = getConstDouble((1LL << 32) - 1);
2026       unsigned Border = getConstDouble(1LL << 31);
2027       unsigned UseZero = MakeReg(MVT::f64);
2028       unsigned UseMaxInt = MakeReg(MVT::f64);
2029       unsigned UseChoice = MakeReg(MVT::f64);
2030       unsigned TmpReg = MakeReg(MVT::f64);
2031       unsigned TmpReg2 = MakeReg(MVT::f64);
2032       unsigned ConvReg = MakeReg(MVT::f64);
2033       unsigned IntTmp = MakeReg(MVT::i32);
2034       unsigned XorReg = MakeReg(MVT::i32);
2035       MachineFunction *F = BB->getParent();
2036       int FrameIdx = F->getFrameInfo()->CreateStackObject(8, 8);
2037       // Update machine-CFG edges
2038       MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2039       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2040       MachineBasicBlock *OldMBB = BB;
2041       ilist<MachineBasicBlock>::iterator It = BB; ++It;
2042       F->getBasicBlockList().insert(It, XorMBB);
2043       F->getBasicBlockList().insert(It, PhiMBB);
2044       BB->addSuccessor(XorMBB);
2045       BB->addSuccessor(PhiMBB);
2046       // Convert from floating point to unsigned 32-bit value
2047       // Use 0 if incoming value is < 0.0
2048       BuildMI(BB, PPC::FSEL, 3, UseZero).addReg(Tmp1).addReg(Tmp1).addReg(Zero);
2049       // Use 2**32 - 1 if incoming value is >= 2**32
2050       BuildMI(BB, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(Tmp1);
2051       BuildMI(BB, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt).addReg(UseZero)
2052         .addReg(MaxInt);
2053       // Subtract 2**31
2054       BuildMI(BB, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2055       // Use difference if >= 2**31
2056       BuildMI(BB, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice).addReg(Border);
2057       BuildMI(BB, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2058         .addReg(UseChoice);
2059       // Convert to integer
2060       BuildMI(BB, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2061       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(ConvReg), FrameIdx);
2062       addFrameReference(BuildMI(BB, PPC::LWZ, 2, IntTmp), FrameIdx, 4);
2063       BuildMI(BB, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2064       BuildMI(BB, PPC::B, 1).addMBB(XorMBB);
2065
2066       // XorMBB:
2067       //   add 2**31 if input was >= 2**31
2068       BB = XorMBB;
2069       BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2070       XorMBB->addSuccessor(PhiMBB);
2071
2072       // PhiMBB:
2073       //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2074       BB = PhiMBB;
2075       BuildMI(BB, PPC::PHI, 4, Result).addReg(IntTmp).addMBB(OldMBB)
2076         .addReg(XorReg).addMBB(XorMBB);
2077       return Result;
2078     }
2079     assert(0 && "Should never get here");
2080     return 0;
2081   }
2082
2083   case ISD::SETCC:
2084     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
2085       if (ConstantSDNode *CN =
2086           dyn_cast<ConstantSDNode>(SetCC->getOperand(1).Val)) {
2087         // We can codegen setcc op, imm very efficiently compared to a brcond.
2088         // Check for those cases here.
2089         // setcc op, 0
2090         if (CN->getValue() == 0) {
2091           Tmp1 = SelectExpr(SetCC->getOperand(0));
2092           switch (SetCC->getCondition()) {
2093           default: SetCC->dump(); assert(0 && "Unhandled SetCC condition"); abort();
2094           case ISD::SETEQ:
2095             Tmp2 = MakeReg(MVT::i32);
2096             BuildMI(BB, PPC::CNTLZW, 1, Tmp2).addReg(Tmp1);
2097             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp2).addImm(27)
2098               .addImm(5).addImm(31);
2099             break;
2100           case ISD::SETNE:
2101             Tmp2 = MakeReg(MVT::i32);
2102             BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(-1);
2103             BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp2).addReg(Tmp1);
2104             break;
2105           case ISD::SETLT:
2106             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(1)
2107               .addImm(31).addImm(31);
2108             break;
2109           case ISD::SETGT:
2110             Tmp2 = MakeReg(MVT::i32);
2111             Tmp3 = MakeReg(MVT::i32);
2112             BuildMI(BB, PPC::NEG, 2, Tmp2).addReg(Tmp1);
2113             BuildMI(BB, PPC::ANDC, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2114             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
2115               .addImm(31).addImm(31);
2116             break;
2117           }
2118           return Result;
2119         }
2120         // setcc op, -1
2121         if (CN->isAllOnesValue()) {
2122           Tmp1 = SelectExpr(SetCC->getOperand(0));
2123           switch (SetCC->getCondition()) {
2124           default: assert(0 && "Unhandled SetCC condition"); abort();
2125           case ISD::SETEQ:
2126             Tmp2 = MakeReg(MVT::i32);
2127             Tmp3 = MakeReg(MVT::i32);
2128             BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(1);
2129             BuildMI(BB, PPC::LI, 1, Tmp3).addSImm(0);
2130             BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp3);
2131             break;
2132           case ISD::SETNE:
2133             Tmp2 = MakeReg(MVT::i32);
2134             Tmp3 = MakeReg(MVT::i32);
2135             BuildMI(BB, PPC::NOR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
2136             BuildMI(BB, PPC::ADDIC, 2, Tmp3).addReg(Tmp2).addSImm(-1);
2137             BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp3).addReg(Tmp2);
2138             break;
2139           case ISD::SETLT:
2140             Tmp2 = MakeReg(MVT::i32);
2141             Tmp3 = MakeReg(MVT::i32);
2142             BuildMI(BB, PPC::ADDI, 2, Tmp2).addReg(Tmp1).addSImm(1);
2143             BuildMI(BB, PPC::AND, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2144             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
2145               .addImm(31).addImm(31);
2146             break;
2147           case ISD::SETGT:
2148             Tmp2 = MakeReg(MVT::i32);
2149             BuildMI(BB, PPC::RLWINM, 4, Tmp2).addReg(Tmp1).addImm(1)
2150               .addImm(31).addImm(31);
2151             BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp2).addImm(1);
2152             break;
2153           }
2154           return Result;
2155         }
2156       }
2157
2158       bool Inv;
2159       unsigned CCReg = SelectCC(N, Opc, Inv, Tmp2);
2160       MoveCRtoGPR(CCReg, Inv, Tmp2, Result);
2161       return Result;
2162     }
2163     assert(0 && "Is this legal?");
2164     return 0;
2165
2166   case ISD::SELECT: {
2167     SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(N.getOperand(0).Val);
2168     if (SetCC && N.getOperand(0).getOpcode() == ISD::SETCC &&
2169         !MVT::isInteger(SetCC->getOperand(0).getValueType()) &&
2170         !MVT::isInteger(N.getOperand(1).getValueType()) &&
2171         !MVT::isInteger(N.getOperand(2).getValueType()) &&
2172         SetCC->getCondition() != ISD::SETEQ &&
2173         SetCC->getCondition() != ISD::SETNE) {
2174       MVT::ValueType VT = SetCC->getOperand(0).getValueType();
2175       unsigned TV = SelectExpr(N.getOperand(1)); // Use if TRUE
2176       unsigned FV = SelectExpr(N.getOperand(2)); // Use if FALSE
2177
2178       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1));
2179       if (CN && (CN->isExactlyValue(-0.0) || CN->isExactlyValue(0.0))) {
2180         switch(SetCC->getCondition()) {
2181         default: assert(0 && "Invalid FSEL condition"); abort();
2182         case ISD::SETULT:
2183         case ISD::SETLT:
2184           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2185         case ISD::SETUGE:
2186         case ISD::SETGE:
2187           Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
2188           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp1).addReg(TV).addReg(FV);
2189           return Result;
2190         case ISD::SETUGT:
2191         case ISD::SETGT:
2192           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2193         case ISD::SETULE:
2194         case ISD::SETLE: {
2195           if (SetCC->getOperand(0).getOpcode() == ISD::FNEG) {
2196             Tmp2 = SelectExpr(SetCC->getOperand(0).getOperand(0));
2197           } else {
2198             Tmp2 = MakeReg(VT);
2199             Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
2200             BuildMI(BB, PPC::FNEG, 1, Tmp2).addReg(Tmp1);
2201           }
2202           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp2).addReg(TV).addReg(FV);
2203           return Result;
2204         }
2205         }
2206       } else {
2207         Opc = (MVT::f64 == VT) ? PPC::FSUB : PPC::FSUBS;
2208         Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
2209         Tmp2 = SelectExpr(SetCC->getOperand(1));
2210         Tmp3 =  MakeReg(VT);
2211         switch(SetCC->getCondition()) {
2212         default: assert(0 && "Invalid FSEL condition"); abort();
2213         case ISD::SETULT:
2214         case ISD::SETLT:
2215           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2216           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
2217           return Result;
2218         case ISD::SETUGE:
2219         case ISD::SETGE:
2220           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2221           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
2222           return Result;
2223         case ISD::SETUGT:
2224         case ISD::SETGT:
2225           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2226           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
2227           return Result;
2228         case ISD::SETULE:
2229         case ISD::SETLE:
2230           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2231           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
2232           return Result;
2233         }
2234       }
2235       assert(0 && "Should never get here");
2236       return 0;
2237     }
2238
2239     bool Inv;
2240     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
2241     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
2242     unsigned CCReg = SelectCC(N.getOperand(0), Opc, Inv, Tmp3);
2243
2244     // Create an iterator with which to insert the MBB for copying the false
2245     // value and the MBB to hold the PHI instruction for this SetCC.
2246     MachineBasicBlock *thisMBB = BB;
2247     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2248     ilist<MachineBasicBlock>::iterator It = BB;
2249     ++It;
2250
2251     //  thisMBB:
2252     //  ...
2253     //   TrueVal = ...
2254     //   cmpTY ccX, r1, r2
2255     //   bCC copy1MBB
2256     //   fallthrough --> copy0MBB
2257     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
2258     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
2259     BuildMI(BB, Opc, 2).addReg(CCReg).addMBB(sinkMBB);
2260     MachineFunction *F = BB->getParent();
2261     F->getBasicBlockList().insert(It, copy0MBB);
2262     F->getBasicBlockList().insert(It, sinkMBB);
2263     // Update machine-CFG edges
2264     BB->addSuccessor(copy0MBB);
2265     BB->addSuccessor(sinkMBB);
2266
2267     //  copy0MBB:
2268     //   %FalseValue = ...
2269     //   # fallthrough to sinkMBB
2270     BB = copy0MBB;
2271     // Update machine-CFG edges
2272     BB->addSuccessor(sinkMBB);
2273
2274     //  sinkMBB:
2275     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2276     //  ...
2277     BB = sinkMBB;
2278     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
2279       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
2280     return Result;
2281   }
2282
2283   case ISD::Constant:
2284     switch (N.getValueType()) {
2285     default: assert(0 && "Cannot use constants of this type!");
2286     case MVT::i1:
2287       BuildMI(BB, PPC::LI, 1, Result)
2288         .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
2289       break;
2290     case MVT::i32:
2291       {
2292         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
2293         if (v < 32768 && v >= -32768) {
2294           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
2295         } else {
2296           Tmp1 = MakeReg(MVT::i32);
2297           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
2298           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
2299         }
2300       }
2301     }
2302     return Result;
2303
2304   case ISD::ConstantFP: {
2305     ConstantFPSDNode *CN = cast<ConstantFPSDNode>(N);
2306     Result = getConstDouble(CN->getValue(), Result);
2307     return Result;
2308   }
2309
2310   case ISD::FNEG:
2311     if (!NoExcessFPPrecision &&
2312         ISD::ADD == N.getOperand(0).getOpcode() &&
2313         N.getOperand(0).Val->hasOneUse() &&
2314         ISD::MUL == N.getOperand(0).getOperand(0).getOpcode() &&
2315         N.getOperand(0).getOperand(0).Val->hasOneUse()) {
2316       ++FusedFP; // Statistic
2317       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0).getOperand(0));
2318       Tmp2 = SelectExpr(N.getOperand(0).getOperand(0).getOperand(1));
2319       Tmp3 = SelectExpr(N.getOperand(0).getOperand(1));
2320       Opc = DestType == MVT::f64 ? PPC::FNMADD : PPC::FNMADDS;
2321       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
2322     } else if (!NoExcessFPPrecision &&
2323         ISD::ADD == N.getOperand(0).getOpcode() &&
2324         N.getOperand(0).Val->hasOneUse() &&
2325         ISD::MUL == N.getOperand(0).getOperand(1).getOpcode() &&
2326         N.getOperand(0).getOperand(1).Val->hasOneUse()) {
2327       ++FusedFP; // Statistic
2328       Tmp1 = SelectExpr(N.getOperand(0).getOperand(1).getOperand(0));
2329       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1).getOperand(1));
2330       Tmp3 = SelectExpr(N.getOperand(0).getOperand(0));
2331       Opc = DestType == MVT::f64 ? PPC::FNMADD : PPC::FNMADDS;
2332       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
2333     } else if (ISD::FABS == N.getOperand(0).getOpcode()) {
2334       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
2335       BuildMI(BB, PPC::FNABS, 1, Result).addReg(Tmp1);
2336     } else {
2337       Tmp1 = SelectExpr(N.getOperand(0));
2338       BuildMI(BB, PPC::FNEG, 1, Result).addReg(Tmp1);
2339     }
2340     return Result;
2341
2342   case ISD::FABS:
2343     Tmp1 = SelectExpr(N.getOperand(0));
2344     BuildMI(BB, PPC::FABS, 1, Result).addReg(Tmp1);
2345     return Result;
2346
2347   case ISD::FSQRT:
2348     Tmp1 = SelectExpr(N.getOperand(0));
2349     Opc = DestType == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS;
2350     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2351     return Result;
2352
2353   case ISD::FP_ROUND:
2354     assert (DestType == MVT::f32 &&
2355             N.getOperand(0).getValueType() == MVT::f64 &&
2356             "only f64 to f32 conversion supported here");
2357     Tmp1 = SelectExpr(N.getOperand(0));
2358     BuildMI(BB, PPC::FRSP, 1, Result).addReg(Tmp1);
2359     return Result;
2360
2361   case ISD::FP_EXTEND:
2362     assert (DestType == MVT::f64 &&
2363             N.getOperand(0).getValueType() == MVT::f32 &&
2364             "only f32 to f64 conversion supported here");
2365     Tmp1 = SelectExpr(N.getOperand(0));
2366     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
2367     return Result;
2368
2369   case ISD::UINT_TO_FP:
2370   case ISD::SINT_TO_FP: {
2371     assert (N.getOperand(0).getValueType() == MVT::i32
2372             && "int to float must operate on i32");
2373     bool IsUnsigned = (ISD::UINT_TO_FP == opcode);
2374     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
2375     Tmp2 = MakeReg(MVT::f64); // temp reg to load the integer value into
2376     Tmp3 = MakeReg(MVT::i32); // temp reg to hold the conversion constant
2377
2378     int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
2379     MachineConstantPool *CP = BB->getParent()->getConstantPool();
2380
2381     if (IsUnsigned) {
2382       unsigned ConstF = getConstDouble(0x1.000000p52);
2383       // Store the hi & low halves of the fp value, currently in int regs
2384       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
2385       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
2386       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp1), FrameIdx, 4);
2387       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
2388       // Generate the return value with a subtract
2389       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
2390     } else {
2391       unsigned ConstF = getConstDouble(0x1.000008p52);
2392       unsigned TmpL = MakeReg(MVT::i32);
2393       // Store the hi & low halves of the fp value, currently in int regs
2394       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
2395       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
2396       BuildMI(BB, PPC::XORIS, 2, TmpL).addReg(Tmp1).addImm(0x8000);
2397       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(TmpL), FrameIdx, 4);
2398       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
2399       // Generate the return value with a subtract
2400       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
2401     }
2402     return Result;
2403   }
2404   }
2405   return 0;
2406 }
2407
2408 void ISel::Select(SDOperand N) {
2409   unsigned Tmp1, Tmp2, Tmp3, Opc;
2410   unsigned opcode = N.getOpcode();
2411
2412   if (!ExprMap.insert(std::make_pair(N, 1)).second)
2413     return;  // Already selected.
2414
2415   SDNode *Node = N.Val;
2416
2417   switch (Node->getOpcode()) {
2418   default:
2419     Node->dump(); std::cerr << "\n";
2420     assert(0 && "Node not handled yet!");
2421   case ISD::EntryToken: return;  // Noop
2422   case ISD::TokenFactor:
2423     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
2424       Select(Node->getOperand(i));
2425     return;
2426   case ISD::CALLSEQ_START:
2427   case ISD::CALLSEQ_END:
2428     Select(N.getOperand(0));
2429     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
2430     Opc = N.getOpcode() == ISD::CALLSEQ_START ? PPC::ADJCALLSTACKDOWN :
2431       PPC::ADJCALLSTACKUP;
2432     BuildMI(BB, Opc, 1).addImm(Tmp1);
2433     return;
2434   case ISD::BR: {
2435     MachineBasicBlock *Dest =
2436       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
2437     Select(N.getOperand(0));
2438     BuildMI(BB, PPC::B, 1).addMBB(Dest);
2439     return;
2440   }
2441   case ISD::BRCOND:
2442   case ISD::BRCONDTWOWAY:
2443     SelectBranchCC(N);
2444     return;
2445   case ISD::CopyToReg:
2446     Select(N.getOperand(0));
2447     Tmp1 = SelectExpr(N.getOperand(1));
2448     Tmp2 = cast<RegSDNode>(N)->getReg();
2449
2450     if (Tmp1 != Tmp2) {
2451       if (N.getOperand(1).getValueType() == MVT::f64 ||
2452           N.getOperand(1).getValueType() == MVT::f32)
2453         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
2454       else
2455         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
2456     }
2457     return;
2458   case ISD::ImplicitDef:
2459     Select(N.getOperand(0));
2460     BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
2461     return;
2462   case ISD::RET:
2463     switch (N.getNumOperands()) {
2464     default:
2465       assert(0 && "Unknown return instruction!");
2466     case 3:
2467       assert(N.getOperand(1).getValueType() == MVT::i32 &&
2468              N.getOperand(2).getValueType() == MVT::i32 &&
2469              "Unknown two-register value!");
2470       Select(N.getOperand(0));
2471       Tmp1 = SelectExpr(N.getOperand(1));
2472       Tmp2 = SelectExpr(N.getOperand(2));
2473       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp2).addReg(Tmp2);
2474       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(Tmp1).addReg(Tmp1);
2475       break;
2476     case 2:
2477       Select(N.getOperand(0));
2478       Tmp1 = SelectExpr(N.getOperand(1));
2479       switch (N.getOperand(1).getValueType()) {
2480         default:
2481           assert(0 && "Unknown return type!");
2482         case MVT::f64:
2483         case MVT::f32:
2484           BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(Tmp1);
2485           break;
2486         case MVT::i32:
2487           BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
2488           break;
2489       }
2490     case 1:
2491       Select(N.getOperand(0));
2492       break;
2493     }
2494     BuildMI(BB, PPC::BLR, 0); // Just emit a 'ret' instruction
2495     return;
2496   case ISD::TRUNCSTORE:
2497   case ISD::STORE: {
2498     SDOperand Chain   = N.getOperand(0);
2499     SDOperand Value   = N.getOperand(1);
2500     SDOperand Address = N.getOperand(2);
2501     Select(Chain);
2502
2503     Tmp1 = SelectExpr(Value); //value
2504
2505     if (opcode == ISD::STORE) {
2506       switch(Value.getValueType()) {
2507       default: assert(0 && "unknown Type in store");
2508       case MVT::i32: Opc = PPC::STW; break;
2509       case MVT::f64: Opc = PPC::STFD; break;
2510       case MVT::f32: Opc = PPC::STFS; break;
2511       }
2512     } else { //ISD::TRUNCSTORE
2513       switch(cast<VTSDNode>(Node->getOperand(4))->getVT()) {
2514       default: assert(0 && "unknown Type in store");
2515       case MVT::i1:
2516       case MVT::i8: Opc  = PPC::STB; break;
2517       case MVT::i16: Opc = PPC::STH; break;
2518       }
2519     }
2520
2521     if(Address.getOpcode() == ISD::FrameIndex) {
2522       Tmp2 = cast<FrameIndexSDNode>(Address)->getIndex();
2523       addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2);
2524     } else if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Address)){
2525       GlobalValue *GV = GN->getGlobal();
2526       Tmp2 = MakeReg(MVT::i32);
2527       if (PICEnabled)
2528         BuildMI(BB, PPC::ADDIS, 2, Tmp2).addReg(getGlobalBaseReg())
2529           .addGlobalAddress(GV);
2530       else
2531         BuildMI(BB, PPC::LIS, 1, Tmp2).addGlobalAddress(GV);
2532       if (GV->hasWeakLinkage() || GV->isExternal()) {
2533         Tmp3 = MakeReg(MVT::i32);
2534         BuildMI(BB, PPC::LWZ, 2, Tmp3).addGlobalAddress(GV).addReg(Tmp2);
2535         BuildMI(BB, Opc, 3).addReg(Tmp1).addSImm(0).addReg(Tmp3);
2536       } else {
2537         BuildMI(BB, Opc, 3).addReg(Tmp1).addGlobalAddress(GV).addReg(Tmp2);
2538       }
2539     } else {
2540       int offset;
2541       switch(SelectAddr(Address, Tmp2, offset)) {
2542       default: assert(0 && "Unhandled return value from SelectAddr");
2543       case 0:   // imm offset, no frame, no index
2544         BuildMI(BB, Opc, 3).addReg(Tmp1).addSImm(offset).addReg(Tmp2);
2545         break;
2546       case 1:   // imm offset + frame index
2547         addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2, offset);
2548         break;
2549       case 2:   // base+index addressing
2550         Opc = IndexedOpForOp(Opc);
2551         BuildMI(BB, Opc, 3).addReg(Tmp1).addReg(Tmp2).addReg(offset);
2552         break;
2553       }
2554     }
2555     return;
2556   }
2557   case ISD::EXTLOAD:
2558   case ISD::SEXTLOAD:
2559   case ISD::ZEXTLOAD:
2560   case ISD::LOAD:
2561   case ISD::CopyFromReg:
2562   case ISD::TAILCALL:
2563   case ISD::CALL:
2564   case ISD::DYNAMIC_STACKALLOC:
2565     ExprMap.erase(N);
2566     SelectExpr(N);
2567     return;
2568   }
2569   assert(0 && "Should not be reached!");
2570 }
2571
2572
2573 /// createPPC32PatternInstructionSelector - This pass converts an LLVM function
2574 /// into a machine code representation using pattern matching and a machine
2575 /// description file.
2576 ///
2577 FunctionPass *llvm::createPPC32ISelPattern(TargetMachine &TM) {
2578   return new ISel(TM);
2579 }
2580