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