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