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