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