blob: d92303889c4595e1e2d235576034aa4c7e2a7522 [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"
11#include "llvm/iTerminators.h"
Brian Gaeke1749d632002-11-07 17:59:21 +000012#include "llvm/iOperators.h"
Brian Gaekea1719c92002-10-31 23:03:59 +000013#include "llvm/iOther.h"
Chris Lattner51b49a92002-11-02 19:45:49 +000014#include "llvm/iPHINode.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "llvm/iMemory.h"
Chris Lattner72614082002-10-25 22:55:53 +000016#include "llvm/Type.h"
Brian Gaeke20244b72002-12-12 15:33:40 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerc5291f52002-10-27 21:16:59 +000018#include "llvm/Constants.h"
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000019#include "llvm/Pass.h"
Chris Lattnereca195e2003-05-08 19:44:13 +000020#include "llvm/Intrinsics.h"
Chris Lattner341a9372002-10-29 17:43:55 +000021#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner94af4142002-12-25 05:13:53 +000023#include "llvm/CodeGen/SSARegMap.h"
Chris Lattneraa09b752002-12-28 21:08:28 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner3e130a22003-01-13 00:32:26 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000026#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000027#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000028#include "llvm/Target/MRegisterInfo.h"
29#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000030
Chris Lattner333b2fa2002-12-13 10:09:43 +000031/// BMI - A special BuildMI variant that takes an iterator to insert the
Chris Lattner8bdd1292003-04-25 21:58:54 +000032/// instruction at as well as a basic block. This is the version for when you
33/// have a destination register in mind.
Brian Gaeke71794c02002-12-13 11:22:48 +000034inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattner333b2fa2002-12-13 10:09:43 +000035 MachineBasicBlock::iterator &I,
36 MachineOpCode Opcode,
37 unsigned NumOperands,
38 unsigned DestReg) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000039 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattner333b2fa2002-12-13 10:09:43 +000040 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000041 I = MBB->insert(I, MI)+1;
Chris Lattner333b2fa2002-12-13 10:09:43 +000042 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
43}
44
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000045/// BMI - A special BuildMI variant that takes an iterator to insert the
46/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000047inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000048 MachineBasicBlock::iterator &I,
49 MachineOpCode Opcode,
50 unsigned NumOperands) {
Chris Lattner8bdd1292003-04-25 21:58:54 +000051 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000052 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000053 I = MBB->insert(I, MI)+1;
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000054 return MachineInstrBuilder(MI);
55}
56
Chris Lattner333b2fa2002-12-13 10:09:43 +000057
Chris Lattner72614082002-10-25 22:55:53 +000058namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000059 struct ISel : public FunctionPass, InstVisitor<ISel> {
60 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000061 MachineFunction *F; // The function we are compiling into
62 MachineBasicBlock *BB; // The current MBB we are compiling
63 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner72614082002-10-25 22:55:53 +000064
Chris Lattner72614082002-10-25 22:55:53 +000065 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
66
Chris Lattner333b2fa2002-12-13 10:09:43 +000067 // MBBMap - Mapping between LLVM BB -> Machine BB
68 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
69
Chris Lattner3e130a22003-01-13 00:32:26 +000070 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000071
72 /// runOnFunction - Top level implementation of instruction selection for
73 /// the entire function.
74 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000075 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000076 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000077
Chris Lattner065faeb2002-12-28 20:24:02 +000078 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000079 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
80 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81
Chris Lattner14aa7fe2002-12-16 22:54:46 +000082 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000083
Chris Lattnerdbd73722003-05-06 21:32:22 +000084 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000085 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000086
Chris Lattner333b2fa2002-12-13 10:09:43 +000087 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000088 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000089
90 // Select the PHI nodes
91 SelectPHINodes();
92
Chris Lattner72614082002-10-25 22:55:53 +000093 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000094 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000095 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000096 return false; // We never modify the LLVM itself.
97 }
98
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000099 virtual const char *getPassName() const {
100 return "X86 Simple Instruction Selection";
101 }
102
Chris Lattner72614082002-10-25 22:55:53 +0000103 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000104 /// block. This simply creates a new MachineBasicBlock to emit code into
105 /// and adds it to the current MachineFunction. Subsequent visit* for
106 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000107 ///
108 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000109 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000110 }
111
Chris Lattner065faeb2002-12-28 20:24:02 +0000112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
114 ///
115 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000116
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
120 ///
121 void SelectPHINodes();
122
Chris Lattner72614082002-10-25 22:55:53 +0000123 // Visitation methods for various instructions. These methods simply emit
124 // fixed X86 code for each instruction.
125 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000126
127 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000128 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000129 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000130
131 struct ValueRecord {
132 unsigned Reg;
133 const Type *Ty;
134 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
135 };
136 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
137 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000138 void visitCallInst(CallInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000139 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000140
141 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000142 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000143 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
144 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattner8a307e82002-12-16 19:32:50 +0000145 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000146 unsigned DestReg, const Type *DestTy,
147 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000148 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000149
Chris Lattnerf01729e2002-11-02 20:54:46 +0000150 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
151 void visitRem(BinaryOperator &B) { visitDivRem(B); }
152 void visitDivRem(BinaryOperator &B);
153
Chris Lattnere2954c82002-11-02 20:04:26 +0000154 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000155 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
156 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
157 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000158
Chris Lattner6d40c192003-01-16 16:43:00 +0000159 // Comparison operators...
160 void visitSetCondInst(SetCondInst &I);
161 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000162
163 // Memory Instructions
Chris Lattner3e130a22003-01-13 00:32:26 +0000164 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
165 MachineBasicBlock::iterator &MBBI,
166 const Type *Ty, unsigned DestReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000167 void visitLoadInst(LoadInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000168 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000169 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000170 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000171 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000172 void visitMallocInst(MallocInst &I);
173 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000174
Chris Lattnere2954c82002-11-02 20:04:26 +0000175 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000176 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000177 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000178 void visitCastInst(CastInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000179 void visitVarArgInst(VarArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000180
181 void visitInstruction(Instruction &I) {
182 std::cerr << "Cannot instruction select: " << I;
183 abort();
184 }
185
Brian Gaeke95780cc2002-12-13 07:56:18 +0000186 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000187 ///
188 void promote32(unsigned targetReg, const ValueRecord &VR);
189
190 /// EmitByteSwap - Byteswap SrcReg into DestReg.
191 ///
192 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
Brian Gaeke95780cc2002-12-13 07:56:18 +0000193
Chris Lattner3e130a22003-01-13 00:32:26 +0000194 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
195 /// constant expression GEP support.
196 ///
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000197 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000198 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000199 User::op_iterator IdxEnd, unsigned TargetReg);
200
Chris Lattner548f61d2003-04-23 17:22:12 +0000201 /// emitCastOperation - Common code shared between visitCastInst and
202 /// constant expression cast support.
203 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
204 Value *Src, const Type *DestTy, unsigned TargetReg);
205
Chris Lattnerc5291f52002-10-27 21:16:59 +0000206 /// copyConstantToRegister - Output the instructions required to put the
207 /// specified constant into the specified register.
208 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000209 void copyConstantToRegister(MachineBasicBlock *MBB,
210 MachineBasicBlock::iterator &MBBI,
211 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000212
Chris Lattner3e130a22003-01-13 00:32:26 +0000213 /// makeAnotherReg - This method returns the next register number we haven't
214 /// yet used.
215 ///
216 /// Long values are handled somewhat specially. They are always allocated
217 /// as pairs of 32 bit integer values. The register number returned is the
218 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
219 /// of the long value.
220 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000221 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000222 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
223 const TargetRegisterClass *RC =
224 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
225 // Create the lower part
226 F->getSSARegMap()->createVirtualRegister(RC);
227 // Create the upper part.
228 return F->getSSARegMap()->createVirtualRegister(RC)-1;
229 }
230
Chris Lattnerc0812d82002-12-13 06:56:29 +0000231 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner94af4142002-12-25 05:13:53 +0000232 const TargetRegisterClass *RC =
233 TM.getRegisterInfo()->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000234 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000235 }
236
Chris Lattner72614082002-10-25 22:55:53 +0000237 /// getReg - This method turns an LLVM value into a register number. This
238 /// is guaranteed to produce the same register number for a particular value
239 /// every time it is queried.
240 ///
241 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000242 unsigned getReg(Value *V) {
243 // Just append to the end of the current bb.
244 MachineBasicBlock::iterator It = BB->end();
245 return getReg(V, BB, It);
246 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000247 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000248 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000249 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000250 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000251 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000252 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000253 }
Chris Lattner72614082002-10-25 22:55:53 +0000254
Chris Lattner6f8fd252002-10-27 21:23:43 +0000255 // If this operand is a constant, emit the code to copy the constant into
256 // the register here...
257 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000258 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000259 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000260 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000261 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
262 // Move the address of the global into the register
Chris Lattner3e130a22003-01-13 00:32:26 +0000263 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000264 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000265 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000266
Chris Lattner72614082002-10-25 22:55:53 +0000267 return Reg;
268 }
Chris Lattner72614082002-10-25 22:55:53 +0000269 };
270}
271
Chris Lattner43189d12002-11-17 20:07:45 +0000272/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
273/// Representation.
274///
275enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000276 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000277};
278
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000279/// getClass - Turn a primitive type into a "class" number which is based on the
280/// size of the type, and whether or not it is floating point.
281///
Chris Lattner43189d12002-11-17 20:07:45 +0000282static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000283 switch (Ty->getPrimitiveID()) {
284 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000285 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000286 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000287 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000288 case Type::IntTyID:
289 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000290 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000291
Chris Lattner94af4142002-12-25 05:13:53 +0000292 case Type::FloatTyID:
293 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000294
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000295 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000296 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000297 default:
298 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000299 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000300 }
301}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000302
Chris Lattner6b993cc2002-12-15 08:02:15 +0000303// getClassB - Just like getClass, but treat boolean values as bytes.
304static inline TypeClass getClassB(const Type *Ty) {
305 if (Ty == Type::BoolTy) return cByte;
306 return getClass(Ty);
307}
308
Chris Lattner06925362002-11-17 21:56:38 +0000309
Chris Lattnerc5291f52002-10-27 21:16:59 +0000310/// copyConstantToRegister - Output the instructions required to put the
311/// specified constant into the specified register.
312///
Chris Lattner8a307e82002-12-16 19:32:50 +0000313void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
314 MachineBasicBlock::iterator &IP,
315 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000316 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
317 if (CE->getOpcode() == Instruction::GetElementPtr) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000318 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000319 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000320 return;
Chris Lattner548f61d2003-04-23 17:22:12 +0000321 } else if (CE->getOpcode() == Instruction::Cast) {
322 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000323 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000324 }
325
Brian Gaeke20244b72002-12-12 15:33:40 +0000326 std::cerr << "Offending expr: " << C << "\n";
Chris Lattner94af4142002-12-25 05:13:53 +0000327 assert(0 && "Constant expressions not yet handled!\n");
Brian Gaeke20244b72002-12-12 15:33:40 +0000328 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000329
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000330 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000331 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000332
333 if (Class == cLong) {
334 // Copy the value into the register pair.
335 uint64_t Val;
336 if (C->getType()->isSigned())
337 Val = cast<ConstantSInt>(C)->getValue();
338 else
339 Val = cast<ConstantUInt>(C)->getValue();
340
341 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
342 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
343 return;
344 }
345
Chris Lattner94af4142002-12-25 05:13:53 +0000346 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000347
348 static const unsigned IntegralOpcodeTab[] = {
349 X86::MOVir8, X86::MOVir16, X86::MOVir32
350 };
351
Chris Lattner6b993cc2002-12-15 08:02:15 +0000352 if (C->getType() == Type::BoolTy) {
353 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
354 } else if (C->getType()->isSigned()) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000355 ConstantSInt *CSI = cast<ConstantSInt>(C);
Chris Lattner3e130a22003-01-13 00:32:26 +0000356 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000357 } else {
358 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000359 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000360 }
Chris Lattner94af4142002-12-25 05:13:53 +0000361 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
362 double Value = CFP->getValue();
363 if (Value == +0.0)
364 BMI(MBB, IP, X86::FLD0, 0, R);
365 else if (Value == +1.0)
366 BMI(MBB, IP, X86::FLD1, 0, R);
367 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000368 // Otherwise we need to spill the constant to memory...
369 MachineConstantPool *CP = F->getConstantPool();
370 unsigned CPI = CP->getConstantPoolIndex(CFP);
371 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000372 }
373
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000374 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000375 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000376 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000377 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000378 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000379 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000380 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000381 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000382 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000383 }
384}
385
Chris Lattner065faeb2002-12-28 20:24:02 +0000386/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
387/// the stack into virtual registers.
388///
389void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
390 // Emit instructions to load the arguments... On entry to a function on the
391 // X86, the stack frame looks like this:
392 //
393 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000394 // [ESP + 4] -- first argument (leftmost lexically)
395 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000396 // ...
397 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000398 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000399 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000400
401 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
402 unsigned Reg = getReg(*I);
403
Chris Lattner065faeb2002-12-28 20:24:02 +0000404 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000405 switch (getClassB(I->getType())) {
406 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000407 FI = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000408 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
409 break;
410 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000411 FI = MFI->CreateFixedObject(2, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000412 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
413 break;
414 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000415 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000416 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
417 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000418 case cLong:
419 FI = MFI->CreateFixedObject(8, ArgOffset);
420 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
421 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
422 ArgOffset += 4; // longs require 4 additional bytes
423 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000424 case cFP:
425 unsigned Opcode;
426 if (I->getType() == Type::FloatTy) {
427 Opcode = X86::FLDr32;
Chris Lattneraa09b752002-12-28 21:08:28 +0000428 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000429 } else {
430 Opcode = X86::FLDr64;
Chris Lattneraa09b752002-12-28 21:08:28 +0000431 FI = MFI->CreateFixedObject(8, ArgOffset);
Chris Lattner3e130a22003-01-13 00:32:26 +0000432 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000433 }
434 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
435 break;
436 default:
437 assert(0 && "Unhandled argument type!");
438 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000439 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000440 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000441
442 // If the function takes variable number of arguments, add a frame offset for
443 // the start of the first vararg value... this is used to expand
444 // llvm.va_start.
445 if (Fn.getFunctionType()->isVarArg())
446 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000447}
448
449
Chris Lattner333b2fa2002-12-13 10:09:43 +0000450/// SelectPHINodes - Insert machine code to generate phis. This is tricky
451/// because we have to generate our sources into the source basic blocks, not
452/// the current one.
453///
454void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000455 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000456 const Function &LF = *F->getFunction(); // The LLVM function...
457 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
458 const BasicBlock *BB = I;
459 MachineBasicBlock *MBB = MBBMap[I];
460
461 // Loop over all of the PHI nodes in the LLVM basic block...
462 unsigned NumPHIs = 0;
463 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattner548f61d2003-04-23 17:22:12 +0000464 PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000465
Chris Lattner333b2fa2002-12-13 10:09:43 +0000466 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000467 unsigned PHIReg = getReg(*PN);
468 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
469 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
470
471 MachineInstr *LongPhiMI = 0;
472 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
473 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
474 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
475 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000476
477 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
478 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
479
480 // Get the incoming value into a virtual register. If it is not already
481 // available in a virtual register, insert the computation code into
482 // PredMBB
Chris Lattner92053632002-12-13 11:52:34 +0000483 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000484 MachineBasicBlock::iterator PI = PredMBB->end();
485 while (PI != PredMBB->begin() &&
Chris Lattner3501fea2003-01-14 22:00:31 +0000486 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
Chris Lattner3e130a22003-01-13 00:32:26 +0000487 --PI;
488 unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
489 PhiMI->addRegOperand(ValReg);
490 PhiMI->addMachineBasicBlockOperand(PredMBB);
491 if (LongPhiMI) {
492 LongPhiMI->addRegOperand(ValReg+1);
493 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
494 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000495 }
496 }
497 }
498}
499
Chris Lattner6d40c192003-01-16 16:43:00 +0000500// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
501// the conditional branch instruction which is the only user of the cc
502// instruction. This is the case if the conditional branch is the only user of
503// the setcc, and if the setcc is in the same basic block as the conditional
504// branch. We also don't handle long arguments below, so we reject them here as
505// well.
506//
507static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
508 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
509 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
510 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
511 const Type *Ty = SCI->getOperand(0)->getType();
512 if (Ty != Type::LongTy && Ty != Type::ULongTy)
513 return SCI;
514 }
515 return 0;
516}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000517
Chris Lattner6d40c192003-01-16 16:43:00 +0000518// Return a fixed numbering for setcc instructions which does not depend on the
519// order of the opcodes.
520//
521static unsigned getSetCCNumber(unsigned Opcode) {
522 switch(Opcode) {
523 default: assert(0 && "Unknown setcc instruction!");
524 case Instruction::SetEQ: return 0;
525 case Instruction::SetNE: return 1;
526 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000527 case Instruction::SetGE: return 3;
528 case Instruction::SetGT: return 4;
529 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000530 }
531}
Chris Lattner06925362002-11-17 21:56:38 +0000532
Chris Lattner6d40c192003-01-16 16:43:00 +0000533// LLVM -> X86 signed X86 unsigned
534// ----- ---------- ------------
535// seteq -> sete sete
536// setne -> setne setne
537// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000538// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000539// setgt -> setg seta
540// setle -> setle setbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000541static const unsigned SetCCOpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000542 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
543 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
Chris Lattner6d40c192003-01-16 16:43:00 +0000544};
545
546bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
547
Brian Gaeke1749d632002-11-07 17:59:21 +0000548 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000549 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000550 bool isSigned = CompTy->isSigned();
Chris Lattner6d40c192003-01-16 16:43:00 +0000551 unsigned reg1 = getReg(Op0);
552 unsigned reg2 = getReg(Op1);
Chris Lattner05093a52002-11-21 15:52:38 +0000553
Chris Lattner3e130a22003-01-13 00:32:26 +0000554 unsigned Class = getClassB(CompTy);
555 switch (Class) {
556 default: assert(0 && "Unknown type class!");
557 // Emit: cmp <var1>, <var2> (do the comparison). We can
558 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
559 // 32-bit.
560 case cByte:
561 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
562 break;
563 case cShort:
564 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
565 break;
566 case cInt:
567 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
568 break;
569 case cFP:
570 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
571 BuildMI(BB, X86::FNSTSWr8, 0);
572 BuildMI(BB, X86::SAHF, 1);
573 isSigned = false; // Compare with unsigned operators
574 break;
575
576 case cLong:
577 if (OpNum < 2) { // seteq, setne
578 unsigned LoTmp = makeAnotherReg(Type::IntTy);
579 unsigned HiTmp = makeAnotherReg(Type::IntTy);
580 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
581 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
582 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
583 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
584 break; // Allow the sete or setne to be generated from flags set by OR
585 } else {
586 // Emit a sequence of code which compares the high and low parts once
587 // each, then uses a conditional move to handle the overflow case. For
588 // example, a setlt for long would generate code like this:
589 //
590 // AL = lo(op1) < lo(op2) // Signedness depends on operands
591 // BL = hi(op1) < hi(op2) // Always unsigned comparison
592 // dest = hi(op1) == hi(op2) ? AL : BL;
593 //
594
Chris Lattner6d40c192003-01-16 16:43:00 +0000595 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000596 // classes! Until then, hardcode registers so that we can deal with their
597 // aliases (because we don't have conditional byte moves).
598 //
599 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
Chris Lattner6d40c192003-01-16 16:43:00 +0000600 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000601 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
Chris Lattner6d40c192003-01-16 16:43:00 +0000602 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000603 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000604 // NOTE: visitSetCondInst knows that the value is dumped into the BL
605 // register at this point for long values...
606 return isSigned;
Chris Lattner3e130a22003-01-13 00:32:26 +0000607 }
608 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000609 return isSigned;
610}
Chris Lattner3e130a22003-01-13 00:32:26 +0000611
Chris Lattner6d40c192003-01-16 16:43:00 +0000612
613/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
614/// register, then move it to wherever the result should be.
615///
616void ISel::visitSetCondInst(SetCondInst &I) {
617 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
618
619 unsigned OpNum = getSetCCNumber(I.getOpcode());
620 unsigned DestReg = getReg(I);
621 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
622 I.getOperand(1));
623
624 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
625 // Handle normal comparisons with a setcc instruction...
626 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
627 } else {
628 // Handle long comparisons by copying the value which is already in BL into
629 // the register we want...
630 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
631 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000632}
Chris Lattner51b49a92002-11-02 19:45:49 +0000633
Brian Gaekec2505982002-11-30 11:57:28 +0000634/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
635/// operand, in the specified target register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000636void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
637 bool isUnsigned = VR.Ty->isUnsigned();
638 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000639 case cByte:
640 // Extend value into target register (8->32)
641 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000642 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000643 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000644 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000645 break;
646 case cShort:
647 // Extend value into target register (16->32)
648 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000649 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000650 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000651 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000652 break;
653 case cInt:
654 // Move value into target register (32->32)
Chris Lattner3e130a22003-01-13 00:32:26 +0000655 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000656 break;
657 default:
658 assert(0 && "Unpromotable operand class in promote32");
659 }
Brian Gaekec2505982002-11-30 11:57:28 +0000660}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000661
Chris Lattner72614082002-10-25 22:55:53 +0000662/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
663/// we have the following possibilities:
664///
665/// ret void: No return value, simply emit a 'ret' instruction
666/// ret sbyte, ubyte : Extend value into EAX and return
667/// ret short, ushort: Extend value into EAX and return
668/// ret int, uint : Move value into EAX and return
669/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000670/// ret long, ulong : Move value into EAX/EDX and return
671/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000672///
Chris Lattner3e130a22003-01-13 00:32:26 +0000673void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000674 if (I.getNumOperands() == 0) {
675 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
676 return;
677 }
678
679 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000680 unsigned RetReg = getReg(RetVal);
681 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000682 case cByte: // integral return values: extend or move into EAX and return
683 case cShort:
684 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000685 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattnerdbd73722003-05-06 21:32:22 +0000686 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000687 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000688 break;
689 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000690 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000691 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000692 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000693 break;
694 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000695 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
696 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000697 // Declare that EAX & EDX are live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000698 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000699 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000700 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000701 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +0000702 }
Chris Lattner43189d12002-11-17 20:07:45 +0000703 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +0000704 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000705}
706
Chris Lattner55f6fab2003-01-16 18:07:23 +0000707// getBlockAfter - Return the basic block which occurs lexically after the
708// specified one.
709static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
710 Function::iterator I = BB; ++I; // Get iterator to next block
711 return I != BB->getParent()->end() ? &*I : 0;
712}
713
Chris Lattner51b49a92002-11-02 19:45:49 +0000714/// visitBranchInst - Handle conditional and unconditional branches here. Note
715/// that since code layout is frozen at this point, that if we are trying to
716/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +0000717/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +0000718///
Chris Lattner94af4142002-12-25 05:13:53 +0000719void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000720 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
721
722 if (!BI.isConditional()) { // Unconditional branch?
723 if (BI.getSuccessor(0) != NextBB)
724 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +0000725 return;
726 }
727
728 // See if we can fold the setcc into the branch itself...
729 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
730 if (SCI == 0) {
731 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
732 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +0000733 unsigned condReg = getReg(BI.getCondition());
Chris Lattner94af4142002-12-25 05:13:53 +0000734 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
Chris Lattner55f6fab2003-01-16 18:07:23 +0000735 if (BI.getSuccessor(1) == NextBB) {
736 if (BI.getSuccessor(0) != NextBB)
737 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
738 } else {
739 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
740
741 if (BI.getSuccessor(0) != NextBB)
742 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
743 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000744 return;
Chris Lattner94af4142002-12-25 05:13:53 +0000745 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000746
747 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
748 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
749 SCI->getOperand(1));
750
751 // LLVM -> X86 signed X86 unsigned
752 // ----- ---------- ------------
753 // seteq -> je je
754 // setne -> jne jne
755 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000756 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +0000757 // setgt -> jg ja
758 // setle -> jle jbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000759 static const unsigned OpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000760 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
761 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
Chris Lattner6d40c192003-01-16 16:43:00 +0000762 };
763
Chris Lattner55f6fab2003-01-16 18:07:23 +0000764 if (BI.getSuccessor(0) != NextBB) {
765 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
766 if (BI.getSuccessor(1) != NextBB)
767 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
768 } else {
769 // Change to the inverse condition...
770 if (BI.getSuccessor(1) != NextBB) {
771 OpNum ^= 1;
772 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
773 }
774 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000775}
776
Chris Lattner3e130a22003-01-13 00:32:26 +0000777
778/// doCall - This emits an abstract call instruction, setting up the arguments
779/// and the return value as appropriate. For the actual function call itself,
780/// it inserts the specified CallMI instruction into the stream.
781///
782void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
783 const std::vector<ValueRecord> &Args) {
784
Chris Lattner065faeb2002-12-28 20:24:02 +0000785 // Count how many bytes are to be pushed on the stack...
786 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000787
Chris Lattner3e130a22003-01-13 00:32:26 +0000788 if (!Args.empty()) {
789 for (unsigned i = 0, e = Args.size(); i != e; ++i)
790 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000791 case cByte: case cShort: case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000792 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000793 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000794 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000795 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000796 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
Chris Lattner065faeb2002-12-28 20:24:02 +0000797 break;
798 default: assert(0 && "Unknown class!");
799 }
800
801 // Adjust the stack pointer for the new arguments...
802 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
803
804 // Arguments go on the stack in reverse order, as specified by the ABI.
805 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +0000806 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
807 unsigned ArgReg = Args[i].Reg;
808 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000809 case cByte:
810 case cShort: {
811 // Promote arg to 32 bits wide into a temporary register...
812 unsigned R = makeAnotherReg(Type::UIntTy);
Chris Lattner3e130a22003-01-13 00:32:26 +0000813 promote32(R, Args[i]);
Chris Lattner065faeb2002-12-28 20:24:02 +0000814 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
815 X86::ESP, ArgOffset).addReg(R);
816 break;
817 }
818 case cInt:
819 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000820 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000821 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000822 case cLong:
823 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
824 X86::ESP, ArgOffset).addReg(ArgReg);
825 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
826 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
827 ArgOffset += 4; // 8 byte entry, not 4.
828 break;
829
Chris Lattner065faeb2002-12-28 20:24:02 +0000830 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000831 if (Args[i].Ty == Type::FloatTy) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000832 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000833 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000834 } else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000835 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
836 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
837 X86::ESP, ArgOffset).addReg(ArgReg);
838 ArgOffset += 4; // 8 byte entry, not 4.
Chris Lattner065faeb2002-12-28 20:24:02 +0000839 }
840 break;
841
Chris Lattner3e130a22003-01-13 00:32:26 +0000842 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +0000843 }
844 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +0000845 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000846 } else {
847 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +0000848 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +0000849
Chris Lattner3e130a22003-01-13 00:32:26 +0000850 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000851
Chris Lattner065faeb2002-12-28 20:24:02 +0000852 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +0000853
854 // If there is a return value, scavenge the result from the location the call
855 // leaves it in...
856 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000857 if (Ret.Ty != Type::VoidTy) {
858 unsigned DestClass = getClassB(Ret.Ty);
859 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000860 case cByte:
861 case cShort:
862 case cInt: {
863 // Integral results are in %eax, or the appropriate portion
864 // thereof.
865 static const unsigned regRegMove[] = {
866 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
867 };
868 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000869 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000870 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000871 }
Chris Lattner94af4142002-12-25 05:13:53 +0000872 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000873 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000874 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000875 case cLong: // Long values are left in EDX:EAX
876 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
877 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
878 break;
879 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000880 }
Chris Lattnera3243642002-12-04 23:45:28 +0000881 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000882}
Chris Lattner2df035b2002-11-02 19:27:56 +0000883
Chris Lattner3e130a22003-01-13 00:32:26 +0000884
885/// visitCallInst - Push args on stack and do a procedure call instruction.
886void ISel::visitCallInst(CallInst &CI) {
887 MachineInstr *TheCall;
888 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +0000889 // Is it an intrinsic function call?
890 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
891 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
892 return;
893 }
894
Chris Lattner3e130a22003-01-13 00:32:26 +0000895 // Emit a CALL instruction with PC-relative displacement.
896 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
897 } else { // Emit an indirect call...
898 unsigned Reg = getReg(CI.getCalledValue());
899 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
900 }
901
902 std::vector<ValueRecord> Args;
903 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
904 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
905 CI.getOperand(i)->getType()));
906
907 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
908 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
909}
910
Chris Lattnereca195e2003-05-08 19:44:13 +0000911void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
912 unsigned TmpReg1, TmpReg2;
913 switch (ID) {
914 case LLVMIntrinsic::va_start:
915 // Get the address of the first vararg value...
916 TmpReg1 = makeAnotherReg(Type::UIntTy);
917 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
918 TmpReg2 = getReg(CI.getOperand(1));
919 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
920 return;
921
922 case LLVMIntrinsic::va_end: return; // Noop on X86
923 case LLVMIntrinsic::va_copy:
924 TmpReg1 = getReg(CI.getOperand(2)); // Get existing va_list
925 TmpReg2 = getReg(CI.getOperand(1)); // Get va_list* to store into
926 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
927 return;
928
929 default: assert(0 && "Unknown intrinsic for X86!");
930 }
931}
932
933
Chris Lattner3e130a22003-01-13 00:32:26 +0000934
Chris Lattner68aad932002-11-02 20:13:22 +0000935/// visitSimpleBinary - Implement simple binary operators for integral types...
936/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
937/// 4 for Xor.
938///
939void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000940 unsigned Class = getClassB(B.getType());
Chris Lattnere2954c82002-11-02 20:04:26 +0000941
942 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000943 // Arithmetic operators
Chris Lattner94af4142002-12-25 05:13:53 +0000944 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
945 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
Chris Lattner68aad932002-11-02 20:13:22 +0000946
947 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000948 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
949 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
950 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
951 };
Chris Lattner3e130a22003-01-13 00:32:26 +0000952
953 bool isLong = false;
954 if (Class == cLong) {
955 isLong = true;
956 Class = cInt; // Bottom 32 bits are handled just like ints
957 }
Chris Lattnere2954c82002-11-02 20:04:26 +0000958
959 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner94af4142002-12-25 05:13:53 +0000960 assert(Opcode && "Floating point arguments to logical inst?");
Chris Lattnere2954c82002-11-02 20:04:26 +0000961 unsigned Op0r = getReg(B.getOperand(0));
962 unsigned Op1r = getReg(B.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +0000963 unsigned DestReg = getReg(B);
964 BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
965
966 if (isLong) { // Handle the upper 32 bits of long values...
967 static const unsigned TopTab[] = {
968 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
969 };
970 BuildMI(BB, TopTab[OperatorClass], 2,
971 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
972 }
Chris Lattnere2954c82002-11-02 20:04:26 +0000973}
974
Chris Lattner3e130a22003-01-13 00:32:26 +0000975/// doMultiply - Emit appropriate instructions to multiply together the
976/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
977/// result should be given as DestTy.
978///
979/// FIXME: doMultiply should use one of the two address IMUL instructions!
980///
Chris Lattner8a307e82002-12-16 19:32:50 +0000981void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000982 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +0000983 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000984 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +0000985 switch (Class) {
986 case cFP: // Floating point multiply
Chris Lattner3e130a22003-01-13 00:32:26 +0000987 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000988 return;
989 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000990 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +0000991 case cByte:
992 case cShort:
993 case cInt: // Small integerals, handled below...
994 break;
995 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000996
997 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000998 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
Brian Gaeke20244b72002-12-12 15:33:40 +0000999 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1000 unsigned Reg = Regs[Class];
1001
1002 // Emit a MOV to put the first operand into the appropriately-sized
1003 // subreg of EAX.
Chris Lattner3e130a22003-01-13 00:32:26 +00001004 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001005
1006 // Emit the appropriate multiply instruction.
Chris Lattner3e130a22003-01-13 00:32:26 +00001007 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001008
1009 // Emit another MOV to put the result into the destination register.
Chris Lattner3e130a22003-01-13 00:32:26 +00001010 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001011}
1012
Chris Lattnerca9671d2002-11-02 20:28:58 +00001013/// visitMul - Multiplies are not simple binary operators because they must deal
1014/// with the EAX register explicitly.
1015///
1016void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00001017 unsigned Op0Reg = getReg(I.getOperand(0));
1018 unsigned Op1Reg = getReg(I.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +00001019 unsigned DestReg = getReg(I);
1020
1021 // Simple scalar multiply?
1022 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1023 MachineBasicBlock::iterator MBBI = BB->end();
1024 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1025 } else {
1026 // Long value. We have to do things the hard way...
1027 // Multiply the two low parts... capturing carry into EDX
1028 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1029 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1030
1031 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1032 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1033 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1034
1035 MachineBasicBlock::iterator MBBI = BB->end();
1036 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1037 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1038
1039 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1040 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1041 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1042
1043 MBBI = BB->end();
1044 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1045 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1046
1047 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1048 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1049 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001050}
Chris Lattnerca9671d2002-11-02 20:28:58 +00001051
Chris Lattner06925362002-11-17 21:56:38 +00001052
Chris Lattnerf01729e2002-11-02 20:54:46 +00001053/// visitDivRem - Handle division and remainder instructions... these
1054/// instruction both require the same instructions to be generated, they just
1055/// select the result from a different register. Note that both of these
1056/// instructions work differently for signed and unsigned operands.
1057///
1058void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001059 unsigned Class = getClass(I.getType());
1060 unsigned Op0Reg = getReg(I.getOperand(0));
1061 unsigned Op1Reg = getReg(I.getOperand(1));
1062 unsigned ResultReg = getReg(I);
1063
1064 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001065 case cFP: // Floating point divide
Chris Lattner94af4142002-12-25 05:13:53 +00001066 if (I.getOpcode() == Instruction::Div)
1067 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001068 else { // Floating point remainder...
1069 MachineInstr *TheCall =
1070 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1071 std::vector<ValueRecord> Args;
1072 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1073 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1074 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1075 }
Chris Lattner94af4142002-12-25 05:13:53 +00001076 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001077 case cLong: {
1078 static const char *FnName[] =
1079 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1080
1081 unsigned NameIdx = I.getType()->isUnsigned()*2;
1082 NameIdx += I.getOpcode() == Instruction::Div;
1083 MachineInstr *TheCall =
1084 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1085
1086 std::vector<ValueRecord> Args;
1087 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1088 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1089 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1090 return;
1091 }
1092 case cByte: case cShort: case cInt:
1093 break; // Small integerals, handled below...
1094 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001095 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001096
1097 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1098 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +00001099 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001100 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1101 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1102
1103 static const unsigned DivOpcode[][4] = {
Chris Lattner3e130a22003-01-13 00:32:26 +00001104 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1105 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001106 };
1107
1108 bool isSigned = I.getType()->isSigned();
1109 unsigned Reg = Regs[Class];
1110 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001111
1112 // Put the first operand into one of the A registers...
1113 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1114
1115 if (isSigned) {
1116 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +00001117 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001118 } else {
1119 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1120 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1121 }
1122
Chris Lattner06925362002-11-17 21:56:38 +00001123 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +00001124 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001125
Chris Lattnerf01729e2002-11-02 20:54:46 +00001126 // Figure out which register we want to pick the result out of...
1127 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1128
Chris Lattnerf01729e2002-11-02 20:54:46 +00001129 // Put the result into the destination register...
Chris Lattner94af4142002-12-25 05:13:53 +00001130 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001131}
Chris Lattnere2954c82002-11-02 20:04:26 +00001132
Chris Lattner06925362002-11-17 21:56:38 +00001133
Brian Gaekea1719c92002-10-31 23:03:59 +00001134/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1135/// for constant immediate shift values, and for constant immediate
1136/// shift values equal to 1. Even the general case is sort of special,
1137/// because the shift amount has to be in CL, not just any old register.
1138///
Chris Lattner3e130a22003-01-13 00:32:26 +00001139void ISel::visitShiftInst(ShiftInst &I) {
1140 unsigned SrcReg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +00001141 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +00001142 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3e130a22003-01-13 00:32:26 +00001143 bool isSigned = I.getType()->isSigned();
1144 unsigned Class = getClass(I.getType());
1145
1146 static const unsigned ConstantOperand[][4] = {
1147 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1148 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1149 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1150 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1151 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001152
Chris Lattner3e130a22003-01-13 00:32:26 +00001153 static const unsigned NonConstantOperand[][4] = {
1154 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1155 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1156 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1157 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1158 };
Chris Lattner796df732002-11-02 00:44:25 +00001159
Chris Lattner3e130a22003-01-13 00:32:26 +00001160 // Longs, as usual, are handled specially...
1161 if (Class == cLong) {
1162 // If we have a constant shift, we can generate much more efficient code
1163 // than otherwise...
1164 //
1165 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1166 unsigned Amount = CUI->getValue();
1167 if (Amount < 32) {
1168 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1169 if (isLeftShift) {
1170 BuildMI(BB, Opc[3], 3,
1171 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1172 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1173 } else {
1174 BuildMI(BB, Opc[3], 3,
1175 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1176 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1177 }
1178 } else { // Shifting more than 32 bits
1179 Amount -= 32;
1180 if (isLeftShift) {
1181 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1182 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1183 } else {
1184 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1185 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1186 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1187 }
1188 }
1189 } else {
1190 visitInstruction(I); // FIXME: Implement long shift by non-constant
Brian Gaekea1719c92002-10-31 23:03:59 +00001191 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001192 return;
1193 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001194
Chris Lattner3e130a22003-01-13 00:32:26 +00001195 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1196 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1197 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001198
Chris Lattner3e130a22003-01-13 00:32:26 +00001199 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1200 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1201 } else { // The shift amount is non-constant.
1202 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001203
Chris Lattner3e130a22003-01-13 00:32:26 +00001204 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1205 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1206 }
1207}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001208
Chris Lattner3e130a22003-01-13 00:32:26 +00001209
1210/// doFPLoad - This method is used to load an FP value from memory using the
1211/// current endianness. NOTE: This method returns a partially constructed load
1212/// instruction which needs to have the memory source filled in still.
1213///
1214MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1215 MachineBasicBlock::iterator &MBBI,
1216 const Type *Ty, unsigned DestReg) {
1217 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1218 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1219
1220 if (TM.getTargetData().isLittleEndian()) // fast path...
1221 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1222
1223 // If we are big-endian, start by creating an LEA instruction to represent the
1224 // address of the memory location to load from...
1225 //
1226 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1227 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1228
1229 // Allocate a temporary stack slot to transform the value into...
1230 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1231
1232 // Perform the bswaps 32 bits at a time...
1233 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1234 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1235 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1236 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1237 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1238 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1239 FrameIdx, Offset).addReg(TmpReg2);
1240
1241 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1242 TmpReg1 = makeAnotherReg(Type::UIntTy);
1243 TmpReg2 = makeAnotherReg(Type::UIntTy);
1244
1245 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1246 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1247 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1248 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1249 }
1250
1251 // Now we can reload the final byteswapped result into the final destination.
1252 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1253 return Result;
1254}
1255
1256/// EmitByteSwap - Byteswap SrcReg into DestReg.
1257///
1258void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1259 // Emit the byte swap instruction...
1260 switch (Class) {
1261 case cByte:
Misha Brukmanbaf06072003-04-22 17:54:23 +00001262 // No byteswap necessary for 8 bit value...
Chris Lattner3e130a22003-01-13 00:32:26 +00001263 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1264 break;
1265 case cInt:
1266 // Use the 32 bit bswap instruction to do a 32 bit swap...
1267 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1268 break;
1269
1270 case cShort:
1271 // For 16 bit we have to use an xchg instruction, because there is no
Misha Brukmanbaf06072003-04-22 17:54:23 +00001272 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
Chris Lattner3e130a22003-01-13 00:32:26 +00001273 // into AX to do the xchg.
1274 //
1275 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1276 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1277 .addReg(X86::AH, MOTy::UseAndDef);
1278 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1279 break;
1280 default: assert(0 && "Cannot byteswap this class!");
1281 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001282}
1283
Chris Lattner06925362002-11-17 21:56:38 +00001284
Chris Lattner6fc3c522002-11-17 21:11:55 +00001285/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001286/// instruction. The load and store instructions are the only place where we
1287/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001288///
1289void ISel::visitLoadInst(LoadInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001290 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1291 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner94af4142002-12-25 05:13:53 +00001292 unsigned SrcAddrReg = getReg(I.getOperand(0));
1293 unsigned DestReg = getReg(I);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001294
Chris Lattner6fc3c522002-11-17 21:11:55 +00001295 unsigned Class = getClass(I.getType());
Chris Lattner94af4142002-12-25 05:13:53 +00001296 switch (Class) {
Chris Lattner94af4142002-12-25 05:13:53 +00001297 case cFP: {
Chris Lattner3e130a22003-01-13 00:32:26 +00001298 MachineBasicBlock::iterator MBBI = BB->end();
1299 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001300 return;
1301 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001302 case cLong: case cInt: case cShort: case cByte:
1303 break; // Integers of various sizes handled below
1304 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001305 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001306
Chris Lattnere8f0d922002-12-24 00:03:11 +00001307 // We need to adjust the input pointer if we are emulating a big-endian
1308 // long-pointer target. On these systems, the pointer that we are interested
1309 // in is in the upper part of the eight byte memory image of the pointer. It
1310 // also happens to be byte-swapped, but this will be handled later.
1311 //
1312 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1313 unsigned R = makeAnotherReg(Type::UIntTy);
1314 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1315 SrcAddrReg = R;
1316 }
Chris Lattner94af4142002-12-25 05:13:53 +00001317
Chris Lattnere8f0d922002-12-24 00:03:11 +00001318 unsigned IReg = DestReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001319 if (!isLittleEndian) // If big endian we need an intermediate stage
1320 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001321
Chris Lattner3e130a22003-01-13 00:32:26 +00001322 static const unsigned Opcode[] = {
1323 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1324 };
Chris Lattnere8f0d922002-12-24 00:03:11 +00001325 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1326
Chris Lattner3e130a22003-01-13 00:32:26 +00001327 // Handle long values now...
1328 if (Class == cLong) {
1329 if (isLittleEndian) {
1330 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1331 } else {
1332 EmitByteSwap(IReg+1, DestReg, cInt);
1333 unsigned TempReg = makeAnotherReg(Type::IntTy);
1334 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1335 EmitByteSwap(IReg, TempReg, cInt);
Chris Lattner94af4142002-12-25 05:13:53 +00001336 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001337 return;
1338 }
1339
1340 if (!isLittleEndian)
1341 EmitByteSwap(IReg, DestReg, Class);
1342}
1343
1344
1345/// doFPStore - This method is used to store an FP value to memory using the
1346/// current endianness.
1347///
1348void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1349 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1350 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1351
1352 if (TM.getTargetData().isLittleEndian()) { // fast path...
1353 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1354 return;
1355 }
1356
1357 // Allocate a temporary stack slot to transform the value into...
1358 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1359 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1360 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1361
1362 // Store the value into a temporary stack slot...
1363 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1364
1365 // Perform the bswaps 32 bits at a time...
1366 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1367 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1368 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1369 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1370 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1371 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1372 DestAddrReg, Offset).addReg(TmpReg2);
1373
1374 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1375 TmpReg1 = makeAnotherReg(Type::UIntTy);
1376 TmpReg2 = makeAnotherReg(Type::UIntTy);
1377
1378 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1379 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1380 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1381 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001382 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001383}
1384
Chris Lattner06925362002-11-17 21:56:38 +00001385
Chris Lattner6fc3c522002-11-17 21:11:55 +00001386/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1387/// instruction.
1388///
1389void ISel::visitStoreInst(StoreInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001390 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1391 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner3e130a22003-01-13 00:32:26 +00001392 unsigned ValReg = getReg(I.getOperand(0));
1393 unsigned AddressReg = getReg(I.getOperand(1));
Chris Lattnere8f0d922002-12-24 00:03:11 +00001394
Chris Lattner94af4142002-12-25 05:13:53 +00001395 unsigned Class = getClass(I.getOperand(0)->getType());
1396 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001397 case cLong:
1398 if (isLittleEndian) {
1399 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1400 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1401 AddressReg, 4).addReg(ValReg+1);
1402 } else {
1403 unsigned T1 = makeAnotherReg(Type::IntTy);
1404 unsigned T2 = makeAnotherReg(Type::IntTy);
1405 EmitByteSwap(T1, ValReg , cInt);
1406 EmitByteSwap(T2, ValReg+1, cInt);
1407 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1408 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1409 }
Chris Lattner94af4142002-12-25 05:13:53 +00001410 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001411 case cFP:
1412 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1413 return;
1414 case cInt: case cShort: case cByte:
1415 break; // Integers of various sizes handled below
1416 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001417 }
1418
1419 if (!isLittleEndian && hasLongPointers &&
1420 isa<PointerType>(I.getOperand(0)->getType())) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001421 unsigned R = makeAnotherReg(Type::UIntTy);
1422 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1423 AddressReg = R;
1424 }
1425
Chris Lattner94af4142002-12-25 05:13:53 +00001426 if (!isLittleEndian && Class != cByte) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001427 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1428 EmitByteSwap(R, ValReg, Class);
1429 ValReg = R;
Chris Lattnere8f0d922002-12-24 00:03:11 +00001430 }
1431
Chris Lattner94af4142002-12-25 05:13:53 +00001432 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner6fc3c522002-11-17 21:11:55 +00001433 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1434}
1435
1436
Brian Gaekec11232a2002-11-26 10:43:30 +00001437/// visitCastInst - Here we have various kinds of copying with or without
1438/// sign extension going on.
Chris Lattner3e130a22003-01-13 00:32:26 +00001439void ISel::visitCastInst(CastInst &CI) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001440 unsigned DestReg = getReg(CI);
1441 MachineBasicBlock::iterator MI = BB->end();
1442 emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1443}
1444
1445/// emitCastOperation - Common code shared between visitCastInst and
1446/// constant expression cast support.
1447void ISel::emitCastOperation(MachineBasicBlock *BB,
1448 MachineBasicBlock::iterator &IP,
1449 Value *Src, const Type *DestTy,
1450 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00001451 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001452 const Type *SrcTy = Src->getType();
1453 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00001454 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00001455
Chris Lattner3e130a22003-01-13 00:32:26 +00001456 // Implement casts to bool by using compare on the operand followed by set if
1457 // not zero on the result.
1458 if (DestTy == Type::BoolTy) {
1459 if (SrcClass == cFP || SrcClass == cLong)
Chris Lattner548f61d2003-04-23 17:22:12 +00001460 abort(); // FIXME: implement cast (long & FP) to bool
Chris Lattner3e130a22003-01-13 00:32:26 +00001461
Chris Lattner548f61d2003-04-23 17:22:12 +00001462 BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1463 BMI(BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001464 return;
1465 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001466
1467 static const unsigned RegRegMove[] = {
1468 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1469 };
1470
1471 // Implement casts between values of the same type class (as determined by
1472 // getClass) by using a register-to-register move.
1473 if (SrcClass == DestClass) {
1474 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001475 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001476 } else if (SrcClass == cFP) {
1477 if (SrcTy == Type::FloatTy) { // double -> float
1478 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001479 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001480 } else { // float -> double
1481 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1482 "Unknown cFP member!");
1483 // Truncate from double to float by storing to memory as short, then
1484 // reading it back.
1485 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1486 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner548f61d2003-04-23 17:22:12 +00001487 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1488 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001489 }
1490 } else if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001491 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1492 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001493 } else {
Chris Lattner548f61d2003-04-23 17:22:12 +00001494 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00001495 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001496 return;
1497 }
1498
1499 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1500 // or zero extension, depending on whether the source type was signed.
1501 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1502 SrcClass < DestClass) {
1503 bool isLong = DestClass == cLong;
1504 if (isLong) DestClass = cInt;
1505
1506 static const unsigned Opc[][4] = {
1507 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1508 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1509 };
1510
1511 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattner548f61d2003-04-23 17:22:12 +00001512 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1513 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001514
1515 if (isLong) { // Handle upper 32 bits as appropriate...
1516 if (isUnsigned) // Zero out top bits...
Chris Lattner548f61d2003-04-23 17:22:12 +00001517 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001518 else // Sign extend bottom half...
Chris Lattner548f61d2003-04-23 17:22:12 +00001519 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00001520 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001521 return;
1522 }
1523
1524 // Special case long -> int ...
1525 if (SrcClass == cLong && DestClass == cInt) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001526 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001527 return;
1528 }
1529
1530 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1531 // move out of AX or AL.
1532 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1533 && SrcClass > DestClass) {
1534 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattner548f61d2003-04-23 17:22:12 +00001535 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1536 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00001537 return;
1538 }
1539
1540 // Handle casts from integer to floating point now...
1541 if (DestClass == cFP) {
1542 // unsigned int -> load as 64 bit int.
1543 // unsigned long long -> more complex
1544 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
Chris Lattner548f61d2003-04-23 17:22:12 +00001545 abort(); // don't handle unsigned src yet!
Chris Lattner3e130a22003-01-13 00:32:26 +00001546
1547 // We don't have the facilities for directly loading byte sized data from
1548 // memory. Promote it to 16 bits.
1549 if (SrcClass == cByte) {
1550 unsigned TmpReg = makeAnotherReg(Type::ShortTy);
Chris Lattner548f61d2003-04-23 17:22:12 +00001551 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1552 1, TmpReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001553 SrcTy = Type::ShortTy; // Pretend the short is our input now!
1554 SrcClass = cShort;
1555 SrcReg = TmpReg;
1556 }
1557
1558 // Spill the integer to memory and reload it from there...
1559 int FrameIdx =
1560 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1561
1562 if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001563 if (SrcTy == Type::ULongTy) abort(); // FIXME: Handle ulong -> FP
1564 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1565 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001566 FrameIdx, 4).addReg(SrcReg+1);
1567 } else {
1568 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001569 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001570 }
1571
1572 static const unsigned Op2[] =
1573 { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001574 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001575 return;
1576 }
1577
1578 // Handle casts from floating point to integer now...
1579 if (SrcClass == cFP) {
1580 // Change the floating point control register to use "round towards zero"
1581 // mode when truncating to an integer value.
1582 //
1583 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Chris Lattner548f61d2003-04-23 17:22:12 +00001584 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001585
1586 // Load the old value of the high byte of the control word...
1587 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Chris Lattner548f61d2003-04-23 17:22:12 +00001588 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001589
1590 // Set the high part to be round to zero...
Chris Lattner548f61d2003-04-23 17:22:12 +00001591 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00001592
1593 // Reload the modified control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001594 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001595
1596 // Restore the memory image of control word to original value
Chris Lattner548f61d2003-04-23 17:22:12 +00001597 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001598 CWFrameIdx, 1).addReg(HighPartOfCW);
1599
1600 // We don't have the facilities for directly storing byte sized data to
1601 // memory. Promote it to 16 bits. We also must promote unsigned values to
1602 // larger classes because we only have signed FP stores.
1603 unsigned StoreClass = DestClass;
1604 const Type *StoreTy = DestTy;
1605 if (StoreClass == cByte || DestTy->isUnsigned())
1606 switch (StoreClass) {
1607 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1608 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1609 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner548f61d2003-04-23 17:22:12 +00001610 case cLong: abort(); // FIXME: unsigned long long -> more complex
Chris Lattner3e130a22003-01-13 00:32:26 +00001611 default: assert(0 && "Unknown store class!");
1612 }
1613
1614 // Spill the integer to memory and reload it from there...
1615 int FrameIdx =
1616 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1617
1618 static const unsigned Op1[] =
1619 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001620 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001621
1622 if (DestClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001623 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1624 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00001625 } else {
1626 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001627 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001628 }
1629
1630 // Reload the original control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001631 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001632 return;
1633 }
1634
Brian Gaeked474e9c2002-12-06 10:49:33 +00001635 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattner548f61d2003-04-23 17:22:12 +00001636 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00001637}
Brian Gaekea1719c92002-10-31 23:03:59 +00001638
Chris Lattnereca195e2003-05-08 19:44:13 +00001639/// visitVarArgInst - Implement the va_arg instruction...
1640///
1641void ISel::visitVarArgInst(VarArgInst &I) {
1642 unsigned SrcReg = getReg(I.getOperand(0));
1643 unsigned DestReg = getReg(I);
1644
1645 // Load the va_list into a register...
1646 unsigned VAList = makeAnotherReg(Type::UIntTy);
1647 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1648
1649 unsigned Size;
1650 switch (I.getType()->getPrimitiveID()) {
1651 default:
1652 std::cerr << I;
1653 assert(0 && "Error: bad type for va_arg instruction!");
1654 return;
1655 case Type::PointerTyID:
1656 case Type::UIntTyID:
1657 case Type::IntTyID:
1658 Size = 4;
1659 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1660 break;
1661 case Type::ULongTyID:
1662 case Type::LongTyID:
1663 Size = 8;
1664 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1665 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1666 break;
1667 case Type::DoubleTyID:
1668 Size = 8;
1669 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1670 break;
1671 }
1672
1673 // Increment the VAList pointer...
1674 unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1675 BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1676
1677 // Update the VAList in memory...
1678 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1679}
1680
1681
Chris Lattner8a307e82002-12-16 19:32:50 +00001682// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1683// returns zero when the input is not exactly a power of two.
1684static unsigned ExactLog2(unsigned Val) {
1685 if (Val == 0) return 0;
1686 unsigned Count = 0;
1687 while (Val != 1) {
1688 if (Val & 1) return 0;
1689 Val >>= 1;
1690 ++Count;
1691 }
1692 return Count+1;
1693}
1694
Chris Lattner3e130a22003-01-13 00:32:26 +00001695void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1696 unsigned outputReg = getReg(I);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001697 MachineBasicBlock::iterator MI = BB->end();
1698 emitGEPOperation(BB, MI, I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00001699 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001700}
1701
Brian Gaeke71794c02002-12-13 11:22:48 +00001702void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001703 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +00001704 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +00001705 User::op_iterator IdxEnd, unsigned TargetReg) {
1706 const TargetData &TD = TM.getTargetData();
1707 const Type *Ty = Src->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +00001708 unsigned BaseReg = getReg(Src, MBB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001709
Brian Gaeke20244b72002-12-12 15:33:40 +00001710 // GEPs have zero or more indices; we must perform a struct access
1711 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +00001712 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1713 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001714 Value *idx = *oi;
Chris Lattner3e130a22003-01-13 00:32:26 +00001715 unsigned NextReg = BaseReg;
Chris Lattner065faeb2002-12-28 20:24:02 +00001716 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001717 // It's a struct access. idx is the index into the structure,
1718 // which names the field. This index must have ubyte type.
Chris Lattner065faeb2002-12-28 20:24:02 +00001719 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1720 assert(CUI->getType() == Type::UByteTy
Brian Gaeke20244b72002-12-12 15:33:40 +00001721 && "Funny-looking structure index in GEP");
1722 // Use the TargetData structure to pick out what the layout of
1723 // the structure is in memory. Since the structure index must
1724 // be constant, we can get its value and use it to find the
1725 // right byte offset from the StructLayout class's list of
1726 // structure member offsets.
Chris Lattnere8f0d922002-12-24 00:03:11 +00001727 unsigned idxValue = CUI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001728 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1729 if (FieldOff) {
1730 NextReg = makeAnotherReg(Type::UIntTy);
1731 // Emit an ADD to add FieldOff to the basePtr.
1732 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1733 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001734 // The next type is the member of the structure selected by the
1735 // index.
Chris Lattner065faeb2002-12-28 20:24:02 +00001736 Ty = StTy->getElementTypes()[idxValue];
1737 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001738 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner8a307e82002-12-16 19:32:50 +00001739
Brian Gaeke20244b72002-12-12 15:33:40 +00001740 // idx is the index into the array. Unlike with structure
1741 // indices, we may not know its actual value at code-generation
1742 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00001743 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1744
Chris Lattner3e130a22003-01-13 00:32:26 +00001745 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00001746 // must find the size of the pointed-to type (Not coincidentally, the next
1747 // type is the type of the elements in the array).
1748 Ty = SqTy->getElementType();
1749 unsigned elementSize = TD.getTypeSize(Ty);
1750
1751 // If idxReg is a constant, we don't need to perform the multiply!
1752 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001753 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00001754 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001755 NextReg = makeAnotherReg(Type::UIntTy);
1756 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
Chris Lattner8a307e82002-12-16 19:32:50 +00001757 }
1758 } else if (elementSize == 1) {
1759 // If the element size is 1, we don't have to multiply, just add
1760 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001761 NextReg = makeAnotherReg(Type::UIntTy);
1762 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001763 } else {
1764 unsigned idxReg = getReg(idx, MBB, IP);
1765 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1766 if (unsigned Shift = ExactLog2(elementSize)) {
1767 // If the element size is exactly a power of 2, use a shift to get it.
Chris Lattner8a307e82002-12-16 19:32:50 +00001768 BMI(MBB, IP, X86::SHLir32, 2,
1769 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1770 } else {
1771 // Most general case, emit a multiply...
1772 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1773 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1774
1775 // Emit a MUL to multiply the register holding the index by
1776 // elementSize, putting the result in OffsetReg.
Chris Lattner3e130a22003-01-13 00:32:26 +00001777 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001778 }
1779 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3e130a22003-01-13 00:32:26 +00001780 NextReg = makeAnotherReg(Type::UIntTy);
1781 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001782 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001783 }
1784 // Now that we are here, further indices refer to subtypes of this
Chris Lattner3e130a22003-01-13 00:32:26 +00001785 // one, so we don't need to worry about BaseReg itself, anymore.
1786 BaseReg = NextReg;
Brian Gaeke20244b72002-12-12 15:33:40 +00001787 }
1788 // After we have processed all the indices, the result is left in
Chris Lattner3e130a22003-01-13 00:32:26 +00001789 // BaseReg. Move it to the register where we were expected to
Brian Gaeke20244b72002-12-12 15:33:40 +00001790 // put the answer. A 32-bit move should do it, because we are in
1791 // ILP32 land.
Chris Lattner3e130a22003-01-13 00:32:26 +00001792 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001793}
1794
1795
Chris Lattner065faeb2002-12-28 20:24:02 +00001796/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1797/// frame manager, otherwise do it the hard way.
1798///
1799void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00001800 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00001801 const Type *Ty = I.getAllocatedType();
1802 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1803
1804 // If this is a fixed size alloca in the entry block for the function,
1805 // statically stack allocate the space.
1806 //
1807 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1808 if (I.getParent() == I.getParent()->getParent()->begin()) {
1809 TySize *= CUI->getValue(); // Get total allocated size...
1810 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1811
1812 // Create a new stack object using the frame manager...
1813 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1814 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1815 return;
1816 }
1817 }
1818
1819 // Create a register to hold the temporary result of multiplying the type size
1820 // constant by the variable amount.
1821 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1822 unsigned SrcReg1 = getReg(I.getArraySize());
1823 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1824 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1825
1826 // TotalSizeReg = mul <numelements>, <TypeSize>
1827 MachineBasicBlock::iterator MBBI = BB->end();
1828 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1829
1830 // AddedSize = add <TotalSizeReg>, 15
1831 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1832 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1833
1834 // AlignedSize = and <AddedSize>, ~15
1835 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1836 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1837
Brian Gaekee48ec012002-12-13 06:46:31 +00001838 // Subtract size from stack pointer, thereby allocating some space.
Chris Lattner3e130a22003-01-13 00:32:26 +00001839 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00001840
Brian Gaekee48ec012002-12-13 06:46:31 +00001841 // Put a pointer to the space into the result register, by copying
1842 // the stack pointer.
Chris Lattner065faeb2002-12-28 20:24:02 +00001843 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1844
Misha Brukman48196b32003-05-03 02:18:17 +00001845 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00001846 // object.
1847 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00001848}
Chris Lattner3e130a22003-01-13 00:32:26 +00001849
1850/// visitMallocInst - Malloc instructions are code generated into direct calls
1851/// to the library malloc.
1852///
1853void ISel::visitMallocInst(MallocInst &I) {
1854 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1855 unsigned Arg;
1856
1857 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1858 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1859 } else {
1860 Arg = makeAnotherReg(Type::UIntTy);
1861 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1862 unsigned Op1Reg = getReg(I.getOperand(0));
1863 MachineBasicBlock::iterator MBBI = BB->end();
1864 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1865
1866
1867 }
1868
1869 std::vector<ValueRecord> Args;
1870 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1871 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1872 1).addExternalSymbol("malloc", true);
1873 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1874}
1875
1876
1877/// visitFreeInst - Free instructions are code gen'd to call the free libc
1878/// function.
1879///
1880void ISel::visitFreeInst(FreeInst &I) {
1881 std::vector<ValueRecord> Args;
1882 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1883 I.getOperand(0)->getType()));
1884 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1885 1).addExternalSymbol("free", true);
1886 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1887}
1888
Brian Gaeke20244b72002-12-12 15:33:40 +00001889
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001890/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1891/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001892/// generated code sucks but the implementation is nice and simple.
1893///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001894Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1895 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001896}