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