* Specify that FP arith options have 3 operands
[oota-llvm.git] / lib / Target / PowerPC / PowerPCISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "isel"
11 #include "PowerPC.h"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/Debug.h"
29 #include <vector>
30 #include <iostream>
31 using namespace llvm;
32
33 namespace {
34   /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
35   /// PPC Representation.
36   ///
37   enum TypeClass {
38     cByte, cShort, cInt, cFP, cLong
39   };
40 }
41
42 /// getClass - Turn a primitive type into a "class" number which is based on the
43 /// size of the type, and whether or not it is floating point.
44 ///
45 static inline TypeClass getClass(const Type *Ty) {
46   switch (Ty->getTypeID()) {
47   case Type::SByteTyID:
48   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
49   case Type::ShortTyID:
50   case Type::UShortTyID:  return cShort;     // Short operands are class #1
51   case Type::IntTyID:
52   case Type::UIntTyID:
53   case Type::PointerTyID: return cInt;       // Ints and pointers are class #2
54
55   case Type::FloatTyID:
56   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
57
58   case Type::LongTyID:
59   case Type::ULongTyID:   return cLong;      // Longs are class #4
60   default:
61     assert(0 && "Invalid type to getClass!");
62     return cByte;  // not reached
63   }
64 }
65
66 // getClassB - Just like getClass, but treat boolean values as ints.
67 static inline TypeClass getClassB(const Type *Ty) {
68   if (Ty == Type::BoolTy) return cInt;
69   return getClass(Ty);
70 }
71
72 namespace {
73   struct ISel : public FunctionPass, InstVisitor<ISel> {
74     TargetMachine &TM;
75     MachineFunction *F;                 // The function we are compiling into
76     MachineBasicBlock *BB;              // The current MBB we are compiling
77     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
78     int ReturnAddressIndex;             // FrameIndex for the return address
79
80     std::map<Value*, unsigned> RegMap;  // Mapping between Values and SSA Regs
81
82     // External functions used in the Module
83     Function *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn, *__udivdi3Fn,
84       *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
85
86     // MBBMap - Mapping between LLVM BB -> Machine BB
87     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
89     // AllocaMap - Mapping from fixed sized alloca instructions to the
90     // FrameIndex for the alloca.
91     std::map<AllocaInst*, unsigned> AllocaMap;
92
93     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
94
95     bool doInitialization(Module &M) {
96       // Add external functions that we may call
97       Type *d = Type::DoubleTy;
98       Type *f = Type::FloatTy;
99       Type *l = Type::LongTy;
100       Type *ul = Type::ULongTy;
101       Type *voidPtr = PointerType::get(Type::SByteTy);
102       // double fmod(double, double);
103       fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
104       // long __moddi3(long, long);
105       __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
106       // long __divdi3(long, long);
107       __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
108       // unsigned long __umoddi3(unsigned long, unsigned long);
109       __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
110       // unsigned long __udivdi3(unsigned long, unsigned long);
111       __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
112       // long __fixdfdi(double)
113       __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
114       // float __floatdisf(long)
115       __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
116       // double __floatdidf(long)
117       __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
118       // void* malloc(size_t)
119       mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
120       // void free(void*)
121       freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
122       return false;
123     }
124
125     /// runOnFunction - Top level implementation of instruction selection for
126     /// the entire function.
127     ///
128     bool runOnFunction(Function &Fn) {
129       // First pass over the function, lower any unknown intrinsic functions
130       // with the IntrinsicLowering class.
131       LowerUnknownIntrinsicFunctionCalls(Fn);
132
133       F = &MachineFunction::construct(&Fn, TM);
134
135       // Create all of the machine basic blocks for the function...
136       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
137         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
138
139       BB = &F->front();
140
141       // Set up a frame object for the return address.  This is used by the
142       // llvm.returnaddress & llvm.frameaddress intrinisics.
143       ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
144
145       // Copy incoming arguments off of the stack...
146       LoadArgumentsToVirtualRegs(Fn);
147
148       // Instruction select everything except PHI nodes
149       visit(Fn);
150
151       // Select the PHI nodes
152       SelectPHINodes();
153
154       RegMap.clear();
155       MBBMap.clear();
156       AllocaMap.clear();
157       F = 0;
158       // We always build a machine code representation for the function
159       return true;
160     }
161
162     virtual const char *getPassName() const {
163       return "PowerPC Simple Instruction Selection";
164     }
165
166     /// visitBasicBlock - This method is called when we are visiting a new basic
167     /// block.  This simply creates a new MachineBasicBlock to emit code into
168     /// and adds it to the current MachineFunction.  Subsequent visit* for
169     /// instructions will be invoked for all instructions in the basic block.
170     ///
171     void visitBasicBlock(BasicBlock &LLVM_BB) {
172       BB = MBBMap[&LLVM_BB];
173     }
174
175     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
176     /// function, lowering any calls to unknown intrinsic functions into the
177     /// equivalent LLVM code.
178     ///
179     void LowerUnknownIntrinsicFunctionCalls(Function &F);
180
181     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
182     /// from the stack into virtual registers.
183     ///
184     void LoadArgumentsToVirtualRegs(Function &F);
185
186     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
187     /// because we have to generate our sources into the source basic blocks,
188     /// not the current one.
189     ///
190     void SelectPHINodes();
191
192     // Visitation methods for various instructions.  These methods simply emit
193     // fixed PowerPC code for each instruction.
194
195     // Control flow operators
196     void visitReturnInst(ReturnInst &RI);
197     void visitBranchInst(BranchInst &BI);
198
199     struct ValueRecord {
200       Value *Val;
201       unsigned Reg;
202       const Type *Ty;
203       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
204       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
205     };
206     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
207                 const std::vector<ValueRecord> &Args, bool isVarArg);
208     void visitCallInst(CallInst &I);
209     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
210
211     // Arithmetic operators
212     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
213     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
214     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
215     void visitMul(BinaryOperator &B);
216
217     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
218     void visitRem(BinaryOperator &B) { visitDivRem(B); }
219     void visitDivRem(BinaryOperator &B);
220
221     // Bitwise operators
222     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
223     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
224     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
225
226     // Comparison operators...
227     void visitSetCondInst(SetCondInst &I);
228     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
229                             MachineBasicBlock *MBB,
230                             MachineBasicBlock::iterator MBBI);
231     void visitSelectInst(SelectInst &SI);
232     
233     
234     // Memory Instructions
235     void visitLoadInst(LoadInst &I);
236     void visitStoreInst(StoreInst &I);
237     void visitGetElementPtrInst(GetElementPtrInst &I);
238     void visitAllocaInst(AllocaInst &I);
239     void visitMallocInst(MallocInst &I);
240     void visitFreeInst(FreeInst &I);
241     
242     // Other operators
243     void visitShiftInst(ShiftInst &I);
244     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
245     void visitCastInst(CastInst &I);
246     void visitVANextInst(VANextInst &I);
247     void visitVAArgInst(VAArgInst &I);
248
249     void visitInstruction(Instruction &I) {
250       std::cerr << "Cannot instruction select: " << I;
251       abort();
252     }
253
254     /// promote32 - Make a value 32-bits wide, and put it somewhere.
255     ///
256     void promote32(unsigned targetReg, const ValueRecord &VR);
257
258     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
259     /// constant expression GEP support.
260     ///
261     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
262                           Value *Src, User::op_iterator IdxBegin,
263                           User::op_iterator IdxEnd, unsigned TargetReg);
264
265     /// emitCastOperation - Common code shared between visitCastInst and
266     /// constant expression cast support.
267     ///
268     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
269                            Value *Src, const Type *DestTy, unsigned TargetReg);
270
271     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
272     /// and constant expression support.
273     ///
274     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
275                                    MachineBasicBlock::iterator IP,
276                                    Value *Op0, Value *Op1,
277                                    unsigned OperatorClass, unsigned TargetReg);
278
279     /// emitBinaryFPOperation - This method handles emission of floating point
280     /// Add (0), Sub (1), Mul (2), and Div (3) operations.
281     void emitBinaryFPOperation(MachineBasicBlock *BB,
282                                MachineBasicBlock::iterator IP,
283                                Value *Op0, Value *Op1,
284                                unsigned OperatorClass, unsigned TargetReg);
285
286     void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
287                       Value *Op0, Value *Op1, unsigned TargetReg);
288
289     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
290                     unsigned DestReg, const Type *DestTy,
291                     unsigned Op0Reg, unsigned Op1Reg);
292     void doMultiplyConst(MachineBasicBlock *MBB, 
293                          MachineBasicBlock::iterator MBBI,
294                          unsigned DestReg, const Type *DestTy,
295                          unsigned Op0Reg, unsigned Op1Val);
296
297     void emitDivRemOperation(MachineBasicBlock *BB,
298                              MachineBasicBlock::iterator IP,
299                              Value *Op0, Value *Op1, bool isDiv,
300                              unsigned TargetReg);
301
302     /// emitSetCCOperation - Common code shared between visitSetCondInst and
303     /// constant expression support.
304     ///
305     void emitSetCCOperation(MachineBasicBlock *BB,
306                             MachineBasicBlock::iterator IP,
307                             Value *Op0, Value *Op1, unsigned Opcode,
308                             unsigned TargetReg);
309
310     /// emitShiftOperation - Common code shared between visitShiftInst and
311     /// constant expression support.
312     ///
313     void emitShiftOperation(MachineBasicBlock *MBB,
314                             MachineBasicBlock::iterator IP,
315                             Value *Op, Value *ShiftAmount, bool isLeftShift,
316                             const Type *ResultTy, unsigned DestReg);
317       
318     /// emitSelectOperation - Common code shared between visitSelectInst and the
319     /// constant expression support.
320     void emitSelectOperation(MachineBasicBlock *MBB,
321                              MachineBasicBlock::iterator IP,
322                              Value *Cond, Value *TrueVal, Value *FalseVal,
323                              unsigned DestReg);
324
325     /// copyConstantToRegister - Output the instructions required to put the
326     /// specified constant into the specified register.
327     ///
328     void copyConstantToRegister(MachineBasicBlock *MBB,
329                                 MachineBasicBlock::iterator MBBI,
330                                 Constant *C, unsigned Reg);
331
332     void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
333                    unsigned LHS, unsigned RHS);
334
335     /// makeAnotherReg - This method returns the next register number we haven't
336     /// yet used.
337     ///
338     /// Long values are handled somewhat specially.  They are always allocated
339     /// as pairs of 32 bit integer values.  The register number returned is the
340     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
341     /// of the long value.
342     ///
343     unsigned makeAnotherReg(const Type *Ty) {
344       assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
345              "Current target doesn't have PPC reg info??");
346       const PowerPCRegisterInfo *MRI =
347         static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
348       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
349         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
350         // Create the lower part
351         F->getSSARegMap()->createVirtualRegister(RC);
352         // Create the upper part.
353         return F->getSSARegMap()->createVirtualRegister(RC)-1;
354       }
355
356       // Add the mapping of regnumber => reg class to MachineFunction
357       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
358       return F->getSSARegMap()->createVirtualRegister(RC);
359     }
360
361     /// getReg - This method turns an LLVM value into a register number.
362     ///
363     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
364     unsigned getReg(Value *V) {
365       // Just append to the end of the current bb.
366       MachineBasicBlock::iterator It = BB->end();
367       return getReg(V, BB, It);
368     }
369     unsigned getReg(Value *V, MachineBasicBlock *MBB,
370                     MachineBasicBlock::iterator IPt);
371
372     /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
373     /// that is to be statically allocated with the initial stack frame
374     /// adjustment.
375     unsigned getFixedSizedAllocaFI(AllocaInst *AI);
376   };
377 }
378
379 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
380 /// instruction in the entry block, return it.  Otherwise, return a null
381 /// pointer.
382 static AllocaInst *dyn_castFixedAlloca(Value *V) {
383   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
384     BasicBlock *BB = AI->getParent();
385     if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
386       return AI;
387   }
388   return 0;
389 }
390
391 /// getReg - This method turns an LLVM value into a register number.
392 ///
393 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
394                       MachineBasicBlock::iterator IPt) {
395   // If this operand is a constant, emit the code to copy the constant into
396   // the register here...
397   //
398   if (Constant *C = dyn_cast<Constant>(V)) {
399     unsigned Reg = makeAnotherReg(V->getType());
400     copyConstantToRegister(MBB, IPt, C, Reg);
401     return Reg;
402   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
403     // GV is located at PC + distance
404     unsigned CurPC = makeAnotherReg(Type::IntTy);
405     unsigned Reg1 = makeAnotherReg(V->getType());
406     unsigned Reg2 = makeAnotherReg(V->getType());
407     // Move PC to destination reg
408     BuildMI(*MBB, IPt, PPC32::MovePCtoLR, 0, CurPC);
409     // Move value at PC + distance into return reg
410     BuildMI(*MBB, IPt, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
411       .addGlobalAddress(GV);
412     BuildMI(*MBB, IPt, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
413       .addGlobalAddress(GV);
414     return Reg2;
415   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
416     // Do not emit noop casts at all.
417     if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
418       return getReg(CI->getOperand(0), MBB, IPt);
419   } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
420     unsigned Reg = makeAnotherReg(V->getType());
421     unsigned FI = getFixedSizedAllocaFI(AI);
422     addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
423     return Reg;
424   }
425
426   unsigned &Reg = RegMap[V];
427   if (Reg == 0) {
428     Reg = makeAnotherReg(V->getType());
429     RegMap[V] = Reg;
430   }
431
432   return Reg;
433 }
434
435 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
436 /// that is to be statically allocated with the initial stack frame
437 /// adjustment.
438 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
439   // Already computed this?
440   std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
441   if (I != AllocaMap.end() && I->first == AI) return I->second;
442
443   const Type *Ty = AI->getAllocatedType();
444   ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
445   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
446   TySize *= CUI->getValue();   // Get total allocated size...
447   unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
448       
449   // Create a new stack object using the frame manager...
450   int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
451   AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
452   return FrameIdx;
453 }
454
455
456 /// copyConstantToRegister - Output the instructions required to put the
457 /// specified constant into the specified register.
458 ///
459 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
460                                   MachineBasicBlock::iterator IP,
461                                   Constant *C, unsigned R) {
462   if (C->getType()->isIntegral()) {
463     unsigned Class = getClassB(C->getType());
464
465     if (Class == cLong) {
466       // Copy the value into the register pair.
467       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
468       unsigned hiTmp = makeAnotherReg(Type::IntTy);
469       unsigned loTmp = makeAnotherReg(Type::IntTy);
470       BuildMI(*MBB, IP, PPC32::ADDIS, 2, loTmp).addReg(PPC32::R0)
471         .addImm(Val >> 48);
472       BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(loTmp)
473         .addImm((Val >> 32) & 0xFFFF);
474       BuildMI(*MBB, IP, PPC32::ADDIS, 2, hiTmp).addReg(PPC32::R0)
475         .addImm((Val >> 16) & 0xFFFF);
476       BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(hiTmp).addImm(Val & 0xFFFF);
477       return;
478     }
479
480     assert(Class <= cInt && "Type not handled yet!");
481
482     if (C->getType() == Type::BoolTy) {
483       BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
484         .addImm(C == ConstantBool::True);
485     } else if (Class == cByte || Class == cShort) {
486       ConstantInt *CI = cast<ConstantInt>(C);
487       BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
488         .addImm(CI->getRawValue());
489     } else {
490       ConstantInt *CI = cast<ConstantInt>(C);
491       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
492       if (TheVal < 32768 && TheVal >= -32768) {
493         BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
494           .addImm(CI->getRawValue());
495       } else {
496         unsigned TmpReg = makeAnotherReg(Type::IntTy);
497         BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
498           .addImm(CI->getRawValue() >> 16);
499         BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
500           .addImm(CI->getRawValue() & 0xFFFF);
501       }
502     }
503   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
504     // We need to spill the constant to memory...
505     MachineConstantPool *CP = F->getConstantPool();
506     unsigned CPI = CP->getConstantPoolIndex(CFP);
507     const Type *Ty = CFP->getType();
508
509     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
510
511     // Load addr of constant to reg; constant is located at PC + distance
512     unsigned CurPC = makeAnotherReg(Type::IntTy);
513     unsigned Reg1 = makeAnotherReg(Type::IntTy);
514     unsigned Reg2 = makeAnotherReg(Type::IntTy);
515     // Move PC to destination reg
516     BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
517     // Move value at PC + distance into return reg
518     BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
519       .addConstantPoolIndex(CPI);
520     BuildMI(*MBB, IP, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
521       .addConstantPoolIndex(CPI);
522
523     unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
524     BuildMI(*MBB, IP, LoadOpcode, 2, R).addImm(0).addReg(Reg2);
525   } else if (isa<ConstantPointerNull>(C)) {
526     // Copy zero (null pointer) to the register.
527     BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(0);
528   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
529     BuildMI(*MBB, IP, PPC32::ADDIS, 2, R).addReg(PPC32::R0)
530       .addGlobalAddress(CPR->getValue());
531     BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(PPC32::R0)
532       .addGlobalAddress(CPR->getValue());
533   } else {
534     std::cerr << "Offending constant: " << C << "\n";
535     assert(0 && "Type not handled yet!");
536   }
537 }
538
539 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
540 /// the stack into virtual registers.
541 ///
542 /// FIXME: When we can calculate which args are coming in via registers
543 /// source them from there instead.
544 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
545   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
546   unsigned GPR_remaining = 8;
547   unsigned FPR_remaining = 13;
548   unsigned GPR_idx = 0, FPR_idx = 0;
549   static const unsigned GPR[] = { 
550     PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
551     PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
552   };
553   static const unsigned FPR[] = {
554     PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7, 
555     PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
556   };
557     
558   MachineFrameInfo *MFI = F->getFrameInfo();
559  
560   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
561     bool ArgLive = !I->use_empty();
562     unsigned Reg = ArgLive ? getReg(*I) : 0;
563     int FI;          // Frame object index
564
565     switch (getClassB(I->getType())) {
566     case cByte:
567       if (ArgLive) {
568         FI = MFI->CreateFixedObject(1, ArgOffset);
569         if (GPR_remaining > 0) {
570           BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
571             .addReg(GPR[GPR_idx]);
572         } else {
573           addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
574         }
575       }
576       break;
577     case cShort:
578       if (ArgLive) {
579         FI = MFI->CreateFixedObject(2, ArgOffset);
580         if (GPR_remaining > 0) {
581           BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
582             .addReg(GPR[GPR_idx]);
583         } else {
584           addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
585         }
586       }
587       break;
588     case cInt:
589       if (ArgLive) {
590         FI = MFI->CreateFixedObject(4, ArgOffset);
591         if (GPR_remaining > 0) {
592           BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
593             .addReg(GPR[GPR_idx]);
594         } else {
595           addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
596         }
597       }
598       break;
599     case cLong:
600       if (ArgLive) {
601         FI = MFI->CreateFixedObject(8, ArgOffset);
602         if (GPR_remaining > 1) {
603           BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
604             .addReg(GPR[GPR_idx]);
605           BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
606             .addReg(GPR[GPR_idx+1]);
607         } else {
608           addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
609           addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
610         }
611       }
612       ArgOffset += 4;   // longs require 4 additional bytes
613       if (GPR_remaining > 1) {
614         GPR_remaining--;    // uses up 2 GPRs
615         GPR_idx++;
616       }
617       break;
618     case cFP:
619       if (ArgLive) {
620         unsigned Opcode;
621         if (I->getType() == Type::FloatTy) {
622           Opcode = PPC32::LFS;
623           FI = MFI->CreateFixedObject(4, ArgOffset);
624         } else {
625           Opcode = PPC32::LFD;
626           FI = MFI->CreateFixedObject(8, ArgOffset);
627         }
628         if (FPR_remaining > 0) {
629           BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
630           FPR_remaining--;
631           FPR_idx++;
632         } else {
633           addFrameReference(BuildMI(BB, Opcode, 2, Reg), FI);
634         }
635       }
636       if (I->getType() == Type::DoubleTy) {
637         ArgOffset += 4;   // doubles require 4 additional bytes
638         if (GPR_remaining > 0) {
639           GPR_remaining--;    // uses up 2 GPRs
640           GPR_idx++;
641         }
642       }
643       break;
644     default:
645       assert(0 && "Unhandled argument type!");
646     }
647     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
648     if (GPR_remaining > 0) {
649       GPR_remaining--;    // uses up 2 GPRs
650       GPR_idx++;
651     }
652   }
653
654   // If the function takes variable number of arguments, add a frame offset for
655   // the start of the first vararg value... this is used to expand
656   // llvm.va_start.
657   if (Fn.getFunctionType()->isVarArg())
658     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
659 }
660
661
662 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
663 /// because we have to generate our sources into the source basic blocks, not
664 /// the current one.
665 ///
666 void ISel::SelectPHINodes() {
667   const TargetInstrInfo &TII = *TM.getInstrInfo();
668   const Function &LF = *F->getFunction();  // The LLVM function...
669   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
670     const BasicBlock *BB = I;
671     MachineBasicBlock &MBB = *MBBMap[I];
672
673     // Loop over all of the PHI nodes in the LLVM basic block...
674     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
675     for (BasicBlock::const_iterator I = BB->begin();
676          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
677
678       // Create a new machine instr PHI node, and insert it.
679       unsigned PHIReg = getReg(*PN);
680       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
681                                     PPC32::PHI, PN->getNumOperands(), PHIReg);
682
683       MachineInstr *LongPhiMI = 0;
684       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
685         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
686                             PPC32::PHI, PN->getNumOperands(), PHIReg+1);
687
688       // PHIValues - Map of blocks to incoming virtual registers.  We use this
689       // so that we only initialize one incoming value for a particular block,
690       // even if the block has multiple entries in the PHI node.
691       //
692       std::map<MachineBasicBlock*, unsigned> PHIValues;
693
694       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
695         MachineBasicBlock *PredMBB = 0;
696         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
697              PE = MBB.pred_end (); PI != PE; ++PI)
698           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
699             PredMBB = *PI;
700             break;
701           }
702         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
703
704         unsigned ValReg;
705         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
706           PHIValues.lower_bound(PredMBB);
707
708         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
709           // We already inserted an initialization of the register for this
710           // predecessor.  Recycle it.
711           ValReg = EntryIt->second;
712
713         } else {        
714           // Get the incoming value into a virtual register.
715           //
716           Value *Val = PN->getIncomingValue(i);
717
718           // If this is a constant or GlobalValue, we may have to insert code
719           // into the basic block to compute it into a virtual register.
720           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
721               isa<GlobalValue>(Val)) {
722             // Simple constants get emitted at the end of the basic block,
723             // before any terminator instructions.  We "know" that the code to
724             // move a constant into a register will never clobber any flags.
725             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
726           } else {
727             // Because we don't want to clobber any values which might be in
728             // physical registers with the computation of this constant (which
729             // might be arbitrarily complex if it is a constant expression),
730             // just insert the computation at the top of the basic block.
731             MachineBasicBlock::iterator PI = PredMBB->begin();
732             
733             // Skip over any PHI nodes though!
734             while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
735               ++PI;
736             
737             ValReg = getReg(Val, PredMBB, PI);
738           }
739
740           // Remember that we inserted a value for this PHI for this predecessor
741           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
742         }
743
744         PhiMI->addRegOperand(ValReg);
745         PhiMI->addMachineBasicBlockOperand(PredMBB);
746         if (LongPhiMI) {
747           LongPhiMI->addRegOperand(ValReg+1);
748           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
749         }
750       }
751
752       // Now that we emitted all of the incoming values for the PHI node, make
753       // sure to reposition the InsertPoint after the PHI that we just added.
754       // This is needed because we might have inserted a constant into this
755       // block, right after the PHI's which is before the old insert point!
756       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
757       ++PHIInsertPoint;
758     }
759   }
760 }
761
762
763 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
764 // it into the conditional branch or select instruction which is the only user
765 // of the cc instruction.  This is the case if the conditional branch is the
766 // only user of the setcc, and if the setcc is in the same basic block as the
767 // conditional branch.  We also don't handle long arguments below, so we reject
768 // them here as well.
769 //
770 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
771   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
772     if (SCI->hasOneUse()) {
773       Instruction *User = cast<Instruction>(SCI->use_back());
774       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
775           SCI->getParent() == User->getParent() &&
776           (getClassB(SCI->getOperand(0)->getType()) != cLong ||
777            SCI->getOpcode() == Instruction::SetEQ ||
778            SCI->getOpcode() == Instruction::SetNE))
779         return SCI;
780     }
781   return 0;
782 }
783
784 // Return a fixed numbering for setcc instructions which does not depend on the
785 // order of the opcodes.
786 //
787 static unsigned getSetCCNumber(unsigned Opcode) {
788   switch (Opcode) {
789   default: assert(0 && "Unknown setcc instruction!");
790   case Instruction::SetEQ: return 0;
791   case Instruction::SetNE: return 1;
792   case Instruction::SetLT: return 2;
793   case Instruction::SetGE: return 3;
794   case Instruction::SetGT: return 4;
795   case Instruction::SetLE: return 5;
796   }
797 }
798
799 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
800   switch (Opcode) {
801   default: assert(0 && "Unknown setcc instruction!");
802   case Instruction::SetEQ: return PPC32::BEQ;
803   case Instruction::SetNE: return PPC32::BNE;
804   case Instruction::SetLT: return PPC32::BLT;
805   case Instruction::SetGE: return PPC32::BGE;
806   case Instruction::SetGT: return PPC32::BGT;
807   case Instruction::SetLE: return PPC32::BLE;
808   }
809 }
810
811 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
812   switch (Opcode) {
813   default: assert(0 && "Unknown PPC32 branch opcode!");
814   case PPC32::BEQ: return PPC32::BNE;
815   case PPC32::BNE: return PPC32::BEQ;
816   case PPC32::BLT: return PPC32::BGE;
817   case PPC32::BGE: return PPC32::BLT;
818   case PPC32::BGT: return PPC32::BLE;
819   case PPC32::BLE: return PPC32::BGT;
820   }
821 }
822
823 /// emitUCOM - emits an unordered FP compare.
824 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
825                      unsigned LHS, unsigned RHS) {
826     BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
827 }
828
829 // EmitComparison - This function emits a comparison of the two operands,
830 // returning the extended setcc code to use.
831 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
832                               MachineBasicBlock *MBB,
833                               MachineBasicBlock::iterator IP) {
834   // The arguments are already supposed to be of the same type.
835   const Type *CompTy = Op0->getType();
836   unsigned Class = getClassB(CompTy);
837   unsigned Op0r = getReg(Op0, MBB, IP);
838
839   // Special case handling of: cmp R, i
840   if (isa<ConstantPointerNull>(Op1)) {
841     BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
842   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
843     if (Class == cByte || Class == cShort || Class == cInt) {
844       unsigned Op1v = CI->getRawValue();
845
846       // Mask off any upper bits of the constant, if there are any...
847       Op1v &= (1ULL << (8 << Class)) - 1;
848
849       // Compare immediate or promote to reg?
850       if (Op1v <= 32767) {
851         BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3, 
852                 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
853       } else {
854         unsigned Op1r = getReg(Op1, MBB, IP);
855         BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3, 
856                 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
857       }
858       return OpNum;
859     } else {
860       assert(Class == cLong && "Unknown integer class!");
861       unsigned LowCst = CI->getRawValue();
862       unsigned HiCst = CI->getRawValue() >> 32;
863       if (OpNum < 2) {    // seteq, setne
864         unsigned LoTmp = Op0r;
865         if (LowCst != 0) {
866           unsigned LoLow = makeAnotherReg(Type::IntTy);
867           unsigned LoTmp = makeAnotherReg(Type::IntTy);
868           BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
869           BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
870             .addImm(LowCst >> 16);
871         }
872         unsigned HiTmp = Op0r+1;
873         if (HiCst != 0) {
874           unsigned HiLow = makeAnotherReg(Type::IntTy);
875           unsigned HiTmp = makeAnotherReg(Type::IntTy);
876           BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
877           BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
878             .addImm(HiCst >> 16);
879         }
880         unsigned FinalTmp = makeAnotherReg(Type::IntTy);
881         BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
882         //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
883         return OpNum;
884       } else {
885         // FIXME: Not Yet Implemented
886         std::cerr << "EmitComparison unimplemented: Opnum >= 2\n";
887         abort();
888         return OpNum;
889       }
890     }
891   }
892
893   unsigned Op1r = getReg(Op1, MBB, IP);
894   switch (Class) {
895   default: assert(0 && "Unknown type class!");
896   case cByte:
897   case cShort:
898   case cInt:
899     BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2, 
900             PPC32::CR0).addReg(Op0r).addReg(Op1r);
901     break;
902
903   case cFP:
904     emitUCOM(MBB, IP, Op0r, Op1r);
905     break;
906
907   case cLong:
908     if (OpNum < 2) {    // seteq, setne
909       unsigned LoTmp = makeAnotherReg(Type::IntTy);
910       unsigned HiTmp = makeAnotherReg(Type::IntTy);
911       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
912       BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
913       BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
914       BuildMI(*MBB, IP, PPC32::ORo,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
915       //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
916       break;  // Allow the sete or setne to be generated from flags set by OR
917     } else {
918       // FIXME: Not Yet Implemented
919       std::cerr << "EmitComparison (cLong) unimplemented: Opnum >= 2\n";
920       abort();
921       return OpNum;
922     }
923   }
924   return OpNum;
925 }
926
927 /// visitSetCondInst - emit code to calculate the condition via
928 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
929 ///
930 void ISel::visitSetCondInst(SetCondInst &I) {
931   if (canFoldSetCCIntoBranchOrSelect(&I))
932     return;
933   
934   unsigned Op0Reg = getReg(I.getOperand(0));
935   unsigned Op1Reg = getReg(I.getOperand(1));
936   unsigned DestReg = getReg(I);
937   unsigned OpNum = I.getOpcode();
938   const Type *Ty = I.getOperand (0)->getType();
939                    
940   EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
941  
942   unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
943   MachineBasicBlock *thisMBB = BB;
944   const BasicBlock *LLVM_BB = BB->getBasicBlock();
945   //  thisMBB:
946   //  ...
947   //   cmpTY cr0, r1, r2
948   //   bCC copy1MBB
949   //   b copy0MBB
950
951   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
952   // if we could insert other, non-terminator instructions after the
953   // bCC. But MBB->getFirstTerminator() can't understand this.
954   MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
955   F->getBasicBlockList().push_back(copy1MBB);
956   BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
957   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
958   F->getBasicBlockList().push_back(copy0MBB);
959   BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
960   // Update machine-CFG edges
961   BB->addSuccessor(copy1MBB);
962   BB->addSuccessor(copy0MBB);
963
964   //  copy0MBB:
965   //   %FalseValue = li 0
966   //   b sinkMBB
967   BB = copy0MBB;
968   unsigned FalseValue = makeAnotherReg(I.getType());
969   BuildMI(BB, PPC32::LI, 1, FalseValue).addZImm(0);
970   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
971   F->getBasicBlockList().push_back(sinkMBB);
972   BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
973   // Update machine-CFG edges
974   BB->addSuccessor(sinkMBB);
975
976   DEBUG(std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
977   DEBUG(std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
978   DEBUG(std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
979   DEBUG(std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
980
981   //  copy1MBB:
982   //   %TrueValue = li 1
983   //   b sinkMBB
984   BB = copy1MBB;
985   unsigned TrueValue = makeAnotherReg (I.getType ());
986   BuildMI(BB, PPC32::LI, 1, TrueValue).addZImm(1);
987   BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
988   // Update machine-CFG edges
989   BB->addSuccessor(sinkMBB);
990
991   //  sinkMBB:
992   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
993   //  ...
994   BB = sinkMBB;
995   BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
996     .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
997 }
998
999 void ISel::visitSelectInst(SelectInst &SI) {
1000   unsigned DestReg = getReg(SI);
1001   MachineBasicBlock::iterator MII = BB->end();
1002   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1003                       SI.getFalseValue(), DestReg);
1004 }
1005  
1006 /// emitSelect - Common code shared between visitSelectInst and the constant
1007 /// expression support.
1008 /// FIXME: this is most likely broken in one or more ways.  Namely, PowerPC has
1009 /// no select instruction.  FSEL only works for comparisons against zero.
1010 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1011                                MachineBasicBlock::iterator IP,
1012                                Value *Cond, Value *TrueVal, Value *FalseVal,
1013                                unsigned DestReg) {
1014   unsigned SelectClass = getClassB(TrueVal->getType());
1015
1016   unsigned TrueReg  = getReg(TrueVal, MBB, IP);
1017   unsigned FalseReg = getReg(FalseVal, MBB, IP);
1018
1019   if (TrueReg == FalseReg) {
1020     if (SelectClass == cFP) {
1021       BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(TrueReg);
1022     } else {
1023       BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TrueReg).addReg(TrueReg);
1024     }
1025     
1026     if (SelectClass == cLong)
1027       BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TrueReg+1)
1028         .addReg(TrueReg+1);
1029     return;
1030   }
1031
1032   unsigned CondReg = getReg(Cond, MBB, IP);
1033   unsigned numZeros = makeAnotherReg(Type::IntTy);
1034   unsigned falseHi = makeAnotherReg(Type::IntTy);
1035   unsigned falseAll = makeAnotherReg(Type::IntTy);
1036   unsigned trueAll = makeAnotherReg(Type::IntTy);
1037   unsigned Temp1 = makeAnotherReg(Type::IntTy);
1038   unsigned Temp2 = makeAnotherReg(Type::IntTy);
1039
1040   BuildMI(*MBB, IP, PPC32::CNTLZW, 1, numZeros).addReg(CondReg);
1041   BuildMI(*MBB, IP, PPC32::RLWINM, 4, falseHi).addReg(numZeros).addImm(26)
1042     .addImm(0).addImm(0);
1043   BuildMI(*MBB, IP, PPC32::SRAWI, 2, falseAll).addReg(falseHi).addImm(31);
1044   BuildMI(*MBB, IP, PPC32::NOR, 2, trueAll).addReg(falseAll).addReg(falseAll);
1045   BuildMI(*MBB, IP, PPC32::AND, 2, Temp1).addReg(TrueReg).addReg(trueAll);
1046   BuildMI(*MBB, IP, PPC32::AND, 2, Temp2).addReg(FalseReg).addReg(falseAll);
1047   BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Temp1).addReg(Temp2);
1048   
1049   if (SelectClass == cLong) {
1050     unsigned Temp3 = makeAnotherReg(Type::IntTy);
1051     unsigned Temp4 = makeAnotherReg(Type::IntTy);
1052     BuildMI(*MBB, IP, PPC32::AND, 2, Temp3).addReg(TrueReg+1).addReg(trueAll);
1053     BuildMI(*MBB, IP, PPC32::AND, 2, Temp4).addReg(FalseReg+1).addReg(falseAll);
1054     BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(Temp3).addReg(Temp4);
1055   }
1056   
1057   return;
1058 }
1059
1060
1061
1062 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1063 /// operand, in the specified target register.
1064 ///
1065 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1066   bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1067
1068   Value *Val = VR.Val;
1069   const Type *Ty = VR.Ty;
1070   if (Val) {
1071     if (Constant *C = dyn_cast<Constant>(Val)) {
1072       Val = ConstantExpr::getCast(C, Type::IntTy);
1073       Ty = Type::IntTy;
1074     }
1075
1076     // If this is a simple constant, just emit a load directly to avoid the copy
1077     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1078       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1079
1080       if (TheVal < 32768 && TheVal >= -32768) {
1081         BuildMI(BB, PPC32::ADDI, 2, targetReg).addReg(PPC32::R0).addImm(TheVal);
1082       } else {
1083         unsigned TmpReg = makeAnotherReg(Type::IntTy);
1084         BuildMI(BB, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
1085           .addImm(TheVal >> 16);
1086         BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1087           .addImm(TheVal & 0xFFFF);
1088       }
1089       return;
1090     }
1091   }
1092
1093   // Make sure we have the register number for this value...
1094   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1095
1096   switch (getClassB(Ty)) {
1097   case cByte:
1098     // Extend value into target register (8->32)
1099     if (isUnsigned)
1100       BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1101         .addZImm(24).addZImm(31);
1102     else
1103       BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1104     break;
1105   case cShort:
1106     // Extend value into target register (16->32)
1107     if (isUnsigned)
1108       BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1109         .addZImm(16).addZImm(31);
1110     else
1111       BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1112     break;
1113   case cInt:
1114     // Move value into target register (32->32)
1115     BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1116     break;
1117   default:
1118     assert(0 && "Unpromotable operand class in promote32");
1119   }
1120 }
1121
1122 /// visitReturnInst - implemented with BLR
1123 ///
1124 void ISel::visitReturnInst(ReturnInst &I) {
1125   // Only do the processing if this is a non-void return
1126   if (I.getNumOperands() > 0) {
1127     Value *RetVal = I.getOperand(0);
1128     switch (getClassB(RetVal->getType())) {
1129     case cByte:   // integral return values: extend or move into r3 and return
1130     case cShort:
1131     case cInt:
1132       promote32(PPC32::R3, ValueRecord(RetVal));
1133       break;
1134     case cFP: {   // Floats & Doubles: Return in f1
1135       unsigned RetReg = getReg(RetVal);
1136       BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1137       break;
1138     }
1139     case cLong: {
1140       unsigned RetReg = getReg(RetVal);
1141       BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1142       BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1143       break;
1144     }
1145     default:
1146       visitInstruction(I);
1147     }
1148   }
1149   BuildMI(BB, PPC32::BLR, 1).addImm(0);
1150 }
1151
1152 // getBlockAfter - Return the basic block which occurs lexically after the
1153 // specified one.
1154 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1155   Function::iterator I = BB; ++I;  // Get iterator to next block
1156   return I != BB->getParent()->end() ? &*I : 0;
1157 }
1158
1159 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1160 /// that since code layout is frozen at this point, that if we are trying to
1161 /// jump to a block that is the immediate successor of the current block, we can
1162 /// just make a fall-through (but we don't currently).
1163 ///
1164 void ISel::visitBranchInst(BranchInst &BI) {
1165   // Update machine-CFG edges
1166   BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1167   if (BI.isConditional())
1168     BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1169   
1170   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1171
1172   if (!BI.isConditional()) {  // Unconditional branch?
1173     if (BI.getSuccessor(0) != NextBB) 
1174       BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1175     return;
1176   }
1177   
1178   // See if we can fold the setcc into the branch itself...
1179   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1180   if (SCI == 0) {
1181     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1182     // computed some other way...
1183     unsigned condReg = getReg(BI.getCondition());
1184     BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1185       .addImm(0);
1186     if (BI.getSuccessor(1) == NextBB) {
1187       if (BI.getSuccessor(0) != NextBB)
1188         BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1189           .addMBB(MBBMap[BI.getSuccessor(0)]);
1190     } else {
1191       BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1192         .addMBB(MBBMap[BI.getSuccessor(1)]);
1193       
1194       if (BI.getSuccessor(0) != NextBB)
1195         BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1196     }
1197     return;
1198   }
1199
1200   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1201   unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1202   MachineBasicBlock::iterator MII = BB->end();
1203   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1204   
1205   if (BI.getSuccessor(0) != NextBB) {
1206     BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1207       .addMBB(MBBMap[BI.getSuccessor(0)]);
1208     if (BI.getSuccessor(1) != NextBB)
1209       BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1210   } else {
1211     // Change to the inverse condition...
1212     if (BI.getSuccessor(1) != NextBB) {
1213       Opcode = invertPPCBranchOpcode(Opcode);
1214       BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1215         .addMBB(MBBMap[BI.getSuccessor(1)]);
1216     }
1217   }
1218 }
1219
1220 static Constant* minUConstantForValue(uint64_t val) {
1221   if (val <= 1)
1222     return ConstantBool::get(val);
1223   else if (ConstantUInt::isValueValidForType(Type::UShortTy, val))
1224     return ConstantUInt::get(Type::UShortTy, val);
1225   else if (ConstantUInt::isValueValidForType(Type::UIntTy, val))
1226     return ConstantUInt::get(Type::UIntTy, val);
1227   else if (ConstantUInt::isValueValidForType(Type::ULongTy, val))
1228     return ConstantUInt::get(Type::ULongTy, val);
1229
1230   std::cerr << "Value: " << val << " not accepted for any integral type!\n";
1231   abort();
1232 }
1233
1234 /// doCall - This emits an abstract call instruction, setting up the arguments
1235 /// and the return value as appropriate.  For the actual function call itself,
1236 /// it inserts the specified CallMI instruction into the stream.
1237 ///
1238 /// FIXME: See Documentation at the following URL for "correct" behavior
1239 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1240 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1241                   const std::vector<ValueRecord> &Args, bool isVarArg) {
1242   // Count how many bytes are to be pushed on the stack...
1243   unsigned NumBytes = 0;
1244
1245   if (!Args.empty()) {
1246     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1247       switch (getClassB(Args[i].Ty)) {
1248       case cByte: case cShort: case cInt:
1249         NumBytes += 4; break;
1250       case cLong:
1251         NumBytes += 8; break;
1252       case cFP:
1253         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1254         break;
1255       default: assert(0 && "Unknown class!");
1256       }
1257
1258     // Adjust the stack pointer for the new arguments...
1259     BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1260
1261     // Arguments go on the stack in reverse order, as specified by the ABI.
1262     unsigned ArgOffset = 0;
1263     int GPR_remaining = 8, FPR_remaining = 13;
1264     unsigned GPR_idx = 0, FPR_idx = 0;
1265     static const unsigned GPR[] = { 
1266       PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1267       PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1268     };
1269     static const unsigned FPR[] = {
1270       PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, 
1271       PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, 
1272       PPC32::F13
1273     };
1274     
1275     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1276       unsigned ArgReg;
1277       switch (getClassB(Args[i].Ty)) {
1278       case cByte:
1279       case cShort:
1280         // Promote arg to 32 bits wide into a temporary register...
1281         ArgReg = makeAnotherReg(Type::UIntTy);
1282         promote32(ArgReg, Args[i]);
1283           
1284         // Reg or stack?
1285         if (GPR_remaining > 0) {
1286           BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1287             .addReg(ArgReg);
1288         } else {
1289           BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1290             .addReg(PPC32::R1);
1291         }
1292         break;
1293       case cInt:
1294         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1295
1296         // Reg or stack?
1297         if (GPR_remaining > 0) {
1298           BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1299             .addReg(ArgReg);
1300         } else {
1301           BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1302             .addReg(PPC32::R1);
1303         }
1304         break;
1305       case cLong:
1306         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1307
1308         // Reg or stack?
1309         if (GPR_remaining > 1) {
1310           BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1311             .addReg(ArgReg);
1312           BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx + 1]).addReg(ArgReg+1)
1313             .addReg(ArgReg+1);
1314         } else {
1315           BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1316             .addReg(PPC32::R1);
1317           BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1318             .addReg(PPC32::R1);
1319         }
1320
1321         ArgOffset += 4;        // 8 byte entry, not 4.
1322         GPR_remaining -= 1;    // uses up 2 GPRs
1323         GPR_idx += 1;
1324         break;
1325       case cFP:
1326         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1327         if (Args[i].Ty == Type::FloatTy) {
1328           assert(!isVarArg && "Cannot pass floats to vararg functions!");
1329           // Reg or stack?
1330           if (FPR_remaining > 0) {
1331             BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1332             FPR_remaining--;
1333             FPR_idx++;
1334           } else {
1335             BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1336               .addReg(PPC32::R1);
1337           }
1338         } else {
1339           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1340           // Reg or stack?
1341           if (FPR_remaining > 0) {
1342             BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1343             FPR_remaining--;
1344             FPR_idx++;
1345             // For vararg functions, must pass doubles via int regs as well
1346             if (isVarArg) {
1347               Value *Val = Args[i].Val;
1348               if (ConstantFP *CFP = dyn_cast<ConstantFP>(Val)) {
1349                 union DU {
1350                   double FVal;
1351                   struct {
1352                     uint32_t hi32;
1353                     uint32_t lo32;
1354                   } UVal;
1355                 } U;
1356                 U.FVal = CFP->getValue();
1357                 if (GPR_remaining > 0) {
1358                   Constant *hi32 = minUConstantForValue(U.UVal.hi32);
1359                   copyConstantToRegister(BB, BB->end(), hi32, GPR[GPR_idx]);
1360                 }
1361                 if (GPR_remaining > 1) {
1362                   Constant *lo32 = minUConstantForValue(U.UVal.lo32);
1363                   copyConstantToRegister(BB, BB->end(), lo32, GPR[GPR_idx+1]);
1364                 }
1365               } else {
1366                 // Since this is not a constant, we must load it into int regs
1367                 // via memory
1368                 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1369                   .addReg(PPC32::R1);
1370                 if (GPR_remaining > 0)
1371                   BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addImm(ArgOffset)
1372                     .addReg(PPC32::R1);
1373                 if (GPR_remaining > 1)
1374                   BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1375                     .addImm(ArgOffset+4).addReg(PPC32::R1);
1376               }
1377             }
1378           } else {
1379             BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1380               .addReg(PPC32::R1);
1381           }
1382
1383           ArgOffset += 4;       // 8 byte entry, not 4.
1384           GPR_remaining--;      // uses up 2 GPRs
1385           GPR_idx++;
1386         }
1387         break;
1388
1389       default: assert(0 && "Unknown class!");
1390       }
1391       ArgOffset += 4;
1392       GPR_remaining--;
1393       GPR_idx++;
1394     }
1395   } else {
1396     BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1397   }
1398
1399   BB->push_back(CallMI);
1400   BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1401
1402   // If there is a return value, scavenge the result from the location the call
1403   // leaves it in...
1404   //
1405   if (Ret.Ty != Type::VoidTy) {
1406     unsigned DestClass = getClassB(Ret.Ty);
1407     switch (DestClass) {
1408     case cByte:
1409     case cShort:
1410     case cInt:
1411       // Integral results are in r3
1412       BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1413       break;
1414     case cFP:     // Floating-point return values live in f1
1415       BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1416       break;
1417     case cLong:   // Long values are in r3:r4
1418       BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1419       BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1420       break;
1421     default: assert(0 && "Unknown class!");
1422     }
1423   }
1424 }
1425
1426
1427 /// visitCallInst - Push args on stack and do a procedure call instruction.
1428 void ISel::visitCallInst(CallInst &CI) {
1429   MachineInstr *TheCall;
1430   Function *F = CI.getCalledFunction();
1431   if (F) {
1432     // Is it an intrinsic function call?
1433     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1434       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1435       return;
1436     }
1437
1438     // Emit a CALL instruction with PC-relative displacement.
1439     TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1440   } else {  // Emit an indirect call through the CTR
1441     unsigned Reg = getReg(CI.getCalledValue());
1442     BuildMI(PPC32::MTSPR, 2).addZImm(9).addReg(Reg);
1443     TheCall = BuildMI(PPC32::CALLindirect, 1).addZImm(20).addZImm(0);
1444   }
1445
1446   std::vector<ValueRecord> Args;
1447   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1448     Args.push_back(ValueRecord(CI.getOperand(i)));
1449
1450   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1451   bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1452   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1453 }         
1454
1455
1456 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1457 ///
1458 static Value *dyncastIsNan(Value *V) {
1459   if (CallInst *CI = dyn_cast<CallInst>(V))
1460     if (Function *F = CI->getCalledFunction())
1461       if (F->getIntrinsicID() == Intrinsic::isunordered)
1462         return CI->getOperand(1);
1463   return 0;
1464 }
1465
1466 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1467 /// or's whos operands are all calls to the isnan predicate.
1468 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1469   assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1470
1471   // Check all uses, which will be or's of isnans if this predicate is true.
1472   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1473     Instruction *I = cast<Instruction>(*UI);
1474     if (I->getOpcode() != Instruction::Or) return false;
1475     if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1476     if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1477   }
1478
1479   return true;
1480 }
1481
1482 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1483 /// function, lowering any calls to unknown intrinsic functions into the
1484 /// equivalent LLVM code.
1485 ///
1486 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1487   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1488     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1489       if (CallInst *CI = dyn_cast<CallInst>(I++))
1490         if (Function *F = CI->getCalledFunction())
1491           switch (F->getIntrinsicID()) {
1492           case Intrinsic::not_intrinsic:
1493           case Intrinsic::vastart:
1494           case Intrinsic::vacopy:
1495           case Intrinsic::vaend:
1496           case Intrinsic::returnaddress:
1497           case Intrinsic::frameaddress:
1498             // FIXME: should lower this ourselves
1499             // case Intrinsic::isunordered:
1500             // We directly implement these intrinsics
1501             break;
1502           case Intrinsic::readio: {
1503             // On PPC, memory operations are in-order.  Lower this intrinsic
1504             // into a volatile load.
1505             Instruction *Before = CI->getPrev();
1506             LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1507             CI->replaceAllUsesWith(LI);
1508             BB->getInstList().erase(CI);
1509             break;
1510           }
1511           case Intrinsic::writeio: {
1512             // On PPC, memory operations are in-order.  Lower this intrinsic
1513             // into a volatile store.
1514             Instruction *Before = CI->getPrev();
1515             StoreInst *LI = new StoreInst(CI->getOperand(1),
1516                                           CI->getOperand(2), true, CI);
1517             CI->replaceAllUsesWith(LI);
1518             BB->getInstList().erase(CI);
1519             break;
1520           }
1521           default:
1522             // All other intrinsic calls we must lower.
1523             Instruction *Before = CI->getPrev();
1524             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1525             if (Before) {        // Move iterator to instruction after call
1526               I = Before; ++I;
1527             } else {
1528               I = BB->begin();
1529             }
1530           }
1531 }
1532
1533 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1534   unsigned TmpReg1, TmpReg2, TmpReg3;
1535   switch (ID) {
1536   case Intrinsic::vastart:
1537     // Get the address of the first vararg value...
1538     TmpReg1 = getReg(CI);
1539     addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex);
1540     return;
1541
1542   case Intrinsic::vacopy:
1543     TmpReg1 = getReg(CI);
1544     TmpReg2 = getReg(CI.getOperand(1));
1545     BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1546     return;
1547   case Intrinsic::vaend: return;
1548
1549   case Intrinsic::returnaddress:
1550   case Intrinsic::frameaddress:
1551     TmpReg1 = getReg(CI);
1552     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1553       if (ID == Intrinsic::returnaddress) {
1554         // Just load the return address
1555         addFrameReference(BuildMI(BB, PPC32::LWZ, 2, TmpReg1),
1556                           ReturnAddressIndex);
1557       } else {
1558         addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1),
1559                           ReturnAddressIndex, -4, false);
1560       }
1561     } else {
1562       // Values other than zero are not implemented yet.
1563       BuildMI(BB, PPC32::ADDI, 2, TmpReg1).addReg(PPC32::R0).addImm(0);
1564     }
1565     return;
1566
1567 #if 0
1568     // This may be useful for supporting isunordered
1569   case Intrinsic::isnan:
1570     // If this is only used by 'isunordered' style comparisons, don't emit it.
1571     if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1572     TmpReg1 = getReg(CI.getOperand(1));
1573     emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1574     TmpReg2 = makeAnotherReg(Type::IntTy);
1575     BuildMI(BB, PPC32::MFCR, TmpReg2);
1576     TmpReg3 = getReg(CI);
1577     BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1578     return;
1579 #endif
1580     
1581   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1582   }
1583 }
1584
1585 /// visitSimpleBinary - Implement simple binary operators for integral types...
1586 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1587 /// Xor.
1588 ///
1589 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1590   unsigned DestReg = getReg(B);
1591   MachineBasicBlock::iterator MI = BB->end();
1592   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1593   unsigned Class = getClassB(B.getType());
1594
1595   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1596 }
1597
1598 /// emitBinaryFPOperation - This method handles emission of floating point
1599 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1600 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1601                                  MachineBasicBlock::iterator IP,
1602                                  Value *Op0, Value *Op1,
1603                                  unsigned OperatorClass, unsigned DestReg) {
1604
1605   // Special case: op Reg, <const fp>
1606   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1607     // Create a constant pool entry for this constant.
1608     MachineConstantPool *CP = F->getConstantPool();
1609     unsigned CPI = CP->getConstantPoolIndex(Op1C);
1610     const Type *Ty = Op1->getType();
1611     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1612
1613     static const unsigned OpcodeTab[][4] = {
1614       { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS },  // Float
1615       { PPC32::FADD,  PPC32::FSUB,  PPC32::FMUL,  PPC32::FDIV },   // Double
1616     };
1617
1618     unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1619     unsigned Op1Reg = getReg(Op1C, BB, IP);
1620     unsigned Op0r = getReg(Op0, BB, IP);
1621     BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1622     return;
1623   }
1624   
1625   // Special case: R1 = op <const fp>, R2
1626   if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1627     if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1628       // -0.0 - X === -X
1629       unsigned op1Reg = getReg(Op1, BB, IP);
1630       BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1631       return;
1632     } else {
1633       // R1 = op CST, R2  -->  R1 = opr R2, CST
1634
1635       // Create a constant pool entry for this constant.
1636       MachineConstantPool *CP = F->getConstantPool();
1637       unsigned CPI = CP->getConstantPoolIndex(Op0C);
1638       const Type *Ty = Op0C->getType();
1639       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1640
1641       static const unsigned OpcodeTab[][4] = {
1642         { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS },  // Float
1643         { PPC32::FADD,  PPC32::FSUB,  PPC32::FMUL,  PPC32::FDIV },   // Double
1644       };
1645
1646       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1647       unsigned Op0Reg = getReg(Op0C, BB, IP);
1648       unsigned Op1Reg = getReg(Op1, BB, IP);
1649       BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1650       return;
1651     }
1652
1653   // General case.
1654   static const unsigned OpcodeTab[] = {
1655     PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1656   };
1657
1658   unsigned Opcode = OpcodeTab[OperatorClass];
1659   unsigned Op0r = getReg(Op0, BB, IP);
1660   unsigned Op1r = getReg(Op1, BB, IP);
1661   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1662 }
1663
1664 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1665 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1666 /// Or, 4 for Xor.
1667 ///
1668 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1669 /// and constant expression support.
1670 ///
1671 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1672                                      MachineBasicBlock::iterator IP,
1673                                      Value *Op0, Value *Op1,
1674                                      unsigned OperatorClass, unsigned DestReg) {
1675   unsigned Class = getClassB(Op0->getType());
1676
1677   // Arithmetic and Bitwise operators
1678   static const unsigned OpcodeTab[] = {
1679     PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1680   };
1681   // Otherwise, code generate the full operation with a constant.
1682   static const unsigned BottomTab[] = {
1683     PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1684   };
1685   static const unsigned TopTab[] = {
1686     PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1687   };
1688   
1689   if (Class == cFP) {
1690     assert(OperatorClass < 2 && "No logical ops for FP!");
1691     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1692     return;
1693   }
1694
1695   if (Op0->getType() == Type::BoolTy) {
1696     if (OperatorClass == 3)
1697       // If this is an or of two isnan's, emit an FP comparison directly instead
1698       // of or'ing two isnan's together.
1699       if (Value *LHS = dyncastIsNan(Op0))
1700         if (Value *RHS = dyncastIsNan(Op1)) {
1701           unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1702           unsigned TmpReg = makeAnotherReg(Type::IntTy);
1703           emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1704           BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1705           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1706             .addImm(31).addImm(31);
1707           return;
1708         }
1709   }
1710
1711   // sub 0, X -> neg X
1712   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1713     if (OperatorClass == 1 && CI->isNullValue()) {
1714       unsigned op1Reg = getReg(Op1, MBB, IP);
1715       BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1716       
1717       if (Class == cLong) {
1718         unsigned zeroes = makeAnotherReg(Type::IntTy);
1719         unsigned overflow = makeAnotherReg(Type::IntTy);
1720         unsigned T = makeAnotherReg(Type::IntTy);
1721         BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1722         BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1723           .addImm(5).addImm(31);
1724         BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1725         BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1726       }
1727       return;
1728     }
1729
1730   // Special case: op Reg, <const int>
1731   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1732     unsigned Op0r = getReg(Op0, MBB, IP);
1733
1734     // xor X, -1 -> not X
1735     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1736       BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1737       if (Class == cLong)  // Invert the top part too
1738         BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1739           .addReg(Op0r+1);
1740       return;
1741     }
1742
1743     unsigned Opcode = OpcodeTab[OperatorClass];
1744     unsigned Op1r = getReg(Op1, MBB, IP);
1745
1746     if (Class != cLong) {
1747       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1748       return;
1749     }
1750     
1751     // If the constant is zero in the low 32-bits, just copy the low part
1752     // across and apply the normal 32-bit operation to the high parts.  There
1753     // will be no carry or borrow into the top.
1754     if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1755       if (OperatorClass != 2) // All but and...
1756         BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1757       else
1758         BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1759       BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1760       return;
1761     }
1762     
1763     // If this is a long value and the high or low bits have a special
1764     // property, emit some special cases.
1765     unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1766     
1767     // If this is a logical operation and the top 32-bits are zero, just
1768     // operate on the lower 32.
1769     if (Op1h == 0 && OperatorClass > 1) {
1770       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1771       if (OperatorClass != 2)  // All but and
1772         BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1773       else
1774         BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg+1).addReg(PPC32::R0).addImm(0);
1775       return;
1776     }
1777     
1778     // TODO: We could handle lots of other special cases here, such as AND'ing
1779     // with 0xFFFFFFFF00000000 -> noop, etc.
1780     
1781     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1782       .addImm(Op1r);
1783     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1784       .addImm(Op1r+1);
1785     return;
1786   }
1787
1788   unsigned Op0r = getReg(Op0, MBB, IP);
1789   unsigned Op1r = getReg(Op1, MBB, IP);
1790
1791   if (Class != cLong) {
1792     unsigned Opcode = OpcodeTab[OperatorClass];
1793     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1794   } else {
1795     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1796       .addImm(Op1r);
1797     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1798       .addImm(Op1r+1);
1799   }
1800   return;
1801 }
1802
1803 /// doMultiply - Emit appropriate instructions to multiply together the
1804 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1805 /// result should be given as DestTy.
1806 ///
1807 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1808                       unsigned DestReg, const Type *DestTy,
1809                       unsigned op0Reg, unsigned op1Reg) {
1810   unsigned Class = getClass(DestTy);
1811   switch (Class) {
1812   case cLong:
1813     BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1814       .addReg(op1Reg+1);
1815   case cInt:
1816   case cShort:
1817   case cByte:
1818     BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1819     return;
1820   default:
1821     assert(0 && "doMultiply cannot operate on unknown type!");
1822   }
1823 }
1824
1825 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1826 // returns zero when the input is not exactly a power of two.
1827 static unsigned ExactLog2(unsigned Val) {
1828   if (Val == 0 || (Val & (Val-1))) return 0;
1829   unsigned Count = 0;
1830   while (Val != 1) {
1831     Val >>= 1;
1832     ++Count;
1833   }
1834   return Count+1;
1835 }
1836
1837
1838 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1839 /// 16, or 32-bit integer multiply by a constant.
1840 ///
1841 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1842                            MachineBasicBlock::iterator IP,
1843                            unsigned DestReg, const Type *DestTy,
1844                            unsigned op0Reg, unsigned ConstRHS) {
1845   unsigned Class = getClass(DestTy);
1846   // Handle special cases here.
1847   switch (ConstRHS) {
1848   case 0:
1849     BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1850     return;
1851   case 1:
1852     BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1853     return;
1854   case 2:
1855     BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1856     return;
1857   }
1858
1859   // If the element size is exactly a power of 2, use a shift to get it.
1860   if (unsigned Shift = ExactLog2(ConstRHS)) {
1861     switch (Class) {
1862     default: assert(0 && "Unknown class for this function!");
1863     case cByte:
1864     case cShort:
1865     case cInt:
1866       BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1867         .addImm(Shift-1).addImm(0).addImm(31-Shift-1);
1868       return;
1869     }
1870   }
1871   
1872   // Most general case, emit a normal multiply...
1873   unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1874   unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1875   BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg1).addReg(PPC32::R0)
1876     .addImm(ConstRHS >> 16);
1877   BuildMI(*MBB, IP, PPC32::ORI, 2, TmpReg2).addReg(TmpReg1).addImm(ConstRHS);
1878   
1879   // Emit a MUL to multiply the register holding the index by
1880   // elementSize, putting the result in OffsetReg.
1881   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg2);
1882 }
1883
1884 void ISel::visitMul(BinaryOperator &I) {
1885   unsigned ResultReg = getReg(I);
1886
1887   Value *Op0 = I.getOperand(0);
1888   Value *Op1 = I.getOperand(1);
1889
1890   MachineBasicBlock::iterator IP = BB->end();
1891   emitMultiply(BB, IP, Op0, Op1, ResultReg);
1892 }
1893
1894 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1895                         Value *Op0, Value *Op1, unsigned DestReg) {
1896   MachineBasicBlock &BB = *MBB;
1897   TypeClass Class = getClass(Op0->getType());
1898
1899   // Simple scalar multiply?
1900   unsigned Op0Reg  = getReg(Op0, &BB, IP);
1901   switch (Class) {
1902   case cByte:
1903   case cShort:
1904   case cInt:
1905     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1906       unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1907       doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1908     } else {
1909       unsigned Op1Reg  = getReg(Op1, &BB, IP);
1910       doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1911     }
1912     return;
1913   case cFP:
1914     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1915     return;
1916   case cLong:
1917     break;
1918   }
1919
1920   // Long value.  We have to do things the hard way...
1921   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1922     unsigned CLow = CI->getRawValue();
1923     unsigned CHi  = CI->getRawValue() >> 32;
1924     
1925     if (CLow == 0) {
1926       // If the low part of the constant is all zeros, things are simple.
1927       BuildMI(BB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1928       doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
1929       return;
1930     }
1931     
1932     // Multiply the two low parts
1933     unsigned OverflowReg = 0;
1934     if (CLow == 1) {
1935       BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
1936     } else {
1937       unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
1938       unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
1939       OverflowReg = makeAnotherReg(Type::UIntTy);
1940       BuildMI(BB, IP, PPC32::ADDIS, 2, TmpRegL).addReg(PPC32::R0)
1941         .addImm(CLow >> 16);
1942       BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
1943       BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
1944       BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
1945         .addReg(Op1RegL);
1946     }
1947     
1948     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1949     doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
1950     
1951     unsigned AHBLplusOverflowReg;
1952     if (OverflowReg) {
1953       AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1954       BuildMI(BB, IP, PPC32::ADD, 2,
1955               AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1956     } else {
1957       AHBLplusOverflowReg = AHBLReg;
1958     }
1959     
1960     if (CHi == 0) {
1961       BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
1962         .addReg(AHBLplusOverflowReg);
1963     } else {
1964       unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1965       doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
1966       
1967       BuildMI(BB, IP, PPC32::ADD, 2,
1968               DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1969     }
1970     return;
1971   }
1972
1973   // General 64x64 multiply
1974
1975   unsigned Op1Reg  = getReg(Op1, &BB, IP);
1976   
1977   // Multiply the two low parts...
1978   BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1979   
1980   unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1981   BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
1982   
1983   unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1984   BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1985   
1986   unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1987   BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
1988     .addReg(OverflowReg);
1989   
1990   unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1991   BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1992   
1993   BuildMI(BB, IP, PPC32::ADD, 2,
1994           DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1995 }
1996
1997
1998 /// visitDivRem - Handle division and remainder instructions... these
1999 /// instruction both require the same instructions to be generated, they just
2000 /// select the result from a different register.  Note that both of these
2001 /// instructions work differently for signed and unsigned operands.
2002 ///
2003 void ISel::visitDivRem(BinaryOperator &I) {
2004   unsigned ResultReg = getReg(I);
2005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2006
2007   MachineBasicBlock::iterator IP = BB->end();
2008   emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2009                       ResultReg);
2010 }
2011
2012 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2013                                MachineBasicBlock::iterator IP,
2014                                Value *Op0, Value *Op1, bool isDiv,
2015                                unsigned ResultReg) {
2016   const Type *Ty = Op0->getType();
2017   unsigned Class = getClass(Ty);
2018   switch (Class) {
2019   case cFP:              // Floating point divide
2020     if (isDiv) {
2021       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2022       return;
2023     } else {               // Floating point remainder...
2024       unsigned Op0Reg = getReg(Op0, BB, IP);
2025       unsigned Op1Reg = getReg(Op1, BB, IP);
2026       MachineInstr *TheCall =
2027         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2028       std::vector<ValueRecord> Args;
2029       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2030       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2031       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2032     }
2033     return;
2034   case cLong: {
2035      static Function* const Funcs[] =
2036       { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2037     unsigned Op0Reg = getReg(Op0, BB, IP);
2038     unsigned Op1Reg = getReg(Op1, BB, IP);
2039     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2040     MachineInstr *TheCall =
2041       BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2042
2043     std::vector<ValueRecord> Args;
2044     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2045     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2046     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2047     return;
2048   }
2049   case cByte: case cShort: case cInt:
2050     break;          // Small integrals, handled below...
2051   default: assert(0 && "Unknown class!");
2052   }
2053
2054   // Special case signed division by power of 2.
2055   if (isDiv)
2056     if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2057       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2058       int V = CI->getValue();
2059
2060       if (V == 1) {       // X /s 1 => X
2061         unsigned Op0Reg = getReg(Op0, BB, IP);
2062         BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2063         return;
2064       }
2065
2066       if (V == -1) {      // X /s -1 => -X
2067         unsigned Op0Reg = getReg(Op0, BB, IP);
2068         BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2069         return;
2070       }
2071
2072       bool isNeg = false;
2073       if (V < 0) {         // Not a positive power of 2?
2074         V = -V;
2075         isNeg = true;      // Maybe it's a negative power of 2.
2076       }
2077       if (unsigned Log = ExactLog2(V)) {
2078         --Log;
2079         unsigned Op0Reg = getReg(Op0, BB, IP);
2080         unsigned TmpReg = makeAnotherReg(Op0->getType());
2081         if (Log != 1) 
2082           BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
2083         else
2084           BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
2085
2086         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2087         BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
2088           .addImm(32-Log).addImm(31);
2089
2090         unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2091         BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
2092
2093         unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2094         BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
2095
2096         if (isNeg)
2097           BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
2098         return;
2099       }
2100     }
2101
2102   unsigned Op0Reg = getReg(Op0, BB, IP);
2103   unsigned Op1Reg = getReg(Op1, BB, IP);
2104
2105   if (isDiv) {
2106     if (Ty->isSigned()) {
2107       BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2108     } else {
2109       BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2110     }
2111   } else { // Remainder
2112     unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2113     unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2114     
2115     if (Ty->isSigned()) {
2116       BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2117     } else {
2118       BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2119     }
2120     BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2121     BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2122   }
2123 }
2124
2125
2126 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2127 /// for constant immediate shift values, and for constant immediate
2128 /// shift values equal to 1. Even the general case is sort of special,
2129 /// because the shift amount has to be in CL, not just any old register.
2130 ///
2131 void ISel::visitShiftInst(ShiftInst &I) {
2132   MachineBasicBlock::iterator IP = BB->end ();
2133   emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2134                      I.getOpcode () == Instruction::Shl, I.getType (),
2135                      getReg (I));
2136 }
2137
2138 /// emitShiftOperation - Common code shared between visitShiftInst and
2139 /// constant expression support.
2140 ///
2141 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2142                               MachineBasicBlock::iterator IP,
2143                               Value *Op, Value *ShiftAmount, bool isLeftShift,
2144                               const Type *ResultTy, unsigned DestReg) {
2145   unsigned SrcReg = getReg (Op, MBB, IP);
2146   bool isSigned = ResultTy->isSigned ();
2147   unsigned Class = getClass (ResultTy);
2148   
2149   // Longs, as usual, are handled specially...
2150   if (Class == cLong) {
2151     // If we have a constant shift, we can generate much more efficient code
2152     // than otherwise...
2153     //
2154     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2155       unsigned Amount = CUI->getValue();
2156       if (Amount < 32) {
2157         if (isLeftShift) {
2158           // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2159           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2160             .addImm(Amount).addImm(0).addImm(31-Amount);
2161           BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2162             .addImm(Amount).addImm(32-Amount).addImm(31);
2163           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2164             .addImm(Amount).addImm(0).addImm(31-Amount);
2165         } else {
2166           // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2167           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2168             .addImm(32-Amount).addImm(Amount).addImm(31);
2169           BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2170             .addImm(32-Amount).addImm(0).addImm(Amount-1);
2171           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2172             .addImm(32-Amount).addImm(Amount).addImm(31);
2173         }
2174       } else {                 // Shifting more than 32 bits
2175         Amount -= 32;
2176         if (isLeftShift) {
2177           if (Amount != 0) {
2178             BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2179               .addImm(Amount).addImm(0).addImm(31-Amount);
2180           } else {
2181             BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2182               .addReg(SrcReg);
2183           }
2184           BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg).addReg(PPC32::R0).addImm(0);
2185         } else {
2186           if (Amount != 0) {
2187             if (isSigned)
2188               BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2189                 .addImm(Amount);
2190             else
2191               BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2192                 .addImm(32-Amount).addImm(Amount).addImm(31);
2193           } else {
2194             BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2195               .addReg(SrcReg+1);
2196           }
2197           BuildMI(*MBB, IP,PPC32::ADDI,2,DestReg+1).addReg(PPC32::R0).addImm(0);
2198         }
2199       }
2200     } else {
2201       unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2202       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2203       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2204       unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2205       unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2206       unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2207       unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2208       
2209       if (isLeftShift) {
2210         BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2211           .addImm(32);
2212         BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2213           .addReg(ShiftAmountReg);
2214         BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2215         BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2216         BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2217           .addImm(-32);
2218         BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2219         BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2220           .addReg(TmpReg6);
2221         BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2222           .addReg(ShiftAmountReg);
2223       } else {
2224         if (isSigned) {
2225           // FIXME: Unimplemented
2226           // Page C-3 of the PowerPC 32bit Programming Environments Manual
2227           std::cerr << "Unimplemented: signed right shift\n";
2228           abort();
2229         } else {
2230           BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2231             .addImm(32);
2232           BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2233             .addReg(ShiftAmountReg);
2234           BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2235             .addReg(TmpReg1);
2236           BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2237             .addReg(TmpReg3);
2238           BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2239             .addImm(-32);
2240           BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2241             .addReg(TmpReg5);
2242           BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2243             .addReg(TmpReg6);
2244           BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2245             .addReg(ShiftAmountReg);
2246         }
2247       }
2248     }
2249     return;
2250   }
2251
2252   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2253     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2254     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2255     unsigned Amount = CUI->getValue();
2256
2257     if (isLeftShift) {
2258       BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2259         .addImm(Amount).addImm(0).addImm(31-Amount);
2260     } else {
2261       if (isSigned) {
2262         BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2263       } else {
2264         BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2265           .addImm(32-Amount).addImm(Amount).addImm(31);
2266       }
2267     }
2268   } else {                  // The shift amount is non-constant.
2269     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2270
2271     if (isLeftShift) {
2272       BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2273         .addReg(ShiftAmountReg);
2274     } else {
2275       BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2276         .addReg(SrcReg).addReg(ShiftAmountReg);
2277     }
2278   }
2279 }
2280
2281
2282 /// visitLoadInst - Implement LLVM load instructions
2283 ///
2284 void ISel::visitLoadInst(LoadInst &I) {
2285   static const unsigned Opcodes[] = { 
2286     PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS 
2287   };
2288   unsigned Class = getClassB(I.getType());
2289   unsigned Opcode = Opcodes[Class];
2290   if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2291
2292   unsigned DestReg = getReg(I);
2293
2294   if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2295     unsigned FI = getFixedSizedAllocaFI(AI);
2296     if (Class == cLong) {
2297       addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2298       addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2299     } else {
2300       addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2301     }
2302   } else {
2303     unsigned SrcAddrReg = getReg(I.getOperand(0));
2304     
2305     if (Class == cLong) {
2306       BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2307       BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2308     } else {
2309       BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2310     }
2311   }
2312 }
2313
2314 /// visitStoreInst - Implement LLVM store instructions
2315 ///
2316 void ISel::visitStoreInst(StoreInst &I) {
2317   unsigned ValReg      = getReg(I.getOperand(0));
2318   unsigned AddressReg  = getReg(I.getOperand(1));
2319  
2320   const Type *ValTy = I.getOperand(0)->getType();
2321   unsigned Class = getClassB(ValTy);
2322
2323   if (Class == cLong) {
2324     BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2325     BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2326     return;
2327   }
2328
2329   static const unsigned Opcodes[] = {
2330     PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2331   };
2332   unsigned Opcode = Opcodes[Class];
2333   if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2334   BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2335 }
2336
2337
2338 /// visitCastInst - Here we have various kinds of copying with or without sign
2339 /// extension going on.
2340 ///
2341 void ISel::visitCastInst(CastInst &CI) {
2342   Value *Op = CI.getOperand(0);
2343
2344   unsigned SrcClass = getClassB(Op->getType());
2345   unsigned DestClass = getClassB(CI.getType());
2346   // Noop casts are not emitted: getReg will return the source operand as the
2347   // register to use for any uses of the noop cast.
2348   if (DestClass == SrcClass)
2349     return;
2350
2351   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2352   // of the case are GEP instructions, then the cast does not need to be
2353   // generated explicitly, it will be folded into the GEP.
2354   if (DestClass == cLong && SrcClass == cInt) {
2355     bool AllUsesAreGEPs = true;
2356     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2357       if (!isa<GetElementPtrInst>(*I)) {
2358         AllUsesAreGEPs = false;
2359         break;
2360       }        
2361
2362     // No need to codegen this cast if all users are getelementptr instrs...
2363     if (AllUsesAreGEPs) return;
2364   }
2365
2366   unsigned DestReg = getReg(CI);
2367   MachineBasicBlock::iterator MI = BB->end();
2368   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2369 }
2370
2371 /// emitCastOperation - Common code shared between visitCastInst and constant
2372 /// expression cast support.
2373 ///
2374 void ISel::emitCastOperation(MachineBasicBlock *BB,
2375                              MachineBasicBlock::iterator IP,
2376                              Value *Src, const Type *DestTy,
2377                              unsigned DestReg) {
2378   const Type *SrcTy = Src->getType();
2379   unsigned SrcClass = getClassB(SrcTy);
2380   unsigned DestClass = getClassB(DestTy);
2381   unsigned SrcReg = getReg(Src, BB, IP);
2382
2383   // Implement casts to bool by using compare on the operand followed by set if
2384   // not zero on the result.
2385   if (DestTy == Type::BoolTy) {
2386     switch (SrcClass) {
2387     case cByte:
2388     case cShort:
2389     case cInt: {
2390       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2391       BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2392       BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2393       break;
2394     }
2395     case cLong: {
2396       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2397       unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2398       BuildMI(*BB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2399       BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2400       BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2401       break;
2402     }
2403     case cFP:
2404       // FIXME
2405       // Load -0.0
2406       // Compare
2407       // move to CR1
2408       // Negate -0.0
2409       // Compare
2410       // CROR
2411       // MFCR
2412       // Left-align
2413       // SRA ?
2414       std::cerr << "Cast fp-to-bool not implemented!";
2415       abort();
2416     }
2417     return;
2418   }
2419
2420   // Implement casts between values of the same type class (as determined by
2421   // getClass) by using a register-to-register move.
2422   if (SrcClass == DestClass) {
2423     if (SrcClass <= cInt) {
2424       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2425     } else if (SrcClass == cFP && SrcTy == DestTy) {
2426       BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2427     } else if (SrcClass == cFP) {
2428       if (SrcTy == Type::FloatTy) {  // float -> double
2429         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2430         BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2431       } else {                       // double -> float
2432         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2433                "Unknown cFP member!");
2434         BuildMI(*BB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2435       }
2436     } else if (SrcClass == cLong) {
2437       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2438       BuildMI(*BB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2439         .addReg(SrcReg+1);
2440     } else {
2441       assert(0 && "Cannot handle this type of cast instruction!");
2442       abort();
2443     }
2444     return;
2445   }
2446
2447   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2448   // or zero extension, depending on whether the source type was signed.
2449   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2450       SrcClass < DestClass) {
2451     bool isLong = DestClass == cLong;
2452     if (isLong) DestClass = cInt;
2453
2454     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2455     if (SrcClass < cInt) {
2456       if (isUnsigned) {
2457         unsigned shift = (SrcClass == cByte) ? 24 : 16;
2458         BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2459           .addImm(shift).addImm(31);
2460       } else {
2461         BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 
2462                 1, DestReg).addReg(SrcReg);
2463       }
2464     } else {
2465       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2466     }
2467
2468     if (isLong) {  // Handle upper 32 bits as appropriate...
2469       if (isUnsigned)     // Zero out top bits...
2470         BuildMI(*BB, IP, PPC32::ADDI, 2, DestReg+1).addReg(PPC32::R0).addImm(0);
2471       else                // Sign extend bottom half...
2472         BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2473     }
2474     return;
2475   }
2476
2477   // Special case long -> int ...
2478   if (SrcClass == cLong && DestClass == cInt) {
2479     BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2480     return;
2481   }
2482   
2483   // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2484   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2485       && SrcClass > DestClass) {
2486     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2487     if (isUnsigned) {
2488       unsigned shift = (SrcClass == cByte) ? 24 : 16;
2489       BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2490         .addImm(shift).addImm(31);
2491     } else {
2492       BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1, 
2493               DestReg).addReg(SrcReg);
2494     }
2495     return;
2496   }
2497
2498   // Handle casts from integer to floating point now...
2499   if (DestClass == cFP) {
2500
2501     // Emit a library call for long to float conversion
2502     if (SrcClass == cLong) {
2503       std::vector<ValueRecord> Args;
2504       Args.push_back(ValueRecord(SrcReg, SrcTy));
2505       Function *floatFn = (SrcTy==Type::FloatTy) ? __floatdisfFn : __floatdidfFn;
2506       MachineInstr *TheCall =
2507         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2508       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2509       return;
2510     }
2511
2512     unsigned TmpReg = makeAnotherReg(Type::IntTy);
2513     switch (SrcTy->getTypeID()) {
2514     case Type::BoolTyID:
2515     case Type::SByteTyID:
2516       BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2517       break;
2518     case Type::UByteTyID:
2519       BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2520         .addImm(24).addImm(31);
2521       break;
2522     case Type::ShortTyID:
2523       BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2524       break;
2525     case Type::UShortTyID:
2526       BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2527         .addImm(16).addImm(31);
2528       break;
2529     case Type::IntTyID:
2530       BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2531       break;
2532     case Type::UIntTyID:
2533       BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2534       break;
2535     default:  // No promotion needed...
2536       break;
2537     }
2538     
2539     SrcReg = TmpReg;
2540     
2541     // Spill the integer to memory and reload it from there.
2542     // Also spill room for a special conversion constant
2543     int ConstantFrameIndex = 
2544       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2545     int ValueFrameIdx =
2546       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2547
2548     unsigned constantHi = makeAnotherReg(Type::IntTy);
2549     unsigned constantLo = makeAnotherReg(Type::IntTy);
2550     unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2551     unsigned TempF = makeAnotherReg(Type::DoubleTy);
2552     
2553     if (!SrcTy->isSigned()) {
2554       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2555         .addImm(0x4330);
2556       BuildMI(*BB, IP, PPC32::ADDI, 2, constantLo).addReg(PPC32::R0).addImm(0);
2557       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2558                         ConstantFrameIndex);
2559       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo), 
2560                         ConstantFrameIndex, 4);
2561       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2562                         ValueFrameIdx);
2563       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg), 
2564                         ValueFrameIdx, 4);
2565       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF), 
2566                         ConstantFrameIndex);
2567       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2568       BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2569     } else {
2570       unsigned TempLo = makeAnotherReg(Type::IntTy);
2571       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2572         .addImm(0x4330);
2573       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantLo).addReg(PPC32::R0)
2574         .addImm(0x8000);
2575       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2576                         ConstantFrameIndex);
2577       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo), 
2578                         ConstantFrameIndex, 4);
2579       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2580                         ValueFrameIdx);
2581       BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2582       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo), 
2583                         ValueFrameIdx, 4);
2584       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF), 
2585                         ConstantFrameIndex);
2586       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2587       BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2588     }
2589     return;
2590   }
2591
2592   // Handle casts from floating point to integer now...
2593   if (SrcClass == cFP) {
2594
2595     // emit library call
2596     if (DestClass == cLong) {
2597       std::vector<ValueRecord> Args;
2598       Args.push_back(ValueRecord(SrcReg, SrcTy));
2599       MachineInstr *TheCall =
2600         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(__fixdfdiFn, true);
2601       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2602       return;
2603     }
2604
2605     int ValueFrameIdx =
2606       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2607
2608     // load into 32 bit value, and then truncate as necessary
2609     // FIXME: This is wrong for unsigned dest types
2610     //if (DestTy->isSigned()) {
2611         unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2612         BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2613         addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2614                             .addReg(TempReg), ValueFrameIdx);
2615         addFrameReference(BuildMI(*BB, IP, PPC32::LWZ, 2, DestReg), 
2616                           ValueFrameIdx+4);
2617     //} else {
2618     //}
2619     
2620     // FIXME: Truncate return value
2621     return;
2622   }
2623
2624   // Anything we haven't handled already, we can't (yet) handle at all.
2625   assert(0 && "Unhandled cast instruction!");
2626   abort();
2627 }
2628
2629 /// visitVANextInst - Implement the va_next instruction...
2630 ///
2631 void ISel::visitVANextInst(VANextInst &I) {
2632   unsigned VAList = getReg(I.getOperand(0));
2633   unsigned DestReg = getReg(I);
2634
2635   unsigned Size;
2636   switch (I.getArgType()->getTypeID()) {
2637   default:
2638     std::cerr << I;
2639     assert(0 && "Error: bad type for va_next instruction!");
2640     return;
2641   case Type::PointerTyID:
2642   case Type::UIntTyID:
2643   case Type::IntTyID:
2644     Size = 4;
2645     break;
2646   case Type::ULongTyID:
2647   case Type::LongTyID:
2648   case Type::DoubleTyID:
2649     Size = 8;
2650     break;
2651   }
2652
2653   // Increment the VAList pointer...
2654   BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2655 }
2656
2657 void ISel::visitVAArgInst(VAArgInst &I) {
2658   unsigned VAList = getReg(I.getOperand(0));
2659   unsigned DestReg = getReg(I);
2660
2661   switch (I.getType()->getTypeID()) {
2662   default:
2663     std::cerr << I;
2664     assert(0 && "Error: bad type for va_next instruction!");
2665     return;
2666   case Type::PointerTyID:
2667   case Type::UIntTyID:
2668   case Type::IntTyID:
2669     BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2670     break;
2671   case Type::ULongTyID:
2672   case Type::LongTyID:
2673     BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2674     BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2675     break;
2676   case Type::DoubleTyID:
2677     BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2678     break;
2679   }
2680 }
2681
2682 /// visitGetElementPtrInst - instruction-select GEP instructions
2683 ///
2684 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2685   unsigned outputReg = getReg(I);
2686   emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(), 
2687                    outputReg);
2688 }
2689
2690 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2691                             MachineBasicBlock::iterator IP,
2692                             Value *Src, User::op_iterator IdxBegin,
2693                             User::op_iterator IdxEnd, unsigned TargetReg) {
2694   const TargetData &TD = TM.getTargetData();
2695   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2696     Src = CPR->getValue();
2697
2698   std::vector<Value*> GEPOps;
2699   GEPOps.resize(IdxEnd-IdxBegin+1);
2700   GEPOps[0] = Src;
2701   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2702   
2703   std::vector<const Type*> GEPTypes;
2704   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2705                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2706
2707   // Keep emitting instructions until we consume the entire GEP instruction.
2708   while (!GEPOps.empty()) {
2709     if (GEPTypes.empty()) {
2710       // Load the base pointer into a register.
2711       unsigned Reg = getReg(Src, MBB, IP);
2712       BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2713       break;          // we are now done
2714     }
2715     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2716       // It's a struct access.  CUI is the index into the structure,
2717       // which names the field. This index must have unsigned type.
2718       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2719
2720       // Use the TargetData structure to pick out what the layout of the
2721       // structure is in memory.  Since the structure index must be constant, we
2722       // can get its value and use it to find the right byte offset from the
2723       // StructLayout class's list of structure member offsets.
2724       unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2725       GEPOps.pop_back();        // Consume a GEP operand
2726       GEPTypes.pop_back();
2727       unsigned Reg = makeAnotherReg(Type::UIntTy);
2728       unsigned DispReg = makeAnotherReg(Type::UIntTy);
2729       BuildMI(*MBB, IP, PPC32::LI, 2, DispReg).addImm(Disp);
2730       BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2731       --IP;            // Insert the next instruction before this one.
2732       TargetReg = Reg; // Codegen the rest of the GEP into this
2733     } else {
2734       // It's an array or pointer access: [ArraySize x ElementType].
2735       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2736       Value *idx = GEPOps.back();
2737       GEPOps.pop_back();        // Consume a GEP operand
2738       GEPTypes.pop_back();
2739     
2740       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2741       // operand.  Handle this case directly now...
2742       if (CastInst *CI = dyn_cast<CastInst>(idx))
2743         if (CI->getOperand(0)->getType() == Type::IntTy ||
2744             CI->getOperand(0)->getType() == Type::UIntTy)
2745           idx = CI->getOperand(0);
2746     
2747       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2748       // must find the size of the pointed-to type (Not coincidentally, the next
2749       // type is the type of the elements in the array).
2750       const Type *ElTy = SqTy->getElementType();
2751       unsigned elementSize = TD.getTypeSize(ElTy);
2752     
2753       if (idx == Constant::getNullValue(idx->getType())) {
2754         // GEP with idx 0 is a no-op
2755       } else if (elementSize == 1) {
2756         // If the element size is 1, we don't have to multiply, just add
2757         unsigned idxReg = getReg(idx, MBB, IP);
2758         unsigned Reg = makeAnotherReg(Type::UIntTy);
2759         BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2760         --IP;            // Insert the next instruction before this one.
2761         TargetReg = Reg; // Codegen the rest of the GEP into this
2762       } else {
2763         unsigned idxReg = getReg(idx, MBB, IP);
2764         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2765     
2766         // Make sure we can back the iterator up to point to the first
2767         // instruction emitted.
2768         MachineBasicBlock::iterator BeforeIt = IP;
2769         if (IP == MBB->begin())
2770           BeforeIt = MBB->end();
2771         else
2772           --BeforeIt;
2773         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2774     
2775         // Emit an ADD to add OffsetReg to the basePtr.
2776         unsigned Reg = makeAnotherReg(Type::UIntTy);
2777         BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2778     
2779         // Step to the first instruction of the multiply.
2780         if (BeforeIt == MBB->end())
2781           IP = MBB->begin();
2782         else
2783           IP = ++BeforeIt;
2784     
2785         TargetReg = Reg; // Codegen the rest of the GEP into this
2786       }
2787     }
2788   }
2789 }
2790
2791 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2792 /// frame manager, otherwise do it the hard way.
2793 ///
2794 void ISel::visitAllocaInst(AllocaInst &I) {
2795   // If this is a fixed size alloca in the entry block for the function, we
2796   // statically stack allocate the space, so we don't need to do anything here.
2797   //
2798   if (dyn_castFixedAlloca(&I)) return;
2799   
2800   // Find the data size of the alloca inst's getAllocatedType.
2801   const Type *Ty = I.getAllocatedType();
2802   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2803
2804   // Create a register to hold the temporary result of multiplying the type size
2805   // constant by the variable amount.
2806   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2807   unsigned SrcReg1 = getReg(I.getArraySize());
2808   
2809   // TotalSizeReg = mul <numelements>, <TypeSize>
2810   MachineBasicBlock::iterator MBBI = BB->end();
2811   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2812
2813   // AddedSize = add <TotalSizeReg>, 15
2814   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2815   BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2816
2817   // AlignedSize = and <AddedSize>, ~15
2818   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2819   BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2820     .addImm(0).addImm(27);
2821   
2822   // Subtract size from stack pointer, thereby allocating some space.
2823   BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2824
2825   // Put a pointer to the space into the result register, by copying
2826   // the stack pointer.
2827   BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2828
2829   // Inform the Frame Information that we have just allocated a variable-sized
2830   // object.
2831   F->getFrameInfo()->CreateVariableSizedObject();
2832 }
2833
2834 /// visitMallocInst - Malloc instructions are code generated into direct calls
2835 /// to the library malloc.
2836 ///
2837 void ISel::visitMallocInst(MallocInst &I) {
2838   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2839   unsigned Arg;
2840
2841   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2842     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2843   } else {
2844     Arg = makeAnotherReg(Type::UIntTy);
2845     unsigned Op0Reg = getReg(I.getOperand(0));
2846     MachineBasicBlock::iterator MBBI = BB->end();
2847     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2848   }
2849
2850   std::vector<ValueRecord> Args;
2851   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2852   MachineInstr *TheCall = 
2853     BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2854   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2855 }
2856
2857
2858 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2859 /// function.
2860 ///
2861 void ISel::visitFreeInst(FreeInst &I) {
2862   std::vector<ValueRecord> Args;
2863   Args.push_back(ValueRecord(I.getOperand(0)));
2864   MachineInstr *TheCall = 
2865     BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2866   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2867 }
2868    
2869 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2870 /// into a machine code representation is a very simple peep-hole fashion.  The
2871 /// generated code sucks but the implementation is nice and simple.
2872 ///
2873 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2874   return new ISel(TM);
2875 }