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