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