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