7d9e7cc12a2d23ec8b31487fba6835317ca42aca
[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 Op1Reg = getReg(Op1C);
1619     unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1620     unsigned Op0r = getReg(Op0, BB, IP);
1621     BuildMI(*BB, IP, Opcode, DestReg).addReg(Op0r).addReg(Op1Reg);
1622     return;
1623   }
1624   
1625   // Special case: R1 = op <const fp>, R2
1626   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1627     if (CFP->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(CFP);
1638       const Type *Ty = CFP->getType();
1639
1640       static const unsigned OpcodeTab[][4] = {
1641         { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS },  // Float
1642         { PPC32::FADD,  PPC32::FSUB,  PPC32::FMUL,  PPC32::FDIV },   // Double
1643       };
1644
1645       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1646       unsigned TempReg = makeAnotherReg(Ty);
1647       unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
1648       addConstantPoolReference(BuildMI(*BB, IP, LoadOpcode, 2, TempReg), CPI);
1649
1650       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1651       unsigned Op1r = getReg(Op1, BB, IP);
1652       BuildMI(*BB, IP, Opcode, DestReg).addReg(TempReg).addReg(Op1r);
1653       return;
1654     }
1655
1656   // General case.
1657   static const unsigned OpcodeTab[] = {
1658     PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1659   };
1660
1661   unsigned Opcode = OpcodeTab[OperatorClass];
1662   unsigned Op0r = getReg(Op0, BB, IP);
1663   unsigned Op1r = getReg(Op1, BB, IP);
1664   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1665 }
1666
1667 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1668 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1669 /// Or, 4 for Xor.
1670 ///
1671 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1672 /// and constant expression support.
1673 ///
1674 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1675                                      MachineBasicBlock::iterator IP,
1676                                      Value *Op0, Value *Op1,
1677                                      unsigned OperatorClass, unsigned DestReg) {
1678   unsigned Class = getClassB(Op0->getType());
1679
1680   // Arithmetic and Bitwise operators
1681   static const unsigned OpcodeTab[] = {
1682     PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1683   };
1684   // Otherwise, code generate the full operation with a constant.
1685   static const unsigned BottomTab[] = {
1686     PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1687   };
1688   static const unsigned TopTab[] = {
1689     PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1690   };
1691   
1692   if (Class == cFP) {
1693     assert(OperatorClass < 2 && "No logical ops for FP!");
1694     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1695     return;
1696   }
1697
1698   if (Op0->getType() == Type::BoolTy) {
1699     if (OperatorClass == 3)
1700       // If this is an or of two isnan's, emit an FP comparison directly instead
1701       // of or'ing two isnan's together.
1702       if (Value *LHS = dyncastIsNan(Op0))
1703         if (Value *RHS = dyncastIsNan(Op1)) {
1704           unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1705           unsigned TmpReg = makeAnotherReg(Type::IntTy);
1706           emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1707           BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1708           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1709             .addImm(31).addImm(31);
1710           return;
1711         }
1712   }
1713
1714   // sub 0, X -> neg X
1715   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1716     if (OperatorClass == 1 && CI->isNullValue()) {
1717       unsigned op1Reg = getReg(Op1, MBB, IP);
1718       BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1719       
1720       if (Class == cLong) {
1721         unsigned zeroes = makeAnotherReg(Type::IntTy);
1722         unsigned overflow = makeAnotherReg(Type::IntTy);
1723         unsigned T = makeAnotherReg(Type::IntTy);
1724         BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1725         BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1726           .addImm(5).addImm(31);
1727         BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1728         BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1729       }
1730       return;
1731     }
1732
1733   // Special case: op Reg, <const int>
1734   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1735     unsigned Op0r = getReg(Op0, MBB, IP);
1736
1737     // xor X, -1 -> not X
1738     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1739       BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1740       if (Class == cLong)  // Invert the top part too
1741         BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1742           .addReg(Op0r+1);
1743       return;
1744     }
1745
1746     unsigned Opcode = OpcodeTab[OperatorClass];
1747     unsigned Op1r = getReg(Op1, MBB, IP);
1748
1749     if (Class != cLong) {
1750       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1751       return;
1752     }
1753     
1754     // If the constant is zero in the low 32-bits, just copy the low part
1755     // across and apply the normal 32-bit operation to the high parts.  There
1756     // will be no carry or borrow into the top.
1757     if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1758       if (OperatorClass != 2) // All but and...
1759         BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1760       else
1761         BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1762       BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1763       return;
1764     }
1765     
1766     // If this is a long value and the high or low bits have a special
1767     // property, emit some special cases.
1768     unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1769     
1770     // If this is a logical operation and the top 32-bits are zero, just
1771     // operate on the lower 32.
1772     if (Op1h == 0 && OperatorClass > 1) {
1773       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1774       if (OperatorClass != 2)  // All but and
1775         BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1776       else
1777         BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg+1).addReg(PPC32::R0).addImm(0);
1778       return;
1779     }
1780     
1781     // TODO: We could handle lots of other special cases here, such as AND'ing
1782     // with 0xFFFFFFFF00000000 -> noop, etc.
1783     
1784     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1785       .addImm(Op1r);
1786     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1787       .addImm(Op1r+1);
1788     return;
1789   }
1790
1791   unsigned Op0r = getReg(Op0, MBB, IP);
1792   unsigned Op1r = getReg(Op1, MBB, IP);
1793
1794   if (Class != cLong) {
1795     unsigned Opcode = OpcodeTab[OperatorClass];
1796     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1797   } else {
1798     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1799       .addImm(Op1r);
1800     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1801       .addImm(Op1r+1);
1802   }
1803   return;
1804 }
1805
1806 /// doMultiply - Emit appropriate instructions to multiply together the
1807 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1808 /// result should be given as DestTy.
1809 ///
1810 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1811                       unsigned DestReg, const Type *DestTy,
1812                       unsigned op0Reg, unsigned op1Reg) {
1813   unsigned Class = getClass(DestTy);
1814   switch (Class) {
1815   case cLong:
1816     BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1817       .addReg(op1Reg+1);
1818   case cInt:
1819   case cShort:
1820   case cByte:
1821     BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1822     return;
1823   default:
1824     assert(0 && "doMultiply cannot operate on unknown type!");
1825   }
1826 }
1827
1828 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1829 // returns zero when the input is not exactly a power of two.
1830 static unsigned ExactLog2(unsigned Val) {
1831   if (Val == 0 || (Val & (Val-1))) return 0;
1832   unsigned Count = 0;
1833   while (Val != 1) {
1834     Val >>= 1;
1835     ++Count;
1836   }
1837   return Count+1;
1838 }
1839
1840
1841 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1842 /// 16, or 32-bit integer multiply by a constant.
1843 ///
1844 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1845                            MachineBasicBlock::iterator IP,
1846                            unsigned DestReg, const Type *DestTy,
1847                            unsigned op0Reg, unsigned ConstRHS) {
1848   unsigned Class = getClass(DestTy);
1849   // Handle special cases here.
1850   switch (ConstRHS) {
1851   case 0:
1852     BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1853     return;
1854   case 1:
1855     BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1856     return;
1857   case 2:
1858     BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1859     return;
1860   }
1861
1862   // If the element size is exactly a power of 2, use a shift to get it.
1863   if (unsigned Shift = ExactLog2(ConstRHS)) {
1864     switch (Class) {
1865     default: assert(0 && "Unknown class for this function!");
1866     case cByte:
1867     case cShort:
1868     case cInt:
1869       BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1870         .addImm(Shift-1).addImm(0).addImm(31-Shift-1);
1871       return;
1872     }
1873   }
1874   
1875   // Most general case, emit a normal multiply...
1876   unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1877   unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1878   BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg1).addReg(PPC32::R0)
1879     .addImm(ConstRHS >> 16);
1880   BuildMI(*MBB, IP, PPC32::ORI, 2, TmpReg2).addReg(TmpReg1).addImm(ConstRHS);
1881   
1882   // Emit a MUL to multiply the register holding the index by
1883   // elementSize, putting the result in OffsetReg.
1884   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg2);
1885 }
1886
1887 void ISel::visitMul(BinaryOperator &I) {
1888   unsigned ResultReg = getReg(I);
1889
1890   Value *Op0 = I.getOperand(0);
1891   Value *Op1 = I.getOperand(1);
1892
1893   MachineBasicBlock::iterator IP = BB->end();
1894   emitMultiply(BB, IP, Op0, Op1, ResultReg);
1895 }
1896
1897 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1898                         Value *Op0, Value *Op1, unsigned DestReg) {
1899   MachineBasicBlock &BB = *MBB;
1900   TypeClass Class = getClass(Op0->getType());
1901
1902   // Simple scalar multiply?
1903   unsigned Op0Reg  = getReg(Op0, &BB, IP);
1904   switch (Class) {
1905   case cByte:
1906   case cShort:
1907   case cInt:
1908     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1909       unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1910       doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1911     } else {
1912       unsigned Op1Reg  = getReg(Op1, &BB, IP);
1913       doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1914     }
1915     return;
1916   case cFP:
1917     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1918     return;
1919   case cLong:
1920     break;
1921   }
1922
1923   // Long value.  We have to do things the hard way...
1924   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1925     unsigned CLow = CI->getRawValue();
1926     unsigned CHi  = CI->getRawValue() >> 32;
1927     
1928     if (CLow == 0) {
1929       // If the low part of the constant is all zeros, things are simple.
1930       BuildMI(BB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1931       doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
1932       return;
1933     }
1934     
1935     // Multiply the two low parts
1936     unsigned OverflowReg = 0;
1937     if (CLow == 1) {
1938       BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
1939     } else {
1940       unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
1941       unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
1942       OverflowReg = makeAnotherReg(Type::UIntTy);
1943       BuildMI(BB, IP, PPC32::ADDIS, 2, TmpRegL).addReg(PPC32::R0)
1944         .addImm(CLow >> 16);
1945       BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
1946       BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
1947       BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
1948         .addReg(Op1RegL);
1949     }
1950     
1951     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1952     doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
1953     
1954     unsigned AHBLplusOverflowReg;
1955     if (OverflowReg) {
1956       AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1957       BuildMI(BB, IP, PPC32::ADD, 2,
1958               AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1959     } else {
1960       AHBLplusOverflowReg = AHBLReg;
1961     }
1962     
1963     if (CHi == 0) {
1964       BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
1965         .addReg(AHBLplusOverflowReg);
1966     } else {
1967       unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1968       doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
1969       
1970       BuildMI(BB, IP, PPC32::ADD, 2,
1971               DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1972     }
1973     return;
1974   }
1975
1976   // General 64x64 multiply
1977
1978   unsigned Op1Reg  = getReg(Op1, &BB, IP);
1979   
1980   // Multiply the two low parts...
1981   BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1982   
1983   unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1984   BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
1985   
1986   unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1987   BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1988   
1989   unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1990   BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
1991     .addReg(OverflowReg);
1992   
1993   unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1994   BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1995   
1996   BuildMI(BB, IP, PPC32::ADD, 2,
1997           DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1998 }
1999
2000
2001 /// visitDivRem - Handle division and remainder instructions... these
2002 /// instruction both require the same instructions to be generated, they just
2003 /// select the result from a different register.  Note that both of these
2004 /// instructions work differently for signed and unsigned operands.
2005 ///
2006 void ISel::visitDivRem(BinaryOperator &I) {
2007   unsigned ResultReg = getReg(I);
2008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2009
2010   MachineBasicBlock::iterator IP = BB->end();
2011   emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2012                       ResultReg);
2013 }
2014
2015 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2016                                MachineBasicBlock::iterator IP,
2017                                Value *Op0, Value *Op1, bool isDiv,
2018                                unsigned ResultReg) {
2019   const Type *Ty = Op0->getType();
2020   unsigned Class = getClass(Ty);
2021   switch (Class) {
2022   case cFP:              // Floating point divide
2023     if (isDiv) {
2024       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2025       return;
2026     } else {               // Floating point remainder...
2027       unsigned Op0Reg = getReg(Op0, BB, IP);
2028       unsigned Op1Reg = getReg(Op1, BB, IP);
2029       MachineInstr *TheCall =
2030         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2031       std::vector<ValueRecord> Args;
2032       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2033       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2034       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2035     }
2036     return;
2037   case cLong: {
2038      static Function* const Funcs[] =
2039       { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2040     unsigned Op0Reg = getReg(Op0, BB, IP);
2041     unsigned Op1Reg = getReg(Op1, BB, IP);
2042     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2043     MachineInstr *TheCall =
2044       BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2045
2046     std::vector<ValueRecord> Args;
2047     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2048     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2049     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2050     return;
2051   }
2052   case cByte: case cShort: case cInt:
2053     break;          // Small integrals, handled below...
2054   default: assert(0 && "Unknown class!");
2055   }
2056
2057   // Special case signed division by power of 2.
2058   if (isDiv)
2059     if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2060       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2061       int V = CI->getValue();
2062
2063       if (V == 1) {       // X /s 1 => X
2064         unsigned Op0Reg = getReg(Op0, BB, IP);
2065         BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2066         return;
2067       }
2068
2069       if (V == -1) {      // X /s -1 => -X
2070         unsigned Op0Reg = getReg(Op0, BB, IP);
2071         BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2072         return;
2073       }
2074
2075       bool isNeg = false;
2076       if (V < 0) {         // Not a positive power of 2?
2077         V = -V;
2078         isNeg = true;      // Maybe it's a negative power of 2.
2079       }
2080       if (unsigned Log = ExactLog2(V)) {
2081         --Log;
2082         unsigned Op0Reg = getReg(Op0, BB, IP);
2083         unsigned TmpReg = makeAnotherReg(Op0->getType());
2084         if (Log != 1) 
2085           BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
2086         else
2087           BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
2088
2089         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2090         BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
2091           .addImm(32-Log).addImm(31);
2092
2093         unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2094         BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
2095
2096         unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2097         BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
2098
2099         if (isNeg)
2100           BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
2101         return;
2102       }
2103     }
2104
2105   unsigned Op0Reg = getReg(Op0, BB, IP);
2106   unsigned Op1Reg = getReg(Op1, BB, IP);
2107
2108   if (isDiv) {
2109     if (Ty->isSigned()) {
2110       BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2111     } else {
2112       BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2113     }
2114   } else { // Remainder
2115     unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2116     unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2117     
2118     if (Ty->isSigned()) {
2119       BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2120     } else {
2121       BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2122     }
2123     BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2124     BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2125   }
2126 }
2127
2128
2129 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2130 /// for constant immediate shift values, and for constant immediate
2131 /// shift values equal to 1. Even the general case is sort of special,
2132 /// because the shift amount has to be in CL, not just any old register.
2133 ///
2134 void ISel::visitShiftInst(ShiftInst &I) {
2135   MachineBasicBlock::iterator IP = BB->end ();
2136   emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2137                      I.getOpcode () == Instruction::Shl, I.getType (),
2138                      getReg (I));
2139 }
2140
2141 /// emitShiftOperation - Common code shared between visitShiftInst and
2142 /// constant expression support.
2143 ///
2144 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2145                               MachineBasicBlock::iterator IP,
2146                               Value *Op, Value *ShiftAmount, bool isLeftShift,
2147                               const Type *ResultTy, unsigned DestReg) {
2148   unsigned SrcReg = getReg (Op, MBB, IP);
2149   bool isSigned = ResultTy->isSigned ();
2150   unsigned Class = getClass (ResultTy);
2151   
2152   // Longs, as usual, are handled specially...
2153   if (Class == cLong) {
2154     // If we have a constant shift, we can generate much more efficient code
2155     // than otherwise...
2156     //
2157     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2158       unsigned Amount = CUI->getValue();
2159       if (Amount < 32) {
2160         if (isLeftShift) {
2161           // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2162           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2163             .addImm(Amount).addImm(0).addImm(31-Amount);
2164           BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2165             .addImm(Amount).addImm(32-Amount).addImm(31);
2166           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2167             .addImm(Amount).addImm(0).addImm(31-Amount);
2168         } else {
2169           // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2170           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2171             .addImm(32-Amount).addImm(Amount).addImm(31);
2172           BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2173             .addImm(32-Amount).addImm(0).addImm(Amount-1);
2174           BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2175             .addImm(32-Amount).addImm(Amount).addImm(31);
2176         }
2177       } else {                 // Shifting more than 32 bits
2178         Amount -= 32;
2179         if (isLeftShift) {
2180           if (Amount != 0) {
2181             BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2182               .addImm(Amount).addImm(0).addImm(31-Amount);
2183           } else {
2184             BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2185               .addReg(SrcReg);
2186           }
2187           BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg).addReg(PPC32::R0).addImm(0);
2188         } else {
2189           if (Amount != 0) {
2190             if (isSigned)
2191               BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2192                 .addImm(Amount);
2193             else
2194               BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2195                 .addImm(32-Amount).addImm(Amount).addImm(31);
2196           } else {
2197             BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2198               .addReg(SrcReg+1);
2199           }
2200           BuildMI(*MBB, IP,PPC32::ADDI,2,DestReg+1).addReg(PPC32::R0).addImm(0);
2201         }
2202       }
2203     } else {
2204       unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2205       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2206       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2207       unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2208       unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2209       unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2210       unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2211       
2212       if (isLeftShift) {
2213         BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2214           .addImm(32);
2215         BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2216           .addReg(ShiftAmountReg);
2217         BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2218         BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2219         BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2220           .addImm(-32);
2221         BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2222         BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2223           .addReg(TmpReg6);
2224         BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2225           .addReg(ShiftAmountReg);
2226       } else {
2227         if (isSigned) {
2228           // FIXME: Unimplemented
2229           // Page C-3 of the PowerPC 32bit Programming Environments Manual
2230           std::cerr << "Unimplemented: signed right shift\n";
2231           abort();
2232         } else {
2233           BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2234             .addImm(32);
2235           BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2236             .addReg(ShiftAmountReg);
2237           BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2238             .addReg(TmpReg1);
2239           BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2240             .addReg(TmpReg3);
2241           BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2242             .addImm(-32);
2243           BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2244             .addReg(TmpReg5);
2245           BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2246             .addReg(TmpReg6);
2247           BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2248             .addReg(ShiftAmountReg);
2249         }
2250       }
2251     }
2252     return;
2253   }
2254
2255   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2256     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2257     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2258     unsigned Amount = CUI->getValue();
2259
2260     if (isLeftShift) {
2261       BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2262         .addImm(Amount).addImm(0).addImm(31-Amount);
2263     } else {
2264       if (isSigned) {
2265         BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2266       } else {
2267         BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2268           .addImm(32-Amount).addImm(Amount).addImm(31);
2269       }
2270     }
2271   } else {                  // The shift amount is non-constant.
2272     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2273
2274     if (isLeftShift) {
2275       BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2276         .addReg(ShiftAmountReg);
2277     } else {
2278       BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2279         .addReg(SrcReg).addReg(ShiftAmountReg);
2280     }
2281   }
2282 }
2283
2284
2285 /// visitLoadInst - Implement LLVM load instructions
2286 ///
2287 void ISel::visitLoadInst(LoadInst &I) {
2288   static const unsigned Opcodes[] = { 
2289     PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS 
2290   };
2291   unsigned Class = getClassB(I.getType());
2292   unsigned Opcode = Opcodes[Class];
2293   if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2294
2295   unsigned DestReg = getReg(I);
2296
2297   if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2298     unsigned FI = getFixedSizedAllocaFI(AI);
2299     if (Class == cLong) {
2300       addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2301       addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2302     } else {
2303       addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2304     }
2305   } else {
2306     unsigned SrcAddrReg = getReg(I.getOperand(0));
2307     
2308     if (Class == cLong) {
2309       BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2310       BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2311     } else {
2312       BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2313     }
2314   }
2315 }
2316
2317 /// visitStoreInst - Implement LLVM store instructions
2318 ///
2319 void ISel::visitStoreInst(StoreInst &I) {
2320   unsigned ValReg      = getReg(I.getOperand(0));
2321   unsigned AddressReg  = getReg(I.getOperand(1));
2322  
2323   const Type *ValTy = I.getOperand(0)->getType();
2324   unsigned Class = getClassB(ValTy);
2325
2326   if (Class == cLong) {
2327     BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2328     BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2329     return;
2330   }
2331
2332   static const unsigned Opcodes[] = {
2333     PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2334   };
2335   unsigned Opcode = Opcodes[Class];
2336   if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2337   BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2338 }
2339
2340
2341 /// visitCastInst - Here we have various kinds of copying with or without sign
2342 /// extension going on.
2343 ///
2344 void ISel::visitCastInst(CastInst &CI) {
2345   Value *Op = CI.getOperand(0);
2346
2347   unsigned SrcClass = getClassB(Op->getType());
2348   unsigned DestClass = getClassB(CI.getType());
2349   // Noop casts are not emitted: getReg will return the source operand as the
2350   // register to use for any uses of the noop cast.
2351   if (DestClass == SrcClass)
2352     return;
2353
2354   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2355   // of the case are GEP instructions, then the cast does not need to be
2356   // generated explicitly, it will be folded into the GEP.
2357   if (DestClass == cLong && SrcClass == cInt) {
2358     bool AllUsesAreGEPs = true;
2359     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2360       if (!isa<GetElementPtrInst>(*I)) {
2361         AllUsesAreGEPs = false;
2362         break;
2363       }        
2364
2365     // No need to codegen this cast if all users are getelementptr instrs...
2366     if (AllUsesAreGEPs) return;
2367   }
2368
2369   unsigned DestReg = getReg(CI);
2370   MachineBasicBlock::iterator MI = BB->end();
2371   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2372 }
2373
2374 /// emitCastOperation - Common code shared between visitCastInst and constant
2375 /// expression cast support.
2376 ///
2377 void ISel::emitCastOperation(MachineBasicBlock *BB,
2378                              MachineBasicBlock::iterator IP,
2379                              Value *Src, const Type *DestTy,
2380                              unsigned DestReg) {
2381   const Type *SrcTy = Src->getType();
2382   unsigned SrcClass = getClassB(SrcTy);
2383   unsigned DestClass = getClassB(DestTy);
2384   unsigned SrcReg = getReg(Src, BB, IP);
2385
2386   // Implement casts to bool by using compare on the operand followed by set if
2387   // not zero on the result.
2388   if (DestTy == Type::BoolTy) {
2389     switch (SrcClass) {
2390     case cByte:
2391     case cShort:
2392     case cInt: {
2393       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2394       BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2395       BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2396       break;
2397     }
2398     case cLong: {
2399       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2400       unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2401       BuildMI(*BB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2402       BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2403       BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2404       break;
2405     }
2406     case cFP:
2407       // FIXME
2408       // Load -0.0
2409       // Compare
2410       // move to CR1
2411       // Negate -0.0
2412       // Compare
2413       // CROR
2414       // MFCR
2415       // Left-align
2416       // SRA ?
2417       std::cerr << "Cast fp-to-bool not implemented!";
2418       abort();
2419     }
2420     return;
2421   }
2422
2423   // Implement casts between values of the same type class (as determined by
2424   // getClass) by using a register-to-register move.
2425   if (SrcClass == DestClass) {
2426     if (SrcClass <= cInt) {
2427       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2428     } else if (SrcClass == cFP && SrcTy == DestTy) {
2429       BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2430     } else if (SrcClass == cFP) {
2431       if (SrcTy == Type::FloatTy) {  // float -> double
2432         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2433         BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2434       } else {                       // double -> float
2435         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2436                "Unknown cFP member!");
2437         BuildMI(*BB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2438       }
2439     } else if (SrcClass == cLong) {
2440       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2441       BuildMI(*BB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2442         .addReg(SrcReg+1);
2443     } else {
2444       assert(0 && "Cannot handle this type of cast instruction!");
2445       abort();
2446     }
2447     return;
2448   }
2449
2450   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2451   // or zero extension, depending on whether the source type was signed.
2452   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2453       SrcClass < DestClass) {
2454     bool isLong = DestClass == cLong;
2455     if (isLong) DestClass = cInt;
2456
2457     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2458     if (SrcClass < cInt) {
2459       if (isUnsigned) {
2460         unsigned shift = (SrcClass == cByte) ? 24 : 16;
2461         BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2462           .addImm(shift).addImm(31);
2463       } else {
2464         BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 
2465                 1, DestReg).addReg(SrcReg);
2466       }
2467     } else {
2468       BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2469     }
2470
2471     if (isLong) {  // Handle upper 32 bits as appropriate...
2472       if (isUnsigned)     // Zero out top bits...
2473         BuildMI(*BB, IP, PPC32::ADDI, 2, DestReg+1).addReg(PPC32::R0).addImm(0);
2474       else                // Sign extend bottom half...
2475         BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2476     }
2477     return;
2478   }
2479
2480   // Special case long -> int ...
2481   if (SrcClass == cLong && DestClass == cInt) {
2482     BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2483     return;
2484   }
2485   
2486   // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2487   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2488       && SrcClass > DestClass) {
2489     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2490     if (isUnsigned) {
2491       unsigned shift = (SrcClass == cByte) ? 24 : 16;
2492       BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2493         .addImm(shift).addImm(31);
2494     } else {
2495       BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1, 
2496               DestReg).addReg(SrcReg);
2497     }
2498     return;
2499   }
2500
2501   // Handle casts from integer to floating point now...
2502   if (DestClass == cFP) {
2503
2504     // Emit a library call for long to float conversion
2505     if (SrcClass == cLong) {
2506       std::vector<ValueRecord> Args;
2507       Args.push_back(ValueRecord(SrcReg, SrcTy));
2508       Function *floatFn = (SrcTy==Type::FloatTy) ? __floatdisfFn : __floatdidfFn;
2509       MachineInstr *TheCall =
2510         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2511       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2512       return;
2513     }
2514
2515     unsigned TmpReg = makeAnotherReg(Type::IntTy);
2516     switch (SrcTy->getTypeID()) {
2517     case Type::BoolTyID:
2518     case Type::SByteTyID:
2519       BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2520       break;
2521     case Type::UByteTyID:
2522       BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2523         .addImm(24).addImm(31);
2524       break;
2525     case Type::ShortTyID:
2526       BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2527       break;
2528     case Type::UShortTyID:
2529       BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2530         .addImm(16).addImm(31);
2531       break;
2532     case Type::IntTyID:
2533       BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2534       break;
2535     case Type::UIntTyID:
2536       BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2537       break;
2538     default:  // No promotion needed...
2539       break;
2540     }
2541     
2542     SrcReg = TmpReg;
2543     
2544     // Spill the integer to memory and reload it from there.
2545     // Also spill room for a special conversion constant
2546     int ConstantFrameIndex = 
2547       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2548     int ValueFrameIdx =
2549       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2550
2551     unsigned constantHi = makeAnotherReg(Type::IntTy);
2552     unsigned constantLo = makeAnotherReg(Type::IntTy);
2553     unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2554     unsigned TempF = makeAnotherReg(Type::DoubleTy);
2555     
2556     if (!SrcTy->isSigned()) {
2557       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2558         .addImm(0x4330);
2559       BuildMI(*BB, IP, PPC32::ADDI, 2, constantLo).addReg(PPC32::R0).addImm(0);
2560       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2561                         ConstantFrameIndex);
2562       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo), 
2563                         ConstantFrameIndex, 4);
2564       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2565                         ValueFrameIdx);
2566       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg), 
2567                         ValueFrameIdx, 4);
2568       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF), 
2569                         ConstantFrameIndex);
2570       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2571       BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2572     } else {
2573       unsigned TempLo = makeAnotherReg(Type::IntTy);
2574       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2575         .addImm(0x4330);
2576       BuildMI(*BB, IP, PPC32::ADDIS, 2, constantLo).addReg(PPC32::R0)
2577         .addImm(0x8000);
2578       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2579                         ConstantFrameIndex);
2580       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo), 
2581                         ConstantFrameIndex, 4);
2582       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi), 
2583                         ValueFrameIdx);
2584       BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2585       addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo), 
2586                         ValueFrameIdx, 4);
2587       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF), 
2588                         ConstantFrameIndex);
2589       addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2590       BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2591     }
2592     return;
2593   }
2594
2595   // Handle casts from floating point to integer now...
2596   if (SrcClass == cFP) {
2597
2598     // emit library call
2599     if (DestClass == cLong) {
2600       std::vector<ValueRecord> Args;
2601       Args.push_back(ValueRecord(SrcReg, SrcTy));
2602       MachineInstr *TheCall =
2603         BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(__fixdfdiFn, true);
2604       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2605       return;
2606     }
2607
2608     int ValueFrameIdx =
2609       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2610
2611     // load into 32 bit value, and then truncate as necessary
2612     // FIXME: This is wrong for unsigned dest types
2613     //if (DestTy->isSigned()) {
2614         unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2615         BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2616         addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2617                             .addReg(TempReg), ValueFrameIdx);
2618         addFrameReference(BuildMI(*BB, IP, PPC32::LWZ, 2, DestReg), 
2619                           ValueFrameIdx+4);
2620     //} else {
2621     //}
2622     
2623     // FIXME: Truncate return value
2624     return;
2625   }
2626
2627   // Anything we haven't handled already, we can't (yet) handle at all.
2628   assert(0 && "Unhandled cast instruction!");
2629   abort();
2630 }
2631
2632 /// visitVANextInst - Implement the va_next instruction...
2633 ///
2634 void ISel::visitVANextInst(VANextInst &I) {
2635   unsigned VAList = getReg(I.getOperand(0));
2636   unsigned DestReg = getReg(I);
2637
2638   unsigned Size;
2639   switch (I.getArgType()->getTypeID()) {
2640   default:
2641     std::cerr << I;
2642     assert(0 && "Error: bad type for va_next instruction!");
2643     return;
2644   case Type::PointerTyID:
2645   case Type::UIntTyID:
2646   case Type::IntTyID:
2647     Size = 4;
2648     break;
2649   case Type::ULongTyID:
2650   case Type::LongTyID:
2651   case Type::DoubleTyID:
2652     Size = 8;
2653     break;
2654   }
2655
2656   // Increment the VAList pointer...
2657   BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2658 }
2659
2660 void ISel::visitVAArgInst(VAArgInst &I) {
2661   unsigned VAList = getReg(I.getOperand(0));
2662   unsigned DestReg = getReg(I);
2663
2664   switch (I.getType()->getTypeID()) {
2665   default:
2666     std::cerr << I;
2667     assert(0 && "Error: bad type for va_next instruction!");
2668     return;
2669   case Type::PointerTyID:
2670   case Type::UIntTyID:
2671   case Type::IntTyID:
2672     BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2673     break;
2674   case Type::ULongTyID:
2675   case Type::LongTyID:
2676     BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2677     BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2678     break;
2679   case Type::DoubleTyID:
2680     BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2681     break;
2682   }
2683 }
2684
2685 /// visitGetElementPtrInst - instruction-select GEP instructions
2686 ///
2687 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2688   unsigned outputReg = getReg(I);
2689   emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(), 
2690                    outputReg);
2691 }
2692
2693 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2694                             MachineBasicBlock::iterator IP,
2695                             Value *Src, User::op_iterator IdxBegin,
2696                             User::op_iterator IdxEnd, unsigned TargetReg) {
2697   const TargetData &TD = TM.getTargetData();
2698   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2699     Src = CPR->getValue();
2700
2701   std::vector<Value*> GEPOps;
2702   GEPOps.resize(IdxEnd-IdxBegin+1);
2703   GEPOps[0] = Src;
2704   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2705   
2706   std::vector<const Type*> GEPTypes;
2707   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2708                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2709
2710   // Keep emitting instructions until we consume the entire GEP instruction.
2711   while (!GEPOps.empty()) {
2712     if (GEPTypes.empty()) {
2713       // Load the base pointer into a register.
2714       unsigned Reg = getReg(Src, MBB, IP);
2715       BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2716       break;          // we are now done
2717     }
2718     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2719       // It's a struct access.  CUI is the index into the structure,
2720       // which names the field. This index must have unsigned type.
2721       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2722
2723       // Use the TargetData structure to pick out what the layout of the
2724       // structure is in memory.  Since the structure index must be constant, we
2725       // can get its value and use it to find the right byte offset from the
2726       // StructLayout class's list of structure member offsets.
2727       unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2728       GEPOps.pop_back();        // Consume a GEP operand
2729       GEPTypes.pop_back();
2730       unsigned Reg = makeAnotherReg(Type::UIntTy);
2731       unsigned DispReg = makeAnotherReg(Type::UIntTy);
2732       BuildMI(*MBB, IP, PPC32::LI, 2, DispReg).addImm(Disp);
2733       BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2734       --IP;            // Insert the next instruction before this one.
2735       TargetReg = Reg; // Codegen the rest of the GEP into this
2736     } else {
2737       // It's an array or pointer access: [ArraySize x ElementType].
2738       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2739       Value *idx = GEPOps.back();
2740       GEPOps.pop_back();        // Consume a GEP operand
2741       GEPTypes.pop_back();
2742     
2743       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2744       // operand.  Handle this case directly now...
2745       if (CastInst *CI = dyn_cast<CastInst>(idx))
2746         if (CI->getOperand(0)->getType() == Type::IntTy ||
2747             CI->getOperand(0)->getType() == Type::UIntTy)
2748           idx = CI->getOperand(0);
2749     
2750       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2751       // must find the size of the pointed-to type (Not coincidentally, the next
2752       // type is the type of the elements in the array).
2753       const Type *ElTy = SqTy->getElementType();
2754       unsigned elementSize = TD.getTypeSize(ElTy);
2755     
2756       if (idx == Constant::getNullValue(idx->getType())) {
2757         // GEP with idx 0 is a no-op
2758       } else if (elementSize == 1) {
2759         // If the element size is 1, we don't have to multiply, just add
2760         unsigned idxReg = getReg(idx, MBB, IP);
2761         unsigned Reg = makeAnotherReg(Type::UIntTy);
2762         BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2763         --IP;            // Insert the next instruction before this one.
2764         TargetReg = Reg; // Codegen the rest of the GEP into this
2765       } else {
2766         unsigned idxReg = getReg(idx, MBB, IP);
2767         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2768     
2769         // Make sure we can back the iterator up to point to the first
2770         // instruction emitted.
2771         MachineBasicBlock::iterator BeforeIt = IP;
2772         if (IP == MBB->begin())
2773           BeforeIt = MBB->end();
2774         else
2775           --BeforeIt;
2776         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2777     
2778         // Emit an ADD to add OffsetReg to the basePtr.
2779         unsigned Reg = makeAnotherReg(Type::UIntTy);
2780         BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2781     
2782         // Step to the first instruction of the multiply.
2783         if (BeforeIt == MBB->end())
2784           IP = MBB->begin();
2785         else
2786           IP = ++BeforeIt;
2787     
2788         TargetReg = Reg; // Codegen the rest of the GEP into this
2789       }
2790     }
2791   }
2792 }
2793
2794 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2795 /// frame manager, otherwise do it the hard way.
2796 ///
2797 void ISel::visitAllocaInst(AllocaInst &I) {
2798   // If this is a fixed size alloca in the entry block for the function, we
2799   // statically stack allocate the space, so we don't need to do anything here.
2800   //
2801   if (dyn_castFixedAlloca(&I)) return;
2802   
2803   // Find the data size of the alloca inst's getAllocatedType.
2804   const Type *Ty = I.getAllocatedType();
2805   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2806
2807   // Create a register to hold the temporary result of multiplying the type size
2808   // constant by the variable amount.
2809   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2810   unsigned SrcReg1 = getReg(I.getArraySize());
2811   
2812   // TotalSizeReg = mul <numelements>, <TypeSize>
2813   MachineBasicBlock::iterator MBBI = BB->end();
2814   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2815
2816   // AddedSize = add <TotalSizeReg>, 15
2817   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2818   BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2819
2820   // AlignedSize = and <AddedSize>, ~15
2821   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2822   BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2823     .addImm(0).addImm(27);
2824   
2825   // Subtract size from stack pointer, thereby allocating some space.
2826   BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2827
2828   // Put a pointer to the space into the result register, by copying
2829   // the stack pointer.
2830   BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2831
2832   // Inform the Frame Information that we have just allocated a variable-sized
2833   // object.
2834   F->getFrameInfo()->CreateVariableSizedObject();
2835 }
2836
2837 /// visitMallocInst - Malloc instructions are code generated into direct calls
2838 /// to the library malloc.
2839 ///
2840 void ISel::visitMallocInst(MallocInst &I) {
2841   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2842   unsigned Arg;
2843
2844   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2845     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2846   } else {
2847     Arg = makeAnotherReg(Type::UIntTy);
2848     unsigned Op0Reg = getReg(I.getOperand(0));
2849     MachineBasicBlock::iterator MBBI = BB->end();
2850     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2851   }
2852
2853   std::vector<ValueRecord> Args;
2854   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2855   MachineInstr *TheCall = 
2856     BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2857   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2858 }
2859
2860
2861 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2862 /// function.
2863 ///
2864 void ISel::visitFreeInst(FreeInst &I) {
2865   std::vector<ValueRecord> Args;
2866   Args.push_back(ValueRecord(I.getOperand(0)));
2867   MachineInstr *TheCall = 
2868     BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2869   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2870 }
2871    
2872 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2873 /// into a machine code representation is a very simple peep-hole fashion.  The
2874 /// generated code sucks but the implementation is nice and simple.
2875 ///
2876 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2877   return new ISel(TM);
2878 }