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