Make abort more explicit
[oota-llvm.git] / lib / Target / X86 / InstSelectSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 target
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include <map>
30
31 /// BMI - A special BuildMI variant that takes an iterator to insert the
32 /// instruction at as well as a basic block.  This is the version for when you
33 /// have a destination register in mind.
34 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
35                                       MachineBasicBlock::iterator &I,
36                                       MachineOpCode Opcode,
37                                       unsigned NumOperands,
38                                       unsigned DestReg) {
39   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
40   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
41   I = MBB->insert(I, MI)+1;
42   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
43 }
44
45 /// BMI - A special BuildMI variant that takes an iterator to insert the
46 /// instruction at as well as a basic block.
47 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
48                                       MachineBasicBlock::iterator &I,
49                                       MachineOpCode Opcode,
50                                       unsigned NumOperands) {
51   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
52   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
53   I = MBB->insert(I, MI)+1;
54   return MachineInstrBuilder(MI);
55 }
56
57
58 namespace {
59   struct ISel : public FunctionPass, InstVisitor<ISel> {
60     TargetMachine &TM;
61     MachineFunction *F;                 // The function we are compiling into
62     MachineBasicBlock *BB;              // The current MBB we are compiling
63     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
64
65     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
66
67     // MBBMap - Mapping between LLVM BB -> Machine BB
68     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
69
70     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
71
72     /// runOnFunction - Top level implementation of instruction selection for
73     /// the entire function.
74     ///
75     bool runOnFunction(Function &Fn) {
76       F = &MachineFunction::construct(&Fn, TM);
77
78       // Create all of the machine basic blocks for the function...
79       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
80         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81
82       BB = &F->front();
83
84       // Copy incoming arguments off of the stack...
85       LoadArgumentsToVirtualRegs(Fn);
86
87       // Instruction select everything except PHI nodes
88       visit(Fn);
89
90       // Select the PHI nodes
91       SelectPHINodes();
92
93       RegMap.clear();
94       MBBMap.clear();
95       F = 0;
96       return false;  // We never modify the LLVM itself.
97     }
98
99     virtual const char *getPassName() const {
100       return "X86 Simple Instruction Selection";
101     }
102
103     /// visitBasicBlock - This method is called when we are visiting a new basic
104     /// block.  This simply creates a new MachineBasicBlock to emit code into
105     /// and adds it to the current MachineFunction.  Subsequent visit* for
106     /// instructions will be invoked for all instructions in the basic block.
107     ///
108     void visitBasicBlock(BasicBlock &LLVM_BB) {
109       BB = MBBMap[&LLVM_BB];
110     }
111
112     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113     /// from the stack into virtual registers.
114     ///
115     void LoadArgumentsToVirtualRegs(Function &F);
116
117     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
118     /// because we have to generate our sources into the source basic blocks,
119     /// not the current one.
120     ///
121     void SelectPHINodes();
122
123     // Visitation methods for various instructions.  These methods simply emit
124     // fixed X86 code for each instruction.
125     //
126
127     // Control flow operators
128     void visitReturnInst(ReturnInst &RI);
129     void visitBranchInst(BranchInst &BI);
130
131     struct ValueRecord {
132       unsigned Reg;
133       const Type *Ty;
134       ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
135     };
136     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
137                 const std::vector<ValueRecord> &Args);
138     void visitCallInst(CallInst &I);
139     void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
140
141     // Arithmetic operators
142     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
143     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
144     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
145     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
146                     unsigned DestReg, const Type *DestTy,
147                     unsigned Op0Reg, unsigned Op1Reg);
148     void visitMul(BinaryOperator &B);
149
150     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
151     void visitRem(BinaryOperator &B) { visitDivRem(B); }
152     void visitDivRem(BinaryOperator &B);
153
154     // Bitwise operators
155     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
156     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
157     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
158
159     // Comparison operators...
160     void visitSetCondInst(SetCondInst &I);
161     bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
162
163     // Memory Instructions
164     MachineInstr *doFPLoad(MachineBasicBlock *MBB,
165                            MachineBasicBlock::iterator &MBBI,
166                            const Type *Ty, unsigned DestReg);
167     void visitLoadInst(LoadInst &I);
168     void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
169     void visitStoreInst(StoreInst &I);
170     void visitGetElementPtrInst(GetElementPtrInst &I);
171     void visitAllocaInst(AllocaInst &I);
172     void visitMallocInst(MallocInst &I);
173     void visitFreeInst(FreeInst &I);
174     
175     // Other operators
176     void visitShiftInst(ShiftInst &I);
177     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
178     void visitCastInst(CastInst &I);
179     void visitVarArgInst(VarArgInst &I);
180
181     void visitInstruction(Instruction &I) {
182       std::cerr << "Cannot instruction select: " << I;
183       abort();
184     }
185
186     /// promote32 - Make a value 32-bits wide, and put it somewhere.
187     ///
188     void promote32(unsigned targetReg, const ValueRecord &VR);
189
190     /// EmitByteSwap - Byteswap SrcReg into DestReg.
191     ///
192     void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
193     
194     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
195     /// constant expression GEP support.
196     ///
197     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
198                           Value *Src, User::op_iterator IdxBegin,
199                           User::op_iterator IdxEnd, unsigned TargetReg);
200
201     /// emitCastOperation - Common code shared between visitCastInst and
202     /// constant expression cast support.
203     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
204                            Value *Src, const Type *DestTy, unsigned TargetReg);
205
206     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
207     /// and constant expression support.
208     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
209                                    MachineBasicBlock::iterator &IP,
210                                    Value *Op0, Value *Op1,
211                                    unsigned OperatorClass, unsigned TargetReg);
212
213     /// copyConstantToRegister - Output the instructions required to put the
214     /// specified constant into the specified register.
215     ///
216     void copyConstantToRegister(MachineBasicBlock *MBB,
217                                 MachineBasicBlock::iterator &MBBI,
218                                 Constant *C, unsigned Reg);
219
220     /// makeAnotherReg - This method returns the next register number we haven't
221     /// yet used.
222     ///
223     /// Long values are handled somewhat specially.  They are always allocated
224     /// as pairs of 32 bit integer values.  The register number returned is the
225     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
226     /// of the long value.
227     ///
228     unsigned makeAnotherReg(const Type *Ty) {
229       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
230         const TargetRegisterClass *RC =
231           TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
232         // Create the lower part
233         F->getSSARegMap()->createVirtualRegister(RC);
234         // Create the upper part.
235         return F->getSSARegMap()->createVirtualRegister(RC)-1;
236       }
237
238       // Add the mapping of regnumber => reg class to MachineFunction
239       const TargetRegisterClass *RC =
240         TM.getRegisterInfo()->getRegClassForType(Ty);
241       return F->getSSARegMap()->createVirtualRegister(RC);
242     }
243
244     /// getReg - This method turns an LLVM value into a register number.  This
245     /// is guaranteed to produce the same register number for a particular value
246     /// every time it is queried.
247     ///
248     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
249     unsigned getReg(Value *V) {
250       // Just append to the end of the current bb.
251       MachineBasicBlock::iterator It = BB->end();
252       return getReg(V, BB, It);
253     }
254     unsigned getReg(Value *V, MachineBasicBlock *MBB,
255                     MachineBasicBlock::iterator &IPt) {
256       unsigned &Reg = RegMap[V];
257       if (Reg == 0) {
258         Reg = makeAnotherReg(V->getType());
259         RegMap[V] = Reg;
260       }
261
262       // If this operand is a constant, emit the code to copy the constant into
263       // the register here...
264       //
265       if (Constant *C = dyn_cast<Constant>(V)) {
266         copyConstantToRegister(MBB, IPt, C, Reg);
267         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
268       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
269         // Move the address of the global into the register
270         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
271         RegMap.erase(V);  // Assign a new name to this address if ref'd again
272       }
273
274       return Reg;
275     }
276   };
277 }
278
279 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
280 /// Representation.
281 ///
282 enum TypeClass {
283   cByte, cShort, cInt, cFP, cLong
284 };
285
286 /// getClass - Turn a primitive type into a "class" number which is based on the
287 /// size of the type, and whether or not it is floating point.
288 ///
289 static inline TypeClass getClass(const Type *Ty) {
290   switch (Ty->getPrimitiveID()) {
291   case Type::SByteTyID:
292   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
293   case Type::ShortTyID:
294   case Type::UShortTyID:  return cShort;     // Short operands are class #1
295   case Type::IntTyID:
296   case Type::UIntTyID:
297   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
298
299   case Type::FloatTyID:
300   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
301
302   case Type::LongTyID:
303   case Type::ULongTyID:   return cLong;      // Longs are class #4
304   default:
305     assert(0 && "Invalid type to getClass!");
306     return cByte;  // not reached
307   }
308 }
309
310 // getClassB - Just like getClass, but treat boolean values as bytes.
311 static inline TypeClass getClassB(const Type *Ty) {
312   if (Ty == Type::BoolTy) return cByte;
313   return getClass(Ty);
314 }
315
316
317 /// copyConstantToRegister - Output the instructions required to put the
318 /// specified constant into the specified register.
319 ///
320 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
321                                   MachineBasicBlock::iterator &IP,
322                                   Constant *C, unsigned R) {
323   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
324     unsigned Class = 0;
325     switch (CE->getOpcode()) {
326     case Instruction::GetElementPtr:
327       emitGEPOperation(MBB, IP, CE->getOperand(0),
328                        CE->op_begin()+1, CE->op_end(), R);
329       return;
330     case Instruction::Cast:
331       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
332       return;
333
334     case Instruction::Xor: ++Class; // FALL THROUGH
335     case Instruction::Or:  ++Class; // FALL THROUGH
336     case Instruction::And: ++Class; // FALL THROUGH
337     case Instruction::Sub: ++Class; // FALL THROUGH
338     case Instruction::Add:
339       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
340                                 Class, R);
341       return;
342
343     default:
344       std::cerr << "Offending expr: " << C << "\n";
345       assert(0 && "Constant expressions not yet handled!\n");
346     }
347   }
348
349   if (C->getType()->isIntegral()) {
350     unsigned Class = getClassB(C->getType());
351
352     if (Class == cLong) {
353       // Copy the value into the register pair.
354       uint64_t Val;
355       if (C->getType()->isSigned())
356         Val = cast<ConstantSInt>(C)->getValue();
357       else
358         Val = cast<ConstantUInt>(C)->getValue();
359
360       BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
361       BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
362       return;
363     }
364
365     assert(Class <= cInt && "Type not handled yet!");
366
367     static const unsigned IntegralOpcodeTab[] = {
368       X86::MOVir8, X86::MOVir16, X86::MOVir32
369     };
370
371     if (C->getType() == Type::BoolTy) {
372       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
373     } else if (C->getType()->isSigned()) {
374       ConstantSInt *CSI = cast<ConstantSInt>(C);
375       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
376     } else {
377       ConstantUInt *CUI = cast<ConstantUInt>(C);
378       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
379     }
380   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
381     double Value = CFP->getValue();
382     if (Value == +0.0)
383       BMI(MBB, IP, X86::FLD0, 0, R);
384     else if (Value == +1.0)
385       BMI(MBB, IP, X86::FLD1, 0, R);
386     else {
387       // Otherwise we need to spill the constant to memory...
388       MachineConstantPool *CP = F->getConstantPool();
389       unsigned CPI = CP->getConstantPoolIndex(CFP);
390       addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
391     }
392
393   } else if (isa<ConstantPointerNull>(C)) {
394     // Copy zero (null pointer) to the register.
395     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
396   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
397     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
398     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
399   } else {
400     std::cerr << "Offending constant: " << C << "\n";
401     assert(0 && "Type not handled yet!");
402   }
403 }
404
405 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
406 /// the stack into virtual registers.
407 ///
408 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
409   // Emit instructions to load the arguments...  On entry to a function on the
410   // X86, the stack frame looks like this:
411   //
412   // [ESP] -- return address
413   // [ESP + 4] -- first argument (leftmost lexically)
414   // [ESP + 8] -- second argument, if first argument is four bytes in size
415   //    ... 
416   //
417   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
418   MachineFrameInfo *MFI = F->getFrameInfo();
419
420   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
421     unsigned Reg = getReg(*I);
422     
423     int FI;          // Frame object index
424     switch (getClassB(I->getType())) {
425     case cByte:
426       FI = MFI->CreateFixedObject(1, ArgOffset);
427       addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
428       break;
429     case cShort:
430       FI = MFI->CreateFixedObject(2, ArgOffset);
431       addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
432       break;
433     case cInt:
434       FI = MFI->CreateFixedObject(4, ArgOffset);
435       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
436       break;
437     case cLong:
438       FI = MFI->CreateFixedObject(8, ArgOffset);
439       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
440       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
441       ArgOffset += 4;   // longs require 4 additional bytes
442       break;
443     case cFP:
444       unsigned Opcode;
445       if (I->getType() == Type::FloatTy) {
446         Opcode = X86::FLDr32;
447         FI = MFI->CreateFixedObject(4, ArgOffset);
448       } else {
449         Opcode = X86::FLDr64;
450         FI = MFI->CreateFixedObject(8, ArgOffset);
451         ArgOffset += 4;   // doubles require 4 additional bytes
452       }
453       addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
454       break;
455     default:
456       assert(0 && "Unhandled argument type!");
457     }
458     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
459   }
460
461   // If the function takes variable number of arguments, add a frame offset for
462   // the start of the first vararg value... this is used to expand
463   // llvm.va_start.
464   if (Fn.getFunctionType()->isVarArg())
465     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
466 }
467
468
469 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
470 /// because we have to generate our sources into the source basic blocks, not
471 /// the current one.
472 ///
473 void ISel::SelectPHINodes() {
474   const TargetInstrInfo &TII = TM.getInstrInfo();
475   const Function &LF = *F->getFunction();  // The LLVM function...
476   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
477     const BasicBlock *BB = I;
478     MachineBasicBlock *MBB = MBBMap[I];
479
480     // Loop over all of the PHI nodes in the LLVM basic block...
481     unsigned NumPHIs = 0;
482     for (BasicBlock::const_iterator I = BB->begin();
483          PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
484
485       // Create a new machine instr PHI node, and insert it.
486       unsigned PHIReg = getReg(*PN);
487       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
488       MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
489
490       MachineInstr *LongPhiMI = 0;
491       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
492         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
493         MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
494       }
495
496       // PHIValues - Map of blocks to incoming virtual registers.  We use this
497       // so that we only initialize one incoming value for a particular block,
498       // even if the block has multiple entries in the PHI node.
499       //
500       std::map<MachineBasicBlock*, unsigned> PHIValues;
501
502       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
503         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
504         unsigned ValReg;
505         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
506           PHIValues.lower_bound(PredMBB);
507
508         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
509           // We already inserted an initialization of the register for this
510           // predecessor.  Recycle it.
511           ValReg = EntryIt->second;
512
513         } else {        
514           // Get the incoming value into a virtual register.  If it is not
515           // already available in a virtual register, insert the computation
516           // code into PredMBB
517           //
518           MachineBasicBlock::iterator PI = PredMBB->end();
519           while (PI != PredMBB->begin() &&
520                  TII.isTerminatorInstr((*(PI-1))->getOpcode()))
521             --PI;
522           ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
523
524           // Remember that we inserted a value for this PHI for this predecessor
525           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
526         }
527
528         PhiMI->addRegOperand(ValReg);
529         PhiMI->addMachineBasicBlockOperand(PredMBB);
530         if (LongPhiMI) {
531           LongPhiMI->addRegOperand(ValReg+1);
532           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
533         }
534       }
535     }
536   }
537 }
538
539 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
540 // the conditional branch instruction which is the only user of the cc
541 // instruction.  This is the case if the conditional branch is the only user of
542 // the setcc, and if the setcc is in the same basic block as the conditional
543 // branch.  We also don't handle long arguments below, so we reject them here as
544 // well.
545 //
546 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
547   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
548     if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
549         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
550       const Type *Ty = SCI->getOperand(0)->getType();
551       if (Ty != Type::LongTy && Ty != Type::ULongTy)
552         return SCI;
553     }
554   return 0;
555 }
556
557 // Return a fixed numbering for setcc instructions which does not depend on the
558 // order of the opcodes.
559 //
560 static unsigned getSetCCNumber(unsigned Opcode) {
561   switch(Opcode) {
562   default: assert(0 && "Unknown setcc instruction!");
563   case Instruction::SetEQ: return 0;
564   case Instruction::SetNE: return 1;
565   case Instruction::SetLT: return 2;
566   case Instruction::SetGE: return 3;
567   case Instruction::SetGT: return 4;
568   case Instruction::SetLE: return 5;
569   }
570 }
571
572 // LLVM  -> X86 signed  X86 unsigned
573 // -----    ----------  ------------
574 // seteq -> sete        sete
575 // setne -> setne       setne
576 // setlt -> setl        setb
577 // setge -> setge       setae
578 // setgt -> setg        seta
579 // setle -> setle       setbe
580 static const unsigned SetCCOpcodeTab[2][6] = {
581   {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
582   {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
583 };
584
585 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
586
587   // The arguments are already supposed to be of the same type.
588   const Type *CompTy = Op0->getType();
589   bool isSigned = CompTy->isSigned();
590   unsigned reg1 = getReg(Op0);
591   unsigned reg2 = getReg(Op1);
592
593   unsigned Class = getClassB(CompTy);
594   switch (Class) {
595   default: assert(0 && "Unknown type class!");
596     // Emit: cmp <var1>, <var2> (do the comparison).  We can
597     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
598     // 32-bit.
599   case cByte:
600     BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
601     break;
602   case cShort:
603     BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
604     break;
605   case cInt:
606     BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
607     break;
608   case cFP:
609     BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
610     BuildMI(BB, X86::FNSTSWr8, 0);
611     BuildMI(BB, X86::SAHF, 1);
612     isSigned = false;   // Compare with unsigned operators
613     break;
614
615   case cLong:
616     if (OpNum < 2) {    // seteq, setne
617       unsigned LoTmp = makeAnotherReg(Type::IntTy);
618       unsigned HiTmp = makeAnotherReg(Type::IntTy);
619       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
620       BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
621       BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
622       BuildMI(BB, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
623       break;  // Allow the sete or setne to be generated from flags set by OR
624     } else {
625       // Emit a sequence of code which compares the high and low parts once
626       // each, then uses a conditional move to handle the overflow case.  For
627       // example, a setlt for long would generate code like this:
628       //
629       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
630       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
631       // dest = hi(op1) == hi(op2) ? AL : BL;
632       //
633
634       // FIXME: This would be much better if we had hierarchical register
635       // classes!  Until then, hardcode registers so that we can deal with their
636       // aliases (because we don't have conditional byte moves).
637       //
638       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
639       BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
640       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
641       BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
642       BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
643       // NOTE: visitSetCondInst knows that the value is dumped into the BL
644       // register at this point for long values...
645       return isSigned;
646     }
647   }
648   return isSigned;
649 }
650
651
652 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
653 /// register, then move it to wherever the result should be. 
654 ///
655 void ISel::visitSetCondInst(SetCondInst &I) {
656   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
657
658   unsigned OpNum = getSetCCNumber(I.getOpcode());
659   unsigned DestReg = getReg(I);
660   bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
661                                               I.getOperand(1));
662
663   if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
664     // Handle normal comparisons with a setcc instruction...
665     BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
666   } else {
667     // Handle long comparisons by copying the value which is already in BL into
668     // the register we want...
669     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
670   }
671 }
672
673 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
674 /// operand, in the specified target register.
675 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
676   bool isUnsigned = VR.Ty->isUnsigned();
677   switch (getClassB(VR.Ty)) {
678   case cByte:
679     // Extend value into target register (8->32)
680     if (isUnsigned)
681       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
682     else
683       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
684     break;
685   case cShort:
686     // Extend value into target register (16->32)
687     if (isUnsigned)
688       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
689     else
690       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
691     break;
692   case cInt:
693     // Move value into target register (32->32)
694     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
695     break;
696   default:
697     assert(0 && "Unpromotable operand class in promote32");
698   }
699 }
700
701 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
702 /// we have the following possibilities:
703 ///
704 ///   ret void: No return value, simply emit a 'ret' instruction
705 ///   ret sbyte, ubyte : Extend value into EAX and return
706 ///   ret short, ushort: Extend value into EAX and return
707 ///   ret int, uint    : Move value into EAX and return
708 ///   ret pointer      : Move value into EAX and return
709 ///   ret long, ulong  : Move value into EAX/EDX and return
710 ///   ret float/double : Top of FP stack
711 ///
712 void ISel::visitReturnInst(ReturnInst &I) {
713   if (I.getNumOperands() == 0) {
714     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
715     return;
716   }
717
718   Value *RetVal = I.getOperand(0);
719   unsigned RetReg = getReg(RetVal);
720   switch (getClassB(RetVal->getType())) {
721   case cByte:   // integral return values: extend or move into EAX and return
722   case cShort:
723   case cInt:
724     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
725     // Declare that EAX is live on exit
726     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
727     break;
728   case cFP:                   // Floats & Doubles: Return in ST(0)
729     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
730     // Declare that top-of-stack is live on exit
731     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
732     break;
733   case cLong:
734     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
735     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
736     // Declare that EAX & EDX are live on exit
737     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
738     break;
739   default:
740     visitInstruction(I);
741   }
742   // Emit a 'ret' instruction
743   BuildMI(BB, X86::RET, 0);
744 }
745
746 // getBlockAfter - Return the basic block which occurs lexically after the
747 // specified one.
748 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
749   Function::iterator I = BB; ++I;  // Get iterator to next block
750   return I != BB->getParent()->end() ? &*I : 0;
751 }
752
753 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
754 /// that since code layout is frozen at this point, that if we are trying to
755 /// jump to a block that is the immediate successor of the current block, we can
756 /// just make a fall-through (but we don't currently).
757 ///
758 void ISel::visitBranchInst(BranchInst &BI) {
759   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
760
761   if (!BI.isConditional()) {  // Unconditional branch?
762     if (BI.getSuccessor(0) != NextBB)
763       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
764     return;
765   }
766
767   // See if we can fold the setcc into the branch itself...
768   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
769   if (SCI == 0) {
770     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
771     // computed some other way...
772     unsigned condReg = getReg(BI.getCondition());
773     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
774     if (BI.getSuccessor(1) == NextBB) {
775       if (BI.getSuccessor(0) != NextBB)
776         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
777     } else {
778       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
779       
780       if (BI.getSuccessor(0) != NextBB)
781         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
782     }
783     return;
784   }
785
786   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
787   bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
788                                               SCI->getOperand(1));
789   
790   // LLVM  -> X86 signed  X86 unsigned
791   // -----    ----------  ------------
792   // seteq -> je          je
793   // setne -> jne         jne
794   // setlt -> jl          jb
795   // setge -> jge         jae
796   // setgt -> jg          ja
797   // setle -> jle         jbe
798   static const unsigned OpcodeTab[2][6] = {
799     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
800     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
801   };
802   
803   if (BI.getSuccessor(0) != NextBB) {
804     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
805     if (BI.getSuccessor(1) != NextBB)
806       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
807   } else {
808     // Change to the inverse condition...
809     if (BI.getSuccessor(1) != NextBB) {
810       OpNum ^= 1;
811       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
812     }
813   }
814 }
815
816
817 /// doCall - This emits an abstract call instruction, setting up the arguments
818 /// and the return value as appropriate.  For the actual function call itself,
819 /// it inserts the specified CallMI instruction into the stream.
820 ///
821 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
822                   const std::vector<ValueRecord> &Args) {
823
824   // Count how many bytes are to be pushed on the stack...
825   unsigned NumBytes = 0;
826
827   if (!Args.empty()) {
828     for (unsigned i = 0, e = Args.size(); i != e; ++i)
829       switch (getClassB(Args[i].Ty)) {
830       case cByte: case cShort: case cInt:
831         NumBytes += 4; break;
832       case cLong:
833         NumBytes += 8; break;
834       case cFP:
835         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
836         break;
837       default: assert(0 && "Unknown class!");
838       }
839
840     // Adjust the stack pointer for the new arguments...
841     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
842
843     // Arguments go on the stack in reverse order, as specified by the ABI.
844     unsigned ArgOffset = 0;
845     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
846       unsigned ArgReg = Args[i].Reg;
847       switch (getClassB(Args[i].Ty)) {
848       case cByte:
849       case cShort: {
850         // Promote arg to 32 bits wide into a temporary register...
851         unsigned R = makeAnotherReg(Type::UIntTy);
852         promote32(R, Args[i]);
853         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
854                      X86::ESP, ArgOffset).addReg(R);
855         break;
856       }
857       case cInt:
858         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
859                      X86::ESP, ArgOffset).addReg(ArgReg);
860         break;
861       case cLong:
862         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
863                      X86::ESP, ArgOffset).addReg(ArgReg);
864         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
865                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
866         ArgOffset += 4;        // 8 byte entry, not 4.
867         break;
868         
869       case cFP:
870         if (Args[i].Ty == Type::FloatTy) {
871           addRegOffset(BuildMI(BB, X86::FSTr32, 5),
872                        X86::ESP, ArgOffset).addReg(ArgReg);
873         } else {
874           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
875           addRegOffset(BuildMI(BB, X86::FSTr64, 5),
876                        X86::ESP, ArgOffset).addReg(ArgReg);
877           ArgOffset += 4;       // 8 byte entry, not 4.
878         }
879         break;
880
881       default: assert(0 && "Unknown class!");
882       }
883       ArgOffset += 4;
884     }
885   } else {
886     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
887   }
888
889   BB->push_back(CallMI);
890
891   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
892
893   // If there is a return value, scavenge the result from the location the call
894   // leaves it in...
895   //
896   if (Ret.Ty != Type::VoidTy) {
897     unsigned DestClass = getClassB(Ret.Ty);
898     switch (DestClass) {
899     case cByte:
900     case cShort:
901     case cInt: {
902       // Integral results are in %eax, or the appropriate portion
903       // thereof.
904       static const unsigned regRegMove[] = {
905         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
906       };
907       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
908       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
909       break;
910     }
911     case cFP:     // Floating-point return values live in %ST(0)
912       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
913       break;
914     case cLong:   // Long values are left in EDX:EAX
915       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
916       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
917       break;
918     default: assert(0 && "Unknown class!");
919     }
920   }
921 }
922
923
924 /// visitCallInst - Push args on stack and do a procedure call instruction.
925 void ISel::visitCallInst(CallInst &CI) {
926   MachineInstr *TheCall;
927   if (Function *F = CI.getCalledFunction()) {
928     // Is it an intrinsic function call?
929     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
930       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
931       return;
932     }
933
934     // Emit a CALL instruction with PC-relative displacement.
935     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
936   } else {  // Emit an indirect call...
937     unsigned Reg = getReg(CI.getCalledValue());
938     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
939   }
940
941   std::vector<ValueRecord> Args;
942   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
943     Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
944                                CI.getOperand(i)->getType()));
945
946   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
947   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
948 }        
949
950 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
951   unsigned TmpReg1, TmpReg2;
952   switch (ID) {
953   case LLVMIntrinsic::va_start:
954     // Get the address of the first vararg value...
955     TmpReg1 = makeAnotherReg(Type::UIntTy);
956     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
957     TmpReg2 = getReg(CI.getOperand(1));
958     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
959     return;
960
961   case LLVMIntrinsic::va_end: return;   // Noop on X86
962   case LLVMIntrinsic::va_copy:
963     TmpReg1 = getReg(CI.getOperand(2));  // Get existing va_list
964     TmpReg2 = getReg(CI.getOperand(1));  // Get va_list* to store into
965     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
966     return;
967
968   default: assert(0 && "Unknown intrinsic for X86!");
969   }
970 }
971
972
973 /// visitSimpleBinary - Implement simple binary operators for integral types...
974 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
975 /// Xor.
976 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
977   unsigned DestReg = getReg(B);
978   MachineBasicBlock::iterator MI = BB->end();
979   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
980                             OperatorClass, DestReg);
981 }
982
983 /// visitSimpleBinary - Implement simple binary operators for integral types...
984 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
985 /// 4 for Xor.
986 ///
987 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
988 /// and constant expression support.
989 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
990                                      MachineBasicBlock::iterator &IP,
991                                      Value *Op0, Value *Op1,
992                                      unsigned OperatorClass,unsigned TargetReg){
993   unsigned Class = getClassB(Op0->getType());
994
995   static const unsigned OpcodeTab[][4] = {
996     // Arithmetic operators
997     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
998     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
999
1000     // Bitwise operators
1001     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
1002     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
1003     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
1004   };
1005
1006   bool isLong = false;
1007   if (Class == cLong) {
1008     isLong = true;
1009     Class = cInt;          // Bottom 32 bits are handled just like ints
1010   }
1011   
1012   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1013   assert(Opcode && "Floating point arguments to logical inst?");
1014   unsigned Op0r = getReg(Op0, BB, IP);
1015   unsigned Op1r = getReg(Op1, BB, IP);
1016   BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
1017
1018   if (isLong) {        // Handle the upper 32 bits of long values...
1019     static const unsigned TopTab[] = {
1020       X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1021     };
1022     BMI(BB, IP, TopTab[OperatorClass], 2,
1023         TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
1024   }
1025 }
1026
1027 /// doMultiply - Emit appropriate instructions to multiply together the
1028 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1029 /// result should be given as DestTy.
1030 ///
1031 /// FIXME: doMultiply should use one of the two address IMUL instructions!
1032 ///
1033 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1034                       unsigned DestReg, const Type *DestTy,
1035                       unsigned op0Reg, unsigned op1Reg) {
1036   unsigned Class = getClass(DestTy);
1037   switch (Class) {
1038   case cFP:              // Floating point multiply
1039     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1040     return;
1041   default:
1042   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1043   case cByte:
1044   case cShort:
1045   case cInt:          // Small integerals, handled below...
1046     break;
1047   }
1048  
1049   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1050   static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32  };
1051   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1052   unsigned Reg     = Regs[Class];
1053
1054   // Emit a MOV to put the first operand into the appropriately-sized
1055   // subreg of EAX.
1056   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
1057   
1058   // Emit the appropriate multiply instruction.
1059   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
1060
1061   // Emit another MOV to put the result into the destination register.
1062   BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
1063 }
1064
1065 /// visitMul - Multiplies are not simple binary operators because they must deal
1066 /// with the EAX register explicitly.
1067 ///
1068 void ISel::visitMul(BinaryOperator &I) {
1069   unsigned Op0Reg  = getReg(I.getOperand(0));
1070   unsigned Op1Reg  = getReg(I.getOperand(1));
1071   unsigned DestReg = getReg(I);
1072
1073   // Simple scalar multiply?
1074   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1075     MachineBasicBlock::iterator MBBI = BB->end();
1076     doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1077   } else {
1078     // Long value.  We have to do things the hard way...
1079     // Multiply the two low parts... capturing carry into EDX
1080     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1081     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1082
1083     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1084     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1085     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1086
1087     MachineBasicBlock::iterator MBBI = BB->end();
1088     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1089     doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1090
1091     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1092     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1093             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1094     
1095     MBBI = BB->end();
1096     unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1097     doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1098     
1099     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1100             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1101   }
1102 }
1103
1104
1105 /// visitDivRem - Handle division and remainder instructions... these
1106 /// instruction both require the same instructions to be generated, they just
1107 /// select the result from a different register.  Note that both of these
1108 /// instructions work differently for signed and unsigned operands.
1109 ///
1110 void ISel::visitDivRem(BinaryOperator &I) {
1111   unsigned Class     = getClass(I.getType());
1112   unsigned Op0Reg    = getReg(I.getOperand(0));
1113   unsigned Op1Reg    = getReg(I.getOperand(1));
1114   unsigned ResultReg = getReg(I);
1115
1116   switch (Class) {
1117   case cFP:              // Floating point divide
1118     if (I.getOpcode() == Instruction::Div)
1119       BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1120     else {               // Floating point remainder...
1121       MachineInstr *TheCall =
1122         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1123       std::vector<ValueRecord> Args;
1124       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1125       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1126       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1127     }
1128     return;
1129   case cLong: {
1130     static const char *FnName[] =
1131       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1132
1133     unsigned NameIdx = I.getType()->isUnsigned()*2;
1134     NameIdx += I.getOpcode() == Instruction::Div;
1135     MachineInstr *TheCall =
1136       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1137
1138     std::vector<ValueRecord> Args;
1139     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1140     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1141     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1142     return;
1143   }
1144   case cByte: case cShort: case cInt:
1145     break;          // Small integerals, handled below...
1146   default: assert(0 && "Unknown class!");
1147   }
1148
1149   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1150   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1151   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
1152   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1153   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1154
1155   static const unsigned DivOpcode[][4] = {
1156     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1157     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1158   };
1159
1160   bool isSigned   = I.getType()->isSigned();
1161   unsigned Reg    = Regs[Class];
1162   unsigned ExtReg = ExtRegs[Class];
1163
1164   // Put the first operand into one of the A registers...
1165   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1166
1167   if (isSigned) {
1168     // Emit a sign extension instruction...
1169     BuildMI(BB, ExtOpcode[Class], 0);
1170   } else {
1171     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1172     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1173   }
1174
1175   // Emit the appropriate divide or remainder instruction...
1176   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1177
1178   // Figure out which register we want to pick the result out of...
1179   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1180   
1181   // Put the result into the destination register...
1182   BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1183 }
1184
1185
1186 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1187 /// for constant immediate shift values, and for constant immediate
1188 /// shift values equal to 1. Even the general case is sort of special,
1189 /// because the shift amount has to be in CL, not just any old register.
1190 ///
1191 void ISel::visitShiftInst(ShiftInst &I) {
1192   unsigned SrcReg = getReg(I.getOperand(0));
1193   unsigned DestReg = getReg(I);
1194   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1195   bool isSigned = I.getType()->isSigned();
1196   unsigned Class = getClass(I.getType());
1197   
1198   static const unsigned ConstantOperand[][4] = {
1199     { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 },  // SHR
1200     { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 },  // SAR
1201     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SHL
1202     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SAL = SHL
1203   };
1204
1205   static const unsigned NonConstantOperand[][4] = {
1206     { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 },  // SHR
1207     { X86::SARrr8, X86::SARrr16, X86::SARrr32 },  // SAR
1208     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SHL
1209     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SAL = SHL
1210   };
1211
1212   // Longs, as usual, are handled specially...
1213   if (Class == cLong) {
1214     // If we have a constant shift, we can generate much more efficient code
1215     // than otherwise...
1216     //
1217     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1218       unsigned Amount = CUI->getValue();
1219       if (Amount < 32) {
1220         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1221         if (isLeftShift) {
1222           BuildMI(BB, Opc[3], 3, 
1223                   DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1224           BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1225         } else {
1226           BuildMI(BB, Opc[3], 3,
1227                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1228           BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1229         }
1230       } else {                 // Shifting more than 32 bits
1231         Amount -= 32;
1232         if (isLeftShift) {
1233           BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1234           BuildMI(BB, X86::MOVir32, 1,DestReg  ).addZImm(0);
1235         } else {
1236           unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1237           BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1238           BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1239         }
1240       }
1241     } else {
1242       visitInstruction(I);  // FIXME: Implement long shift by non-constant
1243     }
1244     return;
1245   }
1246
1247   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1248     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1249     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1250
1251     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1252     BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1253   } else {                  // The shift amount is non-constant.
1254     BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1255
1256     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1257     BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1258   }
1259 }
1260
1261
1262 /// doFPLoad - This method is used to load an FP value from memory using the
1263 /// current endianness.  NOTE: This method returns a partially constructed load
1264 /// instruction which needs to have the memory source filled in still.
1265 ///
1266 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1267                              MachineBasicBlock::iterator &MBBI,
1268                              const Type *Ty, unsigned DestReg) {
1269   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1270   unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1271
1272   if (TM.getTargetData().isLittleEndian()) // fast path...
1273     return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1274
1275   // If we are big-endian, start by creating an LEA instruction to represent the
1276   // address of the memory location to load from...
1277   //
1278   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1279   MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1280
1281   // Allocate a temporary stack slot to transform the value into...
1282   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1283
1284   // Perform the bswaps 32 bits at a time...
1285   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1286   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1287   addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1288   BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1289   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1290   addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1291                     FrameIdx, Offset).addReg(TmpReg2);
1292   
1293   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1294     TmpReg1 = makeAnotherReg(Type::UIntTy);
1295     TmpReg2 = makeAnotherReg(Type::UIntTy);
1296
1297     addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1298     BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1299     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1300     addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1301   }
1302
1303   // Now we can reload the final byteswapped result into the final destination.
1304   addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1305   return Result;
1306 }
1307
1308 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1309 ///
1310 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1311   // Emit the byte swap instruction...
1312   switch (Class) {
1313   case cByte:
1314     // No byteswap necessary for 8 bit value...
1315     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1316     break;
1317   case cInt:
1318     // Use the 32 bit bswap instruction to do a 32 bit swap...
1319     BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1320     break;
1321     
1322   case cShort:
1323     // For 16 bit we have to use an xchg instruction, because there is no
1324     // 16-bit bswap.  XCHG is necessarily not in SSA form, so we force things
1325     // into AX to do the xchg.
1326     //
1327     BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1328     BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1329       .addReg(X86::AH, MOTy::UseAndDef);
1330     BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1331     break;
1332   default: assert(0 && "Cannot byteswap this class!");
1333   }
1334 }
1335
1336
1337 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1338 /// instruction.  The load and store instructions are the only place where we
1339 /// need to worry about the memory layout of the target machine.
1340 ///
1341 void ISel::visitLoadInst(LoadInst &I) {
1342   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1343   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1344   unsigned SrcAddrReg = getReg(I.getOperand(0));
1345   unsigned DestReg = getReg(I);
1346
1347   unsigned Class = getClass(I.getType());
1348   switch (Class) {
1349   case cFP: {
1350     MachineBasicBlock::iterator MBBI = BB->end();
1351     addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1352     return;
1353   }
1354   case cLong: case cInt: case cShort: case cByte:
1355     break;      // Integers of various sizes handled below
1356   default: assert(0 && "Unknown memory class!");
1357   }
1358
1359   // We need to adjust the input pointer if we are emulating a big-endian
1360   // long-pointer target.  On these systems, the pointer that we are interested
1361   // in is in the upper part of the eight byte memory image of the pointer.  It
1362   // also happens to be byte-swapped, but this will be handled later.
1363   //
1364   if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1365     unsigned R = makeAnotherReg(Type::UIntTy);
1366     BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1367     SrcAddrReg = R;
1368   }
1369
1370   unsigned IReg = DestReg;
1371   if (!isLittleEndian)  // If big endian we need an intermediate stage
1372     DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1373
1374   static const unsigned Opcode[] = {
1375     X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1376   };
1377   addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1378
1379   // Handle long values now...
1380   if (Class == cLong) {
1381     if (isLittleEndian) {
1382       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1383     } else {
1384       EmitByteSwap(IReg+1, DestReg, cInt);
1385       unsigned TempReg = makeAnotherReg(Type::IntTy);
1386       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1387       EmitByteSwap(IReg, TempReg, cInt);
1388     }
1389     return;
1390   }
1391
1392   if (!isLittleEndian)
1393     EmitByteSwap(IReg, DestReg, Class);
1394 }
1395
1396
1397 /// doFPStore - This method is used to store an FP value to memory using the
1398 /// current endianness.
1399 ///
1400 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1401   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1402   unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1403
1404   if (TM.getTargetData().isLittleEndian()) {  // fast path...
1405     addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1406     return;
1407   }
1408
1409   // Allocate a temporary stack slot to transform the value into...
1410   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1411   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1412   addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1413
1414   // Store the value into a temporary stack slot...
1415   addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1416
1417   // Perform the bswaps 32 bits at a time...
1418   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1419   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1420   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1421   BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1422   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1423   addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1424                DestAddrReg, Offset).addReg(TmpReg2);
1425   
1426   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1427     TmpReg1 = makeAnotherReg(Type::UIntTy);
1428     TmpReg2 = makeAnotherReg(Type::UIntTy);
1429
1430     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1431     BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1432     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1433     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1434   }
1435 }
1436
1437
1438 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1439 /// instruction.
1440 ///
1441 void ISel::visitStoreInst(StoreInst &I) {
1442   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1443   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1444   unsigned ValReg      = getReg(I.getOperand(0));
1445   unsigned AddressReg  = getReg(I.getOperand(1));
1446
1447   unsigned Class = getClass(I.getOperand(0)->getType());
1448   switch (Class) {
1449   case cLong:
1450     if (isLittleEndian) {
1451       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1452       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1453                    AddressReg, 4).addReg(ValReg+1);
1454     } else {
1455       unsigned T1 = makeAnotherReg(Type::IntTy);
1456       unsigned T2 = makeAnotherReg(Type::IntTy);
1457       EmitByteSwap(T1, ValReg  , cInt);
1458       EmitByteSwap(T2, ValReg+1, cInt);
1459       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1460       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1461     }
1462     return;
1463   case cFP:
1464     doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1465     return;
1466   case cInt: case cShort: case cByte:
1467     break;      // Integers of various sizes handled below
1468   default: assert(0 && "Unknown memory class!");
1469   }
1470
1471   if (!isLittleEndian && hasLongPointers &&
1472       isa<PointerType>(I.getOperand(0)->getType())) {
1473     unsigned R = makeAnotherReg(Type::UIntTy);
1474     BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1475     AddressReg = R;
1476   }
1477
1478   if (!isLittleEndian && Class != cByte) {
1479     unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1480     EmitByteSwap(R, ValReg, Class);
1481     ValReg = R;
1482   }
1483
1484   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1485   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1486 }
1487
1488
1489 /// visitCastInst - Here we have various kinds of copying with or without
1490 /// sign extension going on.
1491 void ISel::visitCastInst(CastInst &CI) {
1492   unsigned DestReg = getReg(CI);
1493   MachineBasicBlock::iterator MI = BB->end();
1494   emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1495 }
1496
1497 /// emitCastOperation - Common code shared between visitCastInst and
1498 /// constant expression cast support.
1499 void ISel::emitCastOperation(MachineBasicBlock *BB,
1500                              MachineBasicBlock::iterator &IP,
1501                              Value *Src, const Type *DestTy,
1502                              unsigned DestReg) {
1503   unsigned SrcReg = getReg(Src, BB, IP);
1504   const Type *SrcTy = Src->getType();
1505   unsigned SrcClass = getClassB(SrcTy);
1506   unsigned DestClass = getClassB(DestTy);
1507
1508   // Implement casts to bool by using compare on the operand followed by set if
1509   // not zero on the result.
1510   if (DestTy == Type::BoolTy) {
1511     if (SrcClass == cFP || SrcClass == cLong)
1512       abort();  // FIXME: implement cast (long & FP) to bool
1513     
1514     BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1515     BMI(BB, IP, X86::SETNEr, 1, DestReg);
1516     return;
1517   }
1518
1519   static const unsigned RegRegMove[] = {
1520     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1521   };
1522
1523   // Implement casts between values of the same type class (as determined by
1524   // getClass) by using a register-to-register move.
1525   if (SrcClass == DestClass) {
1526     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1527       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1528     } else if (SrcClass == cFP) {
1529       if (SrcTy == Type::FloatTy) {  // double -> float
1530         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1531         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1532       } else {                       // float -> double
1533         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1534                "Unknown cFP member!");
1535         // Truncate from double to float by storing to memory as short, then
1536         // reading it back.
1537         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1538         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1539         addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1540         addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1541       }
1542     } else if (SrcClass == cLong) {
1543       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1544       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1545     } else {
1546       assert(0 && "Cannot handle this type of cast instruction!");
1547       abort();
1548     }
1549     return;
1550   }
1551
1552   // Handle cast of SMALLER int to LARGER int using a move with sign extension
1553   // or zero extension, depending on whether the source type was signed.
1554   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1555       SrcClass < DestClass) {
1556     bool isLong = DestClass == cLong;
1557     if (isLong) DestClass = cInt;
1558
1559     static const unsigned Opc[][4] = {
1560       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1561       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
1562     };
1563     
1564     bool isUnsigned = SrcTy->isUnsigned();
1565     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1566         DestReg).addReg(SrcReg);
1567
1568     if (isLong) {  // Handle upper 32 bits as appropriate...
1569       if (isUnsigned)     // Zero out top bits...
1570         BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1571       else                // Sign extend bottom half...
1572         BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1573     }
1574     return;
1575   }
1576
1577   // Special case long -> int ...
1578   if (SrcClass == cLong && DestClass == cInt) {
1579     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1580     return;
1581   }
1582   
1583   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1584   // move out of AX or AL.
1585   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1586       && SrcClass > DestClass) {
1587     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1588     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1589     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1590     return;
1591   }
1592
1593   // Handle casts from integer to floating point now...
1594   if (DestClass == cFP) {
1595     // Promote the integer to a type supported by FLD.  We do this because there
1596     // are no unsigned FLD instructions, so we must promote an unsigned value to
1597     // a larger signed value, then use FLD on the larger value.
1598     //
1599     const Type *PromoteType = 0;
1600     unsigned PromoteOpcode;
1601     switch (SrcTy->getPrimitiveID()) {
1602     case Type::BoolTyID:
1603     case Type::SByteTyID:
1604       // We don't have the facilities for directly loading byte sized data from
1605       // memory (even signed).  Promote it to 16 bits.
1606       PromoteType = Type::ShortTy;
1607       PromoteOpcode = X86::MOVSXr16r8;
1608       break;
1609     case Type::UByteTyID:
1610       PromoteType = Type::ShortTy;
1611       PromoteOpcode = X86::MOVZXr16r8;
1612       break;
1613     case Type::UShortTyID:
1614       PromoteType = Type::IntTy;
1615       PromoteOpcode = X86::MOVZXr32r16;
1616       break;
1617     case Type::UIntTyID: {
1618       // Make a 64 bit temporary... and zero out the top of it...
1619       unsigned TmpReg = makeAnotherReg(Type::LongTy);
1620       BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1621       BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1622       SrcTy = Type::LongTy;
1623       SrcClass = cLong;
1624       SrcReg = TmpReg;
1625       break;
1626     }
1627     case Type::ULongTyID:
1628       assert("FIXME: not implemented: cast ulong X to fp type!");
1629     default:  // No promotion needed...
1630       break;
1631     }
1632     
1633     if (PromoteType) {
1634       unsigned TmpReg = makeAnotherReg(PromoteType);
1635       BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1636           1, TmpReg).addReg(SrcReg);
1637       SrcTy = PromoteType;
1638       SrcClass = getClass(PromoteType);
1639       SrcReg = TmpReg;
1640     }
1641
1642     // Spill the integer to memory and reload it from there...
1643     int FrameIdx =
1644       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1645
1646     if (SrcClass == cLong) {
1647       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1648       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1649                         FrameIdx, 4).addReg(SrcReg+1);
1650     } else {
1651       static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1652       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1653     }
1654
1655     static const unsigned Op2[] =
1656       { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
1657     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1658     return;
1659   }
1660
1661   // Handle casts from floating point to integer now...
1662   if (SrcClass == cFP) {
1663     // Change the floating point control register to use "round towards zero"
1664     // mode when truncating to an integer value.
1665     //
1666     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1667     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1668
1669     // Load the old value of the high byte of the control word...
1670     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1671     addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1672
1673     // Set the high part to be round to zero...
1674     addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1675
1676     // Reload the modified control word now...
1677     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1678     
1679     // Restore the memory image of control word to original value
1680     addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1681                       CWFrameIdx, 1).addReg(HighPartOfCW);
1682
1683     // We don't have the facilities for directly storing byte sized data to
1684     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
1685     // larger classes because we only have signed FP stores.
1686     unsigned StoreClass  = DestClass;
1687     const Type *StoreTy  = DestTy;
1688     if (StoreClass == cByte || DestTy->isUnsigned())
1689       switch (StoreClass) {
1690       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
1691       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
1692       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
1693       case cLong:
1694         assert(0 &&"FIXME not implemented: cast FP to unsigned long long");
1695         abort();
1696       default: assert(0 && "Unknown store class!");
1697       }
1698
1699     // Spill the integer to memory and reload it from there...
1700     int FrameIdx =
1701       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1702
1703     static const unsigned Op1[] =
1704       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1705     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1706
1707     if (DestClass == cLong) {
1708       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1709       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1710     } else {
1711       static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1712       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1713     }
1714
1715     // Reload the original control word now...
1716     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1717     return;
1718   }
1719
1720   // Anything we haven't handled already, we can't (yet) handle at all.
1721   assert(0 && "Unhandled cast instruction!");
1722   abort();
1723 }
1724
1725 /// visitVarArgInst - Implement the va_arg instruction...
1726 ///
1727 void ISel::visitVarArgInst(VarArgInst &I) {
1728   unsigned SrcReg = getReg(I.getOperand(0));
1729   unsigned DestReg = getReg(I);
1730
1731   // Load the va_list into a register...
1732   unsigned VAList = makeAnotherReg(Type::UIntTy);
1733   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1734
1735   unsigned Size;
1736   switch (I.getType()->getPrimitiveID()) {
1737   default:
1738     std::cerr << I;
1739     assert(0 && "Error: bad type for va_arg instruction!");
1740     return;
1741   case Type::PointerTyID:
1742   case Type::UIntTyID:
1743   case Type::IntTyID:
1744     Size = 4;
1745     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1746     break;
1747   case Type::ULongTyID:
1748   case Type::LongTyID:
1749     Size = 8;
1750     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1751     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1752     break;
1753   case Type::DoubleTyID:
1754     Size = 8;
1755     addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1756     break;
1757   }
1758
1759   // Increment the VAList pointer...
1760   unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1761   BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1762
1763   // Update the VAList in memory...
1764   addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1765 }
1766
1767
1768 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1769 // returns zero when the input is not exactly a power of two.
1770 static unsigned ExactLog2(unsigned Val) {
1771   if (Val == 0) return 0;
1772   unsigned Count = 0;
1773   while (Val != 1) {
1774     if (Val & 1) return 0;
1775     Val >>= 1;
1776     ++Count;
1777   }
1778   return Count+1;
1779 }
1780
1781 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1782   unsigned outputReg = getReg(I);
1783   MachineBasicBlock::iterator MI = BB->end();
1784   emitGEPOperation(BB, MI, I.getOperand(0),
1785                    I.op_begin()+1, I.op_end(), outputReg);
1786 }
1787
1788 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1789                             MachineBasicBlock::iterator &IP,
1790                             Value *Src, User::op_iterator IdxBegin,
1791                             User::op_iterator IdxEnd, unsigned TargetReg) {
1792   const TargetData &TD = TM.getTargetData();
1793   const Type *Ty = Src->getType();
1794   unsigned BaseReg = getReg(Src, MBB, IP);
1795
1796   // GEPs have zero or more indices; we must perform a struct access
1797   // or array access for each one.
1798   for (GetElementPtrInst::op_iterator oi = IdxBegin,
1799          oe = IdxEnd; oi != oe; ++oi) {
1800     Value *idx = *oi;
1801     unsigned NextReg = BaseReg;
1802     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1803       // It's a struct access.  idx is the index into the structure,
1804       // which names the field. This index must have ubyte type.
1805       const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1806       assert(CUI->getType() == Type::UByteTy
1807               && "Funny-looking structure index in GEP");
1808       // Use the TargetData structure to pick out what the layout of
1809       // the structure is in memory.  Since the structure index must
1810       // be constant, we can get its value and use it to find the
1811       // right byte offset from the StructLayout class's list of
1812       // structure member offsets.
1813       unsigned idxValue = CUI->getValue();
1814       unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1815       if (FieldOff) {
1816         NextReg = makeAnotherReg(Type::UIntTy);
1817         // Emit an ADD to add FieldOff to the basePtr.
1818         BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1819       }
1820       // The next type is the member of the structure selected by the
1821       // index.
1822       Ty = StTy->getElementTypes()[idxValue];
1823     } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1824       // It's an array or pointer access: [ArraySize x ElementType].
1825
1826       // idx is the index into the array.  Unlike with structure
1827       // indices, we may not know its actual value at code-generation
1828       // time.
1829       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1830
1831       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1832       // must find the size of the pointed-to type (Not coincidentally, the next
1833       // type is the type of the elements in the array).
1834       Ty = SqTy->getElementType();
1835       unsigned elementSize = TD.getTypeSize(Ty);
1836
1837       // If idxReg is a constant, we don't need to perform the multiply!
1838       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1839         if (!CSI->isNullValue()) {
1840           unsigned Offset = elementSize*CSI->getValue();
1841           NextReg = makeAnotherReg(Type::UIntTy);
1842           BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1843         }
1844       } else if (elementSize == 1) {
1845         // If the element size is 1, we don't have to multiply, just add
1846         unsigned idxReg = getReg(idx, MBB, IP);
1847         NextReg = makeAnotherReg(Type::UIntTy);
1848         BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1849       } else {
1850         unsigned idxReg = getReg(idx, MBB, IP);
1851         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1852         if (unsigned Shift = ExactLog2(elementSize)) {
1853           // If the element size is exactly a power of 2, use a shift to get it.
1854           BMI(MBB, IP, X86::SHLir32, 2,
1855               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1856         } else {
1857           // Most general case, emit a multiply...
1858           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1859           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1860         
1861           // Emit a MUL to multiply the register holding the index by
1862           // elementSize, putting the result in OffsetReg.
1863           doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1864         }
1865         // Emit an ADD to add OffsetReg to the basePtr.
1866         NextReg = makeAnotherReg(Type::UIntTy);
1867         BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1868       }
1869     }
1870     // Now that we are here, further indices refer to subtypes of this
1871     // one, so we don't need to worry about BaseReg itself, anymore.
1872     BaseReg = NextReg;
1873   }
1874   // After we have processed all the indices, the result is left in
1875   // BaseReg.  Move it to the register where we were expected to
1876   // put the answer.  A 32-bit move should do it, because we are in
1877   // ILP32 land.
1878   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1879 }
1880
1881
1882 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1883 /// frame manager, otherwise do it the hard way.
1884 ///
1885 void ISel::visitAllocaInst(AllocaInst &I) {
1886   // Find the data size of the alloca inst's getAllocatedType.
1887   const Type *Ty = I.getAllocatedType();
1888   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1889
1890   // If this is a fixed size alloca in the entry block for the function,
1891   // statically stack allocate the space.
1892   //
1893   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1894     if (I.getParent() == I.getParent()->getParent()->begin()) {
1895       TySize *= CUI->getValue();   // Get total allocated size...
1896       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1897       
1898       // Create a new stack object using the frame manager...
1899       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1900       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1901       return;
1902     }
1903   }
1904   
1905   // Create a register to hold the temporary result of multiplying the type size
1906   // constant by the variable amount.
1907   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1908   unsigned SrcReg1 = getReg(I.getArraySize());
1909   unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1910   BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1911   
1912   // TotalSizeReg = mul <numelements>, <TypeSize>
1913   MachineBasicBlock::iterator MBBI = BB->end();
1914   doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1915
1916   // AddedSize = add <TotalSizeReg>, 15
1917   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1918   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1919
1920   // AlignedSize = and <AddedSize>, ~15
1921   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1922   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1923   
1924   // Subtract size from stack pointer, thereby allocating some space.
1925   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1926
1927   // Put a pointer to the space into the result register, by copying
1928   // the stack pointer.
1929   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1930
1931   // Inform the Frame Information that we have just allocated a variable-sized
1932   // object.
1933   F->getFrameInfo()->CreateVariableSizedObject();
1934 }
1935
1936 /// visitMallocInst - Malloc instructions are code generated into direct calls
1937 /// to the library malloc.
1938 ///
1939 void ISel::visitMallocInst(MallocInst &I) {
1940   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1941   unsigned Arg;
1942
1943   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1944     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1945   } else {
1946     Arg = makeAnotherReg(Type::UIntTy);
1947     unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1948     unsigned Op1Reg = getReg(I.getOperand(0));
1949     MachineBasicBlock::iterator MBBI = BB->end();
1950     doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1951                
1952                
1953   }
1954
1955   std::vector<ValueRecord> Args;
1956   Args.push_back(ValueRecord(Arg, Type::UIntTy));
1957   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1958                                   1).addExternalSymbol("malloc", true);
1959   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1960 }
1961
1962
1963 /// visitFreeInst - Free instructions are code gen'd to call the free libc
1964 /// function.
1965 ///
1966 void ISel::visitFreeInst(FreeInst &I) {
1967   std::vector<ValueRecord> Args;
1968   Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1969                              I.getOperand(0)->getType()));
1970   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1971                                   1).addExternalSymbol("free", true);
1972   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1973 }
1974    
1975
1976 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1977 /// into a machine code representation is a very simple peep-hole fashion.  The
1978 /// generated code sucks but the implementation is nice and simple.
1979 ///
1980 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1981   return new ISel(TM);
1982 }