1. If a double FP constant must be put into a constant pool, but it can be
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- X86ISelSimple.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/Pass.h"
22 #include "llvm/CodeGen/IntrinsicLowering.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/ADT/Statistic.h"
32 using namespace llvm;
33
34 namespace {
35   Statistic<>
36   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
37
38   /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39   /// Representation.
40   ///
41   enum TypeClass {
42     cByte, cShort, cInt, cFP, cLong
43   };
44 }
45
46 /// getClass - Turn a primitive type into a "class" number which is based on the
47 /// size of the type, and whether or not it is floating point.
48 ///
49 static inline TypeClass getClass(const Type *Ty) {
50   switch (Ty->getTypeID()) {
51   case Type::SByteTyID:
52   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
53   case Type::ShortTyID:
54   case Type::UShortTyID:  return cShort;     // Short operands are class #1
55   case Type::IntTyID:
56   case Type::UIntTyID:
57   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
58
59   case Type::FloatTyID:
60   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
61
62   case Type::LongTyID:
63   case Type::ULongTyID:   return cLong;      // Longs are class #4
64   default:
65     assert(0 && "Invalid type to getClass!");
66     return cByte;  // not reached
67   }
68 }
69
70 // getClassB - Just like getClass, but treat boolean values as bytes.
71 static inline TypeClass getClassB(const Type *Ty) {
72   if (Ty == Type::BoolTy) return cByte;
73   return getClass(Ty);
74 }
75
76 namespace {
77   struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
78     TargetMachine &TM;
79     MachineFunction *F;                 // The function we are compiling into
80     MachineBasicBlock *BB;              // The current MBB we are compiling
81     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
82     int ReturnAddressIndex;             // FrameIndex for the return address
83
84     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
85
86     // MBBMap - Mapping between LLVM BB -> Machine BB
87     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
89     // AllocaMap - Mapping from fixed sized alloca instructions to the
90     // FrameIndex for the alloca.
91     std::map<AllocaInst*, unsigned> AllocaMap;
92
93     X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
94
95     /// runOnFunction - Top level implementation of instruction selection for
96     /// the entire function.
97     ///
98     bool runOnFunction(Function &Fn) {
99       // Lazily create a stack slot for the return address if needed.
100       ReturnAddressIndex = 0;
101
102       // First pass over the function, lower any unknown intrinsic functions
103       // with the IntrinsicLowering class.
104       LowerUnknownIntrinsicFunctionCalls(Fn);
105
106       F = &MachineFunction::construct(&Fn, TM);
107
108       // Create all of the machine basic blocks for the function...
109       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
110         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
111
112       BB = &F->front();
113
114       // Copy incoming arguments off of the stack...
115       LoadArgumentsToVirtualRegs(Fn);
116
117       // If this is main, emit special code.
118       if (Fn.hasExternalLinkage() && Fn.getName() == "main")
119         EmitSpecialCodeForMain();
120
121       // Instruction select everything except PHI nodes
122       visit(Fn);
123
124       // Select the PHI nodes
125       SelectPHINodes();
126
127       // Insert the FP_REG_KILL instructions into blocks that need them.
128       InsertFPRegKills();
129
130       RegMap.clear();
131       MBBMap.clear();
132       AllocaMap.clear();
133       F = 0;
134       // We always build a machine code representation for the function
135       return true;
136     }
137
138     virtual const char *getPassName() const {
139       return "X86 Simple Instruction Selection";
140     }
141
142     /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
143     /// the main function.
144     void EmitSpecialCodeForMain();
145
146     /// visitBasicBlock - This method is called when we are visiting a new basic
147     /// block.  This simply creates a new MachineBasicBlock to emit code into
148     /// and adds it to the current MachineFunction.  Subsequent visit* for
149     /// instructions will be invoked for all instructions in the basic block.
150     ///
151     void visitBasicBlock(BasicBlock &LLVM_BB) {
152       BB = MBBMap[&LLVM_BB];
153     }
154
155     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
156     /// function, lowering any calls to unknown intrinsic functions into the
157     /// equivalent LLVM code.
158     ///
159     void LowerUnknownIntrinsicFunctionCalls(Function &F);
160
161     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
162     /// from the stack into virtual registers.
163     ///
164     void LoadArgumentsToVirtualRegs(Function &F);
165
166     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
167     /// because we have to generate our sources into the source basic blocks,
168     /// not the current one.
169     ///
170     void SelectPHINodes();
171
172     /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
173     /// that need them.  This only occurs due to the floating point stackifier
174     /// not being aggressive enough to handle arbitrary global stackification.
175     ///
176     void InsertFPRegKills();
177
178     // Visitation methods for various instructions.  These methods simply emit
179     // fixed X86 code for each instruction.
180     //
181
182     // Control flow operators
183     void visitReturnInst(ReturnInst &RI);
184     void visitBranchInst(BranchInst &BI);
185     void visitUnreachableInst(UnreachableInst &UI) {}
186
187     struct ValueRecord {
188       Value *Val;
189       unsigned Reg;
190       const Type *Ty;
191       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
192       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
193     };
194     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
195                 const std::vector<ValueRecord> &Args);
196     void visitCallInst(CallInst &I);
197     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
198
199     // Arithmetic operators
200     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
201     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
202     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
203     void visitMul(BinaryOperator &B);
204
205     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
206     void visitRem(BinaryOperator &B) { visitDivRem(B); }
207     void visitDivRem(BinaryOperator &B);
208
209     // Bitwise operators
210     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
211     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
212     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
213
214     // Comparison operators...
215     void visitSetCondInst(SetCondInst &I);
216     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
217                             MachineBasicBlock *MBB,
218                             MachineBasicBlock::iterator MBBI);
219     void visitSelectInst(SelectInst &SI);
220     
221     
222     // Memory Instructions
223     void visitLoadInst(LoadInst &I);
224     void visitStoreInst(StoreInst &I);
225     void visitGetElementPtrInst(GetElementPtrInst &I);
226     void visitAllocaInst(AllocaInst &I);
227     void visitMallocInst(MallocInst &I);
228     void visitFreeInst(FreeInst &I);
229     
230     // Other operators
231     void visitShiftInst(ShiftInst &I);
232     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
233     void visitCastInst(CastInst &I);
234     void visitVANextInst(VANextInst &I);
235     void visitVAArgInst(VAArgInst &I);
236
237     void visitInstruction(Instruction &I) {
238       std::cerr << "Cannot instruction select: " << I;
239       abort();
240     }
241
242     /// promote32 - Make a value 32-bits wide, and put it somewhere.
243     ///
244     void promote32(unsigned targetReg, const ValueRecord &VR);
245
246     /// getAddressingMode - Get the addressing mode to use to address the
247     /// specified value.  The returned value should be used with addFullAddress.
248     void getAddressingMode(Value *Addr, X86AddressMode &AM);
249
250
251     /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
252     /// expressions.
253     void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
254                      std::vector<Value*> &GEPOps,
255                      std::vector<const Type*> &GEPTypes,
256                      X86AddressMode &AM);
257
258     /// isGEPFoldable - Return true if the specified GEP can be completely
259     /// folded into the addressing mode of a load/store or lea instruction.
260     bool isGEPFoldable(MachineBasicBlock *MBB,
261                        Value *Src, User::op_iterator IdxBegin,
262                        User::op_iterator IdxEnd, X86AddressMode &AM);
263
264     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
265     /// constant expression GEP support.
266     ///
267     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
268                           Value *Src, User::op_iterator IdxBegin,
269                           User::op_iterator IdxEnd, unsigned TargetReg);
270
271     /// emitCastOperation - Common code shared between visitCastInst and
272     /// constant expression cast support.
273     ///
274     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
275                            Value *Src, const Type *DestTy, unsigned TargetReg);
276
277     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
278     /// and constant expression support.
279     ///
280     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
281                                    MachineBasicBlock::iterator IP,
282                                    Value *Op0, Value *Op1,
283                                    unsigned OperatorClass, unsigned TargetReg);
284
285     /// emitBinaryFPOperation - This method handles emission of floating point
286     /// Add (0), Sub (1), Mul (2), and Div (3) operations.
287     void emitBinaryFPOperation(MachineBasicBlock *BB,
288                                MachineBasicBlock::iterator IP,
289                                Value *Op0, Value *Op1,
290                                unsigned OperatorClass, unsigned TargetReg);
291
292     void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
293                       Value *Op0, Value *Op1, unsigned TargetReg);
294
295     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
296                     unsigned DestReg, const Type *DestTy,
297                     unsigned Op0Reg, unsigned Op1Reg);
298     void doMultiplyConst(MachineBasicBlock *MBB, 
299                          MachineBasicBlock::iterator MBBI,
300                          unsigned DestReg, const Type *DestTy,
301                          unsigned Op0Reg, unsigned Op1Val);
302
303     void emitDivRemOperation(MachineBasicBlock *BB,
304                              MachineBasicBlock::iterator IP,
305                              Value *Op0, Value *Op1, bool isDiv,
306                              unsigned TargetReg);
307
308     /// emitSetCCOperation - Common code shared between visitSetCondInst and
309     /// constant expression support.
310     ///
311     void emitSetCCOperation(MachineBasicBlock *BB,
312                             MachineBasicBlock::iterator IP,
313                             Value *Op0, Value *Op1, unsigned Opcode,
314                             unsigned TargetReg);
315
316     /// emitShiftOperation - Common code shared between visitShiftInst and
317     /// constant expression support.
318     ///
319     void emitShiftOperation(MachineBasicBlock *MBB,
320                             MachineBasicBlock::iterator IP,
321                             Value *Op, Value *ShiftAmount, bool isLeftShift,
322                             const Type *ResultTy, unsigned DestReg);
323
324     // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
325     // constant.
326     void doSHLDConst(MachineBasicBlock *MBB, 
327                      MachineBasicBlock::iterator MBBI,
328                      unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
329                      unsigned Op1Val);
330       
331     /// emitSelectOperation - Common code shared between visitSelectInst and the
332     /// constant expression support.
333     void emitSelectOperation(MachineBasicBlock *MBB,
334                              MachineBasicBlock::iterator IP,
335                              Value *Cond, Value *TrueVal, Value *FalseVal,
336                              unsigned DestReg);
337
338     /// copyConstantToRegister - Output the instructions required to put the
339     /// specified constant into the specified register.
340     ///
341     void copyConstantToRegister(MachineBasicBlock *MBB,
342                                 MachineBasicBlock::iterator MBBI,
343                                 Constant *C, unsigned Reg);
344
345     void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
346                    unsigned LHS, unsigned RHS);
347
348     /// makeAnotherReg - This method returns the next register number we haven't
349     /// yet used.
350     ///
351     /// Long values are handled somewhat specially.  They are always allocated
352     /// as pairs of 32 bit integer values.  The register number returned is the
353     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
354     /// of the long value.
355     ///
356     unsigned makeAnotherReg(const Type *Ty) {
357       assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
358              "Current target doesn't have X86 reg info??");
359       const X86RegisterInfo *MRI =
360         static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
361       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
362         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
363         // Create the lower part
364         F->getSSARegMap()->createVirtualRegister(RC);
365         // Create the upper part.
366         return F->getSSARegMap()->createVirtualRegister(RC)-1;
367       }
368
369       // Add the mapping of regnumber => reg class to MachineFunction
370       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
371       return F->getSSARegMap()->createVirtualRegister(RC);
372     }
373
374     /// getReg - This method turns an LLVM value into a register number.
375     ///
376     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
377     unsigned getReg(Value *V) {
378       // Just append to the end of the current bb.
379       MachineBasicBlock::iterator It = BB->end();
380       return getReg(V, BB, It);
381     }
382     unsigned getReg(Value *V, MachineBasicBlock *MBB,
383                     MachineBasicBlock::iterator IPt);
384
385     /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
386     /// that is to be statically allocated with the initial stack frame
387     /// adjustment.
388     unsigned getFixedSizedAllocaFI(AllocaInst *AI);
389   };
390 }
391
392 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
393 /// instruction in the entry block, return it.  Otherwise, return a null
394 /// pointer.
395 static AllocaInst *dyn_castFixedAlloca(Value *V) {
396   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
397     BasicBlock *BB = AI->getParent();
398     if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
399       return AI;
400   }
401   return 0;
402 }
403
404 /// getReg - This method turns an LLVM value into a register number.
405 ///
406 unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
407                          MachineBasicBlock::iterator IPt) {
408   // If this operand is a constant, emit the code to copy the constant into
409   // the register here...
410   if (Constant *C = dyn_cast<Constant>(V)) {
411     unsigned Reg = makeAnotherReg(V->getType());
412     copyConstantToRegister(MBB, IPt, C, Reg);
413     return Reg;
414   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
415     // Do not emit noop casts at all, unless it's a double -> float cast.
416     if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
417         (CI->getType() != Type::FloatTy || 
418          CI->getOperand(0)->getType() != Type::DoubleTy))
419       return getReg(CI->getOperand(0), MBB, IPt);
420   } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
421     // If the alloca address couldn't be folded into the instruction addressing,
422     // emit an explicit LEA as appropriate.
423     unsigned Reg = makeAnotherReg(V->getType());
424     unsigned FI = getFixedSizedAllocaFI(AI);
425     addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
426     return Reg;
427   }
428
429   unsigned &Reg = RegMap[V];
430   if (Reg == 0) {
431     Reg = makeAnotherReg(V->getType());
432     RegMap[V] = Reg;
433   }
434
435   return Reg;
436 }
437
438 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
439 /// that is to be statically allocated with the initial stack frame
440 /// adjustment.
441 unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
442   // Already computed this?
443   std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
444   if (I != AllocaMap.end() && I->first == AI) return I->second;
445
446   const Type *Ty = AI->getAllocatedType();
447   ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
448   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
449   TySize *= CUI->getValue();   // Get total allocated size...
450   unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
451       
452   // Create a new stack object using the frame manager...
453   int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
454   AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
455   return FrameIdx;
456 }
457
458
459 /// copyConstantToRegister - Output the instructions required to put the
460 /// specified constant into the specified register.
461 ///
462 void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
463                                      MachineBasicBlock::iterator IP,
464                                      Constant *C, unsigned R) {
465   if (isa<UndefValue>(C)) {
466     switch (getClassB(C->getType())) {
467     case cFP:
468       // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
469       BuildMI(*MBB, IP, X86::FLD0, 0, R);
470       return;
471     case cLong:
472       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
473       // FALL THROUGH
474     default:
475       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
476       return;
477     }
478   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
479     unsigned Class = 0;
480     switch (CE->getOpcode()) {
481     case Instruction::GetElementPtr:
482       emitGEPOperation(MBB, IP, CE->getOperand(0),
483                        CE->op_begin()+1, CE->op_end(), R);
484       return;
485     case Instruction::Cast:
486       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
487       return;
488
489     case Instruction::Xor: ++Class; // FALL THROUGH
490     case Instruction::Or:  ++Class; // FALL THROUGH
491     case Instruction::And: ++Class; // FALL THROUGH
492     case Instruction::Sub: ++Class; // FALL THROUGH
493     case Instruction::Add:
494       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
495                                 Class, R);
496       return;
497
498     case Instruction::Mul:
499       emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
500       return;
501
502     case Instruction::Div:
503     case Instruction::Rem:
504       emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
505                           CE->getOpcode() == Instruction::Div, R);
506       return;
507
508     case Instruction::SetNE:
509     case Instruction::SetEQ:
510     case Instruction::SetLT:
511     case Instruction::SetGT:
512     case Instruction::SetLE:
513     case Instruction::SetGE:
514       emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
515                          CE->getOpcode(), R);
516       return;
517
518     case Instruction::Shl:
519     case Instruction::Shr:
520       emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
521                          CE->getOpcode() == Instruction::Shl, CE->getType(), R);
522       return;
523
524     case Instruction::Select:
525       emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
526                           CE->getOperand(2), R);
527       return;
528
529     default:
530       std::cerr << "Offending expr: " << *C << "\n";
531       assert(0 && "Constant expression not yet handled!\n");
532     }
533   }
534
535   if (C->getType()->isIntegral()) {
536     unsigned Class = getClassB(C->getType());
537
538     if (Class == cLong) {
539       // Copy the value into the register pair.
540       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
541       BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
542       BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
543       return;
544     }
545
546     assert(Class <= cInt && "Type not handled yet!");
547
548     static const unsigned IntegralOpcodeTab[] = {
549       X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
550     };
551
552     if (C->getType() == Type::BoolTy) {
553       BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
554     } else {
555       ConstantInt *CI = cast<ConstantInt>(C);
556       BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
557     }
558   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
559     if (CFP->isExactlyValue(+0.0))
560       BuildMI(*MBB, IP, X86::FLD0, 0, R);
561     else if (CFP->isExactlyValue(+1.0))
562       BuildMI(*MBB, IP, X86::FLD1, 0, R);
563     else {  // FIXME: PI, other native values
564       // FIXME: Could handle -1.0 with FLD1/FCHS
565       // FIXME: 2*PI -> LDPI + FADD
566
567       // Otherwise we need to spill the constant to memory.
568       MachineConstantPool *CP = F->getConstantPool();
569
570       const Type *Ty = CFP->getType();
571
572       // If a FP immediate is precise when represented as a float, we put it
573       // into the constant pool as a float, even if it's is statically typed as
574       // a double.
575       if (Ty == Type::DoubleTy)
576         if (CFP->isExactlyValue((float)CFP->getValue())) {
577           Ty = Type::FloatTy;
578           CFP = cast<ConstantFP>(ConstantExpr::getCast(CFP, Ty));
579         }
580
581       unsigned CPI = CP->getConstantPoolIndex(CFP);
582       
583       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
584       unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
585       addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
586     }
587
588   } else if (isa<ConstantPointerNull>(C)) {
589     // Copy zero (null pointer) to the register.
590     BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
591   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
592     BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
593   } else {
594     std::cerr << "Offending constant: " << *C << "\n";
595     assert(0 && "Type not handled yet!");
596   }
597 }
598
599 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
600 /// the stack into virtual registers.
601 ///
602 void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
603   // Emit instructions to load the arguments...  On entry to a function on the
604   // X86, the stack frame looks like this:
605   //
606   // [ESP] -- return address
607   // [ESP + 4] -- first argument (leftmost lexically)
608   // [ESP + 8] -- second argument, if first argument is four bytes in size
609   //    ... 
610   //
611   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
612   MachineFrameInfo *MFI = F->getFrameInfo();
613
614   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
615     bool ArgLive = !I->use_empty();
616     unsigned Reg = ArgLive ? getReg(*I) : 0;
617     int FI;          // Frame object index
618
619     switch (getClassB(I->getType())) {
620     case cByte:
621       if (ArgLive) {
622         FI = MFI->CreateFixedObject(1, ArgOffset);
623         addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
624       }
625       break;
626     case cShort:
627       if (ArgLive) {
628         FI = MFI->CreateFixedObject(2, ArgOffset);
629         addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
630       }
631       break;
632     case cInt:
633       if (ArgLive) {
634         FI = MFI->CreateFixedObject(4, ArgOffset);
635         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
636       }
637       break;
638     case cLong:
639       if (ArgLive) {
640         FI = MFI->CreateFixedObject(8, ArgOffset);
641         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
642         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
643       }
644       ArgOffset += 4;   // longs require 4 additional bytes
645       break;
646     case cFP:
647       if (ArgLive) {
648         unsigned Opcode;
649         if (I->getType() == Type::FloatTy) {
650           Opcode = X86::FLD32m;
651           FI = MFI->CreateFixedObject(4, ArgOffset);
652         } else {
653           Opcode = X86::FLD64m;
654           FI = MFI->CreateFixedObject(8, ArgOffset);
655         }
656         addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
657       }
658       if (I->getType() == Type::DoubleTy)
659         ArgOffset += 4;   // doubles require 4 additional bytes
660       break;
661     default:
662       assert(0 && "Unhandled argument type!");
663     }
664     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
665   }
666
667   // If the function takes variable number of arguments, add a frame offset for
668   // the start of the first vararg value... this is used to expand
669   // llvm.va_start.
670   if (Fn.getFunctionType()->isVarArg())
671     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
672 }
673
674 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
675 /// the main function.
676 void X86ISel::EmitSpecialCodeForMain() {
677   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
678   int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
679   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
680   
681   // Set the high part to be 64-bit precision.
682   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
683                     CWFrameIdx, 1).addImm(2);
684
685   // Reload the modified control word now.
686   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
687 }
688
689 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
690 /// because we have to generate our sources into the source basic blocks, not
691 /// the current one.
692 ///
693 void X86ISel::SelectPHINodes() {
694   const TargetInstrInfo &TII = *TM.getInstrInfo();
695   const Function &LF = *F->getFunction();  // The LLVM function...
696   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
697     const BasicBlock *BB = I;
698     MachineBasicBlock &MBB = *MBBMap[I];
699
700     // Loop over all of the PHI nodes in the LLVM basic block...
701     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
702     for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
703       PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
704
705       // Create a new machine instr PHI node, and insert it.
706       unsigned PHIReg = getReg(*PN);
707       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
708                                     X86::PHI, PN->getNumOperands(), PHIReg);
709
710       MachineInstr *LongPhiMI = 0;
711       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
712         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
713                             X86::PHI, PN->getNumOperands(), PHIReg+1);
714
715       // PHIValues - Map of blocks to incoming virtual registers.  We use this
716       // so that we only initialize one incoming value for a particular block,
717       // even if the block has multiple entries in the PHI node.
718       //
719       std::map<MachineBasicBlock*, unsigned> PHIValues;
720
721       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
722         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
723         unsigned ValReg;
724         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
725           PHIValues.lower_bound(PredMBB);
726
727         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
728           // We already inserted an initialization of the register for this
729           // predecessor.  Recycle it.
730           ValReg = EntryIt->second;
731
732         } else {        
733           // Get the incoming value into a virtual register.
734           //
735           Value *Val = PN->getIncomingValue(i);
736
737           // If this is a constant or GlobalValue, we may have to insert code
738           // into the basic block to compute it into a virtual register.
739           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
740             // Simple constants get emitted at the end of the basic block,
741             // before any terminator instructions.  We "know" that the code to
742             // move a constant into a register will never clobber any flags.
743             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
744           } else {
745             // Because we don't want to clobber any values which might be in
746             // physical registers with the computation of this constant (which
747             // might be arbitrarily complex if it is a constant expression),
748             // just insert the computation at the top of the basic block.
749             MachineBasicBlock::iterator PI = PredMBB->begin();
750             
751             // Skip over any PHI nodes though!
752             while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
753               ++PI;
754             
755             ValReg = getReg(Val, PredMBB, PI);
756           }
757
758           // Remember that we inserted a value for this PHI for this predecessor
759           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
760         }
761
762         PhiMI->addRegOperand(ValReg);
763         PhiMI->addMachineBasicBlockOperand(PredMBB);
764         if (LongPhiMI) {
765           LongPhiMI->addRegOperand(ValReg+1);
766           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
767         }
768       }
769
770       // Now that we emitted all of the incoming values for the PHI node, make
771       // sure to reposition the InsertPoint after the PHI that we just added.
772       // This is needed because we might have inserted a constant into this
773       // block, right after the PHI's which is before the old insert point!
774       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
775       ++PHIInsertPoint;
776     }
777   }
778 }
779
780 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
781 /// compensation code on critical edges.  As such, it requires that we kill all
782 /// FP registers on the exit from any blocks that either ARE critical edges, or
783 /// branch to a block that has incoming critical edges.
784 ///
785 /// Note that this kill instruction will eventually be eliminated when
786 /// restrictions in the stackifier are relaxed.
787 ///
788 static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
789 #if 0
790   const BasicBlock *BB = MBB->getBasicBlock ();
791   for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
792     const BasicBlock *Succ = *SI;
793     pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
794     ++PI;  // Block have at least one predecessory
795     if (PI != PE) {             // If it has exactly one, this isn't crit edge
796       // If this block has more than one predecessor, check all of the
797       // predecessors to see if they have multiple successors.  If so, then the
798       // block we are analyzing needs an FPRegKill.
799       for (PI = pred_begin(Succ); PI != PE; ++PI) {
800         const BasicBlock *Pred = *PI;
801         succ_const_iterator SI2 = succ_begin(Pred);
802         ++SI2;  // There must be at least one successor of this block.
803         if (SI2 != succ_end(Pred))
804           return true;   // Yes, we must insert the kill on this edge.
805       }
806     }
807   }
808   // If we got this far, there is no need to insert the kill instruction.
809   return false;
810 #else
811   return true;
812 #endif
813 }
814
815 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
816 // need them.  This only occurs due to the floating point stackifier not being
817 // aggressive enough to handle arbitrary global stackification.
818 //
819 // Currently we insert an FP_REG_KILL instruction into each block that uses or
820 // defines a floating point virtual register.
821 //
822 // When the global register allocators (like linear scan) finally update live
823 // variable analysis, we can keep floating point values in registers across
824 // portions of the CFG that do not involve critical edges.  This will be a big
825 // win, but we are waiting on the global allocators before we can do this.
826 //
827 // With a bit of work, the floating point stackifier pass can be enhanced to
828 // break critical edges as needed (to make a place to put compensation code),
829 // but this will require some infrastructure improvements as well.
830 //
831 void X86ISel::InsertFPRegKills() {
832   SSARegMap &RegMap = *F->getSSARegMap();
833
834   for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
835     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
836       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
837       MachineOperand& MO = I->getOperand(i);
838         if (MO.isRegister() && MO.getReg()) {
839           unsigned Reg = MO.getReg();
840           if (MRegisterInfo::isVirtualRegister(Reg)) {
841             unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
842             if (RegSize == 10 || RegSize == 8)
843               goto UsesFPReg;
844           }
845         }
846       }
847     // If we haven't found an FP register use or def in this basic block, check
848     // to see if any of our successors has an FP PHI node, which will cause a
849     // copy to be inserted into this block.
850     for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
851          SE = BB->succ_end(); SI != SE; ++SI) {
852       MachineBasicBlock *SBB = *SI;
853       for (MachineBasicBlock::iterator I = SBB->begin();
854            I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
855         const TargetRegisterClass *RC =
856           RegMap.getRegClass(I->getOperand(0).getReg());
857         if (RC->getSize() == 10 || RC->getSize() == 8)
858           goto UsesFPReg;
859       }
860     }
861     continue;
862   UsesFPReg:
863     // Okay, this block uses an FP register.  If the block has successors (ie,
864     // it's not an unwind/return), insert the FP_REG_KILL instruction.
865     if (BB->succ_size() && RequiresFPRegKill(BB)) {
866       BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
867       ++NumFPKill;
868     }
869   }
870 }
871
872
873 void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
874   AM.BaseType = X86AddressMode::RegBase;
875   AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
876   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
877     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
878                        AM))
879       return;
880   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
881     if (CE->getOpcode() == Instruction::GetElementPtr)
882       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
883                         AM))
884         return;
885   } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
886     AM.BaseType = X86AddressMode::FrameIndexBase;
887     AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
888     return;
889   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
890     AM.GV = GV;
891     return;
892   }
893
894   // If it's not foldable, reset addr mode.
895   AM.BaseType = X86AddressMode::RegBase;
896   AM.Base.Reg = getReg(Addr);
897   AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
898 }
899
900 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
901 // it into the conditional branch or select instruction which is the only user
902 // of the cc instruction.  This is the case if the conditional branch is the
903 // only user of the setcc.  We also don't handle long arguments below, so we 
904 // reject them here as well.
905 //
906 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
907   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
908     if (SCI->hasOneUse()) {
909       Instruction *User = cast<Instruction>(SCI->use_back());
910       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
911           (getClassB(SCI->getOperand(0)->getType()) != cLong ||
912            SCI->getOpcode() == Instruction::SetEQ ||
913            SCI->getOpcode() == Instruction::SetNE) &&
914           (isa<BranchInst>(User) || User->getOperand(0) == V))
915         return SCI;
916     }
917   return 0;
918 }
919
920 // Return a fixed numbering for setcc instructions which does not depend on the
921 // order of the opcodes.
922 //
923 static unsigned getSetCCNumber(unsigned Opcode) {
924   switch(Opcode) {
925   default: assert(0 && "Unknown setcc instruction!");
926   case Instruction::SetEQ: return 0;
927   case Instruction::SetNE: return 1;
928   case Instruction::SetLT: return 2;
929   case Instruction::SetGE: return 3;
930   case Instruction::SetGT: return 4;
931   case Instruction::SetLE: return 5;
932   }
933 }
934
935 // LLVM  -> X86 signed  X86 unsigned
936 // -----    ----------  ------------
937 // seteq -> sete        sete
938 // setne -> setne       setne
939 // setlt -> setl        setb
940 // setge -> setge       setae
941 // setgt -> setg        seta
942 // setle -> setle       setbe
943 // ----
944 //          sets                       // Used by comparison with 0 optimization
945 //          setns
946 static const unsigned SetCCOpcodeTab[2][8] = {
947   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
948     0, 0 },
949   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
950     X86::SETSr, X86::SETNSr },
951 };
952
953 /// emitUCOMr - In the future when we support processors before the P6, this
954 /// wraps the logic for emitting an FUCOMr vs FUCOMIr.
955 void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
956                         unsigned LHS, unsigned RHS) {
957   if (0) { // for processors prior to the P6
958     BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
959     BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
960     BuildMI(*MBB, IP, X86::SAHF, 1);
961   } else {
962     BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
963   }
964 }
965
966 // EmitComparison - This function emits a comparison of the two operands,
967 // returning the extended setcc code to use.
968 unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
969                                  MachineBasicBlock *MBB,
970                                  MachineBasicBlock::iterator IP) {
971   // The arguments are already supposed to be of the same type.
972   const Type *CompTy = Op0->getType();
973   unsigned Class = getClassB(CompTy);
974
975   // Special case handling of: cmp R, i
976   if (isa<ConstantPointerNull>(Op1)) {
977     unsigned Op0r = getReg(Op0, MBB, IP);
978     if (OpNum < 2)    // seteq/setne -> test
979       BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
980     else
981       BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
982     return OpNum;
983
984   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
985     if (Class == cByte || Class == cShort || Class == cInt) {
986       unsigned Op1v = CI->getRawValue();
987
988       // Mask off any upper bits of the constant, if there are any...
989       Op1v &= (1ULL << (8 << Class)) - 1;
990
991       // If this is a comparison against zero, emit more efficient code.  We
992       // can't handle unsigned comparisons against zero unless they are == or
993       // !=.  These should have been strength reduced already anyway.
994       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
995
996         // If this is a comparison against zero and the LHS is an and of a
997         // register with a constant, use the test to do the and.
998         if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
999           if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
1000               isa<ConstantInt>(Op0I->getOperand(1))) {
1001             static const unsigned TESTTab[] = {
1002               X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
1003             };
1004             
1005             // Emit test X, i
1006             unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
1007             unsigned Imm =
1008               cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
1009             BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
1010             
1011             if (OpNum == 2) return 6;   // Map jl -> js
1012             if (OpNum == 3) return 7;   // Map jg -> jns
1013             return OpNum;
1014           }
1015
1016         unsigned Op0r = getReg(Op0, MBB, IP);
1017         static const unsigned TESTTab[] = {
1018           X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
1019         };
1020         BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
1021
1022         if (OpNum == 2) return 6;   // Map jl -> js
1023         if (OpNum == 3) return 7;   // Map jg -> jns
1024         return OpNum;
1025       }
1026
1027       static const unsigned CMPTab[] = {
1028         X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
1029       };
1030
1031       unsigned Op0r = getReg(Op0, MBB, IP);
1032       BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
1033       return OpNum;
1034     } else {
1035       unsigned Op0r = getReg(Op0, MBB, IP);
1036       assert(Class == cLong && "Unknown integer class!");
1037       unsigned LowCst = CI->getRawValue();
1038       unsigned HiCst = CI->getRawValue() >> 32;
1039       if (OpNum < 2) {    // seteq, setne
1040         unsigned LoTmp = Op0r;
1041         if (LowCst != 0) {
1042           LoTmp = makeAnotherReg(Type::IntTy);
1043           BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1044         }
1045         unsigned HiTmp = Op0r+1;
1046         if (HiCst != 0) {
1047           HiTmp = makeAnotherReg(Type::IntTy);
1048           BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
1049         }
1050         unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1051         BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1052         return OpNum;
1053       } else {
1054         // Emit a sequence of code which compares the high and low parts once
1055         // each, then uses a conditional move to handle the overflow case.  For
1056         // example, a setlt for long would generate code like this:
1057         //
1058         // AL = lo(op1) < lo(op2)   // Always unsigned comparison
1059         // BL = hi(op1) < hi(op2)   // Signedness depends on operands
1060         // dest = hi(op1) == hi(op2) ? BL : AL;
1061         //
1062
1063         // FIXME: This would be much better if we had hierarchical register
1064         // classes!  Until then, hardcode registers so that we can deal with
1065         // their aliases (because we don't have conditional byte moves).
1066         //
1067         BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1068         BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1069         BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1070         BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1071         BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1072         BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1073         BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1074           .addReg(X86::AX);
1075         // NOTE: visitSetCondInst knows that the value is dumped into the BL
1076         // register at this point for long values...
1077         return OpNum;
1078       }
1079     }
1080   }
1081
1082   unsigned Op0r = getReg(Op0, MBB, IP);
1083
1084   // Special case handling of comparison against +/- 0.0
1085   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1086     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
1087       BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
1088       BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
1089       BuildMI(*MBB, IP, X86::SAHF, 1);
1090       return OpNum;
1091     }
1092
1093   unsigned Op1r = getReg(Op1, MBB, IP);
1094   switch (Class) {
1095   default: assert(0 && "Unknown type class!");
1096     // Emit: cmp <var1>, <var2> (do the comparison).  We can
1097     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1098     // 32-bit.
1099   case cByte:
1100     BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
1101     break;
1102   case cShort:
1103     BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
1104     break;
1105   case cInt:
1106     BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1107     break;
1108   case cFP:
1109     emitUCOMr(MBB, IP, Op0r, Op1r);
1110     break;
1111
1112   case cLong:
1113     if (OpNum < 2) {    // seteq, setne
1114       unsigned LoTmp = makeAnotherReg(Type::IntTy);
1115       unsigned HiTmp = makeAnotherReg(Type::IntTy);
1116       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1117       BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1118       BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1119       BuildMI(*MBB, IP, X86::OR32rr,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1120       break;  // Allow the sete or setne to be generated from flags set by OR
1121     } else {
1122       // Emit a sequence of code which compares the high and low parts once
1123       // each, then uses a conditional move to handle the overflow case.  For
1124       // example, a setlt for long would generate code like this:
1125       //
1126       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
1127       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
1128       // dest = hi(op1) == hi(op2) ? BL : AL;
1129       //
1130
1131       // FIXME: This would be much better if we had hierarchical register
1132       // classes!  Until then, hardcode registers so that we can deal with their
1133       // aliases (because we don't have conditional byte moves).
1134       //
1135       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1136       BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1137       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
1138       BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1139       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1140       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1141       BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1142                                                    .addReg(X86::AX);
1143       // NOTE: visitSetCondInst knows that the value is dumped into the BL
1144       // register at this point for long values...
1145       return OpNum;
1146     }
1147   }
1148   return OpNum;
1149 }
1150
1151 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1152 /// register, then move it to wherever the result should be. 
1153 ///
1154 void X86ISel::visitSetCondInst(SetCondInst &I) {
1155   if (canFoldSetCCIntoBranchOrSelect(&I))
1156     return;  // Fold this into a branch or select.
1157
1158   unsigned DestReg = getReg(I);
1159   MachineBasicBlock::iterator MII = BB->end();
1160   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1161                      DestReg);
1162 }
1163
1164 /// emitSetCCOperation - Common code shared between visitSetCondInst and
1165 /// constant expression support.
1166 ///
1167 void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1168                                  MachineBasicBlock::iterator IP,
1169                                  Value *Op0, Value *Op1, unsigned Opcode,
1170                                  unsigned TargetReg) {
1171   unsigned OpNum = getSetCCNumber(Opcode);
1172   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
1173
1174   const Type *CompTy = Op0->getType();
1175   unsigned CompClass = getClassB(CompTy);
1176   bool isSigned = CompTy->isSigned() && CompClass != cFP;
1177
1178   if (CompClass != cLong || OpNum < 2) {
1179     // Handle normal comparisons with a setcc instruction...
1180     BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1181   } else {
1182     // Handle long comparisons by copying the value which is already in BL into
1183     // the register we want...
1184     BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1185   }
1186 }
1187
1188 void X86ISel::visitSelectInst(SelectInst &SI) {
1189   unsigned DestReg = getReg(SI);
1190   MachineBasicBlock::iterator MII = BB->end();
1191   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1192                       SI.getFalseValue(), DestReg);
1193 }
1194  
1195 /// emitSelect - Common code shared between visitSelectInst and the constant
1196 /// expression support.
1197 void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1198                                   MachineBasicBlock::iterator IP,
1199                                   Value *Cond, Value *TrueVal, Value *FalseVal,
1200                                   unsigned DestReg) {
1201   unsigned SelectClass = getClassB(TrueVal->getType());
1202   
1203   // We don't support 8-bit conditional moves.  If we have incoming constants,
1204   // transform them into 16-bit constants to avoid having a run-time conversion.
1205   if (SelectClass == cByte) {
1206     if (Constant *T = dyn_cast<Constant>(TrueVal))
1207       TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1208     if (Constant *F = dyn_cast<Constant>(FalseVal))
1209       FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1210   }
1211
1212   unsigned TrueReg  = getReg(TrueVal, MBB, IP);
1213   unsigned FalseReg = getReg(FalseVal, MBB, IP);
1214   if (TrueReg == FalseReg) {
1215     static const unsigned Opcode[] = {
1216       X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1217     };
1218     BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1219     if (SelectClass == cLong)
1220       BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1221     return;
1222   }
1223
1224   unsigned Opcode;
1225   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1226     // We successfully folded the setcc into the select instruction.
1227     
1228     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1229     OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1230                            IP);
1231
1232     const Type *CompTy = SCI->getOperand(0)->getType();
1233     bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1234   
1235     // LLVM  -> X86 signed  X86 unsigned
1236     // -----    ----------  ------------
1237     // seteq -> cmovNE      cmovNE
1238     // setne -> cmovE       cmovE
1239     // setlt -> cmovGE      cmovAE
1240     // setge -> cmovL       cmovB
1241     // setgt -> cmovLE      cmovBE
1242     // setle -> cmovG       cmovA
1243     // ----
1244     //          cmovNS              // Used by comparison with 0 optimization
1245     //          cmovS
1246     
1247     switch (SelectClass) {
1248     default: assert(0 && "Unknown value class!");
1249     case cFP: {
1250       // Annoyingly, we don't have a full set of floating point conditional
1251       // moves.  :(
1252       static const unsigned OpcodeTab[2][8] = {
1253         { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1254           X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1255         { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1256       };
1257       Opcode = OpcodeTab[isSigned][OpNum];
1258
1259       // If opcode == 0, we hit a case that we don't support.  Output a setcc
1260       // and compare the result against zero.
1261       if (Opcode == 0) {
1262         unsigned CompClass = getClassB(CompTy);
1263         unsigned CondReg;
1264         if (CompClass != cLong || OpNum < 2) {
1265           CondReg = makeAnotherReg(Type::BoolTy);
1266           // Handle normal comparisons with a setcc instruction...
1267           BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1268         } else {
1269           // Long comparisons end up in the BL register.
1270           CondReg = X86::BL;
1271         }
1272         
1273         BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1274         Opcode = X86::FCMOVE;
1275       }
1276       break;
1277     }
1278     case cByte:
1279     case cShort: {
1280       static const unsigned OpcodeTab[2][8] = {
1281         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1282           X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1283         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1284           X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1285       };
1286       Opcode = OpcodeTab[isSigned][OpNum];
1287       break;
1288     }
1289     case cInt:
1290     case cLong: {
1291       static const unsigned OpcodeTab[2][8] = {
1292         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1293           X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1294         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1295           X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1296       };
1297       Opcode = OpcodeTab[isSigned][OpNum];
1298       break;
1299     }
1300     }
1301   } else {
1302     // Get the value being branched on, and use it to set the condition codes.
1303     unsigned CondReg = getReg(Cond, MBB, IP);
1304     BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1305     switch (SelectClass) {
1306     default: assert(0 && "Unknown value class!");
1307     case cFP:    Opcode = X86::FCMOVE; break;
1308     case cByte:
1309     case cShort: Opcode = X86::CMOVE16rr; break;
1310     case cInt:
1311     case cLong:  Opcode = X86::CMOVE32rr; break;
1312     }
1313   }
1314
1315   unsigned RealDestReg = DestReg;
1316
1317
1318   // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves.  Because of
1319   // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1320   // cmove, then truncate the result.
1321   if (SelectClass == cByte) {
1322     DestReg = makeAnotherReg(Type::ShortTy);
1323     if (getClassB(TrueVal->getType()) == cByte) {
1324       // Promote the true value, by storing it into AL, and reading from AX.
1325       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1326       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1327       TrueReg = makeAnotherReg(Type::ShortTy);
1328       BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1329     }
1330     if (getClassB(FalseVal->getType()) == cByte) {
1331       // Promote the true value, by storing it into CL, and reading from CX.
1332       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1333       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1334       FalseReg = makeAnotherReg(Type::ShortTy);
1335       BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1336     }
1337   }
1338
1339   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1340
1341   switch (SelectClass) {
1342   case cByte:
1343     // We did the computation with 16-bit registers.  Truncate back to our
1344     // result by copying into AX then copying out AL.
1345     BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1346     BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1347     break;
1348   case cLong:
1349     // Move the upper half of the value as well.
1350     BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1351     break;
1352   }
1353 }
1354
1355
1356
1357 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1358 /// operand, in the specified target register.
1359 ///
1360 void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1361   bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1362
1363   Value *Val = VR.Val;
1364   const Type *Ty = VR.Ty;
1365   if (Val) {
1366     if (Constant *C = dyn_cast<Constant>(Val)) {
1367       Val = ConstantExpr::getCast(C, Type::IntTy);
1368       Ty = Type::IntTy;
1369     }
1370
1371     // If this is a simple constant, just emit a MOVri directly to avoid the
1372     // copy.
1373     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1374       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1375       BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1376       return;
1377     }
1378   }
1379
1380   // Make sure we have the register number for this value...
1381   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1382
1383   switch (getClassB(Ty)) {
1384   case cByte:
1385     // Extend value into target register (8->32)
1386     if (isUnsigned)
1387       BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1388     else
1389       BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1390     break;
1391   case cShort:
1392     // Extend value into target register (16->32)
1393     if (isUnsigned)
1394       BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1395     else
1396       BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1397     break;
1398   case cInt:
1399     // Move value into target register (32->32)
1400     BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1401     break;
1402   default:
1403     assert(0 && "Unpromotable operand class in promote32");
1404   }
1405 }
1406
1407 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
1408 /// we have the following possibilities:
1409 ///
1410 ///   ret void: No return value, simply emit a 'ret' instruction
1411 ///   ret sbyte, ubyte : Extend value into EAX and return
1412 ///   ret short, ushort: Extend value into EAX and return
1413 ///   ret int, uint    : Move value into EAX and return
1414 ///   ret pointer      : Move value into EAX and return
1415 ///   ret long, ulong  : Move value into EAX/EDX and return
1416 ///   ret float/double : Top of FP stack
1417 ///
1418 void X86ISel::visitReturnInst(ReturnInst &I) {
1419   if (I.getNumOperands() == 0) {
1420     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1421     return;
1422   }
1423
1424   Value *RetVal = I.getOperand(0);
1425   switch (getClassB(RetVal->getType())) {
1426   case cByte:   // integral return values: extend or move into EAX and return
1427   case cShort:
1428   case cInt:
1429     promote32(X86::EAX, ValueRecord(RetVal));
1430     // Declare that EAX is live on exit
1431     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1432     break;
1433   case cFP: {                  // Floats & Doubles: Return in ST(0)
1434     unsigned RetReg = getReg(RetVal);
1435     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1436     // Declare that top-of-stack is live on exit
1437     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1438     break;
1439   }
1440   case cLong: {
1441     unsigned RetReg = getReg(RetVal);
1442     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1443     BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1444     // Declare that EAX & EDX are live on exit
1445     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1446       .addReg(X86::ESP);
1447     break;
1448   }
1449   default:
1450     visitInstruction(I);
1451   }
1452   // Emit a 'ret' instruction
1453   BuildMI(BB, X86::RET, 0);
1454 }
1455
1456 // getBlockAfter - Return the basic block which occurs lexically after the
1457 // specified one.
1458 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1459   Function::iterator I = BB; ++I;  // Get iterator to next block
1460   return I != BB->getParent()->end() ? &*I : 0;
1461 }
1462
1463 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1464 /// that since code layout is frozen at this point, that if we are trying to
1465 /// jump to a block that is the immediate successor of the current block, we can
1466 /// just make a fall-through (but we don't currently).
1467 ///
1468 void X86ISel::visitBranchInst(BranchInst &BI) {
1469   // Update machine-CFG edges
1470   BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1471   if (BI.isConditional())
1472     BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1473
1474   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1475
1476   if (!BI.isConditional()) {  // Unconditional branch?
1477     if (BI.getSuccessor(0) != NextBB)
1478       BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1479     return;
1480   }
1481
1482   // See if we can fold the setcc into the branch itself...
1483   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1484   if (SCI == 0) {
1485     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1486     // computed some other way...
1487     unsigned condReg = getReg(BI.getCondition());
1488     BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1489     if (BI.getSuccessor(1) == NextBB) {
1490       if (BI.getSuccessor(0) != NextBB)
1491         BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1492     } else {
1493       BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1494       
1495       if (BI.getSuccessor(0) != NextBB)
1496         BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1497     }
1498     return;
1499   }
1500
1501   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1502   MachineBasicBlock::iterator MII = BB->end();
1503   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1504
1505   const Type *CompTy = SCI->getOperand(0)->getType();
1506   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1507   
1508
1509   // LLVM  -> X86 signed  X86 unsigned
1510   // -----    ----------  ------------
1511   // seteq -> je          je
1512   // setne -> jne         jne
1513   // setlt -> jl          jb
1514   // setge -> jge         jae
1515   // setgt -> jg          ja
1516   // setle -> jle         jbe
1517   // ----
1518   //          js                  // Used by comparison with 0 optimization
1519   //          jns
1520
1521   static const unsigned OpcodeTab[2][8] = {
1522     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1523     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1524       X86::JS, X86::JNS },
1525   };
1526   
1527   if (BI.getSuccessor(0) != NextBB) {
1528     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1529       .addMBB(MBBMap[BI.getSuccessor(0)]);
1530     if (BI.getSuccessor(1) != NextBB)
1531       BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1532   } else {
1533     // Change to the inverse condition...
1534     if (BI.getSuccessor(1) != NextBB) {
1535       OpNum ^= 1;
1536       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1537         .addMBB(MBBMap[BI.getSuccessor(1)]);
1538     }
1539   }
1540 }
1541
1542
1543 /// doCall - This emits an abstract call instruction, setting up the arguments
1544 /// and the return value as appropriate.  For the actual function call itself,
1545 /// it inserts the specified CallMI instruction into the stream.
1546 ///
1547 void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1548                      const std::vector<ValueRecord> &Args) {
1549   // Count how many bytes are to be pushed on the stack...
1550   unsigned NumBytes = 0;
1551
1552   if (!Args.empty()) {
1553     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1554       switch (getClassB(Args[i].Ty)) {
1555       case cByte: case cShort: case cInt:
1556         NumBytes += 4; break;
1557       case cLong:
1558         NumBytes += 8; break;
1559       case cFP:
1560         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1561         break;
1562       default: assert(0 && "Unknown class!");
1563       }
1564
1565     // Adjust the stack pointer for the new arguments...
1566     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1567
1568     // Arguments go on the stack in reverse order, as specified by the ABI.
1569     unsigned ArgOffset = 0;
1570     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1571       unsigned ArgReg;
1572       switch (getClassB(Args[i].Ty)) {
1573       case cByte:
1574         if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1575           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1576             .addImm(Args[i].Val == ConstantBool::True);
1577           break;
1578         }
1579         // FALL THROUGH
1580       case cShort:
1581         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1582           // Zero/Sign extend constant, then stuff into memory.
1583           ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1584           Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1585           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1586             .addImm(Val->getRawValue() & 0xFFFFFFFF);
1587         } else {
1588           // Promote arg to 32 bits wide into a temporary register...
1589           ArgReg = makeAnotherReg(Type::UIntTy);
1590           promote32(ArgReg, Args[i]);
1591           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1592                        X86::ESP, ArgOffset).addReg(ArgReg);
1593         }
1594         break;
1595       case cInt:
1596         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1597           unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1598           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1599                        X86::ESP, ArgOffset).addImm(Val);
1600         } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1601           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1602                        X86::ESP, ArgOffset).addImm(0);
1603         } else {
1604           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1605           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1606                        X86::ESP, ArgOffset).addReg(ArgReg);
1607         }
1608         break;
1609       case cLong:
1610         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1611           uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1612           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1613                        X86::ESP, ArgOffset).addImm(Val & ~0U);
1614           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1615                        X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1616         } else {
1617           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1618           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1619                        X86::ESP, ArgOffset).addReg(ArgReg);
1620           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1621                        X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1622         }
1623         ArgOffset += 4;        // 8 byte entry, not 4.
1624         break;
1625         
1626       case cFP:
1627         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1628         if (Args[i].Ty == Type::FloatTy) {
1629           addRegOffset(BuildMI(BB, X86::FST32m, 5),
1630                        X86::ESP, ArgOffset).addReg(ArgReg);
1631         } else {
1632           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1633           addRegOffset(BuildMI(BB, X86::FST64m, 5),
1634                        X86::ESP, ArgOffset).addReg(ArgReg);
1635           ArgOffset += 4;       // 8 byte entry, not 4.
1636         }
1637         break;
1638
1639       default: assert(0 && "Unknown class!");
1640       }
1641       ArgOffset += 4;
1642     }
1643   } else {
1644     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1645   }
1646
1647   BB->push_back(CallMI);
1648
1649   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1650
1651   // If there is a return value, scavenge the result from the location the call
1652   // leaves it in...
1653   //
1654   if (Ret.Ty != Type::VoidTy) {
1655     unsigned DestClass = getClassB(Ret.Ty);
1656     switch (DestClass) {
1657     case cByte:
1658     case cShort:
1659     case cInt: {
1660       // Integral results are in %eax, or the appropriate portion
1661       // thereof.
1662       static const unsigned regRegMove[] = {
1663         X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1664       };
1665       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1666       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1667       break;
1668     }
1669     case cFP:     // Floating-point return values live in %ST(0)
1670       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1671       break;
1672     case cLong:   // Long values are left in EDX:EAX
1673       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1674       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1675       break;
1676     default: assert(0 && "Unknown class!");
1677     }
1678   }
1679 }
1680
1681
1682 /// visitCallInst - Push args on stack and do a procedure call instruction.
1683 void X86ISel::visitCallInst(CallInst &CI) {
1684   MachineInstr *TheCall;
1685   if (Function *F = CI.getCalledFunction()) {
1686     // Is it an intrinsic function call?
1687     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1688       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1689       return;
1690     }
1691
1692     // Emit a CALL instruction with PC-relative displacement.
1693     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1694   } else {  // Emit an indirect call...
1695     unsigned Reg = getReg(CI.getCalledValue());
1696     TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1697   }
1698
1699   std::vector<ValueRecord> Args;
1700   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1701     Args.push_back(ValueRecord(CI.getOperand(i)));
1702
1703   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1704   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1705 }         
1706
1707 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1708 /// function, lowering any calls to unknown intrinsic functions into the
1709 /// equivalent LLVM code.
1710 ///
1711 void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1712   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1713     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1714       if (CallInst *CI = dyn_cast<CallInst>(I++))
1715         if (Function *F = CI->getCalledFunction())
1716           switch (F->getIntrinsicID()) {
1717           case Intrinsic::not_intrinsic:
1718           case Intrinsic::vastart:
1719           case Intrinsic::vacopy:
1720           case Intrinsic::vaend:
1721           case Intrinsic::returnaddress:
1722           case Intrinsic::frameaddress:
1723           case Intrinsic::memcpy:
1724           case Intrinsic::memset:
1725           case Intrinsic::isunordered:
1726           case Intrinsic::readport:
1727           case Intrinsic::writeport:
1728             // We directly implement these intrinsics
1729             break;
1730           case Intrinsic::readio: {
1731             // On X86, memory operations are in-order.  Lower this intrinsic
1732             // into a volatile load.
1733             Instruction *Before = CI->getPrev();
1734             LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1735             CI->replaceAllUsesWith(LI);
1736             BB->getInstList().erase(CI);
1737             break;
1738           }
1739           case Intrinsic::writeio: {
1740             // On X86, memory operations are in-order.  Lower this intrinsic
1741             // into a volatile store.
1742             Instruction *Before = CI->getPrev();
1743             StoreInst *LI = new StoreInst(CI->getOperand(1),
1744                                           CI->getOperand(2), true, CI);
1745             CI->replaceAllUsesWith(LI);
1746             BB->getInstList().erase(CI);
1747             break;
1748           }
1749           default:
1750             // All other intrinsic calls we must lower.
1751             Instruction *Before = CI->getPrev();
1752             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1753             if (Before) {        // Move iterator to instruction after call
1754               I = Before; ++I;
1755             } else {
1756               I = BB->begin();
1757             }
1758           }
1759 }
1760
1761 void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1762   unsigned TmpReg1, TmpReg2;
1763   switch (ID) {
1764   case Intrinsic::vastart:
1765     // Get the address of the first vararg value...
1766     TmpReg1 = getReg(CI);
1767     addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1768     return;
1769
1770   case Intrinsic::vacopy:
1771     TmpReg1 = getReg(CI);
1772     TmpReg2 = getReg(CI.getOperand(1));
1773     BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1774     return;
1775   case Intrinsic::vaend: return;   // Noop on X86
1776
1777   case Intrinsic::returnaddress:
1778   case Intrinsic::frameaddress:
1779     TmpReg1 = getReg(CI);
1780     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1781       if (ReturnAddressIndex == 0) {
1782         // Set up a frame object for the return address.
1783         ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
1784       }
1785
1786       if (ID == Intrinsic::returnaddress) {
1787         // Just load the return address
1788         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1789                           ReturnAddressIndex);
1790       } else {
1791         addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1792                           ReturnAddressIndex, -4);
1793       }
1794     } else {
1795       // Values other than zero are not implemented yet.
1796       BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1797     }
1798     return;
1799
1800   case Intrinsic::isunordered:
1801     TmpReg1 = getReg(CI.getOperand(1));
1802     TmpReg2 = getReg(CI.getOperand(2));
1803     emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1804     TmpReg2 = getReg(CI);
1805     BuildMI(BB, X86::SETPr, 0, TmpReg2);
1806     return;
1807
1808   case Intrinsic::memcpy: {
1809     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1810     unsigned Align = 1;
1811     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1812       Align = AlignC->getRawValue();
1813       if (Align == 0) Align = 1;
1814     }
1815
1816     // Turn the byte code into # iterations
1817     unsigned CountReg;
1818     unsigned Opcode;
1819     switch (Align & 3) {
1820     case 2:   // WORD aligned
1821       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1822         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1823       } else {
1824         CountReg = makeAnotherReg(Type::IntTy);
1825         unsigned ByteReg = getReg(CI.getOperand(3));
1826         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1827       }
1828       Opcode = X86::REP_MOVSW;
1829       break;
1830     case 0:   // DWORD aligned
1831       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1832         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1833       } else {
1834         CountReg = makeAnotherReg(Type::IntTy);
1835         unsigned ByteReg = getReg(CI.getOperand(3));
1836         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1837       }
1838       Opcode = X86::REP_MOVSD;
1839       break;
1840     default:  // BYTE aligned
1841       CountReg = getReg(CI.getOperand(3));
1842       Opcode = X86::REP_MOVSB;
1843       break;
1844     }
1845
1846     // No matter what the alignment is, we put the source in ESI, the
1847     // destination in EDI, and the count in ECX.
1848     TmpReg1 = getReg(CI.getOperand(1));
1849     TmpReg2 = getReg(CI.getOperand(2));
1850     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1851     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1852     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1853     BuildMI(BB, Opcode, 0);
1854     return;
1855   }
1856   case Intrinsic::memset: {
1857     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1858     unsigned Align = 1;
1859     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1860       Align = AlignC->getRawValue();
1861       if (Align == 0) Align = 1;
1862     }
1863
1864     // Turn the byte code into # iterations
1865     unsigned CountReg;
1866     unsigned Opcode;
1867     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1868       unsigned Val = ValC->getRawValue() & 255;
1869
1870       // If the value is a constant, then we can potentially use larger copies.
1871       switch (Align & 3) {
1872       case 2:   // WORD aligned
1873         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1874           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1875         } else {
1876           CountReg = makeAnotherReg(Type::IntTy);
1877           unsigned ByteReg = getReg(CI.getOperand(3));
1878           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1879         }
1880         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1881         Opcode = X86::REP_STOSW;
1882         break;
1883       case 0:   // DWORD aligned
1884         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1885           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1886         } else {
1887           CountReg = makeAnotherReg(Type::IntTy);
1888           unsigned ByteReg = getReg(CI.getOperand(3));
1889           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1890         }
1891         Val = (Val << 8) | Val;
1892         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1893         Opcode = X86::REP_STOSD;
1894         break;
1895       default:  // BYTE aligned
1896         CountReg = getReg(CI.getOperand(3));
1897         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1898         Opcode = X86::REP_STOSB;
1899         break;
1900       }
1901     } else {
1902       // If it's not a constant value we are storing, just fall back.  We could
1903       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1904       unsigned ValReg = getReg(CI.getOperand(2));
1905       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1906       CountReg = getReg(CI.getOperand(3));
1907       Opcode = X86::REP_STOSB;
1908     }
1909
1910     // No matter what the alignment is, we put the source in ESI, the
1911     // destination in EDI, and the count in ECX.
1912     TmpReg1 = getReg(CI.getOperand(1));
1913     //TmpReg2 = getReg(CI.getOperand(2));
1914     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1915     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1916     BuildMI(BB, Opcode, 0);
1917     return;
1918   }
1919
1920   case Intrinsic::readport: {
1921     // First, determine that the size of the operand falls within the acceptable
1922     // range for this architecture.
1923     //
1924     if (getClassB(CI.getOperand(1)->getType()) != cShort) {
1925       std::cerr << "llvm.readport: Address size is not 16 bits\n";
1926       exit(1);
1927     }
1928
1929     // Now, move the I/O port address into the DX register and use the IN
1930     // instruction to get the input data.
1931     //
1932     unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1933     unsigned DestReg = getReg(CI);
1934
1935     // If the port is a single-byte constant, use the immediate form.
1936     if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1937       if ((C->getRawValue() & 255) == C->getRawValue()) {
1938         switch (Class) {
1939         case cByte:
1940           BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1941           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1942           return;
1943         case cShort:
1944           BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1945           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1946           return;
1947         case cInt:
1948           BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1949           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1950           return;
1951         }
1952       }
1953
1954     unsigned Reg = getReg(CI.getOperand(1));
1955     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1956     switch (Class) {
1957     case cByte:
1958       BuildMI(BB, X86::IN8rr, 0);
1959       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1960       break;
1961     case cShort:
1962       BuildMI(BB, X86::IN16rr, 0);
1963       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1964       break;
1965     case cInt:
1966       BuildMI(BB, X86::IN32rr, 0);
1967       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1968       break;
1969     default:
1970       std::cerr << "Cannot do input on this data type";
1971       exit (1);
1972     }
1973     return;
1974   }
1975
1976   case Intrinsic::writeport: {
1977     // First, determine that the size of the operand falls within the
1978     // acceptable range for this architecture.
1979     if (getClass(CI.getOperand(2)->getType()) != cShort) {
1980       std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1981       exit(1);
1982     }
1983
1984     unsigned Class = getClassB(CI.getOperand(1)->getType());
1985     unsigned ValReg = getReg(CI.getOperand(1));
1986     switch (Class) {
1987     case cByte:
1988       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1989       break;
1990     case cShort:
1991       BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1992       break;
1993     case cInt:
1994       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1995       break;
1996     default:
1997       std::cerr << "llvm.writeport: invalid data type for X86 target";
1998       exit(1);
1999     }
2000
2001
2002     // If the port is a single-byte constant, use the immediate form.
2003     if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
2004       if ((C->getRawValue() & 255) == C->getRawValue()) {
2005         static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
2006         BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
2007         return;
2008       }
2009
2010     // Otherwise, move the I/O port address into the DX register and the value
2011     // to write into the AL/AX/EAX register.
2012     static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
2013     unsigned Reg = getReg(CI.getOperand(2));
2014     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
2015     BuildMI(BB, Opc[Class], 0);
2016     return;
2017   }
2018     
2019   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
2020   }
2021 }
2022
2023 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
2024   if (LI.getParent() != User.getParent())
2025     return false;
2026   BasicBlock::iterator It = &LI;
2027   // Check all of the instructions between the load and the user.  We should
2028   // really use alias analysis here, but for now we just do something simple.
2029   for (++It; It != BasicBlock::iterator(&User); ++It) {
2030     switch (It->getOpcode()) {
2031     case Instruction::Free:
2032     case Instruction::Store:
2033     case Instruction::Call:
2034     case Instruction::Invoke:
2035       return false;
2036     case Instruction::Load:
2037       if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
2038         return false;
2039       break;
2040     }
2041   }
2042   return true;
2043 }
2044
2045 /// visitSimpleBinary - Implement simple binary operators for integral types...
2046 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2047 /// Xor.
2048 ///
2049 void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
2050   unsigned DestReg = getReg(B);
2051   MachineBasicBlock::iterator MI = BB->end();
2052   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
2053   unsigned Class = getClassB(B.getType());
2054
2055   // If this is AND X, C, and it is only used by a setcc instruction, it will
2056   // be folded.  There is no need to emit this instruction.
2057   if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2058     if (Class == cByte || Class == cShort || Class == cInt) {
2059       Instruction *Use = cast<Instruction>(B.use_back());
2060       if (isa<SetCondInst>(Use) &&
2061           Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2062         switch (getSetCCNumber(Use->getOpcode())) {
2063         case 0:
2064         case 1:
2065           return;
2066         default:
2067           if (B.getType()->isSigned()) return;
2068         }
2069       }
2070     }
2071
2072   // Special case: op Reg, load [mem]
2073   if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
2074       Op0->hasOneUse() && 
2075       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
2076     if (!B.swapOperands())
2077       std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
2078
2079   if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
2080       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2081
2082     unsigned Opcode;
2083     if (Class != cFP) {
2084       static const unsigned OpcodeTab[][3] = {
2085         // Arithmetic operators
2086         { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm },  // ADD
2087         { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm },  // SUB
2088         
2089         // Bitwise operators
2090         { X86::AND8rm, X86::AND16rm, X86::AND32rm },  // AND
2091         { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm },  // OR
2092         { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm },  // XOR
2093       };
2094       Opcode = OpcodeTab[OperatorClass][Class];
2095     } else {
2096       static const unsigned OpcodeTab[][2] = {
2097         { X86::FADD32m, X86::FADD64m },  // ADD
2098         { X86::FSUB32m, X86::FSUB64m },  // SUB
2099       };
2100       const Type *Ty = Op0->getType();
2101       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2102       Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2103     }
2104
2105     unsigned Op0r = getReg(Op0);
2106     if (AllocaInst *AI =
2107         dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2108       unsigned FI = getFixedSizedAllocaFI(AI);
2109       addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2110
2111     } else {
2112       X86AddressMode AM;
2113       getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
2114       
2115       addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
2116     }
2117     return;
2118   }
2119
2120   // If this is a floating point subtract, check to see if we can fold the first
2121   // operand in.
2122   if (Class == cFP && OperatorClass == 1 &&
2123       isa<LoadInst>(Op0) && 
2124       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2125     const Type *Ty = Op0->getType();
2126     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2127     unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2128
2129     unsigned Op1r = getReg(Op1);
2130     if (AllocaInst *AI =
2131         dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2132       unsigned FI = getFixedSizedAllocaFI(AI);
2133       addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2134     } else {
2135       X86AddressMode AM;
2136       getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
2137       
2138       addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
2139     }
2140     return;
2141   }
2142
2143   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
2144 }
2145
2146
2147 /// emitBinaryFPOperation - This method handles emission of floating point
2148 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
2149 void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2150                                     MachineBasicBlock::iterator IP,
2151                                     Value *Op0, Value *Op1,
2152                                     unsigned OperatorClass, unsigned DestReg) {
2153   // Special case: op Reg, <const fp>
2154   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2155     if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2156       // Create a constant pool entry for this constant.
2157       MachineConstantPool *CP = F->getConstantPool();
2158       unsigned CPI = CP->getConstantPoolIndex(Op1C);
2159       const Type *Ty = Op1->getType();
2160
2161       static const unsigned OpcodeTab[][4] = {
2162         { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m },   // Float
2163         { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m },   // Double
2164       };
2165
2166       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2167       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2168       unsigned Op0r = getReg(Op0, BB, IP);
2169       addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2170                                        DestReg).addReg(Op0r), CPI);
2171       return;
2172     }
2173   
2174   // Special case: R1 = op <const fp>, R2
2175   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2176     if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2177       // -0.0 - X === -X
2178       unsigned op1Reg = getReg(Op1, BB, IP);
2179       BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2180       return;
2181     } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
2182       // R1 = op CST, R2  -->  R1 = opr R2, CST
2183
2184       // Create a constant pool entry for this constant.
2185       MachineConstantPool *CP = F->getConstantPool();
2186       unsigned CPI = CP->getConstantPoolIndex(CFP);
2187       const Type *Ty = CFP->getType();
2188
2189       static const unsigned OpcodeTab[][4] = {
2190         { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2191         { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2192       };
2193       
2194       assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2195       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2196       unsigned Op1r = getReg(Op1, BB, IP);
2197       addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2198                                        DestReg).addReg(Op1r), CPI);
2199       return;
2200     }
2201
2202   // General case.
2203   static const unsigned OpcodeTab[4] = {
2204     X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2205   };
2206
2207   unsigned Opcode = OpcodeTab[OperatorClass];
2208   unsigned Op0r = getReg(Op0, BB, IP);
2209   unsigned Op1r = getReg(Op1, BB, IP);
2210   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2211 }
2212
2213 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2214 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2215 /// Or, 4 for Xor.
2216 ///
2217 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2218 /// and constant expression support.
2219 ///
2220 void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2221                                         MachineBasicBlock::iterator IP,
2222                                         Value *Op0, Value *Op1,
2223                                         unsigned OperatorClass, 
2224                                         unsigned DestReg) {
2225   unsigned Class = getClassB(Op0->getType());
2226
2227   if (Class == cFP) {
2228     assert(OperatorClass < 2 && "No logical ops for FP!");
2229     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2230     return;
2231   }
2232
2233   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2234     if (OperatorClass == 1) {
2235       static unsigned const NEGTab[] = {
2236         X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2237       };
2238
2239       // sub 0, X -> neg X
2240       if (CI->isNullValue()) {
2241         unsigned op1Reg = getReg(Op1, MBB, IP);
2242         BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2243       
2244         if (Class == cLong) {
2245           // We just emitted: Dl = neg Sl
2246           // Now emit       : T  = addc Sh, 0
2247           //                : Dh = neg T
2248           unsigned T = makeAnotherReg(Type::IntTy);
2249           BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2250           BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2251         }
2252         return;
2253       } else if (Op1->hasOneUse() && Class != cLong) {
2254         // sub C, X -> tmp = neg X; DestReg = add tmp, C.  This is better
2255         // than copying C into a temporary register, because of register
2256         // pressure (tmp and destreg can share a register.
2257         static unsigned const ADDRITab[] = { 
2258           X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2259         };
2260         unsigned op1Reg = getReg(Op1, MBB, IP);
2261         unsigned Tmp = makeAnotherReg(Op0->getType());
2262         BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
2263         BuildMI(*MBB, IP, ADDRITab[Class], 2,
2264                 DestReg).addReg(Tmp).addImm(CI->getRawValue());
2265         return;
2266       }
2267     }
2268
2269   // Special case: op Reg, <const int>
2270   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
2271     unsigned Op0r = getReg(Op0, MBB, IP);
2272
2273     // xor X, -1 -> not X
2274     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
2275       static unsigned const NOTTab[] = {
2276         X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2277       };
2278       BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
2279       if (Class == cLong)  // Invert the top part too
2280         BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
2281       return;
2282     }
2283
2284     // add X, -1 -> dec X
2285     if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2286       // Note that we can't use dec for 64-bit decrements, because it does not
2287       // set the carry flag!
2288       static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
2289       BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2290       return;
2291     }
2292
2293     // add X, 1 -> inc X
2294     if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2295       // Note that we can't use inc for 64-bit increments, because it does not
2296       // set the carry flag!
2297       static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
2298       BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
2299       return;
2300     }
2301   
2302     static const unsigned OpcodeTab[][5] = {
2303       // Arithmetic operators
2304       { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri },  // ADD
2305       { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri },  // SUB
2306     
2307       // Bitwise operators
2308       { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri },  // AND
2309       { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri  },  // OR
2310       { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri },  // XOR
2311     };
2312   
2313     unsigned Opcode = OpcodeTab[OperatorClass][Class];
2314     unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
2315
2316     if (Class != cLong) {
2317       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2318       return;
2319     }
2320     
2321     // If this is a long value and the high or low bits have a special
2322     // property, emit some special cases.
2323     unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2324     
2325     // If the constant is zero in the low 32-bits, just copy the low part
2326     // across and apply the normal 32-bit operation to the high parts.  There
2327     // will be no carry or borrow into the top.
2328     if (Op1l == 0) {
2329       if (OperatorClass != 2) // All but and...
2330         BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2331       else
2332         BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2333       BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2334         .addReg(Op0r+1).addImm(Op1h);
2335       return;
2336     }
2337     
2338     // If this is a logical operation and the top 32-bits are zero, just
2339     // operate on the lower 32.
2340     if (Op1h == 0 && OperatorClass > 1) {
2341       BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2342         .addReg(Op0r).addImm(Op1l);
2343       if (OperatorClass != 2)  // All but and
2344         BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2345       else
2346         BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2347       return;
2348     }
2349     
2350     // TODO: We could handle lots of other special cases here, such as AND'ing
2351     // with 0xFFFFFFFF00000000 -> noop, etc.
2352     
2353     // Otherwise, code generate the full operation with a constant.
2354     static const unsigned TopTab[] = {
2355       X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2356     };
2357     
2358     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2359     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2360       .addReg(Op0r+1).addImm(Op1h);
2361     return;
2362   }
2363
2364   // Finally, handle the general case now.
2365   static const unsigned OpcodeTab[][5] = {
2366     // Arithmetic operators
2367     { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr },  // ADD
2368     { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr },  // SUB
2369       
2370     // Bitwise operators
2371     { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr },  // AND
2372     { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr },  // OR
2373     { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr },  // XOR
2374   };
2375     
2376   unsigned Opcode = OpcodeTab[OperatorClass][Class];
2377   unsigned Op0r = getReg(Op0, MBB, IP);
2378   unsigned Op1r = getReg(Op1, MBB, IP);
2379   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2380     
2381   if (Class == cLong) {        // Handle the upper 32 bits of long values...
2382     static const unsigned TopTab[] = {
2383       X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2384     };
2385     BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2386             DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2387   }
2388 }
2389
2390 /// doMultiply - Emit appropriate instructions to multiply together the
2391 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
2392 /// result should be given as DestTy.
2393 ///
2394 void X86ISel::doMultiply(MachineBasicBlock *MBB,
2395                          MachineBasicBlock::iterator MBBI,
2396                          unsigned DestReg, const Type *DestTy,
2397                          unsigned op0Reg, unsigned op1Reg) {
2398   unsigned Class = getClass(DestTy);
2399   switch (Class) {
2400   case cInt:
2401   case cShort:
2402     BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2403       .addReg(op0Reg).addReg(op1Reg);
2404     return;
2405   case cByte:
2406     // Must use the MUL instruction, which forces use of AL...
2407     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2408     BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2409     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2410     return;
2411   default:
2412   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2413   }
2414 }
2415
2416 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
2417 // returns zero when the input is not exactly a power of two.
2418 static unsigned ExactLog2(unsigned Val) {
2419   if (Val == 0 || (Val & (Val-1))) return 0;
2420   unsigned Count = 0;
2421   while (Val != 1) {
2422     Val >>= 1;
2423     ++Count;
2424   }
2425   return Count+1;
2426 }
2427
2428
2429 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2430 /// 16, or 32-bit integer multiply by a constant.
2431 void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2432                               MachineBasicBlock::iterator IP,
2433                               unsigned DestReg, const Type *DestTy,
2434                               unsigned op0Reg, unsigned ConstRHS) {
2435   static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2436   static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2437   static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
2438   static const unsigned NEGrTab[]  = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
2439
2440   unsigned Class = getClass(DestTy);
2441   unsigned TmpReg;
2442
2443   // Handle special cases here.
2444   switch (ConstRHS) {
2445   case -2:
2446     TmpReg = makeAnotherReg(DestTy);
2447     BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2448     BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2449     return;
2450   case -1:
2451     BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2452     return;
2453   case 0:
2454     BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2455     return;
2456   case 1:
2457     BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2458     return;
2459   case 2:
2460     BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2461     return;
2462   case 3:
2463   case 5:
2464   case 9:
2465     if (Class == cInt) {
2466       X86AddressMode AM;
2467       AM.BaseType = X86AddressMode::RegBase;
2468       AM.Base.Reg = op0Reg;
2469       AM.Scale = ConstRHS-1;
2470       AM.IndexReg = op0Reg;
2471       AM.Disp = 0;
2472       addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
2473       return;
2474     }
2475   case -3:
2476   case -5:
2477   case -9:
2478     if (Class == cInt) {
2479       TmpReg = makeAnotherReg(DestTy);
2480       X86AddressMode AM;
2481       AM.BaseType = X86AddressMode::RegBase;
2482       AM.Base.Reg = op0Reg;
2483       AM.Scale = -ConstRHS-1;
2484       AM.IndexReg = op0Reg;
2485       AM.Disp = 0;
2486       addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
2487       BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2488       return;
2489     }
2490   }
2491
2492   // If the element size is exactly a power of 2, use a shift to get it.
2493   if (unsigned Shift = ExactLog2(ConstRHS)) {
2494     switch (Class) {
2495     default: assert(0 && "Unknown class for this function!");
2496     case cByte:
2497       BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2498       return;
2499     case cShort:
2500       BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2501       return;
2502     case cInt:
2503       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2504       return;
2505     }
2506   }
2507
2508   // If the element size is a negative power of 2, use a shift/neg to get it.
2509   if (unsigned Shift = ExactLog2(-ConstRHS)) {
2510     TmpReg = makeAnotherReg(DestTy);
2511     BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2512     switch (Class) {
2513     default: assert(0 && "Unknown class for this function!");
2514     case cByte:
2515       BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2516       return;
2517     case cShort:
2518       BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2519       return;
2520     case cInt:
2521       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2522       return;
2523     }
2524   }
2525   
2526   if (Class == cShort) {
2527     BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2528     return;
2529   } else if (Class == cInt) {
2530     BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2531     return;
2532   }
2533
2534   // Most general case, emit a normal multiply...
2535   TmpReg = makeAnotherReg(DestTy);
2536   BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2537   
2538   // Emit a MUL to multiply the register holding the index by
2539   // elementSize, putting the result in OffsetReg.
2540   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2541 }
2542
2543 /// visitMul - Multiplies are not simple binary operators because they must deal
2544 /// with the EAX register explicitly.
2545 ///
2546 void X86ISel::visitMul(BinaryOperator &I) {
2547   unsigned ResultReg = getReg(I);
2548
2549   Value *Op0 = I.getOperand(0);
2550   Value *Op1 = I.getOperand(1);
2551
2552   // Fold loads into floating point multiplies.
2553   if (getClass(Op0->getType()) == cFP) {
2554     if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2555       if (!I.swapOperands())
2556         std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
2557     if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2558       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2559         const Type *Ty = Op0->getType();
2560         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2561         unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2562         
2563         unsigned Op0r = getReg(Op0);
2564         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2565           unsigned FI = getFixedSizedAllocaFI(AI);
2566           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2567         } else {
2568           X86AddressMode AM;
2569           getAddressingMode(LI->getOperand(0), AM);
2570           
2571           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2572         }
2573         return;
2574       }
2575   }
2576
2577   MachineBasicBlock::iterator IP = BB->end();
2578   emitMultiply(BB, IP, Op0, Op1, ResultReg);
2579 }
2580
2581 void X86ISel::emitMultiply(MachineBasicBlock *MBB, 
2582                            MachineBasicBlock::iterator IP,
2583                            Value *Op0, Value *Op1, unsigned DestReg) {
2584   MachineBasicBlock &BB = *MBB;
2585   TypeClass Class = getClass(Op0->getType());
2586
2587   // Simple scalar multiply?
2588   unsigned Op0Reg  = getReg(Op0, &BB, IP);
2589   switch (Class) {
2590   case cByte:
2591   case cShort:
2592   case cInt:
2593     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2594       unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2595       doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
2596     } else {
2597       unsigned Op1Reg  = getReg(Op1, &BB, IP);
2598       doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2599     }
2600     return;
2601   case cFP:
2602     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2603     return;
2604   case cLong:
2605     break;
2606   }
2607
2608   // Long value.  We have to do things the hard way...
2609   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2610     unsigned CLow = CI->getRawValue();
2611     unsigned CHi  = CI->getRawValue() >> 32;
2612     
2613     if (CLow == 0) {
2614       // If the low part of the constant is all zeros, things are simple.
2615       BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2616       doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2617       return;
2618     }
2619     
2620     // Multiply the two low parts... capturing carry into EDX
2621     unsigned OverflowReg = 0;
2622     if (CLow == 1) {
2623       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2624     } else {
2625       unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2626       OverflowReg = makeAnotherReg(Type::UIntTy);
2627       BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2628       BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2629       BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL);  // AL*BL
2630       
2631       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);   // AL*BL
2632       BuildMI(BB, IP, X86::MOV32rr, 1,
2633               OverflowReg).addReg(X86::EDX);                    // AL*BL >> 32
2634     }
2635     
2636     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
2637     doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2638     
2639     unsigned AHBLplusOverflowReg;
2640     if (OverflowReg) {
2641       AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2642       BuildMI(BB, IP, X86::ADD32rr, 2,                // AH*BL+(AL*BL >> 32)
2643               AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2644     } else {
2645       AHBLplusOverflowReg = AHBLReg;
2646     }
2647     
2648     if (CHi == 0) {
2649       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2650     } else {
2651       unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2652       doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2653       
2654       BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
2655               DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2656     }
2657     return;
2658   }
2659
2660   // General 64x64 multiply
2661
2662   unsigned Op1Reg  = getReg(Op1, &BB, IP);
2663   // Multiply the two low parts... capturing carry into EDX
2664   BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2665   BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg);  // AL*BL
2666   
2667   unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2668   BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);     // AL*BL
2669   BuildMI(BB, IP, X86::MOV32rr, 1,
2670           OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2671   
2672   unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
2673   BuildMI(BB, IP, X86::IMUL32rr, 2,
2674           AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2675   
2676   unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2677   BuildMI(BB, IP, X86::ADD32rr, 2,                // AH*BL+(AL*BL >> 32)
2678           AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2679   
2680   unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2681   BuildMI(BB, IP, X86::IMUL32rr, 2,
2682           ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2683   
2684   BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
2685           DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2686 }
2687
2688
2689 /// visitDivRem - Handle division and remainder instructions... these
2690 /// instruction both require the same instructions to be generated, they just
2691 /// select the result from a different register.  Note that both of these
2692 /// instructions work differently for signed and unsigned operands.
2693 ///
2694 void X86ISel::visitDivRem(BinaryOperator &I) {
2695   unsigned ResultReg = getReg(I);
2696   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2697
2698   // Fold loads into floating point divides.
2699   if (getClass(Op0->getType()) == cFP) {
2700     if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2701       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2702         const Type *Ty = Op0->getType();
2703         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2704         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2705         
2706         unsigned Op0r = getReg(Op0);
2707         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2708           unsigned FI = getFixedSizedAllocaFI(AI);
2709           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2710         } else {
2711           X86AddressMode AM;
2712           getAddressingMode(LI->getOperand(0), AM);
2713           
2714           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2715         }
2716         return;
2717       }
2718
2719     if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2720       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2721         const Type *Ty = Op0->getType();
2722         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2723         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2724         
2725         unsigned Op1r = getReg(Op1);
2726         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2727           unsigned FI = getFixedSizedAllocaFI(AI);
2728           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2729         } else {
2730           X86AddressMode AM;
2731           getAddressingMode(LI->getOperand(0), AM);
2732           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
2733         }
2734         return;
2735       }
2736   }
2737
2738
2739   MachineBasicBlock::iterator IP = BB->end();
2740   emitDivRemOperation(BB, IP, Op0, Op1,
2741                       I.getOpcode() == Instruction::Div, ResultReg);
2742 }
2743
2744 void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2745                                   MachineBasicBlock::iterator IP,
2746                                   Value *Op0, Value *Op1, bool isDiv,
2747                                   unsigned ResultReg) {
2748   const Type *Ty = Op0->getType();
2749   unsigned Class = getClass(Ty);
2750   switch (Class) {
2751   case cFP:              // Floating point divide
2752     if (isDiv) {
2753       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2754       return;
2755     } else {               // Floating point remainder...
2756       unsigned Op0Reg = getReg(Op0, BB, IP);
2757       unsigned Op1Reg = getReg(Op1, BB, IP);
2758       MachineInstr *TheCall =
2759         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2760       std::vector<ValueRecord> Args;
2761       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2762       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2763       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2764     }
2765     return;
2766   case cLong: {
2767     static const char *FnName[] =
2768       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2769     unsigned Op0Reg = getReg(Op0, BB, IP);
2770     unsigned Op1Reg = getReg(Op1, BB, IP);
2771     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2772     MachineInstr *TheCall =
2773       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2774
2775     std::vector<ValueRecord> Args;
2776     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2777     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2778     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2779     return;
2780   }
2781   case cByte: case cShort: case cInt:
2782     break;          // Small integrals, handled below...
2783   default: assert(0 && "Unknown class!");
2784   }
2785
2786   static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2787   static const unsigned NEGOpcode[]={ X86::NEG8r,  X86::NEG16r,  X86::NEG32r };
2788   static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2789   static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2790   static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2791
2792   // Special case signed division by power of 2.
2793   if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2794     if (isDiv) {
2795       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2796       int V = CI->getValue();
2797
2798       if (V == 1) {       // X /s 1 => X
2799         unsigned Op0Reg = getReg(Op0, BB, IP);
2800         BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2801         return;
2802       }
2803
2804       if (V == -1) {      // X /s -1 => -X
2805         unsigned Op0Reg = getReg(Op0, BB, IP);
2806         BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2807         return;
2808       }
2809
2810       if (V == 2 || V == -2) {      // X /s 2
2811         static const unsigned CMPOpcode[] = {
2812           X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2813         };
2814         static const unsigned SBBOpcode[] = {
2815           X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2816         };
2817         unsigned Op0Reg = getReg(Op0, BB, IP);
2818         unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2819         BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2820
2821         unsigned TmpReg = makeAnotherReg(Op0->getType());
2822         BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2823
2824         unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2825         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2826         if (V == -2) {
2827           BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2828         }
2829         return;
2830       }
2831
2832       bool isNeg = false;
2833       if (V < 0) {         // Not a positive power of 2?
2834         V = -V;
2835         isNeg = true;      // Maybe it's a negative power of 2.
2836       }
2837       if (unsigned Log = ExactLog2(V)) {
2838         --Log;
2839         unsigned Op0Reg = getReg(Op0, BB, IP);
2840         unsigned TmpReg = makeAnotherReg(Op0->getType());
2841         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2842           .addReg(Op0Reg).addImm(Log-1);
2843         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2844         BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2845           .addReg(TmpReg).addImm(32-Log);
2846         unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2847         BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2848           .addReg(Op0Reg).addReg(TmpReg2);
2849
2850         unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2851         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2852           .addReg(TmpReg3).addImm(Log);
2853         if (isNeg)
2854           BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2855         return;
2856       }
2857     } else {    // X % C
2858       assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2859       int V = CI->getValue();
2860
2861       if (V == 2 || V == -2) {       // X % 2, X % -2
2862         static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2863         static const unsigned BaseReg[]    = { X86::AL , X86::AX , X86::EAX };
2864         static const unsigned SExtReg[]    = { X86::AH , X86::DX , X86::EDX };
2865         static const unsigned ANDOpcode[]  = {
2866           X86::AND8ri, X86::AND16ri, X86::AND32ri
2867         };
2868         static const unsigned XOROpcode[]  = {
2869           X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2870         };
2871         static const unsigned SUBOpcode[]  = {
2872           X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2873         };
2874
2875         // Sign extend result into reg of -1 or 0.
2876         unsigned Op0Reg = getReg(Op0, BB, IP);
2877         BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2878         BuildMI(*BB, IP, SExtOpcode[Class], 0);
2879         unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2880         BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2881
2882         unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2883         BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2884         
2885         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2886         BuildMI(*BB, IP, XOROpcode[Class], 2,
2887                 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2888         BuildMI(*BB, IP, SUBOpcode[Class], 2,
2889                 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2890         return;
2891       }
2892     }
2893
2894   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
2895   static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2896   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
2897   static const unsigned SExOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
2898
2899   static const unsigned DivOpcode[][4] = {
2900     { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 },  // Unsigned division
2901     { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 },  // Signed division
2902   };
2903
2904   unsigned Reg    = Regs[Class];
2905   unsigned ExtReg = ExtRegs[Class];
2906
2907   // Put the first operand into one of the A registers...
2908   unsigned Op0Reg = getReg(Op0, BB, IP);
2909   unsigned Op1Reg = getReg(Op1, BB, IP);
2910   BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2911
2912   if (Ty->isSigned()) {
2913     // Emit a sign extension instruction.
2914     BuildMI(*BB, IP, SExOpcode[Class], 0);
2915
2916     // Emit the appropriate divide or remainder instruction...
2917     BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
2918   } else {
2919     // If unsigned, emit a zeroing instruction... (reg = 0)
2920     BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2921
2922     // Emit the appropriate divide or remainder instruction...
2923     BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2924   }
2925
2926   // Figure out which register we want to pick the result out of...
2927   unsigned DestReg = isDiv ? Reg : ExtReg;
2928   
2929   // Put the result into the destination register...
2930   BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2931 }
2932
2933
2934 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2935 /// for constant immediate shift values, and for constant immediate
2936 /// shift values equal to 1. Even the general case is sort of special,
2937 /// because the shift amount has to be in CL, not just any old register.
2938 ///
2939 void X86ISel::visitShiftInst(ShiftInst &I) {
2940   MachineBasicBlock::iterator IP = BB->end ();
2941   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2942                       I.getOpcode () == Instruction::Shl, I.getType (),
2943                       getReg (I));
2944 }
2945
2946 /// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2947 /// constant.
2948 void X86ISel::doSHLDConst(MachineBasicBlock *MBB, 
2949                           MachineBasicBlock::iterator IP,
2950                           unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2951                           unsigned Amt) {
2952   // SHLD is a very inefficient operation on every processor, try to do
2953   // somethign simpler for common values of 'Amt'.
2954   if (Amt == 0) {
2955     BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2956   } else if (Amt == 1) {
2957     unsigned Tmp = makeAnotherReg(Type::UIntTy);
2958     BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
2959     BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2960   } else if (Amt == 2 || Amt == 3) {
2961     // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
2962     // shift/lea pair.  NOTE: This should not be done on the P6 family!
2963     unsigned Tmp = makeAnotherReg(Type::UIntTy);
2964     BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
2965     X86AddressMode AM;
2966     AM.BaseType = X86AddressMode::RegBase;
2967     AM.Base.Reg = Tmp;
2968     AM.Scale = 1 << Amt;
2969     AM.IndexReg = Op0Reg;
2970     AM.Disp = 0;
2971     addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
2972   } else {
2973     // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
2974     // than it is to emit a real SHLD.
2975
2976     BuildMI(*MBB, IP, X86::SHLD32rri8, 3, 
2977             DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
2978   }
2979 }
2980
2981 /// emitShiftOperation - Common code shared between visitShiftInst and
2982 /// constant expression support.
2983 void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
2984                                  MachineBasicBlock::iterator IP,
2985                                  Value *Op, Value *ShiftAmount, 
2986                                  bool isLeftShift, const Type *ResultTy, 
2987                                  unsigned DestReg) {
2988   unsigned SrcReg = getReg (Op, MBB, IP);
2989   bool isSigned = ResultTy->isSigned ();
2990   unsigned Class = getClass (ResultTy);
2991
2992   static const unsigned ConstantOperand[][3] = {
2993     { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri },  // SHR
2994     { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri },  // SAR
2995     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SHL
2996     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SAL = SHL
2997   };
2998
2999   static const unsigned NonConstantOperand[][3] = {
3000     { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL },  // SHR
3001     { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL },  // SAR
3002     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SHL
3003     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SAL = SHL
3004   };
3005
3006   // Longs, as usual, are handled specially.
3007   if (Class == cLong) {
3008     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
3009       unsigned Amount = CUI->getValue();
3010       if (Amount == 1 && isLeftShift) {   // X << 1 == X+X
3011         BuildMI(*MBB, IP, X86::ADD32rr, 2,
3012                 DestReg).addReg(SrcReg).addReg(SrcReg);
3013         BuildMI(*MBB, IP, X86::ADC32rr, 2,
3014                 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
3015       } else if (Amount < 32) {
3016         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3017         if (isLeftShift) {
3018           doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
3019           BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
3020         } else {
3021           BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
3022                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
3023           BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
3024         }
3025       } else if (Amount == 32) {
3026         if (isLeftShift) {
3027           BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
3028           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3029         } else {
3030           BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
3031           if (!isSigned) {
3032             BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3033           } else {
3034             BuildMI(*MBB, IP, X86::SAR32ri, 2,
3035                     DestReg+1).addReg(SrcReg).addImm(31);
3036           }
3037         }
3038       } else {                 // Shifting more than 32 bits
3039         Amount -= 32;
3040         if (isLeftShift) {
3041           BuildMI(*MBB, IP, X86::SHL32ri, 2,
3042                   DestReg + 1).addReg(SrcReg).addImm(Amount);
3043           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3044         } else {
3045           BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3046                   DestReg).addReg(SrcReg+1).addImm(Amount);
3047           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3048         }
3049       }
3050     } else {
3051       unsigned TmpReg = makeAnotherReg(Type::IntTy);
3052       if (!isLeftShift && isSigned) {
3053         // If this is a SHR of a Long, then we need to do funny sign extension
3054         // stuff.  TmpReg gets the value to use as the high-part if we are
3055         // shifting more than 32 bits.
3056         BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
3057       } else {
3058         // Other shifts use a fixed zero value if the shift is more than 32
3059         // bits.
3060         BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
3061       }
3062
3063       // Initialize CL with the shift amount...
3064       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
3065       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3066
3067       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3068       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3069       if (isLeftShift) {
3070         // TmpReg2 = shld inHi, inLo
3071         BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
3072                                                     .addReg(SrcReg);
3073         // TmpReg3 = shl  inLo, CL
3074         BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
3075
3076         // Set the flags to indicate whether the shift was by more than 32 bits.
3077         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3078
3079         // DestHi = (>32) ? TmpReg3 : TmpReg2;
3080         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3081                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3082         // DestLo = (>32) ? TmpReg : TmpReg3;
3083         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3084             DestReg).addReg(TmpReg3).addReg(TmpReg);
3085       } else {
3086         // TmpReg2 = shrd inLo, inHi
3087         BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
3088                                                     .addReg(SrcReg+1);
3089         // TmpReg3 = s[ah]r  inHi, CL
3090         BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
3091                        .addReg(SrcReg+1);
3092
3093         // Set the flags to indicate whether the shift was by more than 32 bits.
3094         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3095
3096         // DestLo = (>32) ? TmpReg3 : TmpReg2;
3097         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3098                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3099
3100         // DestHi = (>32) ? TmpReg : TmpReg3;
3101         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3102                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3103       }
3104     }
3105     return;
3106   }
3107
3108   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
3109     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3110     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
3111
3112     if (CUI->getValue() == 1 && isLeftShift) {    // X << 1 -> X+X
3113       static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3114       BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3115     } else {
3116       const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3117       BuildMI(*MBB, IP, Opc[Class], 2,
3118               DestReg).addReg(SrcReg).addImm(CUI->getValue());
3119     }
3120   } else {                  // The shift amount is non-constant.
3121     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
3122     BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3123
3124     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
3125     BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
3126   }
3127 }
3128
3129
3130 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
3131 /// instruction.  The load and store instructions are the only place where we
3132 /// need to worry about the memory layout of the target machine.
3133 ///
3134 void X86ISel::visitLoadInst(LoadInst &I) {
3135   // Check to see if this load instruction is going to be folded into a binary
3136   // instruction, like add.  If so, we don't want to emit it.  Wouldn't a real
3137   // pattern matching instruction selector be nice?
3138   unsigned Class = getClassB(I.getType());
3139   if (I.hasOneUse()) {
3140     Instruction *User = cast<Instruction>(I.use_back());
3141     switch (User->getOpcode()) {
3142     case Instruction::Cast:
3143       // If this is a cast from a signed-integer type to a floating point type,
3144       // fold the cast here.
3145       if (getClassB(User->getType()) == cFP &&
3146           (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3147            I.getType() == Type::LongTy)) {
3148         unsigned DestReg = getReg(User);
3149         static const unsigned Opcode[] = {
3150           0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3151         };
3152
3153         if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3154           unsigned FI = getFixedSizedAllocaFI(AI);
3155           addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3156         } else {
3157           X86AddressMode AM;
3158           getAddressingMode(I.getOperand(0), AM);
3159           addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
3160         }
3161         return;
3162       } else {
3163         User = 0;
3164       }
3165       break;
3166
3167     case Instruction::Add:
3168     case Instruction::Sub:
3169     case Instruction::And:
3170     case Instruction::Or:
3171     case Instruction::Xor:
3172       if (Class == cLong) User = 0;
3173       break;
3174     case Instruction::Mul:
3175     case Instruction::Div:
3176       if (Class != cFP) User = 0;
3177       break;  // Folding only implemented for floating point.
3178     default: User = 0; break;
3179     }
3180
3181     if (User) {
3182       // Okay, we found a user.  If the load is the first operand and there is
3183       // no second operand load, reverse the operand ordering.  Note that this
3184       // can fail for a subtract (ie, no change will be made).
3185       bool Swapped = false;
3186       if (!isa<LoadInst>(User->getOperand(1)))
3187         Swapped = !cast<BinaryOperator>(User)->swapOperands();
3188       
3189       // Okay, now that everything is set up, if this load is used by the second
3190       // operand, and if there are no instructions that invalidate the load
3191       // before the binary operator, eliminate the load.
3192       if (User->getOperand(1) == &I &&
3193           isSafeToFoldLoadIntoInstruction(I, *User))
3194         return;   // Eliminate the load!
3195
3196       // If this is a floating point sub or div, we won't be able to swap the
3197       // operands, but we will still be able to eliminate the load.
3198       if (Class == cFP && User->getOperand(0) == &I &&
3199           !isa<LoadInst>(User->getOperand(1)) &&
3200           (User->getOpcode() == Instruction::Sub ||
3201            User->getOpcode() == Instruction::Div) &&
3202           isSafeToFoldLoadIntoInstruction(I, *User))
3203         return;  // Eliminate the load!
3204
3205       // If we swapped the operands to the instruction, but couldn't fold the
3206       // load anyway, swap them back.  We don't want to break add X, int 
3207       // folding.
3208       if (Swapped) cast<BinaryOperator>(User)->swapOperands();
3209     }
3210   }
3211
3212   static const unsigned Opcodes[] = {
3213     X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
3214   };
3215   unsigned Opcode = Opcodes[Class];
3216   if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
3217
3218   unsigned DestReg = getReg(I);
3219
3220   if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3221     unsigned FI = getFixedSizedAllocaFI(AI);
3222     if (Class == cLong) {
3223       addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3224       addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3225     } else {
3226       addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3227     }
3228   } else {
3229     X86AddressMode AM;
3230     getAddressingMode(I.getOperand(0), AM);
3231     
3232     if (Class == cLong) {
3233       addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3234       AM.Disp += 4;
3235       addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
3236     } else {
3237       addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
3238     }
3239   }
3240 }
3241
3242 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3243 /// instruction.
3244 ///
3245 void X86ISel::visitStoreInst(StoreInst &I) {
3246   X86AddressMode AM;
3247   getAddressingMode(I.getOperand(1), AM);
3248
3249   const Type *ValTy = I.getOperand(0)->getType();
3250   unsigned Class = getClassB(ValTy);
3251
3252   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3253     uint64_t Val = CI->getRawValue();
3254     if (Class == cLong) {
3255       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3256       AM.Disp += 4;
3257       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
3258     } else {
3259       static const unsigned Opcodes[] = {
3260         X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
3261       };
3262       unsigned Opcode = Opcodes[Class];
3263       addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
3264     }
3265   } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
3266     addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
3267   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
3268     addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
3269   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3270     // Store constant FP values with integer instructions to avoid having to
3271     // load the constants from the constant pool then do a store.
3272     if (CFP->getType() == Type::FloatTy) {
3273       union {
3274         unsigned I;
3275         float    F;
3276       } V;
3277       V.F = CFP->getValue();
3278       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
3279     } else {
3280       union {
3281         uint64_t I;
3282         double   F;
3283       } V;
3284       V.F = CFP->getValue();
3285       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3286       AM.Disp += 4;
3287       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
3288                                                           unsigned(V.I >> 32));
3289     }
3290     
3291   } else if (Class == cLong) {
3292     unsigned ValReg = getReg(I.getOperand(0));
3293     addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3294     AM.Disp += 4;
3295     addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
3296   } else {
3297     // FIXME: stop emitting these two instructions:
3298     //    movl $global,%eax
3299     //    movl %eax,(%ebx)
3300     // when one instruction will suffice.  That includes when the global
3301     // has an offset applied to it.
3302     unsigned ValReg = getReg(I.getOperand(0));
3303     static const unsigned Opcodes[] = {
3304       X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3305     };
3306     unsigned Opcode = Opcodes[Class];
3307     if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
3308
3309     addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
3310   }
3311 }
3312
3313
3314 /// visitCastInst - Here we have various kinds of copying with or without sign
3315 /// extension going on.
3316 ///
3317 void X86ISel::visitCastInst(CastInst &CI) {
3318   Value *Op = CI.getOperand(0);
3319
3320   unsigned SrcClass = getClassB(Op->getType());
3321   unsigned DestClass = getClassB(CI.getType());
3322   // Noop casts are not emitted: getReg will return the source operand as the
3323   // register to use for any uses of the noop cast.
3324   if (DestClass == SrcClass) {
3325     // The only detail in this plan is that casts from double -> float are 
3326     // truncating operations that we have to codegen through memory (despite
3327     // the fact that the source/dest registers are the same class).
3328     if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3329       return;
3330   }
3331
3332   // If this is a cast from a 32-bit integer to a Long type, and the only uses
3333   // of the case are GEP instructions, then the cast does not need to be
3334   // generated explicitly, it will be folded into the GEP.
3335   if (DestClass == cLong && SrcClass == cInt) {
3336     bool AllUsesAreGEPs = true;
3337     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3338       if (!isa<GetElementPtrInst>(*I)) {
3339         AllUsesAreGEPs = false;
3340         break;
3341       }        
3342
3343     // No need to codegen this cast if all users are getelementptr instrs...
3344     if (AllUsesAreGEPs) return;
3345   }
3346
3347   // If this cast converts a load from a short,int, or long integer to a FP
3348   // value, we will have folded this cast away.
3349   if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3350       (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3351        Op->getType() == Type::LongTy))
3352     return;
3353
3354
3355   unsigned DestReg = getReg(CI);
3356   MachineBasicBlock::iterator MI = BB->end();
3357   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
3358 }
3359
3360 /// emitCastOperation - Common code shared between visitCastInst and constant
3361 /// expression cast support.
3362 ///
3363 void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3364                                 MachineBasicBlock::iterator IP,
3365                                 Value *Src, const Type *DestTy,
3366                                 unsigned DestReg) {
3367   const Type *SrcTy = Src->getType();
3368   unsigned SrcClass = getClassB(SrcTy);
3369   unsigned DestClass = getClassB(DestTy);
3370   unsigned SrcReg = getReg(Src, BB, IP);
3371
3372   // Implement casts to bool by using compare on the operand followed by set if
3373   // not zero on the result.
3374   if (DestTy == Type::BoolTy) {
3375     switch (SrcClass) {
3376     case cByte:
3377       BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
3378       break;
3379     case cShort:
3380       BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
3381       break;
3382     case cInt:
3383       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
3384       break;
3385     case cLong: {
3386       unsigned TmpReg = makeAnotherReg(Type::IntTy);
3387       BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
3388       break;
3389     }
3390     case cFP:
3391       BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
3392       BuildMI(*BB, IP, X86::FNSTSW8r, 0);
3393       BuildMI(*BB, IP, X86::SAHF, 1);
3394       break;
3395     }
3396
3397     // If the zero flag is not set, then the value is true, set the byte to
3398     // true.
3399     BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
3400     return;
3401   }
3402
3403   static const unsigned RegRegMove[] = {
3404     X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
3405   };
3406
3407   // Implement casts between values of the same type class (as determined by
3408   // getClass) by using a register-to-register move.
3409   if (SrcClass == DestClass) {
3410     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
3411       BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
3412     } else if (SrcClass == cFP) {
3413       if (SrcTy == Type::FloatTy) {  // double -> float
3414         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
3415         BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
3416       } else {                       // float -> double
3417         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3418                "Unknown cFP member!");
3419         // Truncate from double to float by storing to memory as short, then
3420         // reading it back.
3421         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
3422         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
3423         addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5),
3424                           FrameIdx).addReg(SrcReg);
3425         addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
3426       }
3427     } else if (SrcClass == cLong) {
3428       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3429       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
3430     } else {
3431       assert(0 && "Cannot handle this type of cast instruction!");
3432       abort();
3433     }
3434     return;
3435   }
3436
3437   // Handle cast of SMALLER int to LARGER int using a move with sign extension
3438   // or zero extension, depending on whether the source type was signed.
3439   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3440       SrcClass < DestClass) {
3441     bool isLong = DestClass == cLong;
3442     if (isLong) DestClass = cInt;
3443
3444     static const unsigned Opc[][4] = {
3445       { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3446       { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr }  // u
3447     };
3448     
3449     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
3450     BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
3451         DestReg).addReg(SrcReg);
3452
3453     if (isLong) {  // Handle upper 32 bits as appropriate...
3454       if (isUnsigned)     // Zero out top bits...
3455         BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3456       else                // Sign extend bottom half...
3457         BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
3458     }
3459     return;
3460   }
3461
3462   // Special case long -> int ...
3463   if (SrcClass == cLong && DestClass == cInt) {
3464     BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3465     return;
3466   }
3467   
3468   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3469   // move out of AX or AL.
3470   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3471       && SrcClass > DestClass) {
3472     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
3473     BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3474     BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
3475     return;
3476   }
3477
3478   // Handle casts from integer to floating point now...
3479   if (DestClass == cFP) {
3480     // Promote the integer to a type supported by FLD.  We do this because there
3481     // are no unsigned FLD instructions, so we must promote an unsigned value to
3482     // a larger signed value, then use FLD on the larger value.
3483     //
3484     const Type *PromoteType = 0;
3485     unsigned PromoteOpcode = 0;
3486     unsigned RealDestReg = DestReg;
3487     switch (SrcTy->getTypeID()) {
3488     case Type::BoolTyID:
3489     case Type::SByteTyID:
3490       // We don't have the facilities for directly loading byte sized data from
3491       // memory (even signed).  Promote it to 16 bits.
3492       PromoteType = Type::ShortTy;
3493       PromoteOpcode = X86::MOVSX16rr8;
3494       break;
3495     case Type::UByteTyID:
3496       PromoteType = Type::ShortTy;
3497       PromoteOpcode = X86::MOVZX16rr8;
3498       break;
3499     case Type::UShortTyID:
3500       PromoteType = Type::IntTy;
3501       PromoteOpcode = X86::MOVZX32rr16;
3502       break;
3503     case Type::ULongTyID:
3504     case Type::UIntTyID:
3505       // Don't fild into the read destination.
3506       DestReg = makeAnotherReg(Type::DoubleTy);
3507       break;
3508     default:  // No promotion needed...
3509       break;
3510     }
3511     
3512     if (PromoteType) {
3513       unsigned TmpReg = makeAnotherReg(PromoteType);
3514       BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
3515       SrcTy = PromoteType;
3516       SrcClass = getClass(PromoteType);
3517       SrcReg = TmpReg;
3518     }
3519
3520     // Spill the integer to memory and reload it from there...
3521     int FrameIdx =
3522       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3523
3524     if (SrcClass == cLong) {
3525       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3526                         FrameIdx).addReg(SrcReg);
3527       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3528                         FrameIdx, 4).addReg(SrcReg+1);
3529     } else {
3530       static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
3531       addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3532                         FrameIdx).addReg(SrcReg);
3533     }
3534
3535     static const unsigned Op2[] =
3536       { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
3537     addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
3538
3539     if (SrcTy == Type::UIntTy) {
3540       // If this is a cast from uint -> double, we need to be careful about if
3541       // the "sign" bit is set.  If so, we don't want to make a negative number,
3542       // we want to make a positive number.  Emit code to add an offset if the
3543       // sign bit is set.
3544
3545       // Compute whether the sign bit is set by shifting the reg right 31 bits.
3546       unsigned IsNeg = makeAnotherReg(Type::IntTy);
3547       BuildMI(BB, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
3548
3549       // Create a CP value that has the offset in one word and 0 in the other.
3550       static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3551                                                         0x4f80000000000000ULL);
3552       unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
3553       BuildMI(BB, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
3554         .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3555
3556     } else if (SrcTy == Type::ULongTy) {
3557       // We need special handling for unsigned 64-bit integer sources.  If the
3558       // input number has the "sign bit" set, then we loaded it incorrectly as a
3559       // negative 64-bit number.  In this case, add an offset value.
3560
3561       // Emit a test instruction to see if the dynamic input value was signed.
3562       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
3563
3564       // If the sign bit is set, get a pointer to an offset, otherwise get a
3565       // pointer to a zero.
3566       MachineConstantPool *CP = F->getConstantPool();
3567       unsigned Zero = makeAnotherReg(Type::IntTy);
3568       Constant *Null = Constant::getNullValue(Type::UIntTy);
3569       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero), 
3570                                CP->getConstantPoolIndex(Null));
3571       unsigned Offset = makeAnotherReg(Type::IntTy);
3572       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3573                                              
3574       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
3575                                CP->getConstantPoolIndex(OffsetCst));
3576       unsigned Addr = makeAnotherReg(Type::IntTy);
3577       BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
3578
3579       // Load the constant for an add.  FIXME: this could make an 'fadd' that
3580       // reads directly from memory, but we don't support these yet.
3581       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
3582       addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
3583
3584       BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3585                 .addReg(ConstReg).addReg(DestReg);
3586     }
3587
3588     return;
3589   }
3590
3591   // Handle casts from floating point to integer now...
3592   if (SrcClass == cFP) {
3593     // Change the floating point control register to use "round towards zero"
3594     // mode when truncating to an integer value.
3595     //
3596     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3597     addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
3598
3599     // Load the old value of the high byte of the control word...
3600     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
3601     addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
3602                       CWFrameIdx, 1);
3603
3604     // Set the high part to be round to zero...
3605     addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
3606                       CWFrameIdx, 1).addImm(12);
3607
3608     // Reload the modified control word now...
3609     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3610     
3611     // Restore the memory image of control word to original value
3612     addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
3613                       CWFrameIdx, 1).addReg(HighPartOfCW);
3614
3615     // We don't have the facilities for directly storing byte sized data to
3616     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
3617     // larger classes because we only have signed FP stores.
3618     unsigned StoreClass  = DestClass;
3619     const Type *StoreTy  = DestTy;
3620     if (StoreClass == cByte || DestTy->isUnsigned())
3621       switch (StoreClass) {
3622       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
3623       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
3624       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
3625       // The following treatment of cLong may not be perfectly right,
3626       // but it survives chains of casts of the form
3627       // double->ulong->double.
3628       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
3629       default: assert(0 && "Unknown store class!");
3630       }
3631
3632     // Spill the integer to memory and reload it from there...
3633     int FrameIdx =
3634       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3635
3636     static const unsigned Op1[] =
3637       { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
3638     addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3639                       FrameIdx).addReg(SrcReg);
3640
3641     if (DestClass == cLong) {
3642       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3643       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
3644                         FrameIdx, 4);
3645     } else {
3646       static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
3647       addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
3648     }
3649
3650     // Reload the original control word now...
3651     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3652     return;
3653   }
3654
3655   // Anything we haven't handled already, we can't (yet) handle at all.
3656   assert(0 && "Unhandled cast instruction!");
3657   abort();
3658 }
3659
3660 /// visitVANextInst - Implement the va_next instruction...
3661 ///
3662 void X86ISel::visitVANextInst(VANextInst &I) {
3663   unsigned VAList = getReg(I.getOperand(0));
3664   unsigned DestReg = getReg(I);
3665
3666   unsigned Size;
3667   switch (I.getArgType()->getTypeID()) {
3668   default:
3669     std::cerr << I;
3670     assert(0 && "Error: bad type for va_next instruction!");
3671     return;
3672   case Type::PointerTyID:
3673   case Type::UIntTyID:
3674   case Type::IntTyID:
3675     Size = 4;
3676     break;
3677   case Type::ULongTyID:
3678   case Type::LongTyID:
3679   case Type::DoubleTyID:
3680     Size = 8;
3681     break;
3682   }
3683
3684   // Increment the VAList pointer...
3685   BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
3686 }
3687
3688 void X86ISel::visitVAArgInst(VAArgInst &I) {
3689   unsigned VAList = getReg(I.getOperand(0));
3690   unsigned DestReg = getReg(I);
3691
3692   switch (I.getType()->getTypeID()) {
3693   default:
3694     std::cerr << I;
3695     assert(0 && "Error: bad type for va_next instruction!");
3696     return;
3697   case Type::PointerTyID:
3698   case Type::UIntTyID:
3699   case Type::IntTyID:
3700     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3701     break;
3702   case Type::ULongTyID:
3703   case Type::LongTyID:
3704     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3705     addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
3706     break;
3707   case Type::DoubleTyID:
3708     addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
3709     break;
3710   }
3711 }
3712
3713 /// visitGetElementPtrInst - instruction-select GEP instructions
3714 ///
3715 void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3716   // If this GEP instruction will be folded into all of its users, we don't need
3717   // to explicitly calculate it!
3718   X86AddressMode AM;
3719   if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
3720     // Check all of the users of the instruction to see if they are loads and
3721     // stores.
3722     bool AllWillFold = true;
3723     for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3724       if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3725         if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3726             cast<Instruction>(*UI)->getOperand(0) == &I) {
3727           AllWillFold = false;
3728           break;
3729         }
3730
3731     // If the instruction is foldable, and will be folded into all users, don't
3732     // emit it!
3733     if (AllWillFold) return;
3734   }
3735
3736   unsigned outputReg = getReg(I);
3737   emitGEPOperation(BB, BB->end(), I.getOperand(0),
3738                    I.op_begin()+1, I.op_end(), outputReg);
3739 }
3740
3741 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3742 /// GEPTypes (the derived types being stepped through at each level).  On return
3743 /// from this function, if some indexes of the instruction are representable as
3744 /// an X86 lea instruction, the machine operands are put into the Ops
3745 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3746 /// lists.  Otherwise, GEPOps.size() is returned.  If this returns a an
3747 /// addressing mode that only partially consumes the input, the BaseReg input of
3748 /// the addressing mode must be left free.
3749 ///
3750 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3751 ///
3752 void X86ISel::getGEPIndex(MachineBasicBlock *MBB, 
3753                           MachineBasicBlock::iterator IP,
3754                           std::vector<Value*> &GEPOps,
3755                           std::vector<const Type*> &GEPTypes,
3756                           X86AddressMode &AM) {
3757   const TargetData &TD = TM.getTargetData();
3758
3759   // Clear out the state we are working with...
3760   AM.BaseType = X86AddressMode::RegBase;
3761   AM.Base.Reg = 0;   // No base register
3762   AM.Scale = 1;      // Unit scale
3763   AM.IndexReg = 0;   // No index register
3764   AM.Disp = 0;       // No displacement
3765
3766   // While there are GEP indexes that can be folded into the current address,
3767   // keep processing them.
3768   while (!GEPTypes.empty()) {
3769     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3770       // It's a struct access.  CUI is the index into the structure,
3771       // which names the field. This index must have unsigned type.
3772       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3773       
3774       // Use the TargetData structure to pick out what the layout of the
3775       // structure is in memory.  Since the structure index must be constant, we
3776       // can get its value and use it to find the right byte offset from the
3777       // StructLayout class's list of structure member offsets.
3778       AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3779       GEPOps.pop_back();        // Consume a GEP operand
3780       GEPTypes.pop_back();
3781     } else {
3782       // It's an array or pointer access: [ArraySize x ElementType].
3783       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3784       Value *idx = GEPOps.back();
3785
3786       // idx is the index into the array.  Unlike with structure
3787       // indices, we may not know its actual value at code-generation
3788       // time.
3789
3790       // If idx is a constant, fold it into the offset.
3791       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3792       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3793         AM.Disp += TypeSize*CSI->getValue();
3794       } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3795         AM.Disp += TypeSize*CUI->getValue();
3796       } else {
3797         // If the index reg is already taken, we can't handle this index.
3798         if (AM.IndexReg) return;
3799
3800         // If this is a size that we can handle, then add the index as 
3801         switch (TypeSize) {
3802         case 1: case 2: case 4: case 8:
3803           // These are all acceptable scales on X86.
3804           AM.Scale = TypeSize;
3805           break;
3806         default:
3807           // Otherwise, we can't handle this scale
3808           return;
3809         }
3810
3811         if (CastInst *CI = dyn_cast<CastInst>(idx))
3812           if (CI->getOperand(0)->getType() == Type::IntTy ||
3813               CI->getOperand(0)->getType() == Type::UIntTy)
3814             idx = CI->getOperand(0);
3815
3816         AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3817       }
3818
3819       GEPOps.pop_back();        // Consume a GEP operand
3820       GEPTypes.pop_back();
3821     }
3822   }
3823
3824   // GEPTypes is empty, which means we have a single operand left.  Set it as
3825   // the base register.
3826   //
3827   assert(AM.Base.Reg == 0);
3828
3829   if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3830     AM.BaseType = X86AddressMode::FrameIndexBase;
3831     AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
3832     GEPOps.pop_back();
3833     return;
3834   }
3835
3836   if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3837     AM.GV = GV;
3838     GEPOps.pop_back();
3839     return;
3840   }
3841
3842   AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3843   GEPOps.pop_back();        // Consume the last GEP operand
3844 }
3845
3846
3847 /// isGEPFoldable - Return true if the specified GEP can be completely
3848 /// folded into the addressing mode of a load/store or lea instruction.
3849 bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3850                             Value *Src, User::op_iterator IdxBegin,
3851                             User::op_iterator IdxEnd, X86AddressMode &AM) {
3852
3853   std::vector<Value*> GEPOps;
3854   GEPOps.resize(IdxEnd-IdxBegin+1);
3855   GEPOps[0] = Src;
3856   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3857   
3858   std::vector<const Type*>
3859     GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3860              gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3861
3862   MachineBasicBlock::iterator IP;
3863   if (MBB) IP = MBB->end();
3864   getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3865
3866   // We can fold it away iff the getGEPIndex call eliminated all operands.
3867   return GEPOps.empty();
3868 }
3869
3870 void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3871                                MachineBasicBlock::iterator IP,
3872                                Value *Src, User::op_iterator IdxBegin,
3873                                User::op_iterator IdxEnd, unsigned TargetReg) {
3874   const TargetData &TD = TM.getTargetData();
3875
3876   // If this is a getelementptr null, with all constant integer indices, just
3877   // replace it with TargetReg = 42.
3878   if (isa<ConstantPointerNull>(Src)) {
3879     User::op_iterator I = IdxBegin;
3880     for (; I != IdxEnd; ++I)
3881       if (!isa<ConstantInt>(*I))
3882         break;
3883     if (I == IdxEnd) {   // All constant indices
3884       unsigned Offset = TD.getIndexedOffset(Src->getType(),
3885                                          std::vector<Value*>(IdxBegin, IdxEnd));
3886       BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3887       return;
3888     }
3889   }
3890
3891   std::vector<Value*> GEPOps;
3892   GEPOps.resize(IdxEnd-IdxBegin+1);
3893   GEPOps[0] = Src;
3894   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3895   
3896   std::vector<const Type*> GEPTypes;
3897   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3898                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3899
3900   // Keep emitting instructions until we consume the entire GEP instruction.
3901   while (!GEPOps.empty()) {
3902     unsigned OldSize = GEPOps.size();
3903     X86AddressMode AM;
3904     getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3905     
3906     if (GEPOps.size() != OldSize) {
3907       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
3908       unsigned NextTarget = 0;
3909       if (!GEPOps.empty()) {
3910         assert(AM.Base.Reg == 0 &&
3911            "getGEPIndex should have left the base register open for chaining!");
3912         NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
3913       }
3914
3915       if (AM.BaseType == X86AddressMode::RegBase &&
3916           AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
3917         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
3918       else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3919                AM.IndexReg == 0 && AM.Disp == 0)
3920         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
3921       else
3922         addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
3923       --IP;
3924       TargetReg = NextTarget;
3925     } else if (GEPTypes.empty()) {
3926       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
3927       // all operands are consumed but the base pointer.  If so, just load it
3928       // into the register.
3929       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3930         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3931       } else {
3932         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3933         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3934       }
3935       break;                // we are now done
3936
3937     } else {
3938       // It's an array or pointer access: [ArraySize x ElementType].
3939       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3940       Value *idx = GEPOps.back();
3941       GEPOps.pop_back();        // Consume a GEP operand
3942       GEPTypes.pop_back();
3943
3944       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3945       // operand on X86.  Handle this case directly now...
3946       if (CastInst *CI = dyn_cast<CastInst>(idx))
3947         if (CI->getOperand(0)->getType() == Type::IntTy ||
3948             CI->getOperand(0)->getType() == Type::UIntTy)
3949           idx = CI->getOperand(0);
3950
3951       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3952       // must find the size of the pointed-to type (Not coincidentally, the next
3953       // type is the type of the elements in the array).
3954       const Type *ElTy = SqTy->getElementType();
3955       unsigned elementSize = TD.getTypeSize(ElTy);
3956
3957       // If idxReg is a constant, we don't need to perform the multiply!
3958       if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3959         if (!CSI->isNullValue()) {
3960           unsigned Offset = elementSize*CSI->getRawValue();
3961           unsigned Reg = makeAnotherReg(Type::UIntTy);
3962           BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3963                                 .addReg(Reg).addImm(Offset);
3964           --IP;            // Insert the next instruction before this one.
3965           TargetReg = Reg; // Codegen the rest of the GEP into this
3966         }
3967       } else if (elementSize == 1) {
3968         // If the element size is 1, we don't have to multiply, just add
3969         unsigned idxReg = getReg(idx, MBB, IP);
3970         unsigned Reg = makeAnotherReg(Type::UIntTy);
3971         BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3972         --IP;            // Insert the next instruction before this one.
3973         TargetReg = Reg; // Codegen the rest of the GEP into this
3974       } else {
3975         unsigned idxReg = getReg(idx, MBB, IP);
3976         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3977
3978         // Make sure we can back the iterator up to point to the first
3979         // instruction emitted.
3980         MachineBasicBlock::iterator BeforeIt = IP;
3981         if (IP == MBB->begin())
3982           BeforeIt = MBB->end();
3983         else
3984           --BeforeIt;
3985         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3986
3987         // Emit an ADD to add OffsetReg to the basePtr.
3988         unsigned Reg = makeAnotherReg(Type::UIntTy);
3989         BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3990                           .addReg(Reg).addReg(OffsetReg);
3991
3992         // Step to the first instruction of the multiply.
3993         if (BeforeIt == MBB->end())
3994           IP = MBB->begin();
3995         else
3996           IP = ++BeforeIt;
3997
3998         TargetReg = Reg; // Codegen the rest of the GEP into this
3999       }
4000     }
4001   }
4002 }
4003
4004 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
4005 /// frame manager, otherwise do it the hard way.
4006 ///
4007 void X86ISel::visitAllocaInst(AllocaInst &I) {
4008   // If this is a fixed size alloca in the entry block for the function, we
4009   // statically stack allocate the space, so we don't need to do anything here.
4010   //
4011   if (dyn_castFixedAlloca(&I)) return;
4012   
4013   // Find the data size of the alloca inst's getAllocatedType.
4014   const Type *Ty = I.getAllocatedType();
4015   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
4016
4017   // Create a register to hold the temporary result of multiplying the type size
4018   // constant by the variable amount.
4019   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
4020   unsigned SrcReg1 = getReg(I.getArraySize());
4021   
4022   // TotalSizeReg = mul <numelements>, <TypeSize>
4023   MachineBasicBlock::iterator MBBI = BB->end();
4024   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
4025
4026   // AddedSize = add <TotalSizeReg>, 15
4027   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
4028   BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
4029
4030   // AlignedSize = and <AddedSize>, ~15
4031   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
4032   BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
4033   
4034   // Subtract size from stack pointer, thereby allocating some space.
4035   BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
4036
4037   // Put a pointer to the space into the result register, by copying
4038   // the stack pointer.
4039   BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
4040
4041   // Inform the Frame Information that we have just allocated a variable-sized
4042   // object.
4043   F->getFrameInfo()->CreateVariableSizedObject();
4044 }
4045
4046 /// visitMallocInst - Malloc instructions are code generated into direct calls
4047 /// to the library malloc.
4048 ///
4049 void X86ISel::visitMallocInst(MallocInst &I) {
4050   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4051   unsigned Arg;
4052
4053   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4054     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4055   } else {
4056     Arg = makeAnotherReg(Type::UIntTy);
4057     unsigned Op0Reg = getReg(I.getOperand(0));
4058     MachineBasicBlock::iterator MBBI = BB->end();
4059     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
4060   }
4061
4062   std::vector<ValueRecord> Args;
4063   Args.push_back(ValueRecord(Arg, Type::UIntTy));
4064   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4065                                   1).addExternalSymbol("malloc", true);
4066   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4067 }
4068
4069
4070 /// visitFreeInst - Free instructions are code gen'd to call the free libc
4071 /// function.
4072 ///
4073 void X86ISel::visitFreeInst(FreeInst &I) {
4074   std::vector<ValueRecord> Args;
4075   Args.push_back(ValueRecord(I.getOperand(0)));
4076   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4077                                   1).addExternalSymbol("free", true);
4078   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4079 }
4080    
4081 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
4082 /// into a machine code representation is a very simple peep-hole fashion.  The
4083 /// generated code sucks but the implementation is nice and simple.
4084 ///
4085 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
4086   return new X86ISel(TM);
4087 }