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