i1 loads should also be from the low byte of the argument word.
[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 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PowerPC.h"
15 #include "PowerPCInstrBuilder.h"
16 #include "PowerPCInstrInfo.h"
17 #include "PPC32RegisterInfo.h"
18 #include "llvm/Constants.h"                   // FIXME: REMOVE
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineConstantPool.h" // FIXME: REMOVE
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <set>
32 #include <algorithm>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
37 namespace {
38   class PPC32TargetLowering : public TargetLowering {
39     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
40     int ReturnAddrIndex;              // FrameIndex for return slot.
41   public:
42     PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
43       // Set up the register classes.
44       addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
45       addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
46       addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
47       
48       // PowerPC has no intrinsics for these particular operations
49       setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
50       setOperationAction(ISD::MEMSET, MVT::Other, Expand);
51       setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
52
53       // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
54       setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
55       setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
56
57       setShiftAmountFlavor(Extend);   // shl X, 32 == 0
58       addLegalFPImmediate(+0.0); // Necessary for FSEL
59       addLegalFPImmediate(-0.0); // 
60
61       computeRegisterProperties();
62     }
63
64     /// LowerArguments - This hook must be implemented to indicate how we should
65     /// lower the arguments for the specified function, into the specified DAG.
66     virtual std::vector<SDOperand>
67     LowerArguments(Function &F, SelectionDAG &DAG);
68     
69     /// LowerCallTo - This hook lowers an abstract call to a function into an
70     /// actual call.
71     virtual std::pair<SDOperand, SDOperand>
72     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
73                 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
74     
75     virtual std::pair<SDOperand, SDOperand>
76     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
77     
78     virtual std::pair<SDOperand,SDOperand>
79     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
80                    const Type *ArgTy, SelectionDAG &DAG);
81
82     virtual std::pair<SDOperand, SDOperand>
83     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
84                             SelectionDAG &DAG);
85   };
86 }
87
88
89 std::vector<SDOperand>
90 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
91   //
92   // add beautiful description of PPC stack frame format, or at least some docs
93   //
94   MachineFunction &MF = DAG.getMachineFunction();
95   MachineFrameInfo *MFI = MF.getFrameInfo();
96   MachineBasicBlock& BB = MF.front();
97   std::vector<SDOperand> ArgValues;
98   
99   // Due to the rather complicated nature of the PowerPC ABI, rather than a 
100   // fixed size array of physical args, for the sake of simplicity let the STL
101   // handle tracking them for us.
102   std::vector<unsigned> argVR, argPR, argOp;
103   unsigned ArgOffset = 24;
104   unsigned GPR_remaining = 8;
105   unsigned FPR_remaining = 13;
106   unsigned GPR_idx = 0, FPR_idx = 0;
107   static const unsigned GPR[] = { 
108     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
109     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
110   };
111   static const unsigned FPR[] = {
112     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
113     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
114   };
115
116   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
117   // the arguments start at offset 24, although they are likely to be passed
118   // in registers.
119   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
120     SDOperand newroot, argt;
121     unsigned ObjSize;
122     bool needsLoad = false;
123     MVT::ValueType ObjectVT = getValueType(I->getType());
124     
125     switch (ObjectVT) {
126     default: assert(0 && "Unhandled argument type!");
127     case MVT::i1:
128     case MVT::i8:
129     case MVT::i16:
130     case MVT::i32: 
131       ObjSize = 4;
132       if (GPR_remaining > 0) {
133         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
134         argt = newroot = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32,
135                                             DAG.getRoot());
136         if (ObjectVT != MVT::i32)
137           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
138       } else {
139         needsLoad = true;
140       }
141       break;
142       case MVT::i64: ObjSize = 8;
143       // FIXME: can split 64b load between reg/mem if it is last arg in regs
144       if (GPR_remaining > 1) {
145         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
146         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
147         // Copy the extracted halves into the virtual registers
148         SDOperand argHi = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, 
149                                              DAG.getRoot());
150         SDOperand argLo = DAG.getCopyFromReg(GPR[GPR_idx+1], MVT::i32, argHi);
151         // Build the outgoing arg thingy
152         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
153         newroot = argLo;
154       } else {
155         needsLoad = true; 
156       }
157       break;
158       case MVT::f32: ObjSize = 4;
159       case MVT::f64: ObjSize = 8;
160       if (FPR_remaining > 0) {
161         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
162         argt = newroot = DAG.getCopyFromReg(FPR[FPR_idx], ObjectVT, 
163                                             DAG.getRoot());
164         --FPR_remaining;
165         ++FPR_idx;
166       } else {
167         needsLoad = true;
168       }
169       break;
170     }
171     
172     // We need to load the argument to a virtual register if we determined above
173     // that we ran out of physical registers of the appropriate type 
174     if (needsLoad) {
175       unsigned SubregOffset = 0;
176       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
177       if (ObjectVT == MVT::i16) SubregOffset = 2;
178       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
179       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
180       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, 
181                         DAG.getConstant(SubregOffset, MVT::i32));
182       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN);
183     }
184     
185     // Every 4 bytes of argument space consumes one of the GPRs available for
186     // argument passing.
187     if (GPR_remaining > 0) {
188       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
189       GPR_remaining -= delta;
190       GPR_idx += delta;
191     }
192     ArgOffset += ObjSize;
193     
194     DAG.setRoot(newroot.getValue(1));
195     ArgValues.push_back(argt);
196   }
197
198   // If the function takes variable number of arguments, make a frame index for
199   // the start of the first vararg value... for expansion of llvm.va_start.
200   if (F.isVarArg()) {
201     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
202     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
203     // If this function is vararg, store any remaining integer argument regs
204     // to their spots on the stack so that they may be loaded by deferencing the
205     // result of va_next.
206     std::vector<SDOperand> MemOps;
207     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
208       BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
209       SDOperand Val = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
210       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1), 
211                                     Val, FIN);
212       MemOps.push_back(Store);
213       // Increment the address by four for the next argument to store
214       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
215       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
216     }
217     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
218   }
219
220   return ArgValues;
221 }
222
223 std::pair<SDOperand, SDOperand>
224 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
225                                  const Type *RetTy, bool isVarArg,
226          SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG) {
227   // args_to_use will accumulate outgoing args for the ISD::CALL case in
228   // SelectExpr to use to put the arguments in the appropriate registers.
229   std::vector<SDOperand> args_to_use;
230
231   // Count how many bytes are to be pushed on the stack, including the linkage
232   // area, and parameter passing area.
233   unsigned NumBytes = 24;
234
235   if (Args.empty()) {
236     Chain = DAG.getNode(ISD::ADJCALLSTACKDOWN, MVT::Other, Chain,
237                         DAG.getConstant(NumBytes, getPointerTy()));
238   } else {
239     for (unsigned i = 0, e = Args.size(); i != e; ++i)
240       switch (getValueType(Args[i].second)) {
241       default: assert(0 && "Unknown value type!");
242       case MVT::i1:
243       case MVT::i8:
244       case MVT::i16:
245       case MVT::i32:
246       case MVT::f32:
247         NumBytes += 4;
248         break;
249       case MVT::i64:
250       case MVT::f64:
251         NumBytes += 8;
252         break;
253       }
254     
255     // Just to be safe, we'll always reserve the full 24 bytes of linkage area 
256     // plus 32 bytes of argument space in case any called code gets funky on us.
257     if (NumBytes < 56) NumBytes = 56;
258
259     // Adjust the stack pointer for the new arguments...
260     // These operations are automatically eliminated by the prolog/epilog pass
261     Chain = DAG.getNode(ISD::ADJCALLSTACKDOWN, MVT::Other, Chain,
262                         DAG.getConstant(NumBytes, getPointerTy()));
263
264     // Set up a copy of the stack pointer for use loading and storing any
265     // arguments that may not fit in the registers available for argument
266     // passing.
267     SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
268                                             DAG.getEntryNode());
269     
270     // Figure out which arguments are going to go in registers, and which in
271     // memory.  Also, if this is a vararg function, floating point operations
272     // must be stored to our stack, and loaded into integer regs as well, if
273     // any integer regs are available for argument passing.
274     unsigned ArgOffset = 24;
275     unsigned GPR_remaining = 8;
276     unsigned FPR_remaining = 13;
277     
278     std::vector<SDOperand> MemOps;
279     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
280       // PtrOff will be used to store the current argument to the stack if a
281       // register cannot be found for it.
282       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
283       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
284       MVT::ValueType ArgVT = getValueType(Args[i].second);
285       
286       switch (ArgVT) {
287       default: assert(0 && "Unexpected ValueType for argument!");
288       case MVT::i1:
289       case MVT::i8:
290       case MVT::i16:
291         // Promote the integer to 32 bits.  If the input type is signed use a
292         // sign extend, otherwise use a zero extend.
293         if (Args[i].second->isSigned())
294           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
295         else
296           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
297         // FALL THROUGH
298       case MVT::i32:
299         if (GPR_remaining > 0) {
300           args_to_use.push_back(Args[i].first);
301           --GPR_remaining;
302         } else {
303           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
304                                           Args[i].first, PtrOff));
305         }
306         ArgOffset += 4;
307         break;
308       case MVT::i64:
309         // If we have one free GPR left, we can place the upper half of the i64
310         // in it, and store the other half to the stack.  If we have two or more
311         // free GPRs, then we can pass both halves of the i64 in registers.
312         if (GPR_remaining > 0) {
313           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
314             Args[i].first, DAG.getConstant(1, MVT::i32));
315           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
316             Args[i].first, DAG.getConstant(0, MVT::i32));
317           args_to_use.push_back(Hi);
318           --GPR_remaining;
319           if (GPR_remaining > 0) {
320             args_to_use.push_back(Lo);
321             --GPR_remaining;
322           } else {
323             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
324             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
325             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
326                                             Lo, PtrOff));
327           }
328         } else {
329           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
330                                           Args[i].first, PtrOff));
331         }
332         ArgOffset += 8;
333         break;
334       case MVT::f32:
335       case MVT::f64:
336         if (FPR_remaining > 0) {
337           args_to_use.push_back(Args[i].first);
338           --FPR_remaining;
339           if (isVarArg) {
340             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
341                                           Args[i].first, PtrOff);
342             MemOps.push_back(Store);
343             // Float varargs are always shadowed in available integer registers
344             if (GPR_remaining > 0) {
345               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff);
346               MemOps.push_back(Load);
347               args_to_use.push_back(Load);
348               --GPR_remaining;
349             }
350             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
351               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
352               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
353               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff);
354               MemOps.push_back(Load);
355               args_to_use.push_back(Load);
356               --GPR_remaining;
357             }
358           } else {
359             // If we have any FPRs remaining, we may also have GPRs remaining.
360             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
361             // GPRs.
362             if (GPR_remaining > 0) {
363               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
364               --GPR_remaining;
365             }
366             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
367               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
368               --GPR_remaining;
369             }
370           }
371         } else {
372           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
373                                           Args[i].first, PtrOff));
374         }
375         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
376         break;
377       }
378     }
379     if (!MemOps.empty())
380       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
381   }
382   
383   std::vector<MVT::ValueType> RetVals;
384   MVT::ValueType RetTyVT = getValueType(RetTy);
385   if (RetTyVT != MVT::isVoid)
386     RetVals.push_back(RetTyVT);
387   RetVals.push_back(MVT::Other);
388
389   SDOperand TheCall = SDOperand(DAG.getCall(RetVals, 
390                                             Chain, Callee, args_to_use), 0);
391   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
392   Chain = DAG.getNode(ISD::ADJCALLSTACKUP, MVT::Other, Chain,
393                       DAG.getConstant(NumBytes, getPointerTy()));
394   return std::make_pair(TheCall, Chain);
395 }
396
397 std::pair<SDOperand, SDOperand>
398 PPC32TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
399   //vastart just returns the address of the VarArgsFrameIndex slot.
400   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32), Chain);
401 }
402
403 std::pair<SDOperand,SDOperand> PPC32TargetLowering::
404 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
405                const Type *ArgTy, SelectionDAG &DAG) {
406   MVT::ValueType ArgVT = getValueType(ArgTy);
407   SDOperand Result;
408   if (!isVANext) {
409     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList);
410   } else {
411     unsigned Amt;
412     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
413       Amt = 4;
414     else {
415       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
416              "Other types should have been promoted for varargs!");
417       Amt = 8;
418     }
419     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
420                          DAG.getConstant(Amt, VAList.getValueType()));
421   }
422   return std::make_pair(Result, Chain);
423 }
424                
425
426 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
427 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
428                         SelectionDAG &DAG) {
429   assert(0 && "LowerFrameReturnAddress unimplemented");
430   abort();
431 }
432
433 namespace {
434 Statistic<>NotLogic("ppc-codegen", "Number of inverted logical ops");
435 //===--------------------------------------------------------------------===//
436 /// ISel - PPC32 specific code to select PPC32 machine instructions for
437 /// SelectionDAG operations.
438 //===--------------------------------------------------------------------===//
439 class ISel : public SelectionDAGISel {
440   
441   /// Comment Here.
442   PPC32TargetLowering PPC32Lowering;
443   
444   /// ExprMap - As shared expressions are codegen'd, we keep track of which
445   /// vreg the value is produced in, so we only emit one copy of each compiled
446   /// tree.
447   std::map<SDOperand, unsigned> ExprMap;
448
449   unsigned GlobalBaseReg;
450   bool GlobalBaseInitialized;
451   
452 public:
453   ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) 
454   {}
455   
456   /// runOnFunction - Override this function in order to reset our per-function
457   /// variables.
458   virtual bool runOnFunction(Function &Fn) {
459     // Make sure we re-emit a set of the global base reg if necessary
460     GlobalBaseInitialized = false;
461     return SelectionDAGISel::runOnFunction(Fn);
462   } 
463   
464   /// InstructionSelectBasicBlock - This callback is invoked by
465   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
466   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
467     DEBUG(BB->dump());
468     // Codegen the basic block.
469     Select(DAG.getRoot());
470     
471     // Clear state used for selection.
472     ExprMap.clear();
473   }
474   
475   unsigned getGlobalBaseReg();
476   unsigned getConstDouble(double floatVal, unsigned Result);
477   unsigned SelectSetCR0(SDOperand CC);
478   unsigned SelectExpr(SDOperand N);
479   unsigned SelectExprFP(SDOperand N, unsigned Result);
480   void Select(SDOperand N);
481   
482   bool SelectAddr(SDOperand N, unsigned& Reg, int& offset);
483   void SelectBranchCC(SDOperand N);
484 };
485
486 /// canUseAsImmediateForOpcode - This method returns a value indicating whether
487 /// the ConstantSDNode N can be used as an immediate to Opcode.  The return
488 /// values are either 0, 1 or 2.  0 indicates that either N is not a
489 /// ConstantSDNode, or is not suitable for use by that opcode.  A return value 
490 /// of 1 indicates that the constant may be used in normal immediate form.  A
491 /// return value of 2 indicates that the constant may be used in shifted
492 /// immediate form.  If the return value is nonzero, the constant value is
493 /// placed in Imm.
494 ///
495 static unsigned canUseAsImmediateForOpcode(SDOperand N, unsigned Opcode,
496                                            unsigned& Imm, bool U = false) {
497   if (N.getOpcode() != ISD::Constant) return 0;
498
499   int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
500   
501   switch(Opcode) {
502   default: return 0;
503   case ISD::ADD:
504     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
505     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
506     break;
507   case ISD::AND:
508   case ISD::XOR:
509   case ISD::OR:
510     if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
511     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
512     break;
513   case ISD::MUL:
514   case ISD::SUB:
515     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
516     break;
517   case ISD::SETCC:
518     if (U && (v >= 0 && v <= 65535)) { Imm = v & 0xFFFF; return 1; }
519     if (!U && (v <= 32767 && v >= -32768)) { Imm = v & 0xFFFF; return 1; }
520     break;
521   }
522   return 0;
523 }
524
525 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
526 /// to Condition.  If the Condition is unordered or unsigned, the bool argument
527 /// U is set to true, otherwise it is set to false.
528 static unsigned getBCCForSetCC(unsigned Condition, bool& U) {
529   U = false;
530   switch (Condition) {
531   default: assert(0 && "Unknown condition!"); abort();
532   case ISD::SETEQ:  return PPC::BEQ;
533   case ISD::SETNE:  return PPC::BNE;
534   case ISD::SETULT: U = true;
535   case ISD::SETLT:  return PPC::BLT;
536   case ISD::SETULE: U = true;
537   case ISD::SETLE:  return PPC::BLE;
538   case ISD::SETUGT: U = true;
539   case ISD::SETGT:  return PPC::BGT;
540   case ISD::SETUGE: U = true;
541   case ISD::SETGE:  return PPC::BGE;
542   }
543   return 0;
544 }
545
546 /// IndexedOpForOp - Return the indexed variant for each of the PowerPC load
547 /// and store immediate instructions.
548 static unsigned IndexedOpForOp(unsigned Opcode) {
549   switch(Opcode) {
550   default: assert(0 && "Unknown opcode!"); abort();
551   case PPC::LBZ: return PPC::LBZX;  case PPC::STB: return PPC::STBX;
552   case PPC::LHZ: return PPC::LHZX;  case PPC::STH: return PPC::STHX;
553   case PPC::LHA: return PPC::LHAX;  case PPC::STW: return PPC::STWX;
554   case PPC::LWZ: return PPC::LWZX;  case PPC::STFS: return PPC::STFSX;
555   case PPC::LFS: return PPC::LFSX;  case PPC::STFD: return PPC::STFDX;
556   case PPC::LFD: return PPC::LFDX;
557   }
558   return 0;
559 }
560 }
561
562 /// getGlobalBaseReg - Output the instructions required to put the
563 /// base address to use for accessing globals into a register.
564 ///
565 unsigned ISel::getGlobalBaseReg() {
566   if (!GlobalBaseInitialized) {
567     // Insert the set of GlobalBaseReg into the first MBB of the function
568     MachineBasicBlock &FirstMBB = BB->getParent()->front();
569     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
570     GlobalBaseReg = MakeReg(MVT::i32);
571     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
572     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
573     GlobalBaseInitialized = true;
574   }
575   return GlobalBaseReg;
576 }
577
578 /// getConstDouble - Loads a floating point value into a register, via the 
579 /// Constant Pool.  Optionally takes a register in which to load the value.
580 unsigned ISel::getConstDouble(double doubleVal, unsigned Result=0) {
581   unsigned Tmp1 = MakeReg(MVT::i32);
582   if (0 == Result) Result = MakeReg(MVT::f64);
583   MachineConstantPool *CP = BB->getParent()->getConstantPool();
584   ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, doubleVal);
585   unsigned CPI = CP->getConstantPoolIndex(CFP);
586   BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
587     .addConstantPoolIndex(CPI);
588   BuildMI(BB, PPC::LFD, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
589   return Result;
590 }
591
592 unsigned ISel::SelectSetCR0(SDOperand CC) {
593   unsigned Opc, Tmp1, Tmp2;
594   static const unsigned CompareOpcodes[] = 
595     { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };
596   
597   // If the first operand to the select is a SETCC node, then we can fold it
598   // into the branch that selects which value to return.
599   SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(CC.Val);
600   if (SetCC && CC.getOpcode() == ISD::SETCC) {
601     bool U;
602     Opc = getBCCForSetCC(SetCC->getCondition(), U);
603     Tmp1 = SelectExpr(SetCC->getOperand(0));
604
605     // Pass the optional argument U to canUseAsImmediateForOpcode for SETCC,
606     // so that it knows whether the SETCC immediate range is signed or not.
607     if (1 == canUseAsImmediateForOpcode(SetCC->getOperand(1), ISD::SETCC, 
608                                         Tmp2, U)) {
609       if (U)
610         BuildMI(BB, PPC::CMPLWI, 2, PPC::CR0).addReg(Tmp1).addImm(Tmp2);
611       else
612         BuildMI(BB, PPC::CMPWI, 2, PPC::CR0).addReg(Tmp1).addSImm(Tmp2);
613     } else {
614       bool IsInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
615       unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
616       Tmp2 = SelectExpr(SetCC->getOperand(1));
617       BuildMI(BB, CompareOpc, 2, PPC::CR0).addReg(Tmp1).addReg(Tmp2);
618     }
619   } else {
620     Tmp1 = SelectExpr(CC);
621     BuildMI(BB, PPC::CMPLWI, 2, PPC::CR0).addReg(Tmp1).addImm(0);
622     Opc = PPC::BNE;
623   }
624   return Opc;
625 }
626
627 /// Check to see if the load is a constant offset from a base register
628 bool ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
629 {
630   unsigned imm = 0, opcode = N.getOpcode();
631   if (N.getOpcode() == ISD::ADD) {
632     Reg = SelectExpr(N.getOperand(0));
633     if (1 == canUseAsImmediateForOpcode(N.getOperand(1), opcode, imm)) {
634       offset = imm;
635       return false;
636     } 
637     offset = SelectExpr(N.getOperand(1));
638     return true;
639   }
640   Reg = SelectExpr(N);
641   offset = 0;
642   return false;
643 }
644
645 void ISel::SelectBranchCC(SDOperand N)
646 {
647   assert(N.getOpcode() == ISD::BRCOND && "Not a BranchCC???");
648   MachineBasicBlock *Dest = 
649     cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
650
651   Select(N.getOperand(0));  //chain
652   unsigned Opc = SelectSetCR0(N.getOperand(1));
653   BuildMI(BB, Opc, 2).addReg(PPC::CR0).addMBB(Dest);
654   return;
655 }
656
657 unsigned ISel::SelectExprFP(SDOperand N, unsigned Result)
658 {
659   unsigned Tmp1, Tmp2, Tmp3;
660   unsigned Opc = 0;
661   SDNode *Node = N.Val;
662   MVT::ValueType DestType = N.getValueType();
663   unsigned opcode = N.getOpcode();
664
665   switch (opcode) {
666   default:
667     Node->dump();
668     assert(0 && "Node not handled!\n");
669
670   case ISD::SELECT: {
671     // Attempt to generate FSEL.  We can do this whenever we have an FP result,
672     // and an FP comparison in the SetCC node.
673     SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(N.getOperand(0).Val);
674     if (SetCC && N.getOperand(0).getOpcode() == ISD::SETCC &&
675         !MVT::isInteger(SetCC->getOperand(0).getValueType()) &&
676         SetCC->getCondition() != ISD::SETEQ &&
677         SetCC->getCondition() != ISD::SETNE) {
678       MVT::ValueType VT = SetCC->getOperand(0).getValueType();
679       Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
680       unsigned TV = SelectExpr(N.getOperand(1)); // Use if TRUE
681       unsigned FV = SelectExpr(N.getOperand(2)); // Use if FALSE
682       
683       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1));
684       if (CN && (CN->isExactlyValue(-0.0) || CN->isExactlyValue(0.0))) {
685         switch(SetCC->getCondition()) {
686         default: assert(0 && "Invalid FSEL condition"); abort();
687         case ISD::SETULT:
688         case ISD::SETLT:
689           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp1).addReg(FV).addReg(TV);
690           return Result;
691         case ISD::SETUGE:
692         case ISD::SETGE:
693           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp1).addReg(TV).addReg(FV);
694           return Result;
695         case ISD::SETUGT:
696         case ISD::SETGT: {
697           Tmp2 = MakeReg(VT);
698           BuildMI(BB, PPC::FNEG, 1, Tmp2).addReg(Tmp1);
699           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp2).addReg(FV).addReg(TV);
700           return Result;
701         }
702         case ISD::SETULE:
703         case ISD::SETLE: {
704           Tmp2 = MakeReg(VT);
705           BuildMI(BB, PPC::FNEG, 1, Tmp2).addReg(Tmp1);
706           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp2).addReg(TV).addReg(FV);
707           return Result;
708         }
709         }
710       } else {
711         Opc = (MVT::f64 == VT) ? PPC::FSUB : PPC::FSUBS;
712         Tmp2 = SelectExpr(SetCC->getOperand(1));
713         Tmp3 =  MakeReg(VT);
714         switch(SetCC->getCondition()) {
715         default: assert(0 && "Invalid FSEL condition"); abort();
716         case ISD::SETULT:
717         case ISD::SETLT:
718           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
719           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
720           return Result;
721         case ISD::SETUGE:
722         case ISD::SETGE:
723           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
724           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
725           return Result;
726         case ISD::SETUGT:
727         case ISD::SETGT:
728           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
729           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
730           return Result;
731         case ISD::SETULE:
732         case ISD::SETLE:
733           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
734           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
735           return Result;
736         }
737       }
738       assert(0 && "Should never get here");
739       return 0;
740     }
741     
742     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
743     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
744     Opc = SelectSetCR0(N.getOperand(0));
745
746     // Create an iterator with which to insert the MBB for copying the false 
747     // value and the MBB to hold the PHI instruction for this SetCC.
748     MachineBasicBlock *thisMBB = BB;
749     const BasicBlock *LLVM_BB = BB->getBasicBlock();
750     ilist<MachineBasicBlock>::iterator It = BB;
751     ++It;
752
753     //  thisMBB:
754     //  ...
755     //   TrueVal = ...
756     //   cmpTY cr0, r1, r2
757     //   bCC copy1MBB
758     //   fallthrough --> copy0MBB
759     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
760     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
761     BuildMI(BB, Opc, 2).addReg(PPC::CR0).addMBB(sinkMBB);
762     MachineFunction *F = BB->getParent();
763     F->getBasicBlockList().insert(It, copy0MBB);
764     F->getBasicBlockList().insert(It, sinkMBB);
765     // Update machine-CFG edges
766     BB->addSuccessor(copy0MBB);
767     BB->addSuccessor(sinkMBB);
768
769     //  copy0MBB:
770     //   %FalseValue = ...
771     //   # fallthrough to sinkMBB
772     BB = copy0MBB;
773     // Update machine-CFG edges
774     BB->addSuccessor(sinkMBB);
775
776     //  sinkMBB:
777     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
778     //  ...
779     BB = sinkMBB;
780     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
781       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
782     return Result;
783   }
784
785   case ISD::FNEG:
786     if (ISD::FABS == N.getOperand(0).getOpcode()) {
787       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
788       BuildMI(BB, PPC::FNABS, 1, Result).addReg(Tmp1);
789     } else {
790       Tmp1 = SelectExpr(N.getOperand(0));
791       BuildMI(BB, PPC::FNEG, 1, Result).addReg(Tmp1);
792     }
793     return Result;
794     
795   case ISD::FABS:
796     Tmp1 = SelectExpr(N.getOperand(0));
797     BuildMI(BB, PPC::FABS, 1, Result).addReg(Tmp1);
798     return Result;
799
800   case ISD::FP_ROUND:
801     assert (DestType == MVT::f32 && 
802             N.getOperand(0).getValueType() == MVT::f64 && 
803             "only f64 to f32 conversion supported here");
804     Tmp1 = SelectExpr(N.getOperand(0));
805     BuildMI(BB, PPC::FRSP, 1, Result).addReg(Tmp1);
806     return Result;
807
808   case ISD::FP_EXTEND:
809     assert (DestType == MVT::f64 && 
810             N.getOperand(0).getValueType() == MVT::f32 && 
811             "only f32 to f64 conversion supported here");
812     Tmp1 = SelectExpr(N.getOperand(0));
813     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
814     return Result;
815
816   case ISD::CopyFromReg:
817     if (Result == 1)
818       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
819     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
820     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
821     return Result;
822     
823   case ISD::ConstantFP: {
824     ConstantFPSDNode *CN = cast<ConstantFPSDNode>(N);
825     Result = getConstDouble(CN->getValue(), Result);
826     return Result;
827   }
828     
829   case ISD::MUL:
830   case ISD::ADD:
831   case ISD::SUB:
832   case ISD::SDIV:
833     switch( opcode ) {
834     case ISD::MUL:  Opc = DestType == MVT::f64 ? PPC::FMUL : PPC::FMULS; break;
835     case ISD::ADD:  Opc = DestType == MVT::f64 ? PPC::FADD : PPC::FADDS; break;
836     case ISD::SUB:  Opc = DestType == MVT::f64 ? PPC::FSUB : PPC::FSUBS; break;
837     case ISD::SDIV: Opc = DestType == MVT::f64 ? PPC::FDIV : PPC::FDIVS; break;
838     };
839     Tmp1 = SelectExpr(N.getOperand(0));
840     Tmp2 = SelectExpr(N.getOperand(1));
841     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
842     return Result;
843
844   case ISD::UINT_TO_FP:
845   case ISD::SINT_TO_FP: {
846     assert (N.getOperand(0).getValueType() == MVT::i32 
847             && "int to float must operate on i32");
848     bool IsUnsigned = (ISD::UINT_TO_FP == opcode);
849     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
850     Tmp2 = MakeReg(MVT::f64); // temp reg to load the integer value into
851     Tmp3 = MakeReg(MVT::i32); // temp reg to hold the conversion constant
852     unsigned ConstF = MakeReg(MVT::f64); // temp reg to hold the fp constant
853     
854     int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
855     MachineConstantPool *CP = BB->getParent()->getConstantPool();
856     
857     // FIXME: pull this FP constant generation stuff out into something like
858     // the simple ISel's getReg.
859     if (IsUnsigned) {
860       ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000000p52);
861       unsigned CPI = CP->getConstantPoolIndex(CFP);
862       // Load constant fp value
863       unsigned Tmp4 = MakeReg(MVT::i32);
864       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp4).addReg(getGlobalBaseReg())
865         .addConstantPoolIndex(CPI);
866       BuildMI(BB, PPC::LFD, 2, ConstF).addConstantPoolIndex(CPI).addReg(Tmp4);
867       // Store the hi & low halves of the fp value, currently in int regs
868       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
869       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
870       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp1), FrameIdx, 4);
871       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
872       // Generate the return value with a subtract
873       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
874     } else {
875       ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000008p52);
876       unsigned CPI = CP->getConstantPoolIndex(CFP);
877       // Load constant fp value
878       unsigned Tmp4 = MakeReg(MVT::i32);
879       unsigned TmpL = MakeReg(MVT::i32);
880       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp4).addReg(getGlobalBaseReg())
881         .addConstantPoolIndex(CPI);
882       BuildMI(BB, PPC::LFD, 2, ConstF).addConstantPoolIndex(CPI).addReg(Tmp4);
883       // Store the hi & low halves of the fp value, currently in int regs
884       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
885       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
886       BuildMI(BB, PPC::XORIS, 2, TmpL).addReg(Tmp1).addImm(0x8000);
887       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(TmpL), FrameIdx, 4);
888       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
889       // Generate the return value with a subtract
890       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
891     }
892     return Result;
893   }
894   }
895   assert(0 && "Should never get here");
896   return 0;
897 }
898
899 unsigned ISel::SelectExpr(SDOperand N) {
900   unsigned Result;
901   unsigned Tmp1, Tmp2, Tmp3;
902   unsigned Opc = 0;
903   unsigned opcode = N.getOpcode();
904
905   SDNode *Node = N.Val;
906   MVT::ValueType DestType = N.getValueType();
907
908   unsigned &Reg = ExprMap[N];
909   if (Reg) return Reg;
910
911   switch (N.getOpcode()) {
912   default:
913     Reg = Result = (N.getValueType() != MVT::Other) ?
914                             MakeReg(N.getValueType()) : 1;
915     break;
916   case ISD::CALL:
917     // If this is a call instruction, make sure to prepare ALL of the result
918     // values as well as the chain.
919     if (Node->getNumValues() == 1)
920       Reg = Result = 1;  // Void call, just a chain.
921     else {
922       Result = MakeReg(Node->getValueType(0));
923       ExprMap[N.getValue(0)] = Result;
924       for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
925         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
926       ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
927     }
928     break;
929   case ISD::ADD_PARTS:
930   case ISD::SUB_PARTS:
931   case ISD::SHL_PARTS:
932   case ISD::SRL_PARTS:
933   case ISD::SRA_PARTS:
934     Result = MakeReg(Node->getValueType(0));
935     ExprMap[N.getValue(0)] = Result;
936     for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
937       ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
938     break;
939   }
940
941   if (ISD::CopyFromReg == opcode)
942     DestType = N.getValue(0).getValueType();
943     
944   if (DestType == MVT::f64 || DestType == MVT::f32)
945     if (ISD::LOAD != opcode && ISD::EXTLOAD != opcode && ISD::UNDEF != opcode)
946       return SelectExprFP(N, Result);
947
948   switch (opcode) {
949   default:
950     Node->dump();
951     assert(0 && "Node not handled!\n");
952   case ISD::UNDEF:
953     BuildMI(BB, PPC::IMPLICIT_DEF, 0, Result);
954     return Result;
955   case ISD::DYNAMIC_STACKALLOC:
956     // Generate both result values.  FIXME: Need a better commment here?
957     if (Result != 1)
958       ExprMap[N.getValue(1)] = 1;
959     else
960       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
961
962     // FIXME: We are currently ignoring the requested alignment for handling
963     // greater than the stack alignment.  This will need to be revisited at some
964     // point.  Align = N.getOperand(2);
965     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
966         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
967       std::cerr << "Cannot allocate stack object with greater alignment than"
968                 << " the stack alignment yet!";
969       abort();
970     }
971     Select(N.getOperand(0));
972     Tmp1 = SelectExpr(N.getOperand(1));
973     // Subtract size from stack pointer, thereby allocating some space.
974     BuildMI(BB, PPC::SUBF, 2, PPC::R1).addReg(Tmp1).addReg(PPC::R1);
975     // Put a pointer to the space into the result register by copying the SP
976     BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R1).addReg(PPC::R1);
977     return Result;
978
979   case ISD::ConstantPool:
980     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
981     Tmp2 = MakeReg(MVT::i32);
982     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp2).addReg(getGlobalBaseReg())
983       .addConstantPoolIndex(Tmp1);
984     BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp2).addConstantPoolIndex(Tmp1);
985     return Result;
986
987   case ISD::FrameIndex:
988     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
989     addFrameReference(BuildMI(BB, PPC::ADDI, 2, Result), (int)Tmp1, 0, false);
990     return Result;
991   
992   case ISD::GlobalAddress: {
993     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
994     Tmp1 = MakeReg(MVT::i32);
995     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
996       .addGlobalAddress(GV);
997     if (GV->hasWeakLinkage() || GV->isExternal()) {
998       BuildMI(BB, PPC::LWZ, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
999     } else {
1000       BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp1).addGlobalAddress(GV);
1001     }
1002     return Result;
1003   }
1004
1005   case ISD::LOAD:
1006   case ISD::EXTLOAD:
1007   case ISD::ZEXTLOAD:
1008   case ISD::SEXTLOAD: {
1009     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
1010       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
1011     bool sext = (ISD::SEXTLOAD == opcode);
1012     bool byte = (MVT::i8 == TypeBeingLoaded);
1013     
1014     // Make sure we generate both values.
1015     if (Result != 1)
1016       ExprMap[N.getValue(1)] = 1;   // Generate the token
1017     else
1018       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1019
1020     SDOperand Chain   = N.getOperand(0);
1021     SDOperand Address = N.getOperand(1);
1022     Select(Chain);
1023
1024     switch (TypeBeingLoaded) {
1025     default: Node->dump(); assert(0 && "Cannot load this type!");
1026     case MVT::i1:  Opc = PPC::LBZ; break;
1027     case MVT::i8:  Opc = PPC::LBZ; break;
1028     case MVT::i16: Opc = sext ? PPC::LHA : PPC::LHZ; break;
1029     case MVT::i32: Opc = PPC::LWZ; break;
1030     case MVT::f32: Opc = PPC::LFS; break;
1031     case MVT::f64: Opc = PPC::LFD; break;
1032     }
1033     
1034     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
1035       Tmp1 = MakeReg(MVT::i32);
1036       int CPI = CP->getIndex();
1037       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
1038         .addConstantPoolIndex(CPI);
1039       BuildMI(BB, Opc, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
1040     }
1041     else if(Address.getOpcode() == ISD::FrameIndex) {
1042       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
1043       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
1044     } else {
1045       int offset;
1046       bool idx = SelectAddr(Address, Tmp1, offset);
1047       if (idx) {
1048         Opc = IndexedOpForOp(Opc);
1049         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(offset);
1050       } else {
1051         BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
1052       }
1053     }
1054     return Result;
1055   }
1056     
1057   case ISD::CALL: {
1058     unsigned GPR_idx = 0, FPR_idx = 0;
1059     static const unsigned GPR[] = { 
1060       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1061       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1062     };
1063     static const unsigned FPR[] = {
1064       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1065       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1066     };
1067
1068     // Lower the chain for this call.
1069     Select(N.getOperand(0));
1070     ExprMap[N.getValue(Node->getNumValues()-1)] = 1;
1071
1072     // Load the register args to virtual regs
1073     std::vector<unsigned> ArgVR;
1074     for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
1075       ArgVR.push_back(SelectExpr(N.getOperand(i)));
1076
1077     // Copy the virtual registers into the appropriate argument register
1078     for(int i = 0, e = ArgVR.size(); i < e; ++i) {
1079       switch(N.getOperand(i+2).getValueType()) {
1080       default: Node->dump(); assert(0 && "Unknown value type for call");
1081       case MVT::i1:
1082       case MVT::i8:
1083       case MVT::i16:
1084       case MVT::i32:
1085         assert(GPR_idx < 8 && "Too many int args");
1086         if (N.getOperand(i+2).getOpcode() != ISD::UNDEF)
1087           BuildMI(BB, PPC::OR,2,GPR[GPR_idx]).addReg(ArgVR[i]).addReg(ArgVR[i]);
1088         ++GPR_idx;
1089         break;
1090       case MVT::f64:
1091       case MVT::f32:
1092         assert(FPR_idx < 13 && "Too many fp args");
1093         BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgVR[i]);
1094         ++FPR_idx;
1095         break;
1096       }
1097     }
1098
1099     // Emit the correct call instruction based on the type of symbol called.
1100     if (GlobalAddressSDNode *GASD = 
1101         dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
1102       BuildMI(BB, PPC::CALLpcrel, 1).addGlobalAddress(GASD->getGlobal(), true);
1103     } else if (ExternalSymbolSDNode *ESSDN = 
1104                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
1105       BuildMI(BB, PPC::CALLpcrel, 1).addExternalSymbol(ESSDN->getSymbol(), true);
1106     } else {
1107       Tmp1 = SelectExpr(N.getOperand(1));
1108       BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Tmp1).addReg(Tmp1);
1109       BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1110       BuildMI(BB, PPC::CALLindirect, 3).addImm(20).addImm(0).addReg(PPC::R12);
1111     }
1112
1113     switch (Node->getValueType(0)) {
1114     default: assert(0 && "Unknown value type for call result!");
1115     case MVT::Other: return 1;
1116     case MVT::i1:
1117     case MVT::i8:
1118     case MVT::i16:
1119     case MVT::i32:
1120       if (Node->getValueType(1) == MVT::i32) {
1121         BuildMI(BB, PPC::OR, 2, Result+1).addReg(PPC::R3).addReg(PPC::R3);
1122         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R4).addReg(PPC::R4);
1123       } else {
1124         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R3).addReg(PPC::R3);
1125       }
1126       break;
1127     case MVT::f32:
1128     case MVT::f64:
1129       BuildMI(BB, PPC::FMR, 1, Result).addReg(PPC::F1);
1130       break;
1131     }
1132     return Result+N.ResNo;
1133   }
1134
1135   case ISD::SIGN_EXTEND:
1136   case ISD::SIGN_EXTEND_INREG:
1137     Tmp1 = SelectExpr(N.getOperand(0));
1138     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1139     default: Node->dump(); assert(0 && "Unhandled SIGN_EXTEND type"); break;
1140     case MVT::i16:  
1141       BuildMI(BB, PPC::EXTSH, 1, Result).addReg(Tmp1); 
1142       break;
1143     case MVT::i8:   
1144       BuildMI(BB, PPC::EXTSB, 1, Result).addReg(Tmp1); 
1145       break;
1146     case MVT::i1:
1147       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp1).addSImm(0);
1148       break;
1149     }
1150     return Result;
1151     
1152   case ISD::ZERO_EXTEND_INREG:
1153     Tmp1 = SelectExpr(N.getOperand(0));
1154     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1155     default: Node->dump(); assert(0 && "Unhandled ZERO_EXTEND type"); break;
1156     case MVT::i16:  Tmp2 = 16; break;
1157     case MVT::i8:   Tmp2 = 24; break;
1158     case MVT::i1:   Tmp2 = 31; break;
1159     }
1160     BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(0).addImm(Tmp2)
1161       .addImm(31);
1162     return Result;
1163     
1164   case ISD::CopyFromReg:
1165     if (Result == 1)
1166       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1167     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
1168     BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1169     return Result;
1170
1171   case ISD::SHL:
1172     Tmp1 = SelectExpr(N.getOperand(0));
1173     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1174       Tmp2 = CN->getValue() & 0x1F;
1175       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
1176         .addImm(31-Tmp2);
1177     } else {
1178       Tmp2 = SelectExpr(N.getOperand(1));
1179       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1180     }
1181     return Result;
1182     
1183   case ISD::SRL:
1184     Tmp1 = SelectExpr(N.getOperand(0));
1185     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1186       Tmp2 = CN->getValue() & 0x1F;
1187       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(32-Tmp2)
1188         .addImm(Tmp2).addImm(31);
1189     } else {
1190       Tmp2 = SelectExpr(N.getOperand(1));
1191       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1192     }
1193     return Result;
1194     
1195   case ISD::SRA:
1196     Tmp1 = SelectExpr(N.getOperand(0));
1197     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1198       Tmp2 = CN->getValue() & 0x1F;
1199       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1200     } else {
1201       Tmp2 = SelectExpr(N.getOperand(1));
1202       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1203     }
1204     return Result;
1205   
1206   case ISD::ADD:
1207     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1208     Tmp1 = SelectExpr(N.getOperand(0));
1209     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1210       default: assert(0 && "unhandled result code");
1211       case 0: // No immediate
1212         Tmp2 = SelectExpr(N.getOperand(1));
1213         BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1214         break;
1215       case 1: // Low immediate
1216         BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1217         break;
1218       case 2: // Shifted immediate
1219         BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1220         break;
1221     }
1222     return Result;
1223
1224   case ISD::AND:
1225   case ISD::OR:
1226     Tmp1 = SelectExpr(N.getOperand(0));
1227     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1228       default: assert(0 && "unhandled result code");
1229       case 0: // No immediate
1230         Tmp2 = SelectExpr(N.getOperand(1));
1231         switch (opcode) {
1232         case ISD::AND: Opc = PPC::AND; break;
1233         case ISD::OR:  Opc = PPC::OR;  break;
1234         }
1235         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1236         break;
1237       case 1: // Low immediate
1238         switch (opcode) {
1239         case ISD::AND: Opc = PPC::ANDIo; break;
1240         case ISD::OR:  Opc = PPC::ORI;   break;
1241         }
1242         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
1243         break;
1244       case 2: // Shifted immediate
1245         switch (opcode) {
1246         case ISD::AND: Opc = PPC::ANDISo;  break;
1247         case ISD::OR:  Opc = PPC::ORIS;    break;
1248         }
1249         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
1250         break;
1251     }
1252     return Result;
1253
1254   case ISD::XOR: {
1255     // Check for EQV: xor, (xor a, -1), b
1256     if (N.getOperand(0).getOpcode() == ISD::XOR &&
1257         N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
1258         cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
1259       ++NotLogic;
1260       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1261       Tmp2 = SelectExpr(N.getOperand(1));
1262       BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
1263       return Result;
1264     }
1265     // Check for NOT, NOR, and NAND: xor (copy, or, and), -1
1266     if (N.getOperand(1).getOpcode() == ISD::Constant &&
1267         cast<ConstantSDNode>(N.getOperand(1))->isAllOnesValue()) {
1268       ++NotLogic;
1269       switch(N.getOperand(0).getOpcode()) {
1270       case ISD::OR:
1271         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1272         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1273         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1274         break;
1275       case ISD::AND:
1276         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1277         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1278         BuildMI(BB, PPC::NAND, 2, Result).addReg(Tmp1).addReg(Tmp2);
1279         break;
1280       default:
1281         Tmp1 = SelectExpr(N.getOperand(0));
1282         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1283         break;
1284       }
1285       return Result;
1286     }
1287     Tmp1 = SelectExpr(N.getOperand(0));
1288     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1289       default: assert(0 && "unhandled result code");
1290       case 0: // No immediate
1291         Tmp2 = SelectExpr(N.getOperand(1));
1292         BuildMI(BB, PPC::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1293         break;
1294       case 1: // Low immediate
1295         BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1296         break;
1297       case 2: // Shifted immediate
1298         BuildMI(BB, PPC::XORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
1299         break;
1300     }
1301     return Result;
1302   }
1303
1304   case ISD::SUB:
1305     Tmp2 = SelectExpr(N.getOperand(1));
1306     if (1 == canUseAsImmediateForOpcode(N.getOperand(0), opcode, Tmp1))
1307       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp2).addSImm(Tmp1);
1308     else {
1309       Tmp1 = SelectExpr(N.getOperand(0));
1310       BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
1311     }
1312     return Result;
1313     
1314   case ISD::MUL:
1315     Tmp1 = SelectExpr(N.getOperand(0));
1316     if (1 == canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
1317       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1318     else {
1319       Tmp2 = SelectExpr(N.getOperand(1));
1320       BuildMI(BB, PPC::MULLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1321     }
1322     return Result;
1323
1324   case ISD::SDIV:
1325   case ISD::UDIV:
1326     Tmp1 = SelectExpr(N.getOperand(0));
1327     Tmp2 = SelectExpr(N.getOperand(1));
1328     Opc = (ISD::UDIV == opcode) ? PPC::DIVWU : PPC::DIVW;
1329     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1330     return Result;
1331
1332   case ISD::UREM:
1333   case ISD::SREM: {
1334     Tmp1 = SelectExpr(N.getOperand(0));
1335     Tmp2 = SelectExpr(N.getOperand(1));
1336     Tmp3 = MakeReg(MVT::i32);
1337     unsigned Tmp4 = MakeReg(MVT::i32);
1338     Opc = (ISD::UREM == opcode) ? PPC::DIVWU : PPC::DIVW;
1339     BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1340     BuildMI(BB, PPC::MULLW, 2, Tmp4).addReg(Tmp3).addReg(Tmp2);
1341     BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp4).addReg(Tmp1);
1342     return Result;
1343   }
1344
1345   case ISD::ADD_PARTS:
1346   case ISD::SUB_PARTS: {
1347     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
1348            "Not an i64 add/sub!");
1349     // Emit all of the operands.
1350     std::vector<unsigned> InVals;
1351     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
1352       InVals.push_back(SelectExpr(N.getOperand(i)));
1353     if (N.getOpcode() == ISD::ADD_PARTS) {
1354       BuildMI(BB, PPC::ADDC, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1355       BuildMI(BB, PPC::ADDE, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
1356     } else {
1357       BuildMI(BB, PPC::SUBFC, 2, Result).addReg(InVals[2]).addReg(InVals[0]);
1358       BuildMI(BB, PPC::SUBFE, 2, Result+1).addReg(InVals[3]).addReg(InVals[1]);
1359     }
1360     return Result+N.ResNo;
1361   }
1362
1363   case ISD::SHL_PARTS:
1364   case ISD::SRA_PARTS:
1365   case ISD::SRL_PARTS: {
1366     assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
1367            "Not an i64 shift!");
1368     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
1369     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
1370     unsigned SHReg = SelectExpr(N.getOperand(2));
1371     Tmp1 = MakeReg(MVT::i32);  
1372     Tmp2 = MakeReg(MVT::i32);  
1373     Tmp3 = MakeReg(MVT::i32);
1374     unsigned Tmp4 = MakeReg(MVT::i32);
1375     unsigned Tmp5 = MakeReg(MVT::i32);
1376     unsigned Tmp6 = MakeReg(MVT::i32);
1377     BuildMI(BB, PPC::SUBFIC, 2, Tmp1).addReg(SHReg).addSImm(32);
1378     if (ISD::SHL_PARTS == opcode) {
1379       BuildMI(BB, PPC::SLW, 2, Tmp2).addReg(ShiftOpHi).addReg(SHReg);
1380       BuildMI(BB, PPC::SRW, 2, Tmp3).addReg(ShiftOpLo).addReg(Tmp1);
1381       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1382       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
1383       BuildMI(BB, PPC::SLW, 2, Tmp6).addReg(ShiftOpLo).addReg(Tmp5);
1384       BuildMI(BB, PPC::OR, 2, Result+1).addReg(Tmp4).addReg(Tmp6);
1385       BuildMI(BB, PPC::SLW, 2, Result).addReg(ShiftOpLo).addReg(SHReg);
1386     } else if (ISD::SRL_PARTS == opcode) {
1387       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
1388       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
1389       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1390       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
1391       BuildMI(BB, PPC::SRW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
1392       BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp4).addReg(Tmp6);
1393       BuildMI(BB, PPC::SRW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
1394     } else {
1395       MachineBasicBlock *TmpMBB = new MachineBasicBlock(BB->getBasicBlock());
1396       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
1397       MachineBasicBlock *OldMBB = BB;
1398       MachineFunction *F = BB->getParent();
1399       ilist<MachineBasicBlock>::iterator It = BB; ++It;
1400       F->getBasicBlockList().insert(It, TmpMBB);
1401       F->getBasicBlockList().insert(It, PhiMBB);
1402       BB->addSuccessor(TmpMBB);
1403       BB->addSuccessor(PhiMBB);
1404       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
1405       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
1406       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
1407       BuildMI(BB, PPC::ADDICo, 2, Tmp5).addReg(SHReg).addSImm(-32);
1408       BuildMI(BB, PPC::SRAW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
1409       BuildMI(BB, PPC::SRAW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
1410       BuildMI(BB, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
1411       // Select correct least significant half if the shift amount > 32
1412       BB = TmpMBB;
1413       unsigned Tmp7 = MakeReg(MVT::i32);
1414       BuildMI(BB, PPC::OR, 2, Tmp7).addReg(Tmp6).addReg(Tmp6);
1415       TmpMBB->addSuccessor(PhiMBB);
1416       BB = PhiMBB;
1417       BuildMI(BB, PPC::PHI, 4, Result).addReg(Tmp4).addMBB(OldMBB)
1418         .addReg(Tmp7).addMBB(TmpMBB);
1419     }
1420     return Result+N.ResNo;
1421   }
1422     
1423   case ISD::FP_TO_UINT:
1424   case ISD::FP_TO_SINT: {
1425     bool U = (ISD::FP_TO_UINT == opcode);
1426     Tmp1 = SelectExpr(N.getOperand(0));
1427     if (!U) {
1428       Tmp2 = MakeReg(MVT::f64);
1429       BuildMI(BB, PPC::FCTIWZ, 1, Tmp2).addReg(Tmp1);
1430       int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
1431       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(Tmp2), FrameIdx);
1432       addFrameReference(BuildMI(BB, PPC::LWZ, 2, Result), FrameIdx, 4);
1433       return Result;
1434     } else {
1435       unsigned Zero = getConstDouble(0.0);
1436       unsigned MaxInt = getConstDouble((1LL << 32) - 1);
1437       unsigned Border = getConstDouble(1LL << 31);
1438       unsigned UseZero = MakeReg(MVT::f64);
1439       unsigned UseMaxInt = MakeReg(MVT::f64);
1440       unsigned UseChoice = MakeReg(MVT::f64);
1441       unsigned TmpReg = MakeReg(MVT::f64);
1442       unsigned TmpReg2 = MakeReg(MVT::f64);
1443       unsigned ConvReg = MakeReg(MVT::f64);
1444       unsigned IntTmp = MakeReg(MVT::i32);
1445       unsigned XorReg = MakeReg(MVT::i32);
1446       MachineFunction *F = BB->getParent();
1447       int FrameIdx = F->getFrameInfo()->CreateStackObject(8, 8);
1448       // Update machine-CFG edges
1449       MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
1450       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
1451       MachineBasicBlock *OldMBB = BB;
1452       ilist<MachineBasicBlock>::iterator It = BB; ++It;
1453       F->getBasicBlockList().insert(It, XorMBB);
1454       F->getBasicBlockList().insert(It, PhiMBB);
1455       BB->addSuccessor(XorMBB);
1456       BB->addSuccessor(PhiMBB);
1457       // Convert from floating point to unsigned 32-bit value
1458       // Use 0 if incoming value is < 0.0
1459       BuildMI(BB, PPC::FSEL, 3, UseZero).addReg(Tmp1).addReg(Tmp1).addReg(Zero);
1460       // Use 2**32 - 1 if incoming value is >= 2**32
1461       BuildMI(BB, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(Tmp1);
1462       BuildMI(BB, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt).addReg(UseZero)
1463         .addReg(MaxInt);
1464       // Subtract 2**31
1465       BuildMI(BB, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
1466       // Use difference if >= 2**31
1467       BuildMI(BB, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice).addReg(Border);
1468       BuildMI(BB, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
1469         .addReg(UseChoice);
1470       // Convert to integer
1471       BuildMI(BB, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
1472       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(ConvReg), FrameIdx);
1473       addFrameReference(BuildMI(BB, PPC::LWZ, 2, IntTmp), FrameIdx, 4);
1474       BuildMI(BB, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
1475       BuildMI(BB, PPC::B, 1).addMBB(XorMBB);
1476
1477       // XorMBB:
1478       //   add 2**31 if input was >= 2**31
1479       BB = XorMBB;
1480       BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
1481       XorMBB->addSuccessor(PhiMBB);
1482
1483       // PhiMBB:
1484       //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
1485       BB = PhiMBB;
1486       BuildMI(BB, PPC::PHI, 4, Result).addReg(IntTmp).addMBB(OldMBB)
1487         .addReg(XorReg).addMBB(XorMBB);
1488       return Result;
1489     }
1490     assert(0 && "Should never get here");
1491     return 0;
1492   }
1493  
1494   case ISD::SETCC:
1495     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
1496       Opc = SelectSetCR0(N);
1497       
1498       unsigned TrueValue = MakeReg(MVT::i32);
1499       BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1500       unsigned FalseValue = MakeReg(MVT::i32);
1501       BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1502
1503       // Create an iterator with which to insert the MBB for copying the false 
1504       // value and the MBB to hold the PHI instruction for this SetCC.
1505       MachineBasicBlock *thisMBB = BB;
1506       const BasicBlock *LLVM_BB = BB->getBasicBlock();
1507       ilist<MachineBasicBlock>::iterator It = BB;
1508       ++It;
1509   
1510       //  thisMBB:
1511       //  ...
1512       //   cmpTY cr0, r1, r2
1513       //   %TrueValue = li 1
1514       //   bCC sinkMBB
1515       MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1516       MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1517       BuildMI(BB, Opc, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1518       MachineFunction *F = BB->getParent();
1519       F->getBasicBlockList().insert(It, copy0MBB);
1520       F->getBasicBlockList().insert(It, sinkMBB);
1521       // Update machine-CFG edges
1522       BB->addSuccessor(copy0MBB);
1523       BB->addSuccessor(sinkMBB);
1524
1525       //  copy0MBB:
1526       //   %FalseValue = li 0
1527       //   fallthrough
1528       BB = copy0MBB;
1529       // Update machine-CFG edges
1530       BB->addSuccessor(sinkMBB);
1531
1532       //  sinkMBB:
1533       //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1534       //  ...
1535       BB = sinkMBB;
1536       BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
1537         .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1538       return Result;
1539     }
1540     assert(0 && "Is this legal?");
1541     return 0;
1542     
1543   case ISD::SELECT: {
1544     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
1545     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
1546     Opc = SelectSetCR0(N.getOperand(0));
1547
1548     // Create an iterator with which to insert the MBB for copying the false 
1549     // value and the MBB to hold the PHI instruction for this SetCC.
1550     MachineBasicBlock *thisMBB = BB;
1551     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1552     ilist<MachineBasicBlock>::iterator It = BB;
1553     ++It;
1554
1555     //  thisMBB:
1556     //  ...
1557     //   TrueVal = ...
1558     //   cmpTY cr0, r1, r2
1559     //   bCC copy1MBB
1560     //   fallthrough --> copy0MBB
1561     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1562     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1563     BuildMI(BB, Opc, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1564     MachineFunction *F = BB->getParent();
1565     F->getBasicBlockList().insert(It, copy0MBB);
1566     F->getBasicBlockList().insert(It, sinkMBB);
1567     // Update machine-CFG edges
1568     BB->addSuccessor(copy0MBB);
1569     BB->addSuccessor(sinkMBB);
1570
1571     //  copy0MBB:
1572     //   %FalseValue = ...
1573     //   # fallthrough to sinkMBB
1574     BB = copy0MBB;
1575     // Update machine-CFG edges
1576     BB->addSuccessor(sinkMBB);
1577
1578     //  sinkMBB:
1579     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1580     //  ...
1581     BB = sinkMBB;
1582     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
1583       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1584
1585     // FIXME: Select i64?
1586     return Result;
1587   }
1588
1589   case ISD::Constant:
1590     switch (N.getValueType()) {
1591     default: assert(0 && "Cannot use constants of this type!");
1592     case MVT::i1:
1593       BuildMI(BB, PPC::LI, 1, Result)
1594         .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
1595       break;
1596     case MVT::i32:
1597       {
1598         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
1599         if (v < 32768 && v >= -32768) {
1600           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
1601         } else {
1602           Tmp1 = MakeReg(MVT::i32);
1603           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
1604           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
1605         }
1606       }
1607     }
1608     return Result;
1609   }
1610
1611   return 0;
1612 }
1613
1614 void ISel::Select(SDOperand N) {
1615   unsigned Tmp1, Tmp2, Opc;
1616   unsigned opcode = N.getOpcode();
1617
1618   if (!ExprMap.insert(std::make_pair(N, 1)).second)
1619     return;  // Already selected.
1620
1621   SDNode *Node = N.Val;
1622   
1623   switch (Node->getOpcode()) {
1624   default:
1625     Node->dump(); std::cerr << "\n";
1626     assert(0 && "Node not handled yet!");
1627   case ISD::EntryToken: return;  // Noop
1628   case ISD::TokenFactor:
1629     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1630       Select(Node->getOperand(i));
1631     return;
1632   case ISD::ADJCALLSTACKDOWN:
1633   case ISD::ADJCALLSTACKUP:
1634     Select(N.getOperand(0));
1635     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
1636     Opc = N.getOpcode() == ISD::ADJCALLSTACKDOWN ? PPC::ADJCALLSTACKDOWN :
1637       PPC::ADJCALLSTACKUP;
1638     BuildMI(BB, Opc, 1).addImm(Tmp1);
1639     return;
1640   case ISD::BR: {
1641     MachineBasicBlock *Dest =
1642       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
1643     Select(N.getOperand(0));
1644     BuildMI(BB, PPC::B, 1).addMBB(Dest);
1645     return;
1646   }
1647   case ISD::BRCOND: 
1648     SelectBranchCC(N);
1649     return;
1650   case ISD::CopyToReg:
1651     Select(N.getOperand(0));
1652     Tmp1 = SelectExpr(N.getOperand(1));
1653     Tmp2 = cast<RegSDNode>(N)->getReg();
1654     
1655     if (Tmp1 != Tmp2) {
1656       if (N.getOperand(1).getValueType() == MVT::f64 || 
1657           N.getOperand(1).getValueType() == MVT::f32)
1658         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
1659       else
1660         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
1661     }
1662     return;
1663   case ISD::ImplicitDef:
1664     Select(N.getOperand(0));
1665     BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
1666     return;
1667   case ISD::RET:
1668     switch (N.getNumOperands()) {
1669     default:
1670       assert(0 && "Unknown return instruction!");
1671     case 3:
1672       assert(N.getOperand(1).getValueType() == MVT::i32 &&
1673              N.getOperand(2).getValueType() == MVT::i32 &&
1674                    "Unknown two-register value!");
1675       Select(N.getOperand(0));
1676       Tmp1 = SelectExpr(N.getOperand(1));
1677       Tmp2 = SelectExpr(N.getOperand(2));
1678       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp2).addReg(Tmp2);
1679       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(Tmp1).addReg(Tmp1);
1680       break;
1681     case 2:
1682       Select(N.getOperand(0));
1683       Tmp1 = SelectExpr(N.getOperand(1));
1684       switch (N.getOperand(1).getValueType()) {
1685         default:
1686           assert(0 && "Unknown return type!");
1687         case MVT::f64:
1688         case MVT::f32:
1689           BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(Tmp1);
1690           break;
1691         case MVT::i32:
1692           BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
1693           break;
1694       }
1695     case 1:
1696       Select(N.getOperand(0));
1697       break;
1698     }
1699     BuildMI(BB, PPC::BLR, 0); // Just emit a 'ret' instruction
1700     return;
1701   case ISD::TRUNCSTORE: 
1702   case ISD::STORE: 
1703     {
1704       SDOperand Chain   = N.getOperand(0);
1705       SDOperand Value   = N.getOperand(1);
1706       SDOperand Address = N.getOperand(2);
1707       Select(Chain);
1708
1709       Tmp1 = SelectExpr(Value); //value
1710
1711       if (opcode == ISD::STORE) {
1712         switch(Value.getValueType()) {
1713         default: assert(0 && "unknown Type in store");
1714         case MVT::i32: Opc = PPC::STW; break;
1715         case MVT::f64: Opc = PPC::STFD; break;
1716         case MVT::f32: Opc = PPC::STFS; break;
1717         }
1718       } else { //ISD::TRUNCSTORE
1719         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1720         default: assert(0 && "unknown Type in store");
1721         case MVT::i1: //FIXME: DAG does not promote this load
1722         case MVT::i8: Opc  = PPC::STB; break;
1723         case MVT::i16: Opc = PPC::STH; break;
1724         }
1725       }
1726
1727       if(Address.getOpcode() == ISD::FrameIndex)
1728       {
1729         Tmp2 = cast<FrameIndexSDNode>(Address)->getIndex();
1730         addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2);
1731       }
1732       else
1733       {
1734         int offset;
1735         bool idx = SelectAddr(Address, Tmp2, offset);
1736         if (idx) { 
1737           Opc = IndexedOpForOp(Opc);
1738           BuildMI(BB, Opc, 3).addReg(Tmp1).addReg(Tmp2).addReg(offset);
1739         } else {
1740           BuildMI(BB, Opc, 3).addReg(Tmp1).addImm(offset).addReg(Tmp2);
1741         }
1742       }
1743       return;
1744     }
1745   case ISD::EXTLOAD:
1746   case ISD::SEXTLOAD:
1747   case ISD::ZEXTLOAD:
1748   case ISD::LOAD:
1749   case ISD::CopyFromReg:
1750   case ISD::CALL:
1751   case ISD::DYNAMIC_STACKALLOC:
1752     ExprMap.erase(N);
1753     SelectExpr(N);
1754     return;
1755   }
1756   assert(0 && "Should not be reached!");
1757 }
1758
1759
1760 /// createPPC32PatternInstructionSelector - This pass converts an LLVM function
1761 /// into a machine code representation using pattern matching and a machine
1762 /// description file.
1763 ///
1764 FunctionPass *llvm::createPPC32ISelPattern(TargetMachine &TM) {
1765   return new ISel(TM);  
1766 }
1767