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