blob: 0379e9fc63f5f94815246e75ab9ea1bdd76b1bc5 [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2//
Chris Lattner3e130a22003-01-13 00:32:26 +00003// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +00004//
5//===----------------------------------------------------------------------===//
6
7#include "X86.h"
Chris Lattner055c9652002-10-29 21:05:24 +00008#include "X86InstrInfo.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +00009#include "X86InstrBuilder.h"
Chris Lattner72614082002-10-25 22:55:53 +000010#include "llvm/Function.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000011#include "llvm/Instructions.h"
Brian Gaeke20244b72002-12-12 15:33:40 +000012#include "llvm/DerivedTypes.h"
Chris Lattnerc5291f52002-10-27 21:16:59 +000013#include "llvm/Constants.h"
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000014#include "llvm/Pass.h"
Chris Lattnereca195e2003-05-08 19:44:13 +000015#include "llvm/Intrinsics.h"
Chris Lattner341a9372002-10-29 17:43:55 +000016#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000017#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner94af4142002-12-25 05:13:53 +000018#include "llvm/CodeGen/SSARegMap.h"
Chris Lattneraa09b752002-12-28 21:08:28 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner3e130a22003-01-13 00:32:26 +000020#include "llvm/CodeGen/MachineConstantPool.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000021#include "llvm/Target/TargetMachine.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000022#include "llvm/Target/MRegisterInfo.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000023#include "llvm/Support/InstVisitor.h"
Chris Lattner72614082002-10-25 22:55:53 +000024
Chris Lattner333b2fa2002-12-13 10:09:43 +000025/// BMI - A special BuildMI variant that takes an iterator to insert the
Chris Lattner8bdd1292003-04-25 21:58:54 +000026/// instruction at as well as a basic block. This is the version for when you
27/// have a destination register in mind.
Brian Gaeke71794c02002-12-13 11:22:48 +000028inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattner333b2fa2002-12-13 10:09:43 +000029 MachineBasicBlock::iterator &I,
30 MachineOpCode Opcode,
31 unsigned NumOperands,
32 unsigned DestReg) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000033 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattner333b2fa2002-12-13 10:09:43 +000034 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000035 I = MBB->insert(I, MI)+1;
Chris Lattner333b2fa2002-12-13 10:09:43 +000036 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
37}
38
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000039/// BMI - A special BuildMI variant that takes an iterator to insert the
40/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000041inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000042 MachineBasicBlock::iterator &I,
43 MachineOpCode Opcode,
44 unsigned NumOperands) {
Chris Lattner8bdd1292003-04-25 21:58:54 +000045 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000046 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000047 I = MBB->insert(I, MI)+1;
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000048 return MachineInstrBuilder(MI);
49}
50
Chris Lattner333b2fa2002-12-13 10:09:43 +000051
Chris Lattner72614082002-10-25 22:55:53 +000052namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000053 struct ISel : public FunctionPass, InstVisitor<ISel> {
54 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000055 MachineFunction *F; // The function we are compiling into
56 MachineBasicBlock *BB; // The current MBB we are compiling
57 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner72614082002-10-25 22:55:53 +000058
Chris Lattner72614082002-10-25 22:55:53 +000059 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
60
Chris Lattner333b2fa2002-12-13 10:09:43 +000061 // MBBMap - Mapping between LLVM BB -> Machine BB
62 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
63
Chris Lattner3e130a22003-01-13 00:32:26 +000064 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000065
66 /// runOnFunction - Top level implementation of instruction selection for
67 /// the entire function.
68 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000069 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000070 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000071
Chris Lattner065faeb2002-12-28 20:24:02 +000072 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000073 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
74 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
75
Chris Lattner14aa7fe2002-12-16 22:54:46 +000076 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000077
Chris Lattnerdbd73722003-05-06 21:32:22 +000078 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000079 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000080
Chris Lattner333b2fa2002-12-13 10:09:43 +000081 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000082 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000083
84 // Select the PHI nodes
85 SelectPHINodes();
86
Chris Lattner72614082002-10-25 22:55:53 +000087 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000088 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000089 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000090 return false; // We never modify the LLVM itself.
91 }
92
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000093 virtual const char *getPassName() const {
94 return "X86 Simple Instruction Selection";
95 }
96
Chris Lattner72614082002-10-25 22:55:53 +000097 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000098 /// block. This simply creates a new MachineBasicBlock to emit code into
99 /// and adds it to the current MachineFunction. Subsequent visit* for
100 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000101 ///
102 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000103 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000104 }
105
Chris Lattner065faeb2002-12-28 20:24:02 +0000106 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
107 /// from the stack into virtual registers.
108 ///
109 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000110
111 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
112 /// because we have to generate our sources into the source basic blocks,
113 /// not the current one.
114 ///
115 void SelectPHINodes();
116
Chris Lattner72614082002-10-25 22:55:53 +0000117 // Visitation methods for various instructions. These methods simply emit
118 // fixed X86 code for each instruction.
119 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000120
121 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000122 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000123 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000124
125 struct ValueRecord {
126 unsigned Reg;
127 const Type *Ty;
128 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
129 };
130 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
131 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000132 void visitCallInst(CallInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000133 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000134
135 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000136 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000137 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
138 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattner8a307e82002-12-16 19:32:50 +0000139 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000140 unsigned DestReg, const Type *DestTy,
141 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000142 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000143
Chris Lattnerf01729e2002-11-02 20:54:46 +0000144 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
145 void visitRem(BinaryOperator &B) { visitDivRem(B); }
146 void visitDivRem(BinaryOperator &B);
147
Chris Lattnere2954c82002-11-02 20:04:26 +0000148 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000149 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
150 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
151 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000152
Chris Lattner6d40c192003-01-16 16:43:00 +0000153 // Comparison operators...
154 void visitSetCondInst(SetCondInst &I);
155 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000156
157 // Memory Instructions
Chris Lattner3e130a22003-01-13 00:32:26 +0000158 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
159 MachineBasicBlock::iterator &MBBI,
160 const Type *Ty, unsigned DestReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000161 void visitLoadInst(LoadInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000162 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000163 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000164 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000165 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000166 void visitMallocInst(MallocInst &I);
167 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000168
Chris Lattnere2954c82002-11-02 20:04:26 +0000169 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000170 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000171 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000172 void visitCastInst(CastInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000173 void visitVarArgInst(VarArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000174
175 void visitInstruction(Instruction &I) {
176 std::cerr << "Cannot instruction select: " << I;
177 abort();
178 }
179
Brian Gaeke95780cc2002-12-13 07:56:18 +0000180 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000181 ///
182 void promote32(unsigned targetReg, const ValueRecord &VR);
183
184 /// EmitByteSwap - Byteswap SrcReg into DestReg.
185 ///
186 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
Brian Gaeke95780cc2002-12-13 07:56:18 +0000187
Chris Lattner3e130a22003-01-13 00:32:26 +0000188 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
189 /// constant expression GEP support.
190 ///
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000191 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000192 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000193 User::op_iterator IdxEnd, unsigned TargetReg);
194
Chris Lattner548f61d2003-04-23 17:22:12 +0000195 /// emitCastOperation - Common code shared between visitCastInst and
196 /// constant expression cast support.
197 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
198 Value *Src, const Type *DestTy, unsigned TargetReg);
199
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000200 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
201 /// and constant expression support.
202 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
203 MachineBasicBlock::iterator &IP,
204 Value *Op0, Value *Op1,
205 unsigned OperatorClass, unsigned TargetReg);
206
Chris Lattnerc5291f52002-10-27 21:16:59 +0000207 /// copyConstantToRegister - Output the instructions required to put the
208 /// specified constant into the specified register.
209 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000210 void copyConstantToRegister(MachineBasicBlock *MBB,
211 MachineBasicBlock::iterator &MBBI,
212 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000213
Chris Lattner3e130a22003-01-13 00:32:26 +0000214 /// makeAnotherReg - This method returns the next register number we haven't
215 /// yet used.
216 ///
217 /// Long values are handled somewhat specially. They are always allocated
218 /// as pairs of 32 bit integer values. The register number returned is the
219 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
220 /// of the long value.
221 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000222 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000223 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
224 const TargetRegisterClass *RC =
225 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
226 // Create the lower part
227 F->getSSARegMap()->createVirtualRegister(RC);
228 // Create the upper part.
229 return F->getSSARegMap()->createVirtualRegister(RC)-1;
230 }
231
Chris Lattnerc0812d82002-12-13 06:56:29 +0000232 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner94af4142002-12-25 05:13:53 +0000233 const TargetRegisterClass *RC =
234 TM.getRegisterInfo()->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000235 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000236 }
237
Chris Lattner72614082002-10-25 22:55:53 +0000238 /// getReg - This method turns an LLVM value into a register number. This
239 /// is guaranteed to produce the same register number for a particular value
240 /// every time it is queried.
241 ///
242 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000243 unsigned getReg(Value *V) {
244 // Just append to the end of the current bb.
245 MachineBasicBlock::iterator It = BB->end();
246 return getReg(V, BB, It);
247 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000248 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000249 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000250 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000251 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000252 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000253 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000254 }
Chris Lattner72614082002-10-25 22:55:53 +0000255
Chris Lattner6f8fd252002-10-27 21:23:43 +0000256 // If this operand is a constant, emit the code to copy the constant into
257 // the register here...
258 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000259 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000260 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000261 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000262 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
263 // Move the address of the global into the register
Chris Lattner3e130a22003-01-13 00:32:26 +0000264 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000265 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000266 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000267
Chris Lattner72614082002-10-25 22:55:53 +0000268 return Reg;
269 }
Chris Lattner72614082002-10-25 22:55:53 +0000270 };
271}
272
Chris Lattner43189d12002-11-17 20:07:45 +0000273/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
274/// Representation.
275///
276enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000277 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000278};
279
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000280/// getClass - Turn a primitive type into a "class" number which is based on the
281/// size of the type, and whether or not it is floating point.
282///
Chris Lattner43189d12002-11-17 20:07:45 +0000283static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000284 switch (Ty->getPrimitiveID()) {
285 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000286 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000287 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000288 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000289 case Type::IntTyID:
290 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000291 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000292
Chris Lattner94af4142002-12-25 05:13:53 +0000293 case Type::FloatTyID:
294 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000295
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000296 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000297 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000298 default:
299 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000300 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000301 }
302}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000303
Chris Lattner6b993cc2002-12-15 08:02:15 +0000304// getClassB - Just like getClass, but treat boolean values as bytes.
305static inline TypeClass getClassB(const Type *Ty) {
306 if (Ty == Type::BoolTy) return cByte;
307 return getClass(Ty);
308}
309
Chris Lattner06925362002-11-17 21:56:38 +0000310
Chris Lattnerc5291f52002-10-27 21:16:59 +0000311/// copyConstantToRegister - Output the instructions required to put the
312/// specified constant into the specified register.
313///
Chris Lattner8a307e82002-12-16 19:32:50 +0000314void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
315 MachineBasicBlock::iterator &IP,
316 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000317 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000318 unsigned Class = 0;
319 switch (CE->getOpcode()) {
320 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000321 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000322 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000323 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000324 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000325 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000326 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000327
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000328 case Instruction::Xor: ++Class; // FALL THROUGH
329 case Instruction::Or: ++Class; // FALL THROUGH
330 case Instruction::And: ++Class; // FALL THROUGH
331 case Instruction::Sub: ++Class; // FALL THROUGH
332 case Instruction::Add:
333 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
334 Class, R);
335 return;
336
337 default:
338 std::cerr << "Offending expr: " << C << "\n";
339 assert(0 && "Constant expressions not yet handled!\n");
340 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000341 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000342
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000343 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000344 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000345
346 if (Class == cLong) {
347 // Copy the value into the register pair.
348 uint64_t Val;
349 if (C->getType()->isSigned())
350 Val = cast<ConstantSInt>(C)->getValue();
351 else
352 Val = cast<ConstantUInt>(C)->getValue();
353
354 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
355 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
356 return;
357 }
358
Chris Lattner94af4142002-12-25 05:13:53 +0000359 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000360
361 static const unsigned IntegralOpcodeTab[] = {
362 X86::MOVir8, X86::MOVir16, X86::MOVir32
363 };
364
Chris Lattner6b993cc2002-12-15 08:02:15 +0000365 if (C->getType() == Type::BoolTy) {
366 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
367 } else if (C->getType()->isSigned()) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000368 ConstantSInt *CSI = cast<ConstantSInt>(C);
Chris Lattner3e130a22003-01-13 00:32:26 +0000369 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000370 } else {
371 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000372 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000373 }
Chris Lattner94af4142002-12-25 05:13:53 +0000374 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
375 double Value = CFP->getValue();
376 if (Value == +0.0)
377 BMI(MBB, IP, X86::FLD0, 0, R);
378 else if (Value == +1.0)
379 BMI(MBB, IP, X86::FLD1, 0, R);
380 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000381 // Otherwise we need to spill the constant to memory...
382 MachineConstantPool *CP = F->getConstantPool();
383 unsigned CPI = CP->getConstantPoolIndex(CFP);
384 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000385 }
386
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000387 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000388 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000389 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000390 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000391 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000392 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000393 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000394 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000395 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000396 }
397}
398
Chris Lattner065faeb2002-12-28 20:24:02 +0000399/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
400/// the stack into virtual registers.
401///
402void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
403 // Emit instructions to load the arguments... On entry to a function on the
404 // X86, the stack frame looks like this:
405 //
406 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000407 // [ESP + 4] -- first argument (leftmost lexically)
408 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000409 // ...
410 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000411 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000412 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000413
414 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
415 unsigned Reg = getReg(*I);
416
Chris Lattner065faeb2002-12-28 20:24:02 +0000417 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000418 switch (getClassB(I->getType())) {
419 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000420 FI = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000421 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
422 break;
423 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000424 FI = MFI->CreateFixedObject(2, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000425 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
426 break;
427 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000428 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000429 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
430 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000431 case cLong:
432 FI = MFI->CreateFixedObject(8, ArgOffset);
433 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
434 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
435 ArgOffset += 4; // longs require 4 additional bytes
436 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000437 case cFP:
438 unsigned Opcode;
439 if (I->getType() == Type::FloatTy) {
440 Opcode = X86::FLDr32;
Chris Lattneraa09b752002-12-28 21:08:28 +0000441 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000442 } else {
443 Opcode = X86::FLDr64;
Chris Lattneraa09b752002-12-28 21:08:28 +0000444 FI = MFI->CreateFixedObject(8, ArgOffset);
Chris Lattner3e130a22003-01-13 00:32:26 +0000445 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000446 }
447 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
448 break;
449 default:
450 assert(0 && "Unhandled argument type!");
451 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000452 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000453 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000454
455 // If the function takes variable number of arguments, add a frame offset for
456 // the start of the first vararg value... this is used to expand
457 // llvm.va_start.
458 if (Fn.getFunctionType()->isVarArg())
459 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000460}
461
462
Chris Lattner333b2fa2002-12-13 10:09:43 +0000463/// SelectPHINodes - Insert machine code to generate phis. This is tricky
464/// because we have to generate our sources into the source basic blocks, not
465/// the current one.
466///
467void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000468 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000469 const Function &LF = *F->getFunction(); // The LLVM function...
470 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
471 const BasicBlock *BB = I;
472 MachineBasicBlock *MBB = MBBMap[I];
473
474 // Loop over all of the PHI nodes in the LLVM basic block...
475 unsigned NumPHIs = 0;
476 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattner548f61d2003-04-23 17:22:12 +0000477 PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000478
Chris Lattner333b2fa2002-12-13 10:09:43 +0000479 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000480 unsigned PHIReg = getReg(*PN);
481 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
482 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
483
484 MachineInstr *LongPhiMI = 0;
485 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
486 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
487 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
488 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000489
Chris Lattnera6e73f12003-05-12 14:22:21 +0000490 // PHIValues - Map of blocks to incoming virtual registers. We use this
491 // so that we only initialize one incoming value for a particular block,
492 // even if the block has multiple entries in the PHI node.
493 //
494 std::map<MachineBasicBlock*, unsigned> PHIValues;
495
Chris Lattner333b2fa2002-12-13 10:09:43 +0000496 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
497 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000498 unsigned ValReg;
499 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
500 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000501
Chris Lattnera6e73f12003-05-12 14:22:21 +0000502 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
503 // We already inserted an initialization of the register for this
504 // predecessor. Recycle it.
505 ValReg = EntryIt->second;
506
507 } else {
508 // Get the incoming value into a virtual register. If it is not
509 // already available in a virtual register, insert the computation
510 // code into PredMBB
511 //
512 MachineBasicBlock::iterator PI = PredMBB->end();
513 while (PI != PredMBB->begin() &&
514 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
515 --PI;
516 ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
517
518 // Remember that we inserted a value for this PHI for this predecessor
519 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
520 }
521
Chris Lattner3e130a22003-01-13 00:32:26 +0000522 PhiMI->addRegOperand(ValReg);
523 PhiMI->addMachineBasicBlockOperand(PredMBB);
524 if (LongPhiMI) {
525 LongPhiMI->addRegOperand(ValReg+1);
526 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
527 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000528 }
529 }
530 }
531}
532
Chris Lattner6d40c192003-01-16 16:43:00 +0000533// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
534// the conditional branch instruction which is the only user of the cc
535// instruction. This is the case if the conditional branch is the only user of
536// the setcc, and if the setcc is in the same basic block as the conditional
537// branch. We also don't handle long arguments below, so we reject them here as
538// well.
539//
540static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
541 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
542 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
543 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
544 const Type *Ty = SCI->getOperand(0)->getType();
545 if (Ty != Type::LongTy && Ty != Type::ULongTy)
546 return SCI;
547 }
548 return 0;
549}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000550
Chris Lattner6d40c192003-01-16 16:43:00 +0000551// Return a fixed numbering for setcc instructions which does not depend on the
552// order of the opcodes.
553//
554static unsigned getSetCCNumber(unsigned Opcode) {
555 switch(Opcode) {
556 default: assert(0 && "Unknown setcc instruction!");
557 case Instruction::SetEQ: return 0;
558 case Instruction::SetNE: return 1;
559 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000560 case Instruction::SetGE: return 3;
561 case Instruction::SetGT: return 4;
562 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000563 }
564}
Chris Lattner06925362002-11-17 21:56:38 +0000565
Chris Lattner6d40c192003-01-16 16:43:00 +0000566// LLVM -> X86 signed X86 unsigned
567// ----- ---------- ------------
568// seteq -> sete sete
569// setne -> setne setne
570// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000571// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000572// setgt -> setg seta
573// setle -> setle setbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000574static const unsigned SetCCOpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000575 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
576 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
Chris Lattner6d40c192003-01-16 16:43:00 +0000577};
578
579bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
580
Brian Gaeke1749d632002-11-07 17:59:21 +0000581 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000582 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000583 bool isSigned = CompTy->isSigned();
Chris Lattner6d40c192003-01-16 16:43:00 +0000584 unsigned reg1 = getReg(Op0);
585 unsigned reg2 = getReg(Op1);
Chris Lattner05093a52002-11-21 15:52:38 +0000586
Chris Lattner3e130a22003-01-13 00:32:26 +0000587 unsigned Class = getClassB(CompTy);
588 switch (Class) {
589 default: assert(0 && "Unknown type class!");
590 // Emit: cmp <var1>, <var2> (do the comparison). We can
591 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
592 // 32-bit.
593 case cByte:
594 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
595 break;
596 case cShort:
597 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
598 break;
599 case cInt:
600 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
601 break;
602 case cFP:
603 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
604 BuildMI(BB, X86::FNSTSWr8, 0);
605 BuildMI(BB, X86::SAHF, 1);
606 isSigned = false; // Compare with unsigned operators
607 break;
608
609 case cLong:
610 if (OpNum < 2) { // seteq, setne
611 unsigned LoTmp = makeAnotherReg(Type::IntTy);
612 unsigned HiTmp = makeAnotherReg(Type::IntTy);
613 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
614 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
615 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
616 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
617 break; // Allow the sete or setne to be generated from flags set by OR
618 } else {
619 // Emit a sequence of code which compares the high and low parts once
620 // each, then uses a conditional move to handle the overflow case. For
621 // example, a setlt for long would generate code like this:
622 //
623 // AL = lo(op1) < lo(op2) // Signedness depends on operands
624 // BL = hi(op1) < hi(op2) // Always unsigned comparison
625 // dest = hi(op1) == hi(op2) ? AL : BL;
626 //
627
Chris Lattner6d40c192003-01-16 16:43:00 +0000628 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000629 // classes! Until then, hardcode registers so that we can deal with their
630 // aliases (because we don't have conditional byte moves).
631 //
632 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
Chris Lattner6d40c192003-01-16 16:43:00 +0000633 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000634 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
Chris Lattner6d40c192003-01-16 16:43:00 +0000635 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000636 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000637 // NOTE: visitSetCondInst knows that the value is dumped into the BL
638 // register at this point for long values...
639 return isSigned;
Chris Lattner3e130a22003-01-13 00:32:26 +0000640 }
641 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000642 return isSigned;
643}
Chris Lattner3e130a22003-01-13 00:32:26 +0000644
Chris Lattner6d40c192003-01-16 16:43:00 +0000645
646/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
647/// register, then move it to wherever the result should be.
648///
649void ISel::visitSetCondInst(SetCondInst &I) {
650 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
651
652 unsigned OpNum = getSetCCNumber(I.getOpcode());
653 unsigned DestReg = getReg(I);
654 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
655 I.getOperand(1));
656
657 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
658 // Handle normal comparisons with a setcc instruction...
659 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
660 } else {
661 // Handle long comparisons by copying the value which is already in BL into
662 // the register we want...
663 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
664 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000665}
Chris Lattner51b49a92002-11-02 19:45:49 +0000666
Brian Gaekec2505982002-11-30 11:57:28 +0000667/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
668/// operand, in the specified target register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000669void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
670 bool isUnsigned = VR.Ty->isUnsigned();
671 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000672 case cByte:
673 // Extend value into target register (8->32)
674 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000675 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000676 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000677 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000678 break;
679 case cShort:
680 // Extend value into target register (16->32)
681 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000682 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000683 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000684 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000685 break;
686 case cInt:
687 // Move value into target register (32->32)
Chris Lattner3e130a22003-01-13 00:32:26 +0000688 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000689 break;
690 default:
691 assert(0 && "Unpromotable operand class in promote32");
692 }
Brian Gaekec2505982002-11-30 11:57:28 +0000693}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000694
Chris Lattner72614082002-10-25 22:55:53 +0000695/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
696/// we have the following possibilities:
697///
698/// ret void: No return value, simply emit a 'ret' instruction
699/// ret sbyte, ubyte : Extend value into EAX and return
700/// ret short, ushort: Extend value into EAX and return
701/// ret int, uint : Move value into EAX and return
702/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000703/// ret long, ulong : Move value into EAX/EDX and return
704/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000705///
Chris Lattner3e130a22003-01-13 00:32:26 +0000706void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000707 if (I.getNumOperands() == 0) {
708 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
709 return;
710 }
711
712 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000713 unsigned RetReg = getReg(RetVal);
714 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000715 case cByte: // integral return values: extend or move into EAX and return
716 case cShort:
717 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000718 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattnerdbd73722003-05-06 21:32:22 +0000719 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000720 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000721 break;
722 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000723 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000724 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000725 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000726 break;
727 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000728 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
729 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000730 // Declare that EAX & EDX are live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000731 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000732 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000733 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000734 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +0000735 }
Chris Lattner43189d12002-11-17 20:07:45 +0000736 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +0000737 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000738}
739
Chris Lattner55f6fab2003-01-16 18:07:23 +0000740// getBlockAfter - Return the basic block which occurs lexically after the
741// specified one.
742static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
743 Function::iterator I = BB; ++I; // Get iterator to next block
744 return I != BB->getParent()->end() ? &*I : 0;
745}
746
Chris Lattner51b49a92002-11-02 19:45:49 +0000747/// visitBranchInst - Handle conditional and unconditional branches here. Note
748/// that since code layout is frozen at this point, that if we are trying to
749/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +0000750/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +0000751///
Chris Lattner94af4142002-12-25 05:13:53 +0000752void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000753 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
754
755 if (!BI.isConditional()) { // Unconditional branch?
756 if (BI.getSuccessor(0) != NextBB)
757 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +0000758 return;
759 }
760
761 // See if we can fold the setcc into the branch itself...
762 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
763 if (SCI == 0) {
764 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
765 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +0000766 unsigned condReg = getReg(BI.getCondition());
Chris Lattner94af4142002-12-25 05:13:53 +0000767 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
Chris Lattner55f6fab2003-01-16 18:07:23 +0000768 if (BI.getSuccessor(1) == NextBB) {
769 if (BI.getSuccessor(0) != NextBB)
770 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
771 } else {
772 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
773
774 if (BI.getSuccessor(0) != NextBB)
775 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
776 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000777 return;
Chris Lattner94af4142002-12-25 05:13:53 +0000778 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000779
780 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
781 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
782 SCI->getOperand(1));
783
784 // LLVM -> X86 signed X86 unsigned
785 // ----- ---------- ------------
786 // seteq -> je je
787 // setne -> jne jne
788 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000789 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +0000790 // setgt -> jg ja
791 // setle -> jle jbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000792 static const unsigned OpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000793 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
794 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
Chris Lattner6d40c192003-01-16 16:43:00 +0000795 };
796
Chris Lattner55f6fab2003-01-16 18:07:23 +0000797 if (BI.getSuccessor(0) != NextBB) {
798 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
799 if (BI.getSuccessor(1) != NextBB)
800 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
801 } else {
802 // Change to the inverse condition...
803 if (BI.getSuccessor(1) != NextBB) {
804 OpNum ^= 1;
805 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
806 }
807 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000808}
809
Chris Lattner3e130a22003-01-13 00:32:26 +0000810
811/// doCall - This emits an abstract call instruction, setting up the arguments
812/// and the return value as appropriate. For the actual function call itself,
813/// it inserts the specified CallMI instruction into the stream.
814///
815void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
816 const std::vector<ValueRecord> &Args) {
817
Chris Lattner065faeb2002-12-28 20:24:02 +0000818 // Count how many bytes are to be pushed on the stack...
819 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000820
Chris Lattner3e130a22003-01-13 00:32:26 +0000821 if (!Args.empty()) {
822 for (unsigned i = 0, e = Args.size(); i != e; ++i)
823 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000824 case cByte: case cShort: case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000825 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000826 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000827 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000828 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000829 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
Chris Lattner065faeb2002-12-28 20:24:02 +0000830 break;
831 default: assert(0 && "Unknown class!");
832 }
833
834 // Adjust the stack pointer for the new arguments...
835 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
836
837 // Arguments go on the stack in reverse order, as specified by the ABI.
838 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +0000839 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
840 unsigned ArgReg = Args[i].Reg;
841 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000842 case cByte:
843 case cShort: {
844 // Promote arg to 32 bits wide into a temporary register...
845 unsigned R = makeAnotherReg(Type::UIntTy);
Chris Lattner3e130a22003-01-13 00:32:26 +0000846 promote32(R, Args[i]);
Chris Lattner065faeb2002-12-28 20:24:02 +0000847 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
848 X86::ESP, ArgOffset).addReg(R);
849 break;
850 }
851 case cInt:
852 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000853 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000854 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000855 case cLong:
856 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
857 X86::ESP, ArgOffset).addReg(ArgReg);
858 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
859 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
860 ArgOffset += 4; // 8 byte entry, not 4.
861 break;
862
Chris Lattner065faeb2002-12-28 20:24:02 +0000863 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000864 if (Args[i].Ty == Type::FloatTy) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000865 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000866 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000867 } else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000868 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
869 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
870 X86::ESP, ArgOffset).addReg(ArgReg);
871 ArgOffset += 4; // 8 byte entry, not 4.
Chris Lattner065faeb2002-12-28 20:24:02 +0000872 }
873 break;
874
Chris Lattner3e130a22003-01-13 00:32:26 +0000875 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +0000876 }
877 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +0000878 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000879 } else {
880 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +0000881 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +0000882
Chris Lattner3e130a22003-01-13 00:32:26 +0000883 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000884
Chris Lattner065faeb2002-12-28 20:24:02 +0000885 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +0000886
887 // If there is a return value, scavenge the result from the location the call
888 // leaves it in...
889 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000890 if (Ret.Ty != Type::VoidTy) {
891 unsigned DestClass = getClassB(Ret.Ty);
892 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000893 case cByte:
894 case cShort:
895 case cInt: {
896 // Integral results are in %eax, or the appropriate portion
897 // thereof.
898 static const unsigned regRegMove[] = {
899 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
900 };
901 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000902 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000903 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000904 }
Chris Lattner94af4142002-12-25 05:13:53 +0000905 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000906 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000907 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000908 case cLong: // Long values are left in EDX:EAX
909 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
910 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
911 break;
912 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000913 }
Chris Lattnera3243642002-12-04 23:45:28 +0000914 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000915}
Chris Lattner2df035b2002-11-02 19:27:56 +0000916
Chris Lattner3e130a22003-01-13 00:32:26 +0000917
918/// visitCallInst - Push args on stack and do a procedure call instruction.
919void ISel::visitCallInst(CallInst &CI) {
920 MachineInstr *TheCall;
921 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +0000922 // Is it an intrinsic function call?
923 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
924 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
925 return;
926 }
927
Chris Lattner3e130a22003-01-13 00:32:26 +0000928 // Emit a CALL instruction with PC-relative displacement.
929 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
930 } else { // Emit an indirect call...
931 unsigned Reg = getReg(CI.getCalledValue());
932 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
933 }
934
935 std::vector<ValueRecord> Args;
936 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
937 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
938 CI.getOperand(i)->getType()));
939
940 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
941 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
942}
943
Chris Lattnereca195e2003-05-08 19:44:13 +0000944void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
945 unsigned TmpReg1, TmpReg2;
946 switch (ID) {
947 case LLVMIntrinsic::va_start:
948 // Get the address of the first vararg value...
949 TmpReg1 = makeAnotherReg(Type::UIntTy);
950 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
951 TmpReg2 = getReg(CI.getOperand(1));
952 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
953 return;
954
955 case LLVMIntrinsic::va_end: return; // Noop on X86
956 case LLVMIntrinsic::va_copy:
957 TmpReg1 = getReg(CI.getOperand(2)); // Get existing va_list
958 TmpReg2 = getReg(CI.getOperand(1)); // Get va_list* to store into
959 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
960 return;
961
962 default: assert(0 && "Unknown intrinsic for X86!");
963 }
964}
965
966
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000967/// visitSimpleBinary - Implement simple binary operators for integral types...
968/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
969/// Xor.
970void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
971 unsigned DestReg = getReg(B);
972 MachineBasicBlock::iterator MI = BB->end();
973 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
974 OperatorClass, DestReg);
975}
Chris Lattner3e130a22003-01-13 00:32:26 +0000976
Chris Lattner68aad932002-11-02 20:13:22 +0000977/// visitSimpleBinary - Implement simple binary operators for integral types...
978/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
979/// 4 for Xor.
980///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000981/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
982/// and constant expression support.
983void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
984 MachineBasicBlock::iterator &IP,
985 Value *Op0, Value *Op1,
986 unsigned OperatorClass,unsigned TargetReg){
987 unsigned Class = getClassB(Op0->getType());
Chris Lattnere2954c82002-11-02 20:04:26 +0000988
989 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000990 // Arithmetic operators
Chris Lattner94af4142002-12-25 05:13:53 +0000991 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
992 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
Chris Lattner68aad932002-11-02 20:13:22 +0000993
994 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000995 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
996 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
997 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
998 };
Chris Lattner3e130a22003-01-13 00:32:26 +0000999
1000 bool isLong = false;
1001 if (Class == cLong) {
1002 isLong = true;
1003 Class = cInt; // Bottom 32 bits are handled just like ints
1004 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001005
1006 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner94af4142002-12-25 05:13:53 +00001007 assert(Opcode && "Floating point arguments to logical inst?");
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001008 unsigned Op0r = getReg(Op0, BB, IP);
1009 unsigned Op1r = getReg(Op1, BB, IP);
1010 BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001011
1012 if (isLong) { // Handle the upper 32 bits of long values...
1013 static const unsigned TopTab[] = {
1014 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1015 };
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001016 BMI(BB, IP, TopTab[OperatorClass], 2,
1017 TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001018 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001019}
1020
Chris Lattner3e130a22003-01-13 00:32:26 +00001021/// doMultiply - Emit appropriate instructions to multiply together the
1022/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1023/// result should be given as DestTy.
1024///
1025/// FIXME: doMultiply should use one of the two address IMUL instructions!
1026///
Chris Lattner8a307e82002-12-16 19:32:50 +00001027void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00001028 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00001029 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001030 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001031 switch (Class) {
1032 case cFP: // Floating point multiply
Chris Lattner3e130a22003-01-13 00:32:26 +00001033 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001034 return;
1035 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001036 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00001037 case cByte:
1038 case cShort:
1039 case cInt: // Small integerals, handled below...
1040 break;
1041 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001042
1043 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001044 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
Brian Gaeke20244b72002-12-12 15:33:40 +00001045 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1046 unsigned Reg = Regs[Class];
1047
1048 // Emit a MOV to put the first operand into the appropriately-sized
1049 // subreg of EAX.
Chris Lattner3e130a22003-01-13 00:32:26 +00001050 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001051
1052 // Emit the appropriate multiply instruction.
Chris Lattner3e130a22003-01-13 00:32:26 +00001053 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001054
1055 // Emit another MOV to put the result into the destination register.
Chris Lattner3e130a22003-01-13 00:32:26 +00001056 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001057}
1058
Chris Lattnerca9671d2002-11-02 20:28:58 +00001059/// visitMul - Multiplies are not simple binary operators because they must deal
1060/// with the EAX register explicitly.
1061///
1062void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00001063 unsigned Op0Reg = getReg(I.getOperand(0));
1064 unsigned Op1Reg = getReg(I.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +00001065 unsigned DestReg = getReg(I);
1066
1067 // Simple scalar multiply?
1068 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1069 MachineBasicBlock::iterator MBBI = BB->end();
1070 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1071 } else {
1072 // Long value. We have to do things the hard way...
1073 // Multiply the two low parts... capturing carry into EDX
1074 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1075 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1076
1077 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1078 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1079 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1080
1081 MachineBasicBlock::iterator MBBI = BB->end();
1082 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1083 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1084
1085 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1086 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1087 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1088
1089 MBBI = BB->end();
1090 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1091 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1092
1093 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1094 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1095 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001096}
Chris Lattnerca9671d2002-11-02 20:28:58 +00001097
Chris Lattner06925362002-11-17 21:56:38 +00001098
Chris Lattnerf01729e2002-11-02 20:54:46 +00001099/// visitDivRem - Handle division and remainder instructions... these
1100/// instruction both require the same instructions to be generated, they just
1101/// select the result from a different register. Note that both of these
1102/// instructions work differently for signed and unsigned operands.
1103///
1104void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001105 unsigned Class = getClass(I.getType());
1106 unsigned Op0Reg = getReg(I.getOperand(0));
1107 unsigned Op1Reg = getReg(I.getOperand(1));
1108 unsigned ResultReg = getReg(I);
1109
1110 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001111 case cFP: // Floating point divide
Chris Lattner94af4142002-12-25 05:13:53 +00001112 if (I.getOpcode() == Instruction::Div)
1113 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001114 else { // Floating point remainder...
1115 MachineInstr *TheCall =
1116 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1117 std::vector<ValueRecord> Args;
1118 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1119 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1120 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1121 }
Chris Lattner94af4142002-12-25 05:13:53 +00001122 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001123 case cLong: {
1124 static const char *FnName[] =
1125 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1126
1127 unsigned NameIdx = I.getType()->isUnsigned()*2;
1128 NameIdx += I.getOpcode() == Instruction::Div;
1129 MachineInstr *TheCall =
1130 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1131
1132 std::vector<ValueRecord> Args;
1133 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1134 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1135 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1136 return;
1137 }
1138 case cByte: case cShort: case cInt:
1139 break; // Small integerals, handled below...
1140 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001141 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001142
1143 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1144 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +00001145 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001146 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1147 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1148
1149 static const unsigned DivOpcode[][4] = {
Chris Lattner3e130a22003-01-13 00:32:26 +00001150 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1151 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001152 };
1153
1154 bool isSigned = I.getType()->isSigned();
1155 unsigned Reg = Regs[Class];
1156 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001157
1158 // Put the first operand into one of the A registers...
1159 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1160
1161 if (isSigned) {
1162 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +00001163 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001164 } else {
1165 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1166 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1167 }
1168
Chris Lattner06925362002-11-17 21:56:38 +00001169 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +00001170 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001171
Chris Lattnerf01729e2002-11-02 20:54:46 +00001172 // Figure out which register we want to pick the result out of...
1173 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1174
Chris Lattnerf01729e2002-11-02 20:54:46 +00001175 // Put the result into the destination register...
Chris Lattner94af4142002-12-25 05:13:53 +00001176 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001177}
Chris Lattnere2954c82002-11-02 20:04:26 +00001178
Chris Lattner06925362002-11-17 21:56:38 +00001179
Brian Gaekea1719c92002-10-31 23:03:59 +00001180/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1181/// for constant immediate shift values, and for constant immediate
1182/// shift values equal to 1. Even the general case is sort of special,
1183/// because the shift amount has to be in CL, not just any old register.
1184///
Chris Lattner3e130a22003-01-13 00:32:26 +00001185void ISel::visitShiftInst(ShiftInst &I) {
1186 unsigned SrcReg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +00001187 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +00001188 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3e130a22003-01-13 00:32:26 +00001189 bool isSigned = I.getType()->isSigned();
1190 unsigned Class = getClass(I.getType());
1191
1192 static const unsigned ConstantOperand[][4] = {
1193 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1194 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1195 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1196 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1197 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001198
Chris Lattner3e130a22003-01-13 00:32:26 +00001199 static const unsigned NonConstantOperand[][4] = {
1200 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1201 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1202 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1203 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1204 };
Chris Lattner796df732002-11-02 00:44:25 +00001205
Chris Lattner3e130a22003-01-13 00:32:26 +00001206 // Longs, as usual, are handled specially...
1207 if (Class == cLong) {
1208 // If we have a constant shift, we can generate much more efficient code
1209 // than otherwise...
1210 //
1211 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1212 unsigned Amount = CUI->getValue();
1213 if (Amount < 32) {
1214 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1215 if (isLeftShift) {
1216 BuildMI(BB, Opc[3], 3,
1217 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1218 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1219 } else {
1220 BuildMI(BB, Opc[3], 3,
1221 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1222 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1223 }
1224 } else { // Shifting more than 32 bits
1225 Amount -= 32;
1226 if (isLeftShift) {
1227 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1228 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1229 } else {
1230 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1231 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1232 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1233 }
1234 }
1235 } else {
1236 visitInstruction(I); // FIXME: Implement long shift by non-constant
Brian Gaekea1719c92002-10-31 23:03:59 +00001237 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001238 return;
1239 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001240
Chris Lattner3e130a22003-01-13 00:32:26 +00001241 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1242 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1243 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001244
Chris Lattner3e130a22003-01-13 00:32:26 +00001245 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1246 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1247 } else { // The shift amount is non-constant.
1248 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001249
Chris Lattner3e130a22003-01-13 00:32:26 +00001250 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1251 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1252 }
1253}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001254
Chris Lattner3e130a22003-01-13 00:32:26 +00001255
1256/// doFPLoad - This method is used to load an FP value from memory using the
1257/// current endianness. NOTE: This method returns a partially constructed load
1258/// instruction which needs to have the memory source filled in still.
1259///
1260MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1261 MachineBasicBlock::iterator &MBBI,
1262 const Type *Ty, unsigned DestReg) {
1263 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1264 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1265
1266 if (TM.getTargetData().isLittleEndian()) // fast path...
1267 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1268
1269 // If we are big-endian, start by creating an LEA instruction to represent the
1270 // address of the memory location to load from...
1271 //
1272 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1273 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1274
1275 // Allocate a temporary stack slot to transform the value into...
1276 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1277
1278 // Perform the bswaps 32 bits at a time...
1279 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1280 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1281 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1282 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1283 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1284 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1285 FrameIdx, Offset).addReg(TmpReg2);
1286
1287 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1288 TmpReg1 = makeAnotherReg(Type::UIntTy);
1289 TmpReg2 = makeAnotherReg(Type::UIntTy);
1290
1291 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1292 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1293 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1294 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1295 }
1296
1297 // Now we can reload the final byteswapped result into the final destination.
1298 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1299 return Result;
1300}
1301
1302/// EmitByteSwap - Byteswap SrcReg into DestReg.
1303///
1304void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1305 // Emit the byte swap instruction...
1306 switch (Class) {
1307 case cByte:
Misha Brukmanbaf06072003-04-22 17:54:23 +00001308 // No byteswap necessary for 8 bit value...
Chris Lattner3e130a22003-01-13 00:32:26 +00001309 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1310 break;
1311 case cInt:
1312 // Use the 32 bit bswap instruction to do a 32 bit swap...
1313 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1314 break;
1315
1316 case cShort:
1317 // For 16 bit we have to use an xchg instruction, because there is no
Misha Brukmanbaf06072003-04-22 17:54:23 +00001318 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
Chris Lattner3e130a22003-01-13 00:32:26 +00001319 // into AX to do the xchg.
1320 //
1321 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1322 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1323 .addReg(X86::AH, MOTy::UseAndDef);
1324 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1325 break;
1326 default: assert(0 && "Cannot byteswap this class!");
1327 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001328}
1329
Chris Lattner06925362002-11-17 21:56:38 +00001330
Chris Lattner6fc3c522002-11-17 21:11:55 +00001331/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001332/// instruction. The load and store instructions are the only place where we
1333/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001334///
1335void ISel::visitLoadInst(LoadInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001336 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1337 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner94af4142002-12-25 05:13:53 +00001338 unsigned SrcAddrReg = getReg(I.getOperand(0));
1339 unsigned DestReg = getReg(I);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001340
Chris Lattner6fc3c522002-11-17 21:11:55 +00001341 unsigned Class = getClass(I.getType());
Chris Lattner94af4142002-12-25 05:13:53 +00001342 switch (Class) {
Chris Lattner94af4142002-12-25 05:13:53 +00001343 case cFP: {
Chris Lattner3e130a22003-01-13 00:32:26 +00001344 MachineBasicBlock::iterator MBBI = BB->end();
1345 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001346 return;
1347 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001348 case cLong: case cInt: case cShort: case cByte:
1349 break; // Integers of various sizes handled below
1350 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001351 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001352
Chris Lattnere8f0d922002-12-24 00:03:11 +00001353 // We need to adjust the input pointer if we are emulating a big-endian
1354 // long-pointer target. On these systems, the pointer that we are interested
1355 // in is in the upper part of the eight byte memory image of the pointer. It
1356 // also happens to be byte-swapped, but this will be handled later.
1357 //
1358 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1359 unsigned R = makeAnotherReg(Type::UIntTy);
1360 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1361 SrcAddrReg = R;
1362 }
Chris Lattner94af4142002-12-25 05:13:53 +00001363
Chris Lattnere8f0d922002-12-24 00:03:11 +00001364 unsigned IReg = DestReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001365 if (!isLittleEndian) // If big endian we need an intermediate stage
1366 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001367
Chris Lattner3e130a22003-01-13 00:32:26 +00001368 static const unsigned Opcode[] = {
1369 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1370 };
Chris Lattnere8f0d922002-12-24 00:03:11 +00001371 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1372
Chris Lattner3e130a22003-01-13 00:32:26 +00001373 // Handle long values now...
1374 if (Class == cLong) {
1375 if (isLittleEndian) {
1376 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1377 } else {
1378 EmitByteSwap(IReg+1, DestReg, cInt);
1379 unsigned TempReg = makeAnotherReg(Type::IntTy);
1380 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1381 EmitByteSwap(IReg, TempReg, cInt);
Chris Lattner94af4142002-12-25 05:13:53 +00001382 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001383 return;
1384 }
1385
1386 if (!isLittleEndian)
1387 EmitByteSwap(IReg, DestReg, Class);
1388}
1389
1390
1391/// doFPStore - This method is used to store an FP value to memory using the
1392/// current endianness.
1393///
1394void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1395 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1396 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1397
1398 if (TM.getTargetData().isLittleEndian()) { // fast path...
1399 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1400 return;
1401 }
1402
1403 // Allocate a temporary stack slot to transform the value into...
1404 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1405 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1406 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1407
1408 // Store the value into a temporary stack slot...
1409 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1410
1411 // Perform the bswaps 32 bits at a time...
1412 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1413 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1414 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1415 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1416 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1417 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1418 DestAddrReg, Offset).addReg(TmpReg2);
1419
1420 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1421 TmpReg1 = makeAnotherReg(Type::UIntTy);
1422 TmpReg2 = makeAnotherReg(Type::UIntTy);
1423
1424 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1425 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1426 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1427 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001428 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001429}
1430
Chris Lattner06925362002-11-17 21:56:38 +00001431
Chris Lattner6fc3c522002-11-17 21:11:55 +00001432/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1433/// instruction.
1434///
1435void ISel::visitStoreInst(StoreInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001436 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1437 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner3e130a22003-01-13 00:32:26 +00001438 unsigned ValReg = getReg(I.getOperand(0));
1439 unsigned AddressReg = getReg(I.getOperand(1));
Chris Lattnere8f0d922002-12-24 00:03:11 +00001440
Chris Lattner94af4142002-12-25 05:13:53 +00001441 unsigned Class = getClass(I.getOperand(0)->getType());
1442 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001443 case cLong:
1444 if (isLittleEndian) {
1445 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1446 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1447 AddressReg, 4).addReg(ValReg+1);
1448 } else {
1449 unsigned T1 = makeAnotherReg(Type::IntTy);
1450 unsigned T2 = makeAnotherReg(Type::IntTy);
1451 EmitByteSwap(T1, ValReg , cInt);
1452 EmitByteSwap(T2, ValReg+1, cInt);
1453 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1454 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1455 }
Chris Lattner94af4142002-12-25 05:13:53 +00001456 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001457 case cFP:
1458 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1459 return;
1460 case cInt: case cShort: case cByte:
1461 break; // Integers of various sizes handled below
1462 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001463 }
1464
1465 if (!isLittleEndian && hasLongPointers &&
1466 isa<PointerType>(I.getOperand(0)->getType())) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001467 unsigned R = makeAnotherReg(Type::UIntTy);
1468 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1469 AddressReg = R;
1470 }
1471
Chris Lattner94af4142002-12-25 05:13:53 +00001472 if (!isLittleEndian && Class != cByte) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001473 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1474 EmitByteSwap(R, ValReg, Class);
1475 ValReg = R;
Chris Lattnere8f0d922002-12-24 00:03:11 +00001476 }
1477
Chris Lattner94af4142002-12-25 05:13:53 +00001478 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner6fc3c522002-11-17 21:11:55 +00001479 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1480}
1481
1482
Brian Gaekec11232a2002-11-26 10:43:30 +00001483/// visitCastInst - Here we have various kinds of copying with or without
1484/// sign extension going on.
Chris Lattner3e130a22003-01-13 00:32:26 +00001485void ISel::visitCastInst(CastInst &CI) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001486 unsigned DestReg = getReg(CI);
1487 MachineBasicBlock::iterator MI = BB->end();
1488 emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1489}
1490
1491/// emitCastOperation - Common code shared between visitCastInst and
1492/// constant expression cast support.
1493void ISel::emitCastOperation(MachineBasicBlock *BB,
1494 MachineBasicBlock::iterator &IP,
1495 Value *Src, const Type *DestTy,
1496 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00001497 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001498 const Type *SrcTy = Src->getType();
1499 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00001500 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00001501
Chris Lattner3e130a22003-01-13 00:32:26 +00001502 // Implement casts to bool by using compare on the operand followed by set if
1503 // not zero on the result.
1504 if (DestTy == Type::BoolTy) {
1505 if (SrcClass == cFP || SrcClass == cLong)
Chris Lattner548f61d2003-04-23 17:22:12 +00001506 abort(); // FIXME: implement cast (long & FP) to bool
Chris Lattner3e130a22003-01-13 00:32:26 +00001507
Chris Lattner548f61d2003-04-23 17:22:12 +00001508 BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1509 BMI(BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001510 return;
1511 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001512
1513 static const unsigned RegRegMove[] = {
1514 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1515 };
1516
1517 // Implement casts between values of the same type class (as determined by
1518 // getClass) by using a register-to-register move.
1519 if (SrcClass == DestClass) {
1520 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001521 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001522 } else if (SrcClass == cFP) {
1523 if (SrcTy == Type::FloatTy) { // double -> float
1524 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001525 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001526 } else { // float -> double
1527 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1528 "Unknown cFP member!");
1529 // Truncate from double to float by storing to memory as short, then
1530 // reading it back.
1531 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1532 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner548f61d2003-04-23 17:22:12 +00001533 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1534 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001535 }
1536 } else if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001537 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1538 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001539 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00001540 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001541 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00001542 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001543 return;
1544 }
1545
1546 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1547 // or zero extension, depending on whether the source type was signed.
1548 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1549 SrcClass < DestClass) {
1550 bool isLong = DestClass == cLong;
1551 if (isLong) DestClass = cInt;
1552
1553 static const unsigned Opc[][4] = {
1554 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1555 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1556 };
1557
1558 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattner548f61d2003-04-23 17:22:12 +00001559 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1560 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001561
1562 if (isLong) { // Handle upper 32 bits as appropriate...
1563 if (isUnsigned) // Zero out top bits...
Chris Lattner548f61d2003-04-23 17:22:12 +00001564 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001565 else // Sign extend bottom half...
Chris Lattner548f61d2003-04-23 17:22:12 +00001566 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00001567 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001568 return;
1569 }
1570
1571 // Special case long -> int ...
1572 if (SrcClass == cLong && DestClass == cInt) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001573 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001574 return;
1575 }
1576
1577 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1578 // move out of AX or AL.
1579 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1580 && SrcClass > DestClass) {
1581 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattner548f61d2003-04-23 17:22:12 +00001582 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1583 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00001584 return;
1585 }
1586
1587 // Handle casts from integer to floating point now...
1588 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001589 // Promote the integer to a type supported by FLD. We do this because there
1590 // are no unsigned FLD instructions, so we must promote an unsigned value to
1591 // a larger signed value, then use FLD on the larger value.
1592 //
1593 const Type *PromoteType = 0;
1594 unsigned PromoteOpcode;
1595 switch (SrcTy->getPrimitiveID()) {
1596 case Type::BoolTyID:
1597 case Type::SByteTyID:
1598 // We don't have the facilities for directly loading byte sized data from
1599 // memory (even signed). Promote it to 16 bits.
1600 PromoteType = Type::ShortTy;
1601 PromoteOpcode = X86::MOVSXr16r8;
1602 break;
1603 case Type::UByteTyID:
1604 PromoteType = Type::ShortTy;
1605 PromoteOpcode = X86::MOVZXr16r8;
1606 break;
1607 case Type::UShortTyID:
1608 PromoteType = Type::IntTy;
1609 PromoteOpcode = X86::MOVZXr32r16;
1610 break;
1611 case Type::UIntTyID: {
1612 // Make a 64 bit temporary... and zero out the top of it...
1613 unsigned TmpReg = makeAnotherReg(Type::LongTy);
1614 BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1615 BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1616 SrcTy = Type::LongTy;
1617 SrcClass = cLong;
1618 SrcReg = TmpReg;
1619 break;
1620 }
1621 case Type::ULongTyID:
1622 assert("FIXME: not implemented: cast ulong X to fp type!");
1623 default: // No promotion needed...
1624 break;
1625 }
1626
1627 if (PromoteType) {
1628 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner548f61d2003-04-23 17:22:12 +00001629 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1630 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001631 SrcTy = PromoteType;
1632 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00001633 SrcReg = TmpReg;
1634 }
1635
1636 // Spill the integer to memory and reload it from there...
1637 int FrameIdx =
1638 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1639
1640 if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001641 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1642 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001643 FrameIdx, 4).addReg(SrcReg+1);
1644 } else {
1645 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001646 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001647 }
1648
1649 static const unsigned Op2[] =
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001650 { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001651 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001652 return;
1653 }
1654
1655 // Handle casts from floating point to integer now...
1656 if (SrcClass == cFP) {
1657 // Change the floating point control register to use "round towards zero"
1658 // mode when truncating to an integer value.
1659 //
1660 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Chris Lattner548f61d2003-04-23 17:22:12 +00001661 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001662
1663 // Load the old value of the high byte of the control word...
1664 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Chris Lattner548f61d2003-04-23 17:22:12 +00001665 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001666
1667 // Set the high part to be round to zero...
Chris Lattner548f61d2003-04-23 17:22:12 +00001668 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00001669
1670 // Reload the modified control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001671 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001672
1673 // Restore the memory image of control word to original value
Chris Lattner548f61d2003-04-23 17:22:12 +00001674 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001675 CWFrameIdx, 1).addReg(HighPartOfCW);
1676
1677 // We don't have the facilities for directly storing byte sized data to
1678 // memory. Promote it to 16 bits. We also must promote unsigned values to
1679 // larger classes because we only have signed FP stores.
1680 unsigned StoreClass = DestClass;
1681 const Type *StoreTy = DestTy;
1682 if (StoreClass == cByte || DestTy->isUnsigned())
1683 switch (StoreClass) {
1684 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1685 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1686 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner9d6d1182003-05-12 21:16:26 +00001687 case cLong:
1688 assert(0 &&"FIXME not implemented: cast FP to unsigned long long");
1689 abort();
Chris Lattner3e130a22003-01-13 00:32:26 +00001690 default: assert(0 && "Unknown store class!");
1691 }
1692
1693 // Spill the integer to memory and reload it from there...
1694 int FrameIdx =
1695 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1696
1697 static const unsigned Op1[] =
1698 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001699 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001700
1701 if (DestClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001702 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1703 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00001704 } else {
1705 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001706 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001707 }
1708
1709 // Reload the original control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001710 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001711 return;
1712 }
1713
Brian Gaeked474e9c2002-12-06 10:49:33 +00001714 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00001715 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001716 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00001717}
Brian Gaekea1719c92002-10-31 23:03:59 +00001718
Chris Lattnereca195e2003-05-08 19:44:13 +00001719/// visitVarArgInst - Implement the va_arg instruction...
1720///
1721void ISel::visitVarArgInst(VarArgInst &I) {
1722 unsigned SrcReg = getReg(I.getOperand(0));
1723 unsigned DestReg = getReg(I);
1724
1725 // Load the va_list into a register...
1726 unsigned VAList = makeAnotherReg(Type::UIntTy);
1727 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1728
1729 unsigned Size;
1730 switch (I.getType()->getPrimitiveID()) {
1731 default:
1732 std::cerr << I;
1733 assert(0 && "Error: bad type for va_arg instruction!");
1734 return;
1735 case Type::PointerTyID:
1736 case Type::UIntTyID:
1737 case Type::IntTyID:
1738 Size = 4;
1739 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1740 break;
1741 case Type::ULongTyID:
1742 case Type::LongTyID:
1743 Size = 8;
1744 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1745 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1746 break;
1747 case Type::DoubleTyID:
1748 Size = 8;
1749 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1750 break;
1751 }
1752
1753 // Increment the VAList pointer...
1754 unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1755 BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1756
1757 // Update the VAList in memory...
1758 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1759}
1760
1761
Chris Lattner8a307e82002-12-16 19:32:50 +00001762// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1763// returns zero when the input is not exactly a power of two.
1764static unsigned ExactLog2(unsigned Val) {
1765 if (Val == 0) return 0;
1766 unsigned Count = 0;
1767 while (Val != 1) {
1768 if (Val & 1) return 0;
1769 Val >>= 1;
1770 ++Count;
1771 }
1772 return Count+1;
1773}
1774
Chris Lattner3e130a22003-01-13 00:32:26 +00001775void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1776 unsigned outputReg = getReg(I);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001777 MachineBasicBlock::iterator MI = BB->end();
1778 emitGEPOperation(BB, MI, I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00001779 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001780}
1781
Brian Gaeke71794c02002-12-13 11:22:48 +00001782void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001783 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +00001784 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +00001785 User::op_iterator IdxEnd, unsigned TargetReg) {
1786 const TargetData &TD = TM.getTargetData();
1787 const Type *Ty = Src->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +00001788 unsigned BaseReg = getReg(Src, MBB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001789
Brian Gaeke20244b72002-12-12 15:33:40 +00001790 // GEPs have zero or more indices; we must perform a struct access
1791 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +00001792 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1793 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001794 Value *idx = *oi;
Chris Lattner3e130a22003-01-13 00:32:26 +00001795 unsigned NextReg = BaseReg;
Chris Lattner065faeb2002-12-28 20:24:02 +00001796 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001797 // It's a struct access. idx is the index into the structure,
1798 // which names the field. This index must have ubyte type.
Chris Lattner065faeb2002-12-28 20:24:02 +00001799 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1800 assert(CUI->getType() == Type::UByteTy
Brian Gaeke20244b72002-12-12 15:33:40 +00001801 && "Funny-looking structure index in GEP");
1802 // Use the TargetData structure to pick out what the layout of
1803 // the structure is in memory. Since the structure index must
1804 // be constant, we can get its value and use it to find the
1805 // right byte offset from the StructLayout class's list of
1806 // structure member offsets.
Chris Lattnere8f0d922002-12-24 00:03:11 +00001807 unsigned idxValue = CUI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001808 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1809 if (FieldOff) {
1810 NextReg = makeAnotherReg(Type::UIntTy);
1811 // Emit an ADD to add FieldOff to the basePtr.
1812 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1813 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001814 // The next type is the member of the structure selected by the
1815 // index.
Chris Lattner065faeb2002-12-28 20:24:02 +00001816 Ty = StTy->getElementTypes()[idxValue];
1817 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001818 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner8a307e82002-12-16 19:32:50 +00001819
Brian Gaeke20244b72002-12-12 15:33:40 +00001820 // idx is the index into the array. Unlike with structure
1821 // indices, we may not know its actual value at code-generation
1822 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00001823 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1824
Chris Lattner3e130a22003-01-13 00:32:26 +00001825 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00001826 // must find the size of the pointed-to type (Not coincidentally, the next
1827 // type is the type of the elements in the array).
1828 Ty = SqTy->getElementType();
1829 unsigned elementSize = TD.getTypeSize(Ty);
1830
1831 // If idxReg is a constant, we don't need to perform the multiply!
1832 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001833 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00001834 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001835 NextReg = makeAnotherReg(Type::UIntTy);
1836 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
Chris Lattner8a307e82002-12-16 19:32:50 +00001837 }
1838 } else if (elementSize == 1) {
1839 // If the element size is 1, we don't have to multiply, just add
1840 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001841 NextReg = makeAnotherReg(Type::UIntTy);
1842 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001843 } else {
1844 unsigned idxReg = getReg(idx, MBB, IP);
1845 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1846 if (unsigned Shift = ExactLog2(elementSize)) {
1847 // If the element size is exactly a power of 2, use a shift to get it.
Chris Lattner8a307e82002-12-16 19:32:50 +00001848 BMI(MBB, IP, X86::SHLir32, 2,
1849 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1850 } else {
1851 // Most general case, emit a multiply...
1852 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1853 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1854
1855 // Emit a MUL to multiply the register holding the index by
1856 // elementSize, putting the result in OffsetReg.
Chris Lattner3e130a22003-01-13 00:32:26 +00001857 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001858 }
1859 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3e130a22003-01-13 00:32:26 +00001860 NextReg = makeAnotherReg(Type::UIntTy);
1861 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001862 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001863 }
1864 // Now that we are here, further indices refer to subtypes of this
Chris Lattner3e130a22003-01-13 00:32:26 +00001865 // one, so we don't need to worry about BaseReg itself, anymore.
1866 BaseReg = NextReg;
Brian Gaeke20244b72002-12-12 15:33:40 +00001867 }
1868 // After we have processed all the indices, the result is left in
Chris Lattner3e130a22003-01-13 00:32:26 +00001869 // BaseReg. Move it to the register where we were expected to
Brian Gaeke20244b72002-12-12 15:33:40 +00001870 // put the answer. A 32-bit move should do it, because we are in
1871 // ILP32 land.
Chris Lattner3e130a22003-01-13 00:32:26 +00001872 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001873}
1874
1875
Chris Lattner065faeb2002-12-28 20:24:02 +00001876/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1877/// frame manager, otherwise do it the hard way.
1878///
1879void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00001880 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00001881 const Type *Ty = I.getAllocatedType();
1882 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1883
1884 // If this is a fixed size alloca in the entry block for the function,
1885 // statically stack allocate the space.
1886 //
1887 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1888 if (I.getParent() == I.getParent()->getParent()->begin()) {
1889 TySize *= CUI->getValue(); // Get total allocated size...
1890 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1891
1892 // Create a new stack object using the frame manager...
1893 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1894 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1895 return;
1896 }
1897 }
1898
1899 // Create a register to hold the temporary result of multiplying the type size
1900 // constant by the variable amount.
1901 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1902 unsigned SrcReg1 = getReg(I.getArraySize());
1903 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1904 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1905
1906 // TotalSizeReg = mul <numelements>, <TypeSize>
1907 MachineBasicBlock::iterator MBBI = BB->end();
1908 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1909
1910 // AddedSize = add <TotalSizeReg>, 15
1911 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1912 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1913
1914 // AlignedSize = and <AddedSize>, ~15
1915 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1916 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1917
Brian Gaekee48ec012002-12-13 06:46:31 +00001918 // Subtract size from stack pointer, thereby allocating some space.
Chris Lattner3e130a22003-01-13 00:32:26 +00001919 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00001920
Brian Gaekee48ec012002-12-13 06:46:31 +00001921 // Put a pointer to the space into the result register, by copying
1922 // the stack pointer.
Chris Lattner065faeb2002-12-28 20:24:02 +00001923 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1924
Misha Brukman48196b32003-05-03 02:18:17 +00001925 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00001926 // object.
1927 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00001928}
Chris Lattner3e130a22003-01-13 00:32:26 +00001929
1930/// visitMallocInst - Malloc instructions are code generated into direct calls
1931/// to the library malloc.
1932///
1933void ISel::visitMallocInst(MallocInst &I) {
1934 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1935 unsigned Arg;
1936
1937 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1938 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1939 } else {
1940 Arg = makeAnotherReg(Type::UIntTy);
1941 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1942 unsigned Op1Reg = getReg(I.getOperand(0));
1943 MachineBasicBlock::iterator MBBI = BB->end();
1944 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1945
1946
1947 }
1948
1949 std::vector<ValueRecord> Args;
1950 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1951 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1952 1).addExternalSymbol("malloc", true);
1953 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1954}
1955
1956
1957/// visitFreeInst - Free instructions are code gen'd to call the free libc
1958/// function.
1959///
1960void ISel::visitFreeInst(FreeInst &I) {
1961 std::vector<ValueRecord> Args;
1962 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1963 I.getOperand(0)->getType()));
1964 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1965 1).addExternalSymbol("free", true);
1966 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1967}
1968
Brian Gaeke20244b72002-12-12 15:33:40 +00001969
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001970/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1971/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001972/// generated code sucks but the implementation is nice and simple.
1973///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001974Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1975 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001976}