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