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