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