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