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