d44288678ca0c6c012d5a2f1e29158e5888f81b5
[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         return SCI;
761     }
762   return 0;
763 }
764
765 // Return a fixed numbering for setcc instructions which does not depend on the
766 // order of the opcodes.
767 //
768 static unsigned getSetCCNumber(unsigned Opcode) {
769   switch(Opcode) {
770   default: assert(0 && "Unknown setcc instruction!");
771   case Instruction::SetEQ: return 0;
772   case Instruction::SetNE: return 1;
773   case Instruction::SetLT: return 2;
774   case Instruction::SetGE: return 3;
775   case Instruction::SetGT: return 4;
776   case Instruction::SetLE: return 5;
777   }
778 }
779
780 // LLVM  -> X86 signed  X86 unsigned
781 // -----    ----------  ------------
782 // seteq -> sete        sete
783 // setne -> setne       setne
784 // setlt -> setl        setb
785 // setge -> setge       setae
786 // setgt -> setg        seta
787 // setle -> setle       setbe
788 // ----
789 //          sets                       // Used by comparison with 0 optimization
790 //          setns
791 static const unsigned SetCCOpcodeTab[2][8] = {
792   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
793     0, 0 },
794   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
795     X86::SETSr, X86::SETNSr },
796 };
797
798 // EmitComparison - This function emits a comparison of the two operands,
799 // returning the extended setcc code to use.
800 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
801                               MachineBasicBlock *MBB,
802                               MachineBasicBlock::iterator IP) {
803   // The arguments are already supposed to be of the same type.
804   const Type *CompTy = Op0->getType();
805   unsigned Class = getClassB(CompTy);
806   unsigned Op0r = getReg(Op0, MBB, IP);
807
808   // Special case handling of: cmp R, i
809   if (Class == cByte || Class == cShort || Class == cInt)
810     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
811       uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
812
813       // Mask off any upper bits of the constant, if there are any...
814       Op1v &= (1ULL << (8 << Class)) - 1;
815
816       // If this is a comparison against zero, emit more efficient code.  We
817       // can't handle unsigned comparisons against zero unless they are == or
818       // !=.  These should have been strength reduced already anyway.
819       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
820         static const unsigned TESTTab[] = {
821           X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
822         };
823         BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
824
825         if (OpNum == 2) return 6;   // Map jl -> js
826         if (OpNum == 3) return 7;   // Map jg -> jns
827         return OpNum;
828       }
829
830       static const unsigned CMPTab[] = {
831         X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
832       };
833
834       BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
835       return OpNum;
836     }
837
838   // Special case handling of comparison against +/- 0.0
839   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
840     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
841       BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
842       BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
843       BuildMI(*MBB, IP, X86::SAHF, 1);
844       return OpNum;
845     }
846
847   unsigned Op1r = getReg(Op1, MBB, IP);
848   switch (Class) {
849   default: assert(0 && "Unknown type class!");
850     // Emit: cmp <var1>, <var2> (do the comparison).  We can
851     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
852     // 32-bit.
853   case cByte:
854     BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
855     break;
856   case cShort:
857     BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
858     break;
859   case cInt:
860     BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
861     break;
862   case cFP:
863     BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
864     BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
865     BuildMI(*MBB, IP, X86::SAHF, 1);
866     break;
867
868   case cLong:
869     if (OpNum < 2) {    // seteq, setne
870       unsigned LoTmp = makeAnotherReg(Type::IntTy);
871       unsigned HiTmp = makeAnotherReg(Type::IntTy);
872       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
873       BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
874       BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
875       BuildMI(*MBB, IP, X86::OR32rr,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
876       break;  // Allow the sete or setne to be generated from flags set by OR
877     } else {
878       // Emit a sequence of code which compares the high and low parts once
879       // each, then uses a conditional move to handle the overflow case.  For
880       // example, a setlt for long would generate code like this:
881       //
882       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
883       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
884       // dest = hi(op1) == hi(op2) ? AL : BL;
885       //
886
887       // FIXME: This would be much better if we had hierarchical register
888       // classes!  Until then, hardcode registers so that we can deal with their
889       // aliases (because we don't have conditional byte moves).
890       //
891       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
892       BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
893       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
894       BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
895       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
896       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
897       BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
898                                                    .addReg(X86::AX);
899       // NOTE: visitSetCondInst knows that the value is dumped into the BL
900       // register at this point for long values...
901       return OpNum;
902     }
903   }
904   return OpNum;
905 }
906
907 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
908 /// register, then move it to wherever the result should be. 
909 ///
910 void ISel::visitSetCondInst(SetCondInst &I) {
911   if (canFoldSetCCIntoBranchOrSelect(&I))
912     return;  // Fold this into a branch or select.
913
914   unsigned DestReg = getReg(I);
915   MachineBasicBlock::iterator MII = BB->end();
916   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
917                      DestReg);
918 }
919
920 /// emitSetCCOperation - Common code shared between visitSetCondInst and
921 /// constant expression support.
922 ///
923 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
924                               MachineBasicBlock::iterator IP,
925                               Value *Op0, Value *Op1, unsigned Opcode,
926                               unsigned TargetReg) {
927   unsigned OpNum = getSetCCNumber(Opcode);
928   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
929
930   const Type *CompTy = Op0->getType();
931   unsigned CompClass = getClassB(CompTy);
932   bool isSigned = CompTy->isSigned() && CompClass != cFP;
933
934   if (CompClass != cLong || OpNum < 2) {
935     // Handle normal comparisons with a setcc instruction...
936     BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
937   } else {
938     // Handle long comparisons by copying the value which is already in BL into
939     // the register we want...
940     BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
941   }
942 }
943
944 void ISel::visitSelectInst(SelectInst &SI) {
945   unsigned DestReg = getReg(SI);
946   MachineBasicBlock::iterator MII = BB->end();
947   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
948                       SI.getFalseValue(), DestReg);
949 }
950  
951 /// emitSelect - Common code shared between visitSelectInst and the constant
952 /// expression support.
953 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
954                                MachineBasicBlock::iterator IP,
955                                Value *Cond, Value *TrueVal, Value *FalseVal,
956                                unsigned DestReg) {
957   unsigned SelectClass = getClassB(TrueVal->getType());
958   
959   // We don't support 8-bit conditional moves.  If we have incoming constants,
960   // transform them into 16-bit constants to avoid having a run-time conversion.
961   if (SelectClass == cByte) {
962     if (Constant *T = dyn_cast<Constant>(TrueVal))
963       TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
964     if (Constant *F = dyn_cast<Constant>(FalseVal))
965       FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
966   }
967
968   
969   unsigned Opcode;
970   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
971     // We successfully folded the setcc into the select instruction.
972     
973     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
974     OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
975                            IP);
976
977     const Type *CompTy = SCI->getOperand(0)->getType();
978     bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
979   
980     // LLVM  -> X86 signed  X86 unsigned
981     // -----    ----------  ------------
982     // seteq -> cmovNE      cmovNE
983     // setne -> cmovE       cmovE
984     // setlt -> cmovGE      cmovAE
985     // setge -> cmovL       cmovB
986     // setgt -> cmovLE      cmovBE
987     // setle -> cmovG       cmovA
988     // ----
989     //          cmovNS              // Used by comparison with 0 optimization
990     //          cmovS
991     
992     switch (SelectClass) {
993     default: assert(0 && "Unknown value class!");
994     case cFP: {
995       // Annoyingly, we don't have a full set of floating point conditional
996       // moves.  :(
997       static const unsigned OpcodeTab[2][8] = {
998         { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
999           X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1000         { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1001       };
1002       Opcode = OpcodeTab[isSigned][OpNum];
1003
1004       // If opcode == 0, we hit a case that we don't support.  Output a setcc
1005       // and compare the result against zero.
1006       if (Opcode == 0) {
1007         unsigned CompClass = getClassB(CompTy);
1008         unsigned CondReg;
1009         if (CompClass != cLong || OpNum < 2) {
1010           CondReg = makeAnotherReg(Type::BoolTy);
1011           // Handle normal comparisons with a setcc instruction...
1012           BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1013         } else {
1014           // Long comparisons end up in the BL register.
1015           CondReg = X86::BL;
1016         }
1017         
1018         BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1019         Opcode = X86::FCMOVE;
1020       }
1021       break;
1022     }
1023     case cByte:
1024     case cShort: {
1025       static const unsigned OpcodeTab[2][8] = {
1026         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1027           X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1028         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1029           X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1030       };
1031       Opcode = OpcodeTab[isSigned][OpNum];
1032       break;
1033     }
1034     case cInt:
1035     case cLong: {
1036       static const unsigned OpcodeTab[2][8] = {
1037         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1038           X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1039         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1040           X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1041       };
1042       Opcode = OpcodeTab[isSigned][OpNum];
1043       break;
1044     }
1045     }
1046   } else {
1047     // Get the value being branched on, and use it to set the condition codes.
1048     unsigned CondReg = getReg(Cond, MBB, IP);
1049     BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1050     switch (SelectClass) {
1051     default: assert(0 && "Unknown value class!");
1052     case cFP:    Opcode = X86::FCMOVE; break;
1053     case cByte:
1054     case cShort: Opcode = X86::CMOVE16rr; break;
1055     case cInt:
1056     case cLong:  Opcode = X86::CMOVE32rr; break;
1057     }
1058   }
1059
1060   unsigned TrueReg  = getReg(TrueVal, MBB, IP);
1061   unsigned FalseReg = getReg(FalseVal, MBB, IP);
1062   unsigned RealDestReg = DestReg;
1063
1064
1065   // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves.  Because of
1066   // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1067   // cmove, then truncate the result.
1068   if (SelectClass == cByte) {
1069     DestReg = makeAnotherReg(Type::ShortTy);
1070     if (getClassB(TrueVal->getType()) == cByte) {
1071       // Promote the true value, by storing it into AL, and reading from AX.
1072       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1073       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1074       TrueReg = makeAnotherReg(Type::ShortTy);
1075       BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1076     }
1077     if (getClassB(FalseVal->getType()) == cByte) {
1078       // Promote the true value, by storing it into CL, and reading from CX.
1079       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1080       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1081       FalseReg = makeAnotherReg(Type::ShortTy);
1082       BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1083     }
1084   }
1085
1086   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1087
1088   switch (SelectClass) {
1089   case cByte:
1090     // We did the computation with 16-bit registers.  Truncate back to our
1091     // result by copying into AX then copying out AL.
1092     BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1093     BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1094     break;
1095   case cLong:
1096     // Move the upper half of the value as well.
1097     BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1098     break;
1099   }
1100 }
1101
1102
1103
1104 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1105 /// operand, in the specified target register.
1106 ///
1107 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1108   bool isUnsigned = VR.Ty->isUnsigned();
1109
1110   Value *Val = VR.Val;
1111   const Type *Ty = VR.Ty;
1112   if (Val) {
1113     if (Constant *C = dyn_cast<Constant>(Val)) {
1114       Val = ConstantExpr::getCast(C, Type::IntTy);
1115       Ty = Type::IntTy;
1116     }
1117
1118     // If this is a simple constant, just emit a MOVri directly to avoid the
1119     // copy.
1120     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1121       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1122     BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1123       return;
1124     }
1125   }
1126
1127   // Make sure we have the register number for this value...
1128   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1129
1130   switch (getClassB(Ty)) {
1131   case cByte:
1132     // Extend value into target register (8->32)
1133     if (isUnsigned)
1134       BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1135     else
1136       BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1137     break;
1138   case cShort:
1139     // Extend value into target register (16->32)
1140     if (isUnsigned)
1141       BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1142     else
1143       BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1144     break;
1145   case cInt:
1146     // Move value into target register (32->32)
1147     BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1148     break;
1149   default:
1150     assert(0 && "Unpromotable operand class in promote32");
1151   }
1152 }
1153
1154 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
1155 /// we have the following possibilities:
1156 ///
1157 ///   ret void: No return value, simply emit a 'ret' instruction
1158 ///   ret sbyte, ubyte : Extend value into EAX and return
1159 ///   ret short, ushort: Extend value into EAX and return
1160 ///   ret int, uint    : Move value into EAX and return
1161 ///   ret pointer      : Move value into EAX and return
1162 ///   ret long, ulong  : Move value into EAX/EDX and return
1163 ///   ret float/double : Top of FP stack
1164 ///
1165 void ISel::visitReturnInst(ReturnInst &I) {
1166   if (I.getNumOperands() == 0) {
1167     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1168     return;
1169   }
1170
1171   Value *RetVal = I.getOperand(0);
1172   switch (getClassB(RetVal->getType())) {
1173   case cByte:   // integral return values: extend or move into EAX and return
1174   case cShort:
1175   case cInt:
1176     promote32(X86::EAX, ValueRecord(RetVal));
1177     // Declare that EAX is live on exit
1178     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1179     break;
1180   case cFP: {                  // Floats & Doubles: Return in ST(0)
1181     unsigned RetReg = getReg(RetVal);
1182     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1183     // Declare that top-of-stack is live on exit
1184     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1185     break;
1186   }
1187   case cLong: {
1188     unsigned RetReg = getReg(RetVal);
1189     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1190     BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1191     // Declare that EAX & EDX are live on exit
1192     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1193       .addReg(X86::ESP);
1194     break;
1195   }
1196   default:
1197     visitInstruction(I);
1198   }
1199   // Emit a 'ret' instruction
1200   BuildMI(BB, X86::RET, 0);
1201 }
1202
1203 // getBlockAfter - Return the basic block which occurs lexically after the
1204 // specified one.
1205 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1206   Function::iterator I = BB; ++I;  // Get iterator to next block
1207   return I != BB->getParent()->end() ? &*I : 0;
1208 }
1209
1210 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1211 /// that since code layout is frozen at this point, that if we are trying to
1212 /// jump to a block that is the immediate successor of the current block, we can
1213 /// just make a fall-through (but we don't currently).
1214 ///
1215 void ISel::visitBranchInst(BranchInst &BI) {
1216   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1217
1218   if (!BI.isConditional()) {  // Unconditional branch?
1219     if (BI.getSuccessor(0) != NextBB)
1220       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1221     return;
1222   }
1223
1224   // See if we can fold the setcc into the branch itself...
1225   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1226   if (SCI == 0) {
1227     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1228     // computed some other way...
1229     unsigned condReg = getReg(BI.getCondition());
1230     BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1231     if (BI.getSuccessor(1) == NextBB) {
1232       if (BI.getSuccessor(0) != NextBB)
1233         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1234     } else {
1235       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1236       
1237       if (BI.getSuccessor(0) != NextBB)
1238         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1239     }
1240     return;
1241   }
1242
1243   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1244   MachineBasicBlock::iterator MII = BB->end();
1245   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1246
1247   const Type *CompTy = SCI->getOperand(0)->getType();
1248   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1249   
1250
1251   // LLVM  -> X86 signed  X86 unsigned
1252   // -----    ----------  ------------
1253   // seteq -> je          je
1254   // setne -> jne         jne
1255   // setlt -> jl          jb
1256   // setge -> jge         jae
1257   // setgt -> jg          ja
1258   // setle -> jle         jbe
1259   // ----
1260   //          js                  // Used by comparison with 0 optimization
1261   //          jns
1262
1263   static const unsigned OpcodeTab[2][8] = {
1264     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1265     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1266       X86::JS, X86::JNS },
1267   };
1268   
1269   if (BI.getSuccessor(0) != NextBB) {
1270     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1271     if (BI.getSuccessor(1) != NextBB)
1272       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1273   } else {
1274     // Change to the inverse condition...
1275     if (BI.getSuccessor(1) != NextBB) {
1276       OpNum ^= 1;
1277       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1278     }
1279   }
1280 }
1281
1282
1283 /// doCall - This emits an abstract call instruction, setting up the arguments
1284 /// and the return value as appropriate.  For the actual function call itself,
1285 /// it inserts the specified CallMI instruction into the stream.
1286 ///
1287 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1288                   const std::vector<ValueRecord> &Args) {
1289
1290   // Count how many bytes are to be pushed on the stack...
1291   unsigned NumBytes = 0;
1292
1293   if (!Args.empty()) {
1294     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1295       switch (getClassB(Args[i].Ty)) {
1296       case cByte: case cShort: case cInt:
1297         NumBytes += 4; break;
1298       case cLong:
1299         NumBytes += 8; break;
1300       case cFP:
1301         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1302         break;
1303       default: assert(0 && "Unknown class!");
1304       }
1305
1306     // Adjust the stack pointer for the new arguments...
1307     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1308
1309     // Arguments go on the stack in reverse order, as specified by the ABI.
1310     unsigned ArgOffset = 0;
1311     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1312       unsigned ArgReg;
1313       switch (getClassB(Args[i].Ty)) {
1314       case cByte:
1315       case cShort:
1316         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1317           // Zero/Sign extend constant, then stuff into memory.
1318           ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1319           Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1320           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1321             .addImm(Val->getRawValue() & 0xFFFFFFFF);
1322         } else {
1323           // Promote arg to 32 bits wide into a temporary register...
1324           ArgReg = makeAnotherReg(Type::UIntTy);
1325           promote32(ArgReg, Args[i]);
1326           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1327                        X86::ESP, ArgOffset).addReg(ArgReg);
1328         }
1329         break;
1330       case cInt:
1331         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1332           unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1333           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1334                        X86::ESP, ArgOffset).addImm(Val);
1335         } else {
1336           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1337           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1338                        X86::ESP, ArgOffset).addReg(ArgReg);
1339         }
1340         break;
1341       case cLong:
1342         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1343         addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1344                      X86::ESP, ArgOffset).addReg(ArgReg);
1345         addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1346                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1347         ArgOffset += 4;        // 8 byte entry, not 4.
1348         break;
1349         
1350       case cFP:
1351         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1352         if (Args[i].Ty == Type::FloatTy) {
1353           addRegOffset(BuildMI(BB, X86::FST32m, 5),
1354                        X86::ESP, ArgOffset).addReg(ArgReg);
1355         } else {
1356           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1357           addRegOffset(BuildMI(BB, X86::FST64m, 5),
1358                        X86::ESP, ArgOffset).addReg(ArgReg);
1359           ArgOffset += 4;       // 8 byte entry, not 4.
1360         }
1361         break;
1362
1363       default: assert(0 && "Unknown class!");
1364       }
1365       ArgOffset += 4;
1366     }
1367   } else {
1368     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1369   }
1370
1371   BB->push_back(CallMI);
1372
1373   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1374
1375   // If there is a return value, scavenge the result from the location the call
1376   // leaves it in...
1377   //
1378   if (Ret.Ty != Type::VoidTy) {
1379     unsigned DestClass = getClassB(Ret.Ty);
1380     switch (DestClass) {
1381     case cByte:
1382     case cShort:
1383     case cInt: {
1384       // Integral results are in %eax, or the appropriate portion
1385       // thereof.
1386       static const unsigned regRegMove[] = {
1387         X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1388       };
1389       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1390       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1391       break;
1392     }
1393     case cFP:     // Floating-point return values live in %ST(0)
1394       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1395       break;
1396     case cLong:   // Long values are left in EDX:EAX
1397       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1398       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1399       break;
1400     default: assert(0 && "Unknown class!");
1401     }
1402   }
1403 }
1404
1405
1406 /// visitCallInst - Push args on stack and do a procedure call instruction.
1407 void ISel::visitCallInst(CallInst &CI) {
1408   MachineInstr *TheCall;
1409   if (Function *F = CI.getCalledFunction()) {
1410     // Is it an intrinsic function call?
1411     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1412       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1413       return;
1414     }
1415
1416     // Emit a CALL instruction with PC-relative displacement.
1417     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1418   } else {  // Emit an indirect call...
1419     unsigned Reg = getReg(CI.getCalledValue());
1420     TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1421   }
1422
1423   std::vector<ValueRecord> Args;
1424   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1425     Args.push_back(ValueRecord(CI.getOperand(i)));
1426
1427   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1428   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1429 }         
1430
1431
1432 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1433 /// function, lowering any calls to unknown intrinsic functions into the
1434 /// equivalent LLVM code.
1435 ///
1436 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1437   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1438     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1439       if (CallInst *CI = dyn_cast<CallInst>(I++))
1440         if (Function *F = CI->getCalledFunction())
1441           switch (F->getIntrinsicID()) {
1442           case Intrinsic::not_intrinsic:
1443           case Intrinsic::vastart:
1444           case Intrinsic::vacopy:
1445           case Intrinsic::vaend:
1446           case Intrinsic::returnaddress:
1447           case Intrinsic::frameaddress:
1448           case Intrinsic::memcpy:
1449           case Intrinsic::memset:
1450             // We directly implement these intrinsics
1451             break;
1452           default:
1453             // All other intrinsic calls we must lower.
1454             Instruction *Before = CI->getPrev();
1455             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1456             if (Before) {        // Move iterator to instruction after call
1457               I = Before;  ++I;
1458             } else {
1459               I = BB->begin();
1460             }
1461           }
1462
1463 }
1464
1465 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1466   unsigned TmpReg1, TmpReg2;
1467   switch (ID) {
1468   case Intrinsic::vastart:
1469     // Get the address of the first vararg value...
1470     TmpReg1 = getReg(CI);
1471     addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1472     return;
1473
1474   case Intrinsic::vacopy:
1475     TmpReg1 = getReg(CI);
1476     TmpReg2 = getReg(CI.getOperand(1));
1477     BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1478     return;
1479   case Intrinsic::vaend: return;   // Noop on X86
1480
1481   case Intrinsic::returnaddress:
1482   case Intrinsic::frameaddress:
1483     TmpReg1 = getReg(CI);
1484     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1485       if (ID == Intrinsic::returnaddress) {
1486         // Just load the return address
1487         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1488                           ReturnAddressIndex);
1489       } else {
1490         addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1491                           ReturnAddressIndex, -4);
1492       }
1493     } else {
1494       // Values other than zero are not implemented yet.
1495       BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1496     }
1497     return;
1498
1499   case Intrinsic::memcpy: {
1500     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1501     unsigned Align = 1;
1502     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1503       Align = AlignC->getRawValue();
1504       if (Align == 0) Align = 1;
1505     }
1506
1507     // Turn the byte code into # iterations
1508     unsigned CountReg;
1509     unsigned Opcode;
1510     switch (Align & 3) {
1511     case 2:   // WORD aligned
1512       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1513         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1514       } else {
1515         CountReg = makeAnotherReg(Type::IntTy);
1516         unsigned ByteReg = getReg(CI.getOperand(3));
1517         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1518       }
1519       Opcode = X86::REP_MOVSW;
1520       break;
1521     case 0:   // DWORD aligned
1522       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1523         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1524       } else {
1525         CountReg = makeAnotherReg(Type::IntTy);
1526         unsigned ByteReg = getReg(CI.getOperand(3));
1527         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1528       }
1529       Opcode = X86::REP_MOVSD;
1530       break;
1531     default:  // BYTE aligned
1532       CountReg = getReg(CI.getOperand(3));
1533       Opcode = X86::REP_MOVSB;
1534       break;
1535     }
1536
1537     // No matter what the alignment is, we put the source in ESI, the
1538     // destination in EDI, and the count in ECX.
1539     TmpReg1 = getReg(CI.getOperand(1));
1540     TmpReg2 = getReg(CI.getOperand(2));
1541     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1542     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1543     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1544     BuildMI(BB, Opcode, 0);
1545     return;
1546   }
1547   case Intrinsic::memset: {
1548     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1549     unsigned Align = 1;
1550     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1551       Align = AlignC->getRawValue();
1552       if (Align == 0) Align = 1;
1553     }
1554
1555     // Turn the byte code into # iterations
1556     unsigned CountReg;
1557     unsigned Opcode;
1558     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1559       unsigned Val = ValC->getRawValue() & 255;
1560
1561       // If the value is a constant, then we can potentially use larger copies.
1562       switch (Align & 3) {
1563       case 2:   // WORD aligned
1564         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1565           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1566         } else {
1567           CountReg = makeAnotherReg(Type::IntTy);
1568           unsigned ByteReg = getReg(CI.getOperand(3));
1569           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1570         }
1571         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1572         Opcode = X86::REP_STOSW;
1573         break;
1574       case 0:   // DWORD aligned
1575         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1576           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1577         } else {
1578           CountReg = makeAnotherReg(Type::IntTy);
1579           unsigned ByteReg = getReg(CI.getOperand(3));
1580           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1581         }
1582         Val = (Val << 8) | Val;
1583         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1584         Opcode = X86::REP_STOSD;
1585         break;
1586       default:  // BYTE aligned
1587         CountReg = getReg(CI.getOperand(3));
1588         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1589         Opcode = X86::REP_STOSB;
1590         break;
1591       }
1592     } else {
1593       // If it's not a constant value we are storing, just fall back.  We could
1594       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1595       unsigned ValReg = getReg(CI.getOperand(2));
1596       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1597       CountReg = getReg(CI.getOperand(3));
1598       Opcode = X86::REP_STOSB;
1599     }
1600
1601     // No matter what the alignment is, we put the source in ESI, the
1602     // destination in EDI, and the count in ECX.
1603     TmpReg1 = getReg(CI.getOperand(1));
1604     //TmpReg2 = getReg(CI.getOperand(2));
1605     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1606     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1607     BuildMI(BB, Opcode, 0);
1608     return;
1609   }
1610
1611   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1612   }
1613 }
1614
1615 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1616   if (LI.getParent() != User.getParent())
1617     return false;
1618   BasicBlock::iterator It = &LI;
1619   // Check all of the instructions between the load and the user.  We should
1620   // really use alias analysis here, but for now we just do something simple.
1621   for (++It; It != BasicBlock::iterator(&User); ++It) {
1622     switch (It->getOpcode()) {
1623     case Instruction::Free:
1624     case Instruction::Store:
1625     case Instruction::Call:
1626     case Instruction::Invoke:
1627       return false;
1628     }
1629   }
1630   return true;
1631 }
1632
1633
1634 /// visitSimpleBinary - Implement simple binary operators for integral types...
1635 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1636 /// Xor.
1637 ///
1638 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1639   unsigned DestReg = getReg(B);
1640   MachineBasicBlock::iterator MI = BB->end();
1641   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1642
1643   // Special case: op Reg, load [mem]
1644   if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1645     if (!B.swapOperands())
1646       std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
1647
1648   unsigned Class = getClassB(B.getType());
1649   if (isa<LoadInst>(Op1) && Class < cFP &&
1650       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1651
1652     static const unsigned OpcodeTab[][3] = {
1653       // Arithmetic operators
1654       { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm },  // ADD
1655       { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm },  // SUB
1656       
1657       // Bitwise operators
1658       { X86::AND8rm, X86::AND16rm, X86::AND32rm },  // AND
1659       { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm },  // OR
1660       { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm },  // XOR
1661     };
1662   
1663     assert(Class < cFP && "General code handles 64-bit integer types!");
1664     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1665
1666     unsigned BaseReg, Scale, IndexReg, Disp;
1667     getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1668                       Scale, IndexReg, Disp);
1669
1670     unsigned Op0r = getReg(Op0);
1671     addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1672                    BaseReg, Scale, IndexReg, Disp);
1673     return;
1674   }
1675
1676   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1677 }
1678
1679 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1680 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1681 /// Or, 4 for Xor.
1682 ///
1683 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1684 /// and constant expression support.
1685 ///
1686 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1687                                      MachineBasicBlock::iterator IP,
1688                                      Value *Op0, Value *Op1,
1689                                      unsigned OperatorClass, unsigned DestReg) {
1690   unsigned Class = getClassB(Op0->getType());
1691
1692   // sub 0, X -> neg X
1693   if (OperatorClass == 1)
1694     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1695       if (CI->isNullValue()) {
1696         unsigned op1Reg = getReg(Op1, MBB, IP);
1697         static unsigned const NEGTab[] = {
1698           X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
1699         };
1700         BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
1701
1702         if (Class == cLong) {
1703           // We just emitted: Dl = neg Sl
1704           // Now emit       : T  = addc Sh, 0
1705           //                : Dh = neg T
1706           unsigned T = makeAnotherReg(Type::IntTy);
1707           BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
1708           BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
1709         }
1710         return;
1711       }
1712     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1713       if (CFP->isExactlyValue(-0.0)) {
1714         // -0.0 - X === -X
1715         unsigned op1Reg = getReg(Op1, MBB, IP);
1716         BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1717         return;
1718       }
1719
1720   // Special case: op Reg, <const>
1721   if (Class != cLong && isa<ConstantInt>(Op1)) {
1722     ConstantInt *Op1C = cast<ConstantInt>(Op1);
1723     unsigned Op0r = getReg(Op0, MBB, IP);
1724
1725     // xor X, -1 -> not X
1726     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1727       static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1728       BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1729       return;
1730     }
1731
1732     // add X, -1 -> dec X
1733     if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1734       static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1735       BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1736       return;
1737     }
1738
1739     // add X, 1 -> inc X
1740     if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1741       static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1742       BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
1743       return;
1744     }
1745   
1746     static const unsigned OpcodeTab[][3] = {
1747       // Arithmetic operators
1748       { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri },  // ADD
1749       { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri },  // SUB
1750     
1751       // Bitwise operators
1752       { X86::AND8ri, X86::AND16ri, X86::AND32ri },  // AND
1753       { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri },  // OR
1754       { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri },  // XOR
1755     };
1756   
1757     assert(Class < cFP && "General code handles 64-bit integer types!");
1758     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1759
1760
1761     uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1762     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1v);
1763     return;
1764   }
1765
1766   // Finally, handle the general case now.
1767   static const unsigned OpcodeTab[][4] = {
1768     // Arithmetic operators
1769     { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD },  // ADD
1770     { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB },  // SUB
1771       
1772     // Bitwise operators
1773     { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 },  // AND
1774     { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 },  // OR
1775     { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 },  // XOR
1776   };
1777     
1778   bool isLong = false;
1779   if (Class == cLong) {
1780     isLong = true;
1781     Class = cInt;          // Bottom 32 bits are handled just like ints
1782   }
1783     
1784   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1785   assert(Opcode && "Floating point arguments to logical inst?");
1786   unsigned Op0r = getReg(Op0, MBB, IP);
1787   unsigned Op1r = getReg(Op1, MBB, IP);
1788   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1789     
1790   if (isLong) {        // Handle the upper 32 bits of long values...
1791     static const unsigned TopTab[] = {
1792       X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1793     };
1794     BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1795             DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1796   }
1797 }
1798
1799 /// doMultiply - Emit appropriate instructions to multiply together the
1800 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1801 /// result should be given as DestTy.
1802 ///
1803 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1804                       unsigned DestReg, const Type *DestTy,
1805                       unsigned op0Reg, unsigned op1Reg) {
1806   unsigned Class = getClass(DestTy);
1807   switch (Class) {
1808   case cFP:              // Floating point multiply
1809     BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1810     return;
1811   case cInt:
1812   case cShort:
1813     BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
1814       .addReg(op0Reg).addReg(op1Reg);
1815     return;
1816   case cByte:
1817     // Must use the MUL instruction, which forces use of AL...
1818     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1819     BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1820     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1821     return;
1822   default:
1823   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1824   }
1825 }
1826
1827 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1828 // returns zero when the input is not exactly a power of two.
1829 static unsigned ExactLog2(unsigned Val) {
1830   if (Val == 0) return 0;
1831   unsigned Count = 0;
1832   while (Val != 1) {
1833     if (Val & 1) return 0;
1834     Val >>= 1;
1835     ++Count;
1836   }
1837   return Count+1;
1838 }
1839
1840 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1841                            MachineBasicBlock::iterator IP,
1842                            unsigned DestReg, const Type *DestTy,
1843                            unsigned op0Reg, unsigned ConstRHS) {
1844   unsigned Class = getClass(DestTy);
1845
1846   // If the element size is exactly a power of 2, use a shift to get it.
1847   if (unsigned Shift = ExactLog2(ConstRHS)) {
1848     switch (Class) {
1849     default: assert(0 && "Unknown class for this function!");
1850     case cByte:
1851       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1852       return;
1853     case cShort:
1854       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1855       return;
1856     case cInt:
1857       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1858       return;
1859     }
1860   }
1861   
1862   if (Class == cShort) {
1863     BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1864     return;
1865   } else if (Class == cInt) {
1866     BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1867     return;
1868   }
1869
1870   // Most general case, emit a normal multiply...
1871   static const unsigned MOVriTab[] = {
1872     X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
1873   };
1874
1875   unsigned TmpReg = makeAnotherReg(DestTy);
1876   BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1877   
1878   // Emit a MUL to multiply the register holding the index by
1879   // elementSize, putting the result in OffsetReg.
1880   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1881 }
1882
1883 /// visitMul - Multiplies are not simple binary operators because they must deal
1884 /// with the EAX register explicitly.
1885 ///
1886 void ISel::visitMul(BinaryOperator &I) {
1887   unsigned Op0Reg  = getReg(I.getOperand(0));
1888   unsigned DestReg = getReg(I);
1889
1890   // Simple scalar multiply?
1891   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1892     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1893       unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1894       MachineBasicBlock::iterator MBBI = BB->end();
1895       doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1896     } else {
1897       unsigned Op1Reg  = getReg(I.getOperand(1));
1898       MachineBasicBlock::iterator MBBI = BB->end();
1899       doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1900     }
1901   } else {
1902     unsigned Op1Reg  = getReg(I.getOperand(1));
1903
1904     // Long value.  We have to do things the hard way...
1905     // Multiply the two low parts... capturing carry into EDX
1906     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1907     BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg);  // AL*BL
1908
1909     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1910     BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);     // AL*BL
1911     BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1912
1913     MachineBasicBlock::iterator MBBI = BB->end();
1914     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
1915     BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1916
1917     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1918     BuildMI(*BB, MBBI, X86::ADD32rr, 2,                  // AH*BL+(AL*BL >> 32)
1919             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1920     
1921     MBBI = BB->end();
1922     unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1923     BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1924     
1925     BuildMI(*BB, MBBI, X86::ADD32rr, 2,         // AL*BH + AH*BL + (AL*BL >> 32)
1926             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1927   }
1928 }
1929
1930
1931 /// visitDivRem - Handle division and remainder instructions... these
1932 /// instruction both require the same instructions to be generated, they just
1933 /// select the result from a different register.  Note that both of these
1934 /// instructions work differently for signed and unsigned operands.
1935 ///
1936 void ISel::visitDivRem(BinaryOperator &I) {
1937   unsigned Op0Reg = getReg(I.getOperand(0));
1938   unsigned Op1Reg = getReg(I.getOperand(1));
1939   unsigned ResultReg = getReg(I);
1940
1941   MachineBasicBlock::iterator IP = BB->end();
1942   emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1943                       I.getType(), ResultReg);
1944 }
1945
1946 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1947                                MachineBasicBlock::iterator IP,
1948                                unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1949                                const Type *Ty, unsigned ResultReg) {
1950   unsigned Class = getClass(Ty);
1951   switch (Class) {
1952   case cFP:              // Floating point divide
1953     if (isDiv) {
1954       BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1955     } else {               // Floating point remainder...
1956       MachineInstr *TheCall =
1957         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1958       std::vector<ValueRecord> Args;
1959       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1960       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1961       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1962     }
1963     return;
1964   case cLong: {
1965     static const char *FnName[] =
1966       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1967
1968     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1969     MachineInstr *TheCall =
1970       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1971
1972     std::vector<ValueRecord> Args;
1973     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1974     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1975     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1976     return;
1977   }
1978   case cByte: case cShort: case cInt:
1979     break;          // Small integrals, handled below...
1980   default: assert(0 && "Unknown class!");
1981   }
1982
1983   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1984   static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1985   static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1986   static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
1987   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1988
1989   static const unsigned DivOpcode[][4] = {
1990     { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 },  // Unsigned division
1991     { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 },  // Signed division
1992   };
1993
1994   bool isSigned   = Ty->isSigned();
1995   unsigned Reg    = Regs[Class];
1996   unsigned ExtReg = ExtRegs[Class];
1997
1998   // Put the first operand into one of the A registers...
1999   BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2000
2001   if (isSigned) {
2002     // Emit a sign extension instruction...
2003     unsigned ShiftResult = makeAnotherReg(Ty);
2004     BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2005     BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2006   } else {
2007     // If unsigned, emit a zeroing instruction... (reg = 0)
2008     BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2009   }
2010
2011   // Emit the appropriate divide or remainder instruction...
2012   BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
2013
2014   // Figure out which register we want to pick the result out of...
2015   unsigned DestReg = isDiv ? Reg : ExtReg;
2016   
2017   // Put the result into the destination register...
2018   BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2019 }
2020
2021
2022 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2023 /// for constant immediate shift values, and for constant immediate
2024 /// shift values equal to 1. Even the general case is sort of special,
2025 /// because the shift amount has to be in CL, not just any old register.
2026 ///
2027 void ISel::visitShiftInst(ShiftInst &I) {
2028   MachineBasicBlock::iterator IP = BB->end ();
2029   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2030                       I.getOpcode () == Instruction::Shl, I.getType (),
2031                       getReg (I));
2032 }
2033
2034 /// emitShiftOperation - Common code shared between visitShiftInst and
2035 /// constant expression support.
2036 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2037                               MachineBasicBlock::iterator IP,
2038                               Value *Op, Value *ShiftAmount, bool isLeftShift,
2039                               const Type *ResultTy, unsigned DestReg) {
2040   unsigned SrcReg = getReg (Op, MBB, IP);
2041   bool isSigned = ResultTy->isSigned ();
2042   unsigned Class = getClass (ResultTy);
2043   
2044   static const unsigned ConstantOperand[][4] = {
2045     { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 },  // SHR
2046     { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 },  // SAR
2047     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SHL
2048     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SAL = SHL
2049   };
2050
2051   static const unsigned NonConstantOperand[][4] = {
2052     { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL },  // SHR
2053     { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL },  // SAR
2054     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SHL
2055     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SAL = SHL
2056   };
2057
2058   // Longs, as usual, are handled specially...
2059   if (Class == cLong) {
2060     // If we have a constant shift, we can generate much more efficient code
2061     // than otherwise...
2062     //
2063     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2064       unsigned Amount = CUI->getValue();
2065       if (Amount < 32) {
2066         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2067         if (isLeftShift) {
2068           BuildMI(*MBB, IP, Opc[3], 3, 
2069               DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2070           BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2071         } else {
2072           BuildMI(*MBB, IP, Opc[3], 3,
2073               DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
2074           BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2075         }
2076       } else {                 // Shifting more than 32 bits
2077         Amount -= 32;
2078         if (isLeftShift) {
2079           BuildMI(*MBB, IP, X86::SHL32ri, 2,
2080               DestReg + 1).addReg(SrcReg).addImm(Amount);
2081           BuildMI(*MBB, IP, X86::MOV32ri, 1,
2082               DestReg).addImm(0);
2083         } else {
2084           unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
2085           BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
2086           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2087         }
2088       }
2089     } else {
2090       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2091
2092       if (!isLeftShift && isSigned) {
2093         // If this is a SHR of a Long, then we need to do funny sign extension
2094         // stuff.  TmpReg gets the value to use as the high-part if we are
2095         // shifting more than 32 bits.
2096         BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
2097       } else {
2098         // Other shifts use a fixed zero value if the shift is more than 32
2099         // bits.
2100         BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2101       }
2102
2103       // Initialize CL with the shift amount...
2104       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2105       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2106
2107       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2108       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2109       if (isLeftShift) {
2110         // TmpReg2 = shld inHi, inLo
2111         BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2112                                                     .addReg(SrcReg);
2113         // TmpReg3 = shl  inLo, CL
2114         BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2115
2116         // Set the flags to indicate whether the shift was by more than 32 bits.
2117         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2118
2119         // DestHi = (>32) ? TmpReg3 : TmpReg2;
2120         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2121                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2122         // DestLo = (>32) ? TmpReg : TmpReg3;
2123         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2124             DestReg).addReg(TmpReg3).addReg(TmpReg);
2125       } else {
2126         // TmpReg2 = shrd inLo, inHi
2127         BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2128                                                     .addReg(SrcReg+1);
2129         // TmpReg3 = s[ah]r  inHi, CL
2130         BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2131                        .addReg(SrcReg+1);
2132
2133         // Set the flags to indicate whether the shift was by more than 32 bits.
2134         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2135
2136         // DestLo = (>32) ? TmpReg3 : TmpReg2;
2137         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2138                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2139
2140         // DestHi = (>32) ? TmpReg : TmpReg3;
2141         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2142                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2143       }
2144     }
2145     return;
2146   }
2147
2148   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2149     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2150     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2151
2152     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2153     BuildMI(*MBB, IP, Opc[Class], 2,
2154         DestReg).addReg(SrcReg).addImm(CUI->getValue());
2155   } else {                  // The shift amount is non-constant.
2156     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2157     BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2158
2159     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2160     BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2161   }
2162 }
2163
2164
2165 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2166                              unsigned &IndexReg, unsigned &Disp) {
2167   BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2168   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2169     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2170                        BaseReg, Scale, IndexReg, Disp))
2171       return;
2172   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2173     if (CE->getOpcode() == Instruction::GetElementPtr)
2174       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2175                         BaseReg, Scale, IndexReg, Disp))
2176         return;
2177   }
2178
2179   // If it's not foldable, reset addr mode.
2180   BaseReg = getReg(Addr);
2181   Scale = 1; IndexReg = 0; Disp = 0;
2182 }
2183
2184
2185 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2186 /// instruction.  The load and store instructions are the only place where we
2187 /// need to worry about the memory layout of the target machine.
2188 ///
2189 void ISel::visitLoadInst(LoadInst &I) {
2190   // Check to see if this load instruction is going to be folded into a binary
2191   // instruction, like add.  If so, we don't want to emit it.  Wouldn't a real
2192   // pattern matching instruction selector be nice?
2193   if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2194     Instruction *User = cast<Instruction>(I.use_back());
2195     switch (User->getOpcode()) {
2196     default: User = 0; break;
2197     case Instruction::Add:
2198     case Instruction::Sub:
2199     case Instruction::And:
2200     case Instruction::Or:
2201     case Instruction::Xor:
2202       break;
2203     }
2204
2205     if (User) {
2206       // Okay, we found a user.  If the load is the first operand and there is
2207       // no second operand load, reverse the operand ordering.  Note that this
2208       // can fail for a subtract (ie, no change will be made).
2209       if (!isa<LoadInst>(User->getOperand(1)))
2210         cast<BinaryOperator>(User)->swapOperands();
2211       
2212       // Okay, now that everything is set up, if this load is used by the second
2213       // operand, and if there are no instructions that invalidate the load
2214       // before the binary operator, eliminate the load.
2215       if (User->getOperand(1) == &I &&
2216           isSafeToFoldLoadIntoInstruction(I, *User))
2217         return;   // Eliminate the load!
2218     }
2219   }
2220
2221   unsigned DestReg = getReg(I);
2222   unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2223   getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2224
2225   unsigned Class = getClassB(I.getType());
2226   if (Class == cLong) {
2227     addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2228                    BaseReg, Scale, IndexReg, Disp);
2229     addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2230                    BaseReg, Scale, IndexReg, Disp+4);
2231     return;
2232   }
2233
2234   static const unsigned Opcodes[] = {
2235     X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2236   };
2237   unsigned Opcode = Opcodes[Class];
2238   if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2239   addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2240                  BaseReg, Scale, IndexReg, Disp);
2241 }
2242
2243 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2244 /// instruction.
2245 ///
2246 void ISel::visitStoreInst(StoreInst &I) {
2247   unsigned BaseReg, Scale, IndexReg, Disp;
2248   getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2249
2250   const Type *ValTy = I.getOperand(0)->getType();
2251   unsigned Class = getClassB(ValTy);
2252
2253   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2254     uint64_t Val = CI->getRawValue();
2255     if (Class == cLong) {
2256       addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2257                      BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2258       addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2259                      BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2260     } else {
2261       static const unsigned Opcodes[] = {
2262         X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2263       };
2264       unsigned Opcode = Opcodes[Class];
2265       addFullAddress(BuildMI(BB, Opcode, 5),
2266                      BaseReg, Scale, IndexReg, Disp).addImm(Val);
2267     }
2268   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2269     addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2270                    BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2271   } else {    
2272     if (Class == cLong) {
2273       unsigned ValReg = getReg(I.getOperand(0));
2274       addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2275                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2276       addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2277                      BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2278     } else {
2279       unsigned ValReg = getReg(I.getOperand(0));
2280       static const unsigned Opcodes[] = {
2281         X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2282       };
2283       unsigned Opcode = Opcodes[Class];
2284       if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2285       addFullAddress(BuildMI(BB, Opcode, 1+4),
2286                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2287     }
2288   }
2289 }
2290
2291
2292 /// visitCastInst - Here we have various kinds of copying with or without sign
2293 /// extension going on.
2294 ///
2295 void ISel::visitCastInst(CastInst &CI) {
2296   Value *Op = CI.getOperand(0);
2297   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2298   // of the case are GEP instructions, then the cast does not need to be
2299   // generated explicitly, it will be folded into the GEP.
2300   if (CI.getType() == Type::LongTy &&
2301       (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2302     bool AllUsesAreGEPs = true;
2303     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2304       if (!isa<GetElementPtrInst>(*I)) {
2305         AllUsesAreGEPs = false;
2306         break;
2307       }        
2308
2309     // No need to codegen this cast if all users are getelementptr instrs...
2310     if (AllUsesAreGEPs) return;
2311   }
2312
2313   unsigned DestReg = getReg(CI);
2314   MachineBasicBlock::iterator MI = BB->end();
2315   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2316 }
2317
2318 /// emitCastOperation - Common code shared between visitCastInst and constant
2319 /// expression cast support.
2320 ///
2321 void ISel::emitCastOperation(MachineBasicBlock *BB,
2322                              MachineBasicBlock::iterator IP,
2323                              Value *Src, const Type *DestTy,
2324                              unsigned DestReg) {
2325   unsigned SrcReg = getReg(Src, BB, IP);
2326   const Type *SrcTy = Src->getType();
2327   unsigned SrcClass = getClassB(SrcTy);
2328   unsigned DestClass = getClassB(DestTy);
2329
2330   // Implement casts to bool by using compare on the operand followed by set if
2331   // not zero on the result.
2332   if (DestTy == Type::BoolTy) {
2333     switch (SrcClass) {
2334     case cByte:
2335       BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2336       break;
2337     case cShort:
2338       BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2339       break;
2340     case cInt:
2341       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2342       break;
2343     case cLong: {
2344       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2345       BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2346       break;
2347     }
2348     case cFP:
2349       BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2350       BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2351       BuildMI(*BB, IP, X86::SAHF, 1);
2352       break;
2353     }
2354
2355     // If the zero flag is not set, then the value is true, set the byte to
2356     // true.
2357     BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2358     return;
2359   }
2360
2361   static const unsigned RegRegMove[] = {
2362     X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2363   };
2364
2365   // Implement casts between values of the same type class (as determined by
2366   // getClass) by using a register-to-register move.
2367   if (SrcClass == DestClass) {
2368     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2369       BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2370     } else if (SrcClass == cFP) {
2371       if (SrcTy == Type::FloatTy) {  // double -> float
2372         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2373         BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2374       } else {                       // float -> double
2375         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2376                "Unknown cFP member!");
2377         // Truncate from double to float by storing to memory as short, then
2378         // reading it back.
2379         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2380         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2381         addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2382         addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2383       }
2384     } else if (SrcClass == cLong) {
2385       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2386       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2387     } else {
2388       assert(0 && "Cannot handle this type of cast instruction!");
2389       abort();
2390     }
2391     return;
2392   }
2393
2394   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2395   // or zero extension, depending on whether the source type was signed.
2396   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2397       SrcClass < DestClass) {
2398     bool isLong = DestClass == cLong;
2399     if (isLong) DestClass = cInt;
2400
2401     static const unsigned Opc[][4] = {
2402       { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2403       { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr }  // u
2404     };
2405     
2406     bool isUnsigned = SrcTy->isUnsigned();
2407     BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2408         DestReg).addReg(SrcReg);
2409
2410     if (isLong) {  // Handle upper 32 bits as appropriate...
2411       if (isUnsigned)     // Zero out top bits...
2412         BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2413       else                // Sign extend bottom half...
2414         BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2415     }
2416     return;
2417   }
2418
2419   // Special case long -> int ...
2420   if (SrcClass == cLong && DestClass == cInt) {
2421     BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2422     return;
2423   }
2424   
2425   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2426   // move out of AX or AL.
2427   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2428       && SrcClass > DestClass) {
2429     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2430     BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2431     BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2432     return;
2433   }
2434
2435   // Handle casts from integer to floating point now...
2436   if (DestClass == cFP) {
2437     // Promote the integer to a type supported by FLD.  We do this because there
2438     // are no unsigned FLD instructions, so we must promote an unsigned value to
2439     // a larger signed value, then use FLD on the larger value.
2440     //
2441     const Type *PromoteType = 0;
2442     unsigned PromoteOpcode;
2443     unsigned RealDestReg = DestReg;
2444     switch (SrcTy->getPrimitiveID()) {
2445     case Type::BoolTyID:
2446     case Type::SByteTyID:
2447       // We don't have the facilities for directly loading byte sized data from
2448       // memory (even signed).  Promote it to 16 bits.
2449       PromoteType = Type::ShortTy;
2450       PromoteOpcode = X86::MOVSX16rr8;
2451       break;
2452     case Type::UByteTyID:
2453       PromoteType = Type::ShortTy;
2454       PromoteOpcode = X86::MOVZX16rr8;
2455       break;
2456     case Type::UShortTyID:
2457       PromoteType = Type::IntTy;
2458       PromoteOpcode = X86::MOVZX32rr16;
2459       break;
2460     case Type::UIntTyID: {
2461       // Make a 64 bit temporary... and zero out the top of it...
2462       unsigned TmpReg = makeAnotherReg(Type::LongTy);
2463       BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2464       BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2465       SrcTy = Type::LongTy;
2466       SrcClass = cLong;
2467       SrcReg = TmpReg;
2468       break;
2469     }
2470     case Type::ULongTyID:
2471       // Don't fild into the read destination.
2472       DestReg = makeAnotherReg(Type::DoubleTy);
2473       break;
2474     default:  // No promotion needed...
2475       break;
2476     }
2477     
2478     if (PromoteType) {
2479       unsigned TmpReg = makeAnotherReg(PromoteType);
2480       unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
2481       BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2482       SrcTy = PromoteType;
2483       SrcClass = getClass(PromoteType);
2484       SrcReg = TmpReg;
2485     }
2486
2487     // Spill the integer to memory and reload it from there...
2488     int FrameIdx =
2489       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2490
2491     if (SrcClass == cLong) {
2492       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2493                         FrameIdx).addReg(SrcReg);
2494       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2495                         FrameIdx, 4).addReg(SrcReg+1);
2496     } else {
2497       static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2498       addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2499                         FrameIdx).addReg(SrcReg);
2500     }
2501
2502     static const unsigned Op2[] =
2503       { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2504     addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2505
2506     // We need special handling for unsigned 64-bit integer sources.  If the
2507     // input number has the "sign bit" set, then we loaded it incorrectly as a
2508     // negative 64-bit number.  In this case, add an offset value.
2509     if (SrcTy == Type::ULongTy) {
2510       // Emit a test instruction to see if the dynamic input value was signed.
2511       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2512
2513       // If the sign bit is set, get a pointer to an offset, otherwise get a
2514       // pointer to a zero.
2515       MachineConstantPool *CP = F->getConstantPool();
2516       unsigned Zero = makeAnotherReg(Type::IntTy);
2517       Constant *Null = Constant::getNullValue(Type::UIntTy);
2518       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero), 
2519                                CP->getConstantPoolIndex(Null));
2520       unsigned Offset = makeAnotherReg(Type::IntTy);
2521       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2522                                              
2523       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2524                                CP->getConstantPoolIndex(OffsetCst));
2525       unsigned Addr = makeAnotherReg(Type::IntTy);
2526       BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2527
2528       // Load the constant for an add.  FIXME: this could make an 'fadd' that
2529       // reads directly from memory, but we don't support these yet.
2530       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2531       addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2532
2533       BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2534                 .addReg(ConstReg).addReg(DestReg);
2535     }
2536
2537     return;
2538   }
2539
2540   // Handle casts from floating point to integer now...
2541   if (SrcClass == cFP) {
2542     // Change the floating point control register to use "round towards zero"
2543     // mode when truncating to an integer value.
2544     //
2545     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2546     addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2547
2548     // Load the old value of the high byte of the control word...
2549     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2550     addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2551                       CWFrameIdx, 1);
2552
2553     // Set the high part to be round to zero...
2554     addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2555                       CWFrameIdx, 1).addImm(12);
2556
2557     // Reload the modified control word now...
2558     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2559     
2560     // Restore the memory image of control word to original value
2561     addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2562                       CWFrameIdx, 1).addReg(HighPartOfCW);
2563
2564     // We don't have the facilities for directly storing byte sized data to
2565     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
2566     // larger classes because we only have signed FP stores.
2567     unsigned StoreClass  = DestClass;
2568     const Type *StoreTy  = DestTy;
2569     if (StoreClass == cByte || DestTy->isUnsigned())
2570       switch (StoreClass) {
2571       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
2572       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
2573       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2574       // The following treatment of cLong may not be perfectly right,
2575       // but it survives chains of casts of the form
2576       // double->ulong->double.
2577       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2578       default: assert(0 && "Unknown store class!");
2579       }
2580
2581     // Spill the integer to memory and reload it from there...
2582     int FrameIdx =
2583       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2584
2585     static const unsigned Op1[] =
2586       { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2587     addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2588                       FrameIdx).addReg(SrcReg);
2589
2590     if (DestClass == cLong) {
2591       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2592       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2593                         FrameIdx, 4);
2594     } else {
2595       static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2596       addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2597     }
2598
2599     // Reload the original control word now...
2600     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2601     return;
2602   }
2603
2604   // Anything we haven't handled already, we can't (yet) handle at all.
2605   assert(0 && "Unhandled cast instruction!");
2606   abort();
2607 }
2608
2609 /// visitVANextInst - Implement the va_next instruction...
2610 ///
2611 void ISel::visitVANextInst(VANextInst &I) {
2612   unsigned VAList = getReg(I.getOperand(0));
2613   unsigned DestReg = getReg(I);
2614
2615   unsigned Size;
2616   switch (I.getArgType()->getPrimitiveID()) {
2617   default:
2618     std::cerr << I;
2619     assert(0 && "Error: bad type for va_next instruction!");
2620     return;
2621   case Type::PointerTyID:
2622   case Type::UIntTyID:
2623   case Type::IntTyID:
2624     Size = 4;
2625     break;
2626   case Type::ULongTyID:
2627   case Type::LongTyID:
2628   case Type::DoubleTyID:
2629     Size = 8;
2630     break;
2631   }
2632
2633   // Increment the VAList pointer...
2634   BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2635 }
2636
2637 void ISel::visitVAArgInst(VAArgInst &I) {
2638   unsigned VAList = getReg(I.getOperand(0));
2639   unsigned DestReg = getReg(I);
2640
2641   switch (I.getType()->getPrimitiveID()) {
2642   default:
2643     std::cerr << I;
2644     assert(0 && "Error: bad type for va_next instruction!");
2645     return;
2646   case Type::PointerTyID:
2647   case Type::UIntTyID:
2648   case Type::IntTyID:
2649     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2650     break;
2651   case Type::ULongTyID:
2652   case Type::LongTyID:
2653     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2654     addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2655     break;
2656   case Type::DoubleTyID:
2657     addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2658     break;
2659   }
2660 }
2661
2662 /// visitGetElementPtrInst - instruction-select GEP instructions
2663 ///
2664 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2665   // If this GEP instruction will be folded into all of its users, we don't need
2666   // to explicitly calculate it!
2667   unsigned A, B, C, D;
2668   if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2669     // Check all of the users of the instruction to see if they are loads and
2670     // stores.
2671     bool AllWillFold = true;
2672     for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2673       if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2674         if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2675             cast<Instruction>(*UI)->getOperand(0) == &I) {
2676           AllWillFold = false;
2677           break;
2678         }
2679
2680     // If the instruction is foldable, and will be folded into all users, don't
2681     // emit it!
2682     if (AllWillFold) return;
2683   }
2684
2685   unsigned outputReg = getReg(I);
2686   emitGEPOperation(BB, BB->end(), I.getOperand(0),
2687                    I.op_begin()+1, I.op_end(), outputReg);
2688 }
2689
2690 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2691 /// GEPTypes (the derived types being stepped through at each level).  On return
2692 /// from this function, if some indexes of the instruction are representable as
2693 /// an X86 lea instruction, the machine operands are put into the Ops
2694 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2695 /// lists.  Otherwise, GEPOps.size() is returned.  If this returns a an
2696 /// addressing mode that only partially consumes the input, the BaseReg input of
2697 /// the addressing mode must be left free.
2698 ///
2699 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2700 ///
2701 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2702                        std::vector<Value*> &GEPOps,
2703                        std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2704                        unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2705   const TargetData &TD = TM.getTargetData();
2706
2707   // Clear out the state we are working with...
2708   BaseReg = 0;    // No base register
2709   Scale = 1;      // Unit scale
2710   IndexReg = 0;   // No index register
2711   Disp = 0;       // No displacement
2712
2713   // While there are GEP indexes that can be folded into the current address,
2714   // keep processing them.
2715   while (!GEPTypes.empty()) {
2716     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2717       // It's a struct access.  CUI is the index into the structure,
2718       // which names the field. This index must have unsigned type.
2719       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2720       
2721       // Use the TargetData structure to pick out what the layout of the
2722       // structure is in memory.  Since the structure index must be constant, we
2723       // can get its value and use it to find the right byte offset from the
2724       // StructLayout class's list of structure member offsets.
2725       Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2726       GEPOps.pop_back();        // Consume a GEP operand
2727       GEPTypes.pop_back();
2728     } else {
2729       // It's an array or pointer access: [ArraySize x ElementType].
2730       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2731       Value *idx = GEPOps.back();
2732
2733       // idx is the index into the array.  Unlike with structure
2734       // indices, we may not know its actual value at code-generation
2735       // time.
2736
2737       // If idx is a constant, fold it into the offset.
2738       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2739       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2740         Disp += TypeSize*CSI->getValue();
2741       } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
2742         Disp += TypeSize*CUI->getValue();
2743       } else {
2744         // If the index reg is already taken, we can't handle this index.
2745         if (IndexReg) return;
2746
2747         // If this is a size that we can handle, then add the index as 
2748         switch (TypeSize) {
2749         case 1: case 2: case 4: case 8:
2750           // These are all acceptable scales on X86.
2751           Scale = TypeSize;
2752           break;
2753         default:
2754           // Otherwise, we can't handle this scale
2755           return;
2756         }
2757
2758         if (CastInst *CI = dyn_cast<CastInst>(idx))
2759           if (CI->getOperand(0)->getType() == Type::IntTy ||
2760               CI->getOperand(0)->getType() == Type::UIntTy)
2761             idx = CI->getOperand(0);
2762
2763         IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2764       }
2765
2766       GEPOps.pop_back();        // Consume a GEP operand
2767       GEPTypes.pop_back();
2768     }
2769   }
2770
2771   // GEPTypes is empty, which means we have a single operand left.  See if we
2772   // can set it as the base register.
2773   //
2774   // FIXME: When addressing modes are more powerful/correct, we could load
2775   // global addresses directly as 32-bit immediates.
2776   assert(BaseReg == 0);
2777   BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2778   GEPOps.pop_back();        // Consume the last GEP operand
2779 }
2780
2781
2782 /// isGEPFoldable - Return true if the specified GEP can be completely
2783 /// folded into the addressing mode of a load/store or lea instruction.
2784 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2785                          Value *Src, User::op_iterator IdxBegin,
2786                          User::op_iterator IdxEnd, unsigned &BaseReg,
2787                          unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2788   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2789     Src = CPR->getValue();
2790
2791   std::vector<Value*> GEPOps;
2792   GEPOps.resize(IdxEnd-IdxBegin+1);
2793   GEPOps[0] = Src;
2794   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2795   
2796   std::vector<const Type*> GEPTypes;
2797   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2798                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2799
2800   MachineBasicBlock::iterator IP;
2801   if (MBB) IP = MBB->end();
2802   getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2803
2804   // We can fold it away iff the getGEPIndex call eliminated all operands.
2805   return GEPOps.empty();
2806 }
2807
2808 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2809                             MachineBasicBlock::iterator IP,
2810                             Value *Src, User::op_iterator IdxBegin,
2811                             User::op_iterator IdxEnd, unsigned TargetReg) {
2812   const TargetData &TD = TM.getTargetData();
2813   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2814     Src = CPR->getValue();
2815
2816   std::vector<Value*> GEPOps;
2817   GEPOps.resize(IdxEnd-IdxBegin+1);
2818   GEPOps[0] = Src;
2819   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2820   
2821   std::vector<const Type*> GEPTypes;
2822   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2823                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2824
2825   // Keep emitting instructions until we consume the entire GEP instruction.
2826   while (!GEPOps.empty()) {
2827     unsigned OldSize = GEPOps.size();
2828     unsigned BaseReg, Scale, IndexReg, Disp;
2829     getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2830     
2831     if (GEPOps.size() != OldSize) {
2832       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
2833       unsigned NextTarget = 0;
2834       if (!GEPOps.empty()) {
2835         assert(BaseReg == 0 &&
2836            "getGEPIndex should have left the base register open for chaining!");
2837         NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2838       }
2839
2840       if (IndexReg == 0 && Disp == 0)
2841         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2842       else
2843         addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
2844                        BaseReg, Scale, IndexReg, Disp);
2845       --IP;
2846       TargetReg = NextTarget;
2847     } else if (GEPTypes.empty()) {
2848       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
2849       // all operands are consumed but the base pointer.  If so, just load it
2850       // into the register.
2851       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2852         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
2853       } else {
2854         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2855         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2856       }
2857       break;                // we are now done
2858
2859     } else {
2860       // It's an array or pointer access: [ArraySize x ElementType].
2861       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2862       Value *idx = GEPOps.back();
2863       GEPOps.pop_back();        // Consume a GEP operand
2864       GEPTypes.pop_back();
2865
2866       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2867       // operand on X86.  Handle this case directly now...
2868       if (CastInst *CI = dyn_cast<CastInst>(idx))
2869         if (CI->getOperand(0)->getType() == Type::IntTy ||
2870             CI->getOperand(0)->getType() == Type::UIntTy)
2871           idx = CI->getOperand(0);
2872
2873       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2874       // must find the size of the pointed-to type (Not coincidentally, the next
2875       // type is the type of the elements in the array).
2876       const Type *ElTy = SqTy->getElementType();
2877       unsigned elementSize = TD.getTypeSize(ElTy);
2878
2879       // If idxReg is a constant, we don't need to perform the multiply!
2880       if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
2881         if (!CSI->isNullValue()) {
2882           unsigned Offset = elementSize*CSI->getRawValue();
2883           unsigned Reg = makeAnotherReg(Type::UIntTy);
2884           BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
2885                                 .addReg(Reg).addImm(Offset);
2886           --IP;            // Insert the next instruction before this one.
2887           TargetReg = Reg; // Codegen the rest of the GEP into this
2888         }
2889       } else if (elementSize == 1) {
2890         // If the element size is 1, we don't have to multiply, just add
2891         unsigned idxReg = getReg(idx, MBB, IP);
2892         unsigned Reg = makeAnotherReg(Type::UIntTy);
2893         BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
2894         --IP;            // Insert the next instruction before this one.
2895         TargetReg = Reg; // Codegen the rest of the GEP into this
2896       } else {
2897         unsigned idxReg = getReg(idx, MBB, IP);
2898         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2899
2900         // Make sure we can back the iterator up to point to the first
2901         // instruction emitted.
2902         MachineBasicBlock::iterator BeforeIt = IP;
2903         if (IP == MBB->begin())
2904           BeforeIt = MBB->end();
2905         else
2906           --BeforeIt;
2907         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2908
2909         // Emit an ADD to add OffsetReg to the basePtr.
2910         unsigned Reg = makeAnotherReg(Type::UIntTy);
2911         BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
2912                           .addReg(Reg).addReg(OffsetReg);
2913
2914         // Step to the first instruction of the multiply.
2915         if (BeforeIt == MBB->end())
2916           IP = MBB->begin();
2917         else
2918           IP = ++BeforeIt;
2919
2920         TargetReg = Reg; // Codegen the rest of the GEP into this
2921       }
2922     }
2923   }
2924 }
2925
2926
2927 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2928 /// frame manager, otherwise do it the hard way.
2929 ///
2930 void ISel::visitAllocaInst(AllocaInst &I) {
2931   // Find the data size of the alloca inst's getAllocatedType.
2932   const Type *Ty = I.getAllocatedType();
2933   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2934
2935   // If this is a fixed size alloca in the entry block for the function,
2936   // statically stack allocate the space.
2937   //
2938   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2939     if (I.getParent() == I.getParent()->getParent()->begin()) {
2940       TySize *= CUI->getValue();   // Get total allocated size...
2941       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2942       
2943       // Create a new stack object using the frame manager...
2944       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2945       addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
2946       return;
2947     }
2948   }
2949   
2950   // Create a register to hold the temporary result of multiplying the type size
2951   // constant by the variable amount.
2952   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2953   unsigned SrcReg1 = getReg(I.getArraySize());
2954   
2955   // TotalSizeReg = mul <numelements>, <TypeSize>
2956   MachineBasicBlock::iterator MBBI = BB->end();
2957   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2958
2959   // AddedSize = add <TotalSizeReg>, 15
2960   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2961   BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2962
2963   // AlignedSize = and <AddedSize>, ~15
2964   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2965   BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2966   
2967   // Subtract size from stack pointer, thereby allocating some space.
2968   BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2969
2970   // Put a pointer to the space into the result register, by copying
2971   // the stack pointer.
2972   BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
2973
2974   // Inform the Frame Information that we have just allocated a variable-sized
2975   // object.
2976   F->getFrameInfo()->CreateVariableSizedObject();
2977 }
2978
2979 /// visitMallocInst - Malloc instructions are code generated into direct calls
2980 /// to the library malloc.
2981 ///
2982 void ISel::visitMallocInst(MallocInst &I) {
2983   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2984   unsigned Arg;
2985
2986   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2987     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2988   } else {
2989     Arg = makeAnotherReg(Type::UIntTy);
2990     unsigned Op0Reg = getReg(I.getOperand(0));
2991     MachineBasicBlock::iterator MBBI = BB->end();
2992     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2993   }
2994
2995   std::vector<ValueRecord> Args;
2996   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2997   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2998                                   1).addExternalSymbol("malloc", true);
2999   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3000 }
3001
3002
3003 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3004 /// function.
3005 ///
3006 void ISel::visitFreeInst(FreeInst &I) {
3007   std::vector<ValueRecord> Args;
3008   Args.push_back(ValueRecord(I.getOperand(0)));
3009   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3010                                   1).addExternalSymbol("free", true);
3011   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3012 }
3013    
3014 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
3015 /// into a machine code representation is a very simple peep-hole fashion.  The
3016 /// generated code sucks but the implementation is nice and simple.
3017 ///
3018 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3019   return new ISel(TM);
3020 }