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