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