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