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