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