blob: 1adcd52c2e38653c553c892f0d84327c828c34b9 [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner3e130a22003-01-13 00:32:26 +000010// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "X86InstrBuilder.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000016#include "X86InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner72614082002-10-25 22:55:53 +000019#include "llvm/Function.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000020#include "llvm/Instructions.h"
Chris Lattner44827152003-12-28 09:47:19 +000021#include "llvm/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000022#include "llvm/Pass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner341a9372002-10-29 17:43:55 +000025#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner94af4142002-12-25 05:13:53 +000026#include "llvm/CodeGen/SSARegMap.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000027#include "llvm/Target/MRegisterInfo.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000028#include "llvm/Target/TargetMachine.h"
Chris Lattner3f1e8e72004-02-22 07:04:00 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000030#include "llvm/Support/InstVisitor.h"
Chris Lattner986618e2004-02-22 19:47:26 +000031#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner986618e2004-02-22 19:47:26 +000034namespace {
35 Statistic<>
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
Chris Lattner427aeb42004-04-11 19:21:59 +000037
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39 /// Representation.
40 ///
41 enum TypeClass {
42 cByte, cShort, cInt, cFP, cLong
43 };
44}
45
46/// getClass - Turn a primitive type into a "class" number which is based on the
47/// size of the type, and whether or not it is floating point.
48///
49static inline TypeClass getClass(const Type *Ty) {
50 switch (Ty->getPrimitiveID()) {
51 case Type::SByteTyID:
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::ShortTyID:
54 case Type::UShortTyID: return cShort; // Short operands are class #1
55 case Type::IntTyID:
56 case Type::UIntTyID:
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
58
59 case Type::FloatTyID:
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
61
62 case Type::LongTyID:
63 case Type::ULongTyID: return cLong; // Longs are class #4
64 default:
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
67 }
68}
69
70// getClassB - Just like getClass, but treat boolean values as bytes.
71static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
73 return getClass(Ty);
Chris Lattner986618e2004-02-22 19:47:26 +000074}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000075
Chris Lattner72614082002-10-25 22:55:53 +000076namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000077 struct ISel : public FunctionPass, InstVisitor<ISel> {
78 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000079 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000082 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000083
Chris Lattner72614082002-10-25 22:55:53 +000084 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
85
Chris Lattner333b2fa2002-12-13 10:09:43 +000086 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
Chris Lattnercb2fd552004-05-13 07:40:27 +000089 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
92
Chris Lattnerf70e0c22003-12-28 21:23:38 +000093 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000094
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
97 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000098 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000099 // First pass over the function, lower any unknown intrinsic functions
100 // with the IntrinsicLowering class.
101 LowerUnknownIntrinsicFunctionCalls(Fn);
102
Chris Lattner36b36032002-10-29 23:40:58 +0000103 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104
Chris Lattner065faeb2002-12-28 20:24:02 +0000105 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000106 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
107 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
108
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000109 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000110
Chris Lattner0e5b79c2004-02-15 01:04:03 +0000111 // Set up a frame object for the return address. This is used by the
112 // llvm.returnaddress & llvm.frameaddress intrinisics.
113 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
114
Chris Lattnerdbd73722003-05-06 21:32:22 +0000115 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000116 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000117
Chris Lattner333b2fa2002-12-13 10:09:43 +0000118 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000119 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000120
121 // Select the PHI nodes
122 SelectPHINodes();
123
Chris Lattner986618e2004-02-22 19:47:26 +0000124 // Insert the FP_REG_KILL instructions into blocks that need them.
125 InsertFPRegKills();
126
Chris Lattner72614082002-10-25 22:55:53 +0000127 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000128 MBBMap.clear();
Chris Lattnercb2fd552004-05-13 07:40:27 +0000129 AllocaMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000130 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000131 // We always build a machine code representation for the function
132 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000133 }
134
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000135 virtual const char *getPassName() const {
136 return "X86 Simple Instruction Selection";
137 }
138
Chris Lattner72614082002-10-25 22:55:53 +0000139 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000140 /// block. This simply creates a new MachineBasicBlock to emit code into
141 /// and adds it to the current MachineFunction. Subsequent visit* for
142 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000143 ///
144 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000145 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000146 }
147
Chris Lattner44827152003-12-28 09:47:19 +0000148 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
149 /// function, lowering any calls to unknown intrinsic functions into the
150 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000151 ///
Chris Lattner44827152003-12-28 09:47:19 +0000152 void LowerUnknownIntrinsicFunctionCalls(Function &F);
153
Chris Lattner065faeb2002-12-28 20:24:02 +0000154 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
155 /// from the stack into virtual registers.
156 ///
157 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000158
159 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
160 /// because we have to generate our sources into the source basic blocks,
161 /// not the current one.
162 ///
163 void SelectPHINodes();
164
Chris Lattner986618e2004-02-22 19:47:26 +0000165 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
166 /// that need them. This only occurs due to the floating point stackifier
167 /// not being aggressive enough to handle arbitrary global stackification.
168 ///
169 void InsertFPRegKills();
170
Chris Lattner72614082002-10-25 22:55:53 +0000171 // Visitation methods for various instructions. These methods simply emit
172 // fixed X86 code for each instruction.
173 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000174
175 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000176 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000177 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000178
179 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000180 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000181 unsigned Reg;
182 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000183 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
184 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000185 };
186 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000187 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000188 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000189 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000190
191 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000192 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000193 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
194 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerca9671d2002-11-02 20:28:58 +0000195 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000196
Chris Lattnerf01729e2002-11-02 20:54:46 +0000197 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
198 void visitRem(BinaryOperator &B) { visitDivRem(B); }
199 void visitDivRem(BinaryOperator &B);
200
Chris Lattnere2954c82002-11-02 20:04:26 +0000201 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000202 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
203 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
204 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000205
Chris Lattner6d40c192003-01-16 16:43:00 +0000206 // Comparison operators...
207 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000208 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
209 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000210 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000211 void visitSelectInst(SelectInst &SI);
212
Chris Lattnerb2acc512003-10-19 21:09:10 +0000213
Chris Lattner6fc3c522002-11-17 21:11:55 +0000214 // Memory Instructions
215 void visitLoadInst(LoadInst &I);
216 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000217 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000218 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000219 void visitMallocInst(MallocInst &I);
220 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000221
Chris Lattnere2954c82002-11-02 20:04:26 +0000222 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000223 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000224 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000225 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000226 void visitVANextInst(VANextInst &I);
227 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000228
229 void visitInstruction(Instruction &I) {
230 std::cerr << "Cannot instruction select: " << I;
231 abort();
232 }
233
Brian Gaeke95780cc2002-12-13 07:56:18 +0000234 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000235 ///
236 void promote32(unsigned targetReg, const ValueRecord &VR);
237
Chris Lattner721d2d42004-03-08 01:18:36 +0000238 /// getAddressingMode - Get the addressing mode to use to address the
239 /// specified value. The returned value should be used with addFullAddress.
240 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
241 unsigned &IndexReg, unsigned &Disp);
242
243
244 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
245 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000246 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
247 std::vector<Value*> &GEPOps,
248 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
249 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
250
251 /// isGEPFoldable - Return true if the specified GEP can be completely
252 /// folded into the addressing mode of a load/store or lea instruction.
253 bool isGEPFoldable(MachineBasicBlock *MBB,
254 Value *Src, User::op_iterator IdxBegin,
255 User::op_iterator IdxEnd, unsigned &BaseReg,
256 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
257
Chris Lattner3e130a22003-01-13 00:32:26 +0000258 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
259 /// constant expression GEP support.
260 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000261 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000262 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000263 User::op_iterator IdxEnd, unsigned TargetReg);
264
Chris Lattner548f61d2003-04-23 17:22:12 +0000265 /// emitCastOperation - Common code shared between visitCastInst and
266 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000267 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000268 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000269 Value *Src, const Type *DestTy, unsigned TargetReg);
270
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000271 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
272 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000273 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000274 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000275 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000276 Value *Op0, Value *Op1,
277 unsigned OperatorClass, unsigned TargetReg);
278
Chris Lattner6621ed92004-04-11 21:23:56 +0000279 /// emitBinaryFPOperation - This method handles emission of floating point
280 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
281 void emitBinaryFPOperation(MachineBasicBlock *BB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1,
284 unsigned OperatorClass, unsigned TargetReg);
285
Chris Lattner462fa822004-04-11 20:56:28 +0000286 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
287 Value *Op0, Value *Op1, unsigned TargetReg);
288
289 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
290 unsigned DestReg, const Type *DestTy,
291 unsigned Op0Reg, unsigned Op1Reg);
292 void doMultiplyConst(MachineBasicBlock *MBB,
293 MachineBasicBlock::iterator MBBI,
294 unsigned DestReg, const Type *DestTy,
295 unsigned Op0Reg, unsigned Op1Val);
296
Chris Lattnercadff442003-10-23 17:21:43 +0000297 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000298 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +0000299 Value *Op0, Value *Op1, bool isDiv,
300 unsigned TargetReg);
Chris Lattnercadff442003-10-23 17:21:43 +0000301
Chris Lattner58c41fe2003-08-24 19:19:47 +0000302 /// emitSetCCOperation - Common code shared between visitSetCondInst and
303 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000304 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000305 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000306 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000307 Value *Op0, Value *Op1, unsigned Opcode,
308 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000309
310 /// emitShiftOperation - Common code shared between visitShiftInst and
311 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000312 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000313 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000314 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000315 Value *Op, Value *ShiftAmount, bool isLeftShift,
316 const Type *ResultTy, unsigned DestReg);
317
Chris Lattner12d96a02004-03-30 21:22:00 +0000318 /// emitSelectOperation - Common code shared between visitSelectInst and the
319 /// constant expression support.
320 void emitSelectOperation(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 Value *Cond, Value *TrueVal, Value *FalseVal,
323 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000324
Chris Lattnerc5291f52002-10-27 21:16:59 +0000325 /// copyConstantToRegister - Output the instructions required to put the
326 /// specified constant into the specified register.
327 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000328 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000329 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000330 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000331
Chris Lattner3e130a22003-01-13 00:32:26 +0000332 /// makeAnotherReg - This method returns the next register number we haven't
333 /// yet used.
334 ///
335 /// Long values are handled somewhat specially. They are always allocated
336 /// as pairs of 32 bit integer values. The register number returned is the
337 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
338 /// of the long value.
339 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000340 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000341 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
342 "Current target doesn't have X86 reg info??");
343 const X86RegisterInfo *MRI =
344 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000345 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000346 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
347 // Create the lower part
348 F->getSSARegMap()->createVirtualRegister(RC);
349 // Create the upper part.
350 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000351 }
352
Chris Lattnerc0812d82002-12-13 06:56:29 +0000353 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000354 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000355 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000356 }
357
Chris Lattnercb2fd552004-05-13 07:40:27 +0000358 /// getReg - This method turns an LLVM value into a register number.
Chris Lattner72614082002-10-25 22:55:53 +0000359 ///
360 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000361 unsigned getReg(Value *V) {
362 // Just append to the end of the current bb.
363 MachineBasicBlock::iterator It = BB->end();
364 return getReg(V, BB, It);
365 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000366 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnercb2fd552004-05-13 07:40:27 +0000367 MachineBasicBlock::iterator IPt);
Chris Lattner427aeb42004-04-11 19:21:59 +0000368
Chris Lattnercb2fd552004-05-13 07:40:27 +0000369 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
370 /// that is to be statically allocated with the initial stack frame
371 /// adjustment.
372 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
Chris Lattner72614082002-10-25 22:55:53 +0000373 };
374}
375
Chris Lattnercb2fd552004-05-13 07:40:27 +0000376/// dyn_castFixedAlloca - If the specified value is a fixed size alloca
377/// instruction in the entry block, return it. Otherwise, return a null
378/// pointer.
379static AllocaInst *dyn_castFixedAlloca(Value *V) {
380 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
381 BasicBlock *BB = AI->getParent();
382 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
383 return AI;
384 }
385 return 0;
386}
387
388/// getReg - This method turns an LLVM value into a register number.
389///
390unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
391 MachineBasicBlock::iterator IPt) {
392 // If this operand is a constant, emit the code to copy the constant into
393 // the register here...
394 //
395 if (Constant *C = dyn_cast<Constant>(V)) {
396 unsigned Reg = makeAnotherReg(V->getType());
397 copyConstantToRegister(MBB, IPt, C, Reg);
398 return Reg;
399 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
400 unsigned Reg = makeAnotherReg(V->getType());
401 // Move the address of the global into the register
402 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
403 return Reg;
404 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
405 // Do not emit noop casts at all.
406 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
407 return getReg(CI->getOperand(0), MBB, IPt);
408 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
409 // If the alloca address couldn't be folded into the instruction addressing,
410 // emit an explicit LEA as appropriate.
411 unsigned Reg = makeAnotherReg(V->getType());
412 unsigned FI = getFixedSizedAllocaFI(AI);
413 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
414 return Reg;
415 }
416
417 unsigned &Reg = RegMap[V];
418 if (Reg == 0) {
419 Reg = makeAnotherReg(V->getType());
420 RegMap[V] = Reg;
421 }
422
423 return Reg;
424}
425
426/// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
427/// that is to be statically allocated with the initial stack frame
428/// adjustment.
429unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
430 // Already computed this?
431 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
432 if (I != AllocaMap.end() && I->first == AI) return I->second;
433
434 const Type *Ty = AI->getAllocatedType();
435 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
436 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
437 TySize *= CUI->getValue(); // Get total allocated size...
438 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
439
440 // Create a new stack object using the frame manager...
441 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
442 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
443 return FrameIdx;
444}
445
446
Chris Lattnerc5291f52002-10-27 21:16:59 +0000447/// copyConstantToRegister - Output the instructions required to put the
448/// specified constant into the specified register.
449///
Chris Lattner8a307e82002-12-16 19:32:50 +0000450void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000451 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000452 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000454 unsigned Class = 0;
455 switch (CE->getOpcode()) {
456 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000457 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000458 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000459 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000460 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000461 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000462 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000463
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000464 case Instruction::Xor: ++Class; // FALL THROUGH
465 case Instruction::Or: ++Class; // FALL THROUGH
466 case Instruction::And: ++Class; // FALL THROUGH
467 case Instruction::Sub: ++Class; // FALL THROUGH
468 case Instruction::Add:
469 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
470 Class, R);
471 return;
472
Chris Lattner462fa822004-04-11 20:56:28 +0000473 case Instruction::Mul:
474 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
Chris Lattnercadff442003-10-23 17:21:43 +0000475 return;
Chris Lattner462fa822004-04-11 20:56:28 +0000476
Chris Lattnercadff442003-10-23 17:21:43 +0000477 case Instruction::Div:
Chris Lattner462fa822004-04-11 20:56:28 +0000478 case Instruction::Rem:
479 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
480 CE->getOpcode() == Instruction::Div, R);
Chris Lattnercadff442003-10-23 17:21:43 +0000481 return;
Chris Lattnercadff442003-10-23 17:21:43 +0000482
Chris Lattner58c41fe2003-08-24 19:19:47 +0000483 case Instruction::SetNE:
484 case Instruction::SetEQ:
485 case Instruction::SetLT:
486 case Instruction::SetGT:
487 case Instruction::SetLE:
488 case Instruction::SetGE:
489 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
490 CE->getOpcode(), R);
491 return;
492
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000493 case Instruction::Shl:
494 case Instruction::Shr:
495 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000496 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
497 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000498
Chris Lattner12d96a02004-03-30 21:22:00 +0000499 case Instruction::Select:
500 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
501 CE->getOperand(2), R);
502 return;
503
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000504 default:
505 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000506 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000507 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000508 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000509
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000510 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000511 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000512
513 if (Class == cLong) {
514 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000515 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000516 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
517 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000518 return;
519 }
520
Chris Lattner94af4142002-12-25 05:13:53 +0000521 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000522
523 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000524 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000525 };
526
Chris Lattner6b993cc2002-12-15 08:02:15 +0000527 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000528 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000529 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000530 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000531 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000532 }
Chris Lattner94af4142002-12-25 05:13:53 +0000533 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000534 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000535 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000536 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000537 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000538 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000539 // Otherwise we need to spill the constant to memory...
540 MachineConstantPool *CP = F->getConstantPool();
541 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000542 const Type *Ty = CFP->getType();
543
544 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000545 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000546 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000547 }
548
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000549 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000550 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000551 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000552 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000553 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000554 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000555 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000556 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000557 }
558}
559
Chris Lattner065faeb2002-12-28 20:24:02 +0000560/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
561/// the stack into virtual registers.
562///
563void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
564 // Emit instructions to load the arguments... On entry to a function on the
565 // X86, the stack frame looks like this:
566 //
567 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000568 // [ESP + 4] -- first argument (leftmost lexically)
569 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000570 // ...
571 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000572 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000573 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000574
575 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000576 bool ArgLive = !I->use_empty();
577 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000578 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000579
Chris Lattner065faeb2002-12-28 20:24:02 +0000580 switch (getClassB(I->getType())) {
581 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000582 if (ArgLive) {
583 FI = MFI->CreateFixedObject(1, ArgOffset);
584 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
585 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000586 break;
587 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000588 if (ArgLive) {
589 FI = MFI->CreateFixedObject(2, ArgOffset);
590 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
591 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000592 break;
593 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000594 if (ArgLive) {
595 FI = MFI->CreateFixedObject(4, ArgOffset);
596 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
597 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000598 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000599 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000600 if (ArgLive) {
601 FI = MFI->CreateFixedObject(8, ArgOffset);
602 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
603 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
604 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000605 ArgOffset += 4; // longs require 4 additional bytes
606 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000607 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000608 if (ArgLive) {
609 unsigned Opcode;
610 if (I->getType() == Type::FloatTy) {
611 Opcode = X86::FLD32m;
612 FI = MFI->CreateFixedObject(4, ArgOffset);
613 } else {
614 Opcode = X86::FLD64m;
615 FI = MFI->CreateFixedObject(8, ArgOffset);
616 }
617 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000618 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000619 if (I->getType() == Type::DoubleTy)
620 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000621 break;
622 default:
623 assert(0 && "Unhandled argument type!");
624 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000625 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000626 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000627
628 // If the function takes variable number of arguments, add a frame offset for
629 // the start of the first vararg value... this is used to expand
630 // llvm.va_start.
631 if (Fn.getFunctionType()->isVarArg())
632 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000633}
634
635
Chris Lattner333b2fa2002-12-13 10:09:43 +0000636/// SelectPHINodes - Insert machine code to generate phis. This is tricky
637/// because we have to generate our sources into the source basic blocks, not
638/// the current one.
639///
640void ISel::SelectPHINodes() {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000641 const TargetInstrInfo &TII = *TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000642 const Function &LF = *F->getFunction(); // The LLVM function...
643 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
644 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000645 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000646
647 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000648 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000649 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000650 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000651
Chris Lattner333b2fa2002-12-13 10:09:43 +0000652 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000653 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000654 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
655 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000656
657 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000658 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
659 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
660 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000661
Chris Lattnera6e73f12003-05-12 14:22:21 +0000662 // PHIValues - Map of blocks to incoming virtual registers. We use this
663 // so that we only initialize one incoming value for a particular block,
664 // even if the block has multiple entries in the PHI node.
665 //
666 std::map<MachineBasicBlock*, unsigned> PHIValues;
667
Chris Lattner333b2fa2002-12-13 10:09:43 +0000668 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
669 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000670 unsigned ValReg;
671 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
672 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000673
Chris Lattnera6e73f12003-05-12 14:22:21 +0000674 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
675 // We already inserted an initialization of the register for this
676 // predecessor. Recycle it.
677 ValReg = EntryIt->second;
678
679 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000680 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000681 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000682 Value *Val = PN->getIncomingValue(i);
683
684 // If this is a constant or GlobalValue, we may have to insert code
685 // into the basic block to compute it into a virtual register.
Chris Lattnercb2fd552004-05-13 07:40:27 +0000686 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
687 isa<GlobalValue>(Val)) {
688 // Simple constants get emitted at the end of the basic block,
689 // before any terminator instructions. We "know" that the code to
690 // move a constant into a register will never clobber any flags.
691 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
Chris Lattnera81fc682003-10-19 00:26:11 +0000692 } else {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000693 // Because we don't want to clobber any values which might be in
694 // physical registers with the computation of this constant (which
695 // might be arbitrarily complex if it is a constant expression),
696 // just insert the computation at the top of the basic block.
697 MachineBasicBlock::iterator PI = PredMBB->begin();
698
699 // Skip over any PHI nodes though!
700 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
701 ++PI;
702
703 ValReg = getReg(Val, PredMBB, PI);
Chris Lattnera81fc682003-10-19 00:26:11 +0000704 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000705
706 // Remember that we inserted a value for this PHI for this predecessor
707 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
708 }
709
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000710 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000711 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000712 if (LongPhiMI) {
713 LongPhiMI->addRegOperand(ValReg+1);
714 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
715 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000716 }
Chris Lattner168aa902004-02-29 07:10:16 +0000717
718 // Now that we emitted all of the incoming values for the PHI node, make
719 // sure to reposition the InsertPoint after the PHI that we just added.
720 // This is needed because we might have inserted a constant into this
721 // block, right after the PHI's which is before the old insert point!
722 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
723 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000724 }
725 }
726}
727
Chris Lattner986618e2004-02-22 19:47:26 +0000728/// RequiresFPRegKill - The floating point stackifier pass cannot insert
729/// compensation code on critical edges. As such, it requires that we kill all
730/// FP registers on the exit from any blocks that either ARE critical edges, or
731/// branch to a block that has incoming critical edges.
732///
733/// Note that this kill instruction will eventually be eliminated when
734/// restrictions in the stackifier are relaxed.
735///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000736static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000737#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000738 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000739 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
740 const BasicBlock *Succ = *SI;
741 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
742 ++PI; // Block have at least one predecessory
743 if (PI != PE) { // If it has exactly one, this isn't crit edge
744 // If this block has more than one predecessor, check all of the
745 // predecessors to see if they have multiple successors. If so, then the
746 // block we are analyzing needs an FPRegKill.
747 for (PI = pred_begin(Succ); PI != PE; ++PI) {
748 const BasicBlock *Pred = *PI;
749 succ_const_iterator SI2 = succ_begin(Pred);
750 ++SI2; // There must be at least one successor of this block.
751 if (SI2 != succ_end(Pred))
752 return true; // Yes, we must insert the kill on this edge.
753 }
754 }
755 }
756 // If we got this far, there is no need to insert the kill instruction.
757 return false;
758#else
759 return true;
760#endif
761}
762
763// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
764// need them. This only occurs due to the floating point stackifier not being
765// aggressive enough to handle arbitrary global stackification.
766//
767// Currently we insert an FP_REG_KILL instruction into each block that uses or
768// defines a floating point virtual register.
769//
770// When the global register allocators (like linear scan) finally update live
771// variable analysis, we can keep floating point values in registers across
772// portions of the CFG that do not involve critical edges. This will be a big
773// win, but we are waiting on the global allocators before we can do this.
774//
775// With a bit of work, the floating point stackifier pass can be enhanced to
776// break critical edges as needed (to make a place to put compensation code),
777// but this will require some infrastructure improvements as well.
778//
779void ISel::InsertFPRegKills() {
780 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000781
782 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000783 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000784 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
785 MachineOperand& MO = I->getOperand(i);
786 if (MO.isRegister() && MO.getReg()) {
787 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000788 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000789 if (RegMap.getRegClass(Reg)->getSize() == 10)
790 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000791 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000792 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000793 // If we haven't found an FP register use or def in this basic block, check
794 // to see if any of our successors has an FP PHI node, which will cause a
795 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000796 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
797 SE = BB->succ_end(); SI != SE; ++SI) {
798 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000799 for (MachineBasicBlock::iterator I = SBB->begin();
800 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
801 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
802 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000803 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000804 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000805 continue;
806 UsesFPReg:
807 // Okay, this block uses an FP register. If the block has successors (ie,
808 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Brian Gaeke1afe7732004-04-28 04:45:55 +0000809 if (BB->succ_size () && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000810 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000811 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000812 }
813 }
814}
815
816
Chris Lattner9f1b5312004-05-13 15:12:43 +0000817void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
818 unsigned &IndexReg, unsigned &Disp) {
819 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
820 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
821 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
822 BaseReg, Scale, IndexReg, Disp))
823 return;
824 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
825 if (CE->getOpcode() == Instruction::GetElementPtr)
826 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
827 BaseReg, Scale, IndexReg, Disp))
828 return;
829 }
830
831 // If it's not foldable, reset addr mode.
832 BaseReg = getReg(Addr);
833 Scale = 1; IndexReg = 0; Disp = 0;
834}
835
Chris Lattner307ecba2004-03-30 22:39:09 +0000836// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
837// it into the conditional branch or select instruction which is the only user
838// of the cc instruction. This is the case if the conditional branch is the
839// only user of the setcc, and if the setcc is in the same basic block as the
840// conditional branch. We also don't handle long arguments below, so we reject
841// them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000842//
Chris Lattner307ecba2004-03-30 22:39:09 +0000843static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000844 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000845 if (SCI->hasOneUse()) {
846 Instruction *User = cast<Instruction>(SCI->use_back());
847 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
848 SCI->getParent() == User->getParent() &&
Chris Lattner48c937e2004-04-06 17:34:50 +0000849 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
850 SCI->getOpcode() == Instruction::SetEQ ||
851 SCI->getOpcode() == Instruction::SetNE))
Chris Lattner6d40c192003-01-16 16:43:00 +0000852 return SCI;
853 }
854 return 0;
855}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000856
Chris Lattner6d40c192003-01-16 16:43:00 +0000857// Return a fixed numbering for setcc instructions which does not depend on the
858// order of the opcodes.
859//
860static unsigned getSetCCNumber(unsigned Opcode) {
861 switch(Opcode) {
862 default: assert(0 && "Unknown setcc instruction!");
863 case Instruction::SetEQ: return 0;
864 case Instruction::SetNE: return 1;
865 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000866 case Instruction::SetGE: return 3;
867 case Instruction::SetGT: return 4;
868 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000869 }
870}
Chris Lattner06925362002-11-17 21:56:38 +0000871
Chris Lattner6d40c192003-01-16 16:43:00 +0000872// LLVM -> X86 signed X86 unsigned
873// ----- ---------- ------------
874// seteq -> sete sete
875// setne -> setne setne
876// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000877// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000878// setgt -> setg seta
879// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000880// ----
881// sets // Used by comparison with 0 optimization
882// setns
883static const unsigned SetCCOpcodeTab[2][8] = {
884 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
885 0, 0 },
886 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
887 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000888};
889
Chris Lattnerb2acc512003-10-19 21:09:10 +0000890// EmitComparison - This function emits a comparison of the two operands,
891// returning the extended setcc code to use.
892unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
893 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000894 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000895 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000896 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000897 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000898 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000899
900 // Special case handling of: cmp R, i
Chris Lattner260195d2004-05-07 19:55:55 +0000901 if (isa<ConstantPointerNull>(Op1)) {
902 if (OpNum < 2) // seteq/setne -> test
903 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
904 else
905 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
906 return OpNum;
907
908 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere80e6372004-04-06 16:02:27 +0000909 if (Class == cByte || Class == cShort || Class == cInt) {
910 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000911
Chris Lattner333864d2003-06-05 19:30:30 +0000912 // Mask off any upper bits of the constant, if there are any...
913 Op1v &= (1ULL << (8 << Class)) - 1;
914
Chris Lattnerb2acc512003-10-19 21:09:10 +0000915 // If this is a comparison against zero, emit more efficient code. We
916 // can't handle unsigned comparisons against zero unless they are == or
917 // !=. These should have been strength reduced already anyway.
918 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
919 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000920 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000921 };
Chris Lattneree352852004-02-29 07:22:16 +0000922 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000923
924 if (OpNum == 2) return 6; // Map jl -> js
925 if (OpNum == 3) return 7; // Map jg -> jns
926 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000927 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000928
929 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000930 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000931 };
932
Chris Lattneree352852004-02-29 07:22:16 +0000933 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000934 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000935 } else {
936 assert(Class == cLong && "Unknown integer class!");
937 unsigned LowCst = CI->getRawValue();
938 unsigned HiCst = CI->getRawValue() >> 32;
939 if (OpNum < 2) { // seteq, setne
940 unsigned LoTmp = Op0r;
941 if (LowCst != 0) {
942 LoTmp = makeAnotherReg(Type::IntTy);
943 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
944 }
945 unsigned HiTmp = Op0r+1;
946 if (HiCst != 0) {
947 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +0000948 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +0000949 }
950 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
951 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
952 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +0000953 } else {
954 // Emit a sequence of code which compares the high and low parts once
955 // each, then uses a conditional move to handle the overflow case. For
956 // example, a setlt for long would generate code like this:
957 //
Chris Lattner9984fd02004-05-09 23:16:33 +0000958 // AL = lo(op1) < lo(op2) // Always unsigned comparison
959 // BL = hi(op1) < hi(op2) // Signedness depends on operands
960 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner48c937e2004-04-06 17:34:50 +0000961 //
962
963 // FIXME: This would be much better if we had hierarchical register
964 // classes! Until then, hardcode registers so that we can deal with
965 // their aliases (because we don't have conditional byte moves).
966 //
967 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
968 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
969 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
970 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
971 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
972 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
973 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
974 .addReg(X86::AX);
975 // NOTE: visitSetCondInst knows that the value is dumped into the BL
976 // register at this point for long values...
977 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000978 }
Chris Lattner333864d2003-06-05 19:30:30 +0000979 }
Chris Lattnere80e6372004-04-06 16:02:27 +0000980 }
Chris Lattner333864d2003-06-05 19:30:30 +0000981
Chris Lattner9f08a922004-02-03 18:54:04 +0000982 // Special case handling of comparison against +/- 0.0
983 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
984 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000985 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000986 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000987 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000988 return OpNum;
989 }
990
Chris Lattner58c41fe2003-08-24 19:19:47 +0000991 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000992 switch (Class) {
993 default: assert(0 && "Unknown type class!");
994 // Emit: cmp <var1>, <var2> (do the comparison). We can
995 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
996 // 32-bit.
997 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000998 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000999 break;
1000 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001001 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001002 break;
1003 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001004 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001005 break;
1006 case cFP:
Chris Lattner8d2822e2004-04-12 01:43:36 +00001007 if (0) { // for processors prior to the P6
1008 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
1009 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
1010 BuildMI(*MBB, IP, X86::SAHF, 1);
1011 } else {
Chris Lattner133dbb12004-04-12 03:02:48 +00001012 BuildMI(*MBB, IP, X86::FpUCOMI, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner8d2822e2004-04-12 01:43:36 +00001013 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001014 break;
1015
1016 case cLong:
1017 if (OpNum < 2) { // seteq, setne
1018 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1019 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1020 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001021 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1022 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1023 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001024 break; // Allow the sete or setne to be generated from flags set by OR
1025 } else {
1026 // Emit a sequence of code which compares the high and low parts once
1027 // each, then uses a conditional move to handle the overflow case. For
1028 // example, a setlt for long would generate code like this:
1029 //
1030 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1031 // BL = hi(op1) < hi(op2) // Always unsigned comparison
Chris Lattner9984fd02004-05-09 23:16:33 +00001032 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner3e130a22003-01-13 00:32:26 +00001033 //
1034
Chris Lattner6d40c192003-01-16 16:43:00 +00001035 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +00001036 // classes! Until then, hardcode registers so that we can deal with their
1037 // aliases (because we don't have conditional byte moves).
1038 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001039 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +00001040 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001041 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +00001042 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1043 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1044 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001045 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +00001046 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +00001047 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1048 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +00001049 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +00001050 }
1051 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001052 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +00001053}
Chris Lattner3e130a22003-01-13 00:32:26 +00001054
Chris Lattner6d40c192003-01-16 16:43:00 +00001055/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1056/// register, then move it to wherever the result should be.
1057///
1058void ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +00001059 if (canFoldSetCCIntoBranchOrSelect(&I))
1060 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +00001061
Chris Lattner6d40c192003-01-16 16:43:00 +00001062 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001063 MachineBasicBlock::iterator MII = BB->end();
1064 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1065 DestReg);
1066}
Chris Lattner6d40c192003-01-16 16:43:00 +00001067
Chris Lattner58c41fe2003-08-24 19:19:47 +00001068/// emitSetCCOperation - Common code shared between visitSetCondInst and
1069/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +00001070///
Chris Lattner58c41fe2003-08-24 19:19:47 +00001071void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001072 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +00001073 Value *Op0, Value *Op1, unsigned Opcode,
1074 unsigned TargetReg) {
1075 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001076 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001077
Chris Lattnerb2acc512003-10-19 21:09:10 +00001078 const Type *CompTy = Op0->getType();
1079 unsigned CompClass = getClassB(CompTy);
1080 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1081
1082 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +00001083 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001084 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +00001085 } else {
1086 // Handle long comparisons by copying the value which is already in BL into
1087 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001088 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +00001089 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001090}
Chris Lattner51b49a92002-11-02 19:45:49 +00001091
Chris Lattner12d96a02004-03-30 21:22:00 +00001092void ISel::visitSelectInst(SelectInst &SI) {
1093 unsigned DestReg = getReg(SI);
1094 MachineBasicBlock::iterator MII = BB->end();
1095 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1096 SI.getFalseValue(), DestReg);
1097}
1098
1099/// emitSelect - Common code shared between visitSelectInst and the constant
1100/// expression support.
1101void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1102 MachineBasicBlock::iterator IP,
1103 Value *Cond, Value *TrueVal, Value *FalseVal,
1104 unsigned DestReg) {
1105 unsigned SelectClass = getClassB(TrueVal->getType());
1106
1107 // We don't support 8-bit conditional moves. If we have incoming constants,
1108 // transform them into 16-bit constants to avoid having a run-time conversion.
1109 if (SelectClass == cByte) {
1110 if (Constant *T = dyn_cast<Constant>(TrueVal))
1111 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1112 if (Constant *F = dyn_cast<Constant>(FalseVal))
1113 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1114 }
1115
Chris Lattner82c5a992004-04-13 21:56:09 +00001116 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1117 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1118 if (TrueReg == FalseReg) {
1119 static const unsigned Opcode[] = {
1120 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1121 };
1122 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1123 if (SelectClass == cLong)
1124 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1125 return;
1126 }
1127
Chris Lattner307ecba2004-03-30 22:39:09 +00001128 unsigned Opcode;
1129 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1130 // We successfully folded the setcc into the select instruction.
1131
1132 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1133 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1134 IP);
1135
1136 const Type *CompTy = SCI->getOperand(0)->getType();
1137 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1138
1139 // LLVM -> X86 signed X86 unsigned
1140 // ----- ---------- ------------
1141 // seteq -> cmovNE cmovNE
1142 // setne -> cmovE cmovE
1143 // setlt -> cmovGE cmovAE
1144 // setge -> cmovL cmovB
1145 // setgt -> cmovLE cmovBE
1146 // setle -> cmovG cmovA
1147 // ----
1148 // cmovNS // Used by comparison with 0 optimization
1149 // cmovS
1150
1151 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001152 default: assert(0 && "Unknown value class!");
1153 case cFP: {
1154 // Annoyingly, we don't have a full set of floating point conditional
1155 // moves. :(
1156 static const unsigned OpcodeTab[2][8] = {
1157 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1158 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1159 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1160 };
1161 Opcode = OpcodeTab[isSigned][OpNum];
1162
1163 // If opcode == 0, we hit a case that we don't support. Output a setcc
1164 // and compare the result against zero.
1165 if (Opcode == 0) {
1166 unsigned CompClass = getClassB(CompTy);
1167 unsigned CondReg;
1168 if (CompClass != cLong || OpNum < 2) {
1169 CondReg = makeAnotherReg(Type::BoolTy);
1170 // Handle normal comparisons with a setcc instruction...
1171 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1172 } else {
1173 // Long comparisons end up in the BL register.
1174 CondReg = X86::BL;
1175 }
1176
Chris Lattner68626c22004-03-31 22:22:36 +00001177 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001178 Opcode = X86::FCMOVE;
1179 }
1180 break;
1181 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001182 case cByte:
1183 case cShort: {
1184 static const unsigned OpcodeTab[2][8] = {
1185 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1186 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1187 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1188 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1189 };
1190 Opcode = OpcodeTab[isSigned][OpNum];
1191 break;
1192 }
1193 case cInt:
1194 case cLong: {
1195 static const unsigned OpcodeTab[2][8] = {
1196 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1197 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1198 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1199 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1200 };
1201 Opcode = OpcodeTab[isSigned][OpNum];
1202 break;
1203 }
1204 }
1205 } else {
1206 // Get the value being branched on, and use it to set the condition codes.
1207 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001208 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001209 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001210 default: assert(0 && "Unknown value class!");
1211 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001212 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001213 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001214 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001215 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001216 }
1217 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001218
Chris Lattner12d96a02004-03-30 21:22:00 +00001219 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001220
Chris Lattner12d96a02004-03-30 21:22:00 +00001221
1222 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1223 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1224 // cmove, then truncate the result.
1225 if (SelectClass == cByte) {
1226 DestReg = makeAnotherReg(Type::ShortTy);
1227 if (getClassB(TrueVal->getType()) == cByte) {
1228 // Promote the true value, by storing it into AL, and reading from AX.
1229 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1230 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1231 TrueReg = makeAnotherReg(Type::ShortTy);
1232 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1233 }
1234 if (getClassB(FalseVal->getType()) == cByte) {
1235 // Promote the true value, by storing it into CL, and reading from CX.
1236 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1237 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1238 FalseReg = makeAnotherReg(Type::ShortTy);
1239 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1240 }
1241 }
1242
1243 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1244
1245 switch (SelectClass) {
1246 case cByte:
1247 // We did the computation with 16-bit registers. Truncate back to our
1248 // result by copying into AX then copying out AL.
1249 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1250 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1251 break;
1252 case cLong:
1253 // Move the upper half of the value as well.
1254 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1255 break;
1256 }
1257}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001258
1259
1260
Brian Gaekec2505982002-11-30 11:57:28 +00001261/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1262/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001263///
Chris Lattner3e130a22003-01-13 00:32:26 +00001264void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
Chris Lattner9984fd02004-05-09 23:16:33 +00001265 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001266
Chris Lattner29bf0622004-04-06 01:21:00 +00001267 Value *Val = VR.Val;
1268 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001269 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001270 if (Constant *C = dyn_cast<Constant>(Val)) {
1271 Val = ConstantExpr::getCast(C, Type::IntTy);
1272 Ty = Type::IntTy;
1273 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001274
Chris Lattner502e36c2004-04-06 01:25:33 +00001275 // If this is a simple constant, just emit a MOVri directly to avoid the
1276 // copy.
1277 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1278 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
Chris Lattner2b10b082004-05-12 16:35:04 +00001279 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
Chris Lattner502e36c2004-04-06 01:25:33 +00001280 return;
1281 }
1282 }
1283
Chris Lattner29bf0622004-04-06 01:21:00 +00001284 // Make sure we have the register number for this value...
1285 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1286
1287 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001288 case cByte:
1289 // Extend value into target register (8->32)
1290 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001291 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001292 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001293 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001294 break;
1295 case cShort:
1296 // Extend value into target register (16->32)
1297 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001298 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001299 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001300 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001301 break;
1302 case cInt:
1303 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001304 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001305 break;
1306 default:
1307 assert(0 && "Unpromotable operand class in promote32");
1308 }
Brian Gaekec2505982002-11-30 11:57:28 +00001309}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001310
Chris Lattner72614082002-10-25 22:55:53 +00001311/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1312/// we have the following possibilities:
1313///
1314/// ret void: No return value, simply emit a 'ret' instruction
1315/// ret sbyte, ubyte : Extend value into EAX and return
1316/// ret short, ushort: Extend value into EAX and return
1317/// ret int, uint : Move value into EAX and return
1318/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001319/// ret long, ulong : Move value into EAX/EDX and return
1320/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001321///
Chris Lattner3e130a22003-01-13 00:32:26 +00001322void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001323 if (I.getNumOperands() == 0) {
1324 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1325 return;
1326 }
1327
1328 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001329 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001330 case cByte: // integral return values: extend or move into EAX and return
1331 case cShort:
1332 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001333 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001334 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001335 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001336 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001337 case cFP: { // Floats & Doubles: Return in ST(0)
1338 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001339 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001340 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001341 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001342 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001343 }
1344 case cLong: {
1345 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001346 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1347 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001348 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001349 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1350 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001351 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001352 }
Chris Lattner94af4142002-12-25 05:13:53 +00001353 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001354 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001355 }
Chris Lattner43189d12002-11-17 20:07:45 +00001356 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001357 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001358}
1359
Chris Lattner55f6fab2003-01-16 18:07:23 +00001360// getBlockAfter - Return the basic block which occurs lexically after the
1361// specified one.
1362static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1363 Function::iterator I = BB; ++I; // Get iterator to next block
1364 return I != BB->getParent()->end() ? &*I : 0;
1365}
1366
Chris Lattner51b49a92002-11-02 19:45:49 +00001367/// visitBranchInst - Handle conditional and unconditional branches here. Note
1368/// that since code layout is frozen at this point, that if we are trying to
1369/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001370/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001371///
Chris Lattner94af4142002-12-25 05:13:53 +00001372void ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001373 // Update machine-CFG edges
1374 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1375 if (BI.isConditional())
1376 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1377
Chris Lattner55f6fab2003-01-16 18:07:23 +00001378 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1379
1380 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001381 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001382 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner6d40c192003-01-16 16:43:00 +00001383 return;
1384 }
1385
1386 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001387 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001388 if (SCI == 0) {
1389 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1390 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001391 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001392 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001393 if (BI.getSuccessor(1) == NextBB) {
1394 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001395 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001396 } else {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001397 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001398
1399 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001400 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001401 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001402 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001403 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001404
1405 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001406 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001407 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001408
1409 const Type *CompTy = SCI->getOperand(0)->getType();
1410 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001411
Chris Lattnerb2acc512003-10-19 21:09:10 +00001412
Chris Lattner6d40c192003-01-16 16:43:00 +00001413 // LLVM -> X86 signed X86 unsigned
1414 // ----- ---------- ------------
1415 // seteq -> je je
1416 // setne -> jne jne
1417 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001418 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001419 // setgt -> jg ja
1420 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001421 // ----
1422 // js // Used by comparison with 0 optimization
1423 // jns
1424
1425 static const unsigned OpcodeTab[2][8] = {
1426 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1427 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1428 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001429 };
1430
Chris Lattner55f6fab2003-01-16 18:07:23 +00001431 if (BI.getSuccessor(0) != NextBB) {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001432 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1433 .addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001434 if (BI.getSuccessor(1) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001435 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001436 } else {
1437 // Change to the inverse condition...
1438 if (BI.getSuccessor(1) != NextBB) {
1439 OpNum ^= 1;
Brian Gaeke9f088e42004-05-14 06:54:56 +00001440 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1441 .addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001442 }
1443 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001444}
1445
Chris Lattner3e130a22003-01-13 00:32:26 +00001446
1447/// doCall - This emits an abstract call instruction, setting up the arguments
1448/// and the return value as appropriate. For the actual function call itself,
1449/// it inserts the specified CallMI instruction into the stream.
1450///
1451void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001452 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001453
Chris Lattner065faeb2002-12-28 20:24:02 +00001454 // Count how many bytes are to be pushed on the stack...
1455 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001456
Chris Lattner3e130a22003-01-13 00:32:26 +00001457 if (!Args.empty()) {
1458 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1459 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001460 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001461 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001462 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001463 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001464 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001465 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1466 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001467 default: assert(0 && "Unknown class!");
1468 }
1469
1470 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001471 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001472
1473 // Arguments go on the stack in reverse order, as specified by the ABI.
1474 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001475 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001476 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001477 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001478 case cByte:
Chris Lattner2b10b082004-05-12 16:35:04 +00001479 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1480 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1481 .addImm(Args[i].Val == ConstantBool::True);
1482 break;
1483 }
1484 // FALL THROUGH
Chris Lattner21585222004-03-01 02:42:43 +00001485 case cShort:
1486 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1487 // Zero/Sign extend constant, then stuff into memory.
1488 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1489 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1490 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1491 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1492 } else {
1493 // Promote arg to 32 bits wide into a temporary register...
1494 ArgReg = makeAnotherReg(Type::UIntTy);
1495 promote32(ArgReg, Args[i]);
1496 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1497 X86::ESP, ArgOffset).addReg(ArgReg);
1498 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001499 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001500 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001501 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1502 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1503 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1504 X86::ESP, ArgOffset).addImm(Val);
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00001505 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1506 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1507 X86::ESP, ArgOffset).addImm(0);
Chris Lattner21585222004-03-01 02:42:43 +00001508 } else {
1509 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1510 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1511 X86::ESP, ArgOffset).addReg(ArgReg);
1512 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001513 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001514 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001515 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1516 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1517 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1518 X86::ESP, ArgOffset).addImm(Val & ~0U);
1519 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1520 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1521 } else {
1522 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1523 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1524 X86::ESP, ArgOffset).addReg(ArgReg);
1525 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1526 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1527 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001528 ArgOffset += 4; // 8 byte entry, not 4.
1529 break;
1530
Chris Lattner065faeb2002-12-28 20:24:02 +00001531 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001532 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001533 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001534 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001535 X86::ESP, ArgOffset).addReg(ArgReg);
1536 } else {
1537 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001538 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001539 X86::ESP, ArgOffset).addReg(ArgReg);
1540 ArgOffset += 4; // 8 byte entry, not 4.
1541 }
1542 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001543
Chris Lattner3e130a22003-01-13 00:32:26 +00001544 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001545 }
1546 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001547 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001548 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001549 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001550 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001551
Chris Lattner3e130a22003-01-13 00:32:26 +00001552 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001553
Chris Lattneree352852004-02-29 07:22:16 +00001554 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001555
1556 // If there is a return value, scavenge the result from the location the call
1557 // leaves it in...
1558 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001559 if (Ret.Ty != Type::VoidTy) {
1560 unsigned DestClass = getClassB(Ret.Ty);
1561 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001562 case cByte:
1563 case cShort:
1564 case cInt: {
1565 // Integral results are in %eax, or the appropriate portion
1566 // thereof.
1567 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001568 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001569 };
1570 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001571 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001572 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001573 }
Chris Lattner94af4142002-12-25 05:13:53 +00001574 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001575 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001576 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001577 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001578 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1579 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001580 break;
1581 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001582 }
Chris Lattnera3243642002-12-04 23:45:28 +00001583 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001584}
Chris Lattner2df035b2002-11-02 19:27:56 +00001585
Chris Lattner3e130a22003-01-13 00:32:26 +00001586
1587/// visitCallInst - Push args on stack and do a procedure call instruction.
1588void ISel::visitCallInst(CallInst &CI) {
1589 MachineInstr *TheCall;
1590 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001591 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001592 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001593 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1594 return;
1595 }
1596
Chris Lattner3e130a22003-01-13 00:32:26 +00001597 // Emit a CALL instruction with PC-relative displacement.
1598 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1599 } else { // Emit an indirect call...
1600 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001601 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001602 }
1603
1604 std::vector<ValueRecord> Args;
1605 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001606 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001607
1608 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1609 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001610}
Chris Lattner3e130a22003-01-13 00:32:26 +00001611
Chris Lattneraeb54b82003-08-28 21:23:43 +00001612
Chris Lattner44827152003-12-28 09:47:19 +00001613/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1614/// function, lowering any calls to unknown intrinsic functions into the
1615/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001616///
Chris Lattner44827152003-12-28 09:47:19 +00001617void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1618 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1619 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1620 if (CallInst *CI = dyn_cast<CallInst>(I++))
1621 if (Function *F = CI->getCalledFunction())
1622 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001623 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001624 case Intrinsic::vastart:
1625 case Intrinsic::vacopy:
1626 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001627 case Intrinsic::returnaddress:
1628 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001629 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001630 case Intrinsic::memset:
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001631 case Intrinsic::isnan:
John Criswell4ffff9e2004-04-08 20:31:47 +00001632 case Intrinsic::readport:
1633 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001634 // We directly implement these intrinsics
1635 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001636 case Intrinsic::readio: {
1637 // On X86, memory operations are in-order. Lower this intrinsic
1638 // into a volatile load.
1639 Instruction *Before = CI->getPrev();
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001640 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1641 CI->replaceAllUsesWith(LI);
1642 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001643 break;
1644 }
1645 case Intrinsic::writeio: {
1646 // On X86, memory operations are in-order. Lower this intrinsic
1647 // into a volatile store.
1648 Instruction *Before = CI->getPrev();
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001649 StoreInst *LI = new StoreInst(CI->getOperand(1),
1650 CI->getOperand(2), true, CI);
1651 CI->replaceAllUsesWith(LI);
1652 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001653 break;
1654 }
Chris Lattner44827152003-12-28 09:47:19 +00001655 default:
1656 // All other intrinsic calls we must lower.
1657 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001658 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001659 if (Before) { // Move iterator to instruction after call
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001660 I = Before; ++I;
Chris Lattner44827152003-12-28 09:47:19 +00001661 } else {
1662 I = BB->begin();
1663 }
1664 }
Chris Lattner44827152003-12-28 09:47:19 +00001665}
1666
Brian Gaeked0fde302003-11-11 22:41:34 +00001667void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001668 unsigned TmpReg1, TmpReg2;
1669 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001670 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001671 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001672 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001673 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001674 return;
1675
Chris Lattner5634b9f2004-03-13 00:24:52 +00001676 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001677 TmpReg1 = getReg(CI);
1678 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001679 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001680 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001681 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001682
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001683 case Intrinsic::returnaddress:
1684 case Intrinsic::frameaddress:
1685 TmpReg1 = getReg(CI);
1686 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1687 if (ID == Intrinsic::returnaddress) {
1688 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001689 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001690 ReturnAddressIndex);
1691 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001692 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001693 ReturnAddressIndex, -4);
1694 }
1695 } else {
1696 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001697 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001698 }
1699 return;
1700
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001701 case Intrinsic::isnan:
1702 TmpReg1 = getReg(CI.getOperand(1));
1703 if (0) { // for processors prior to the P6
1704 BuildMI(BB, X86::FpUCOM, 2).addReg(TmpReg1).addReg(TmpReg1);
1705 BuildMI(BB, X86::FNSTSW8r, 0);
1706 BuildMI(BB, X86::SAHF, 1);
1707 } else {
1708 BuildMI(BB, X86::FpUCOMI, 2).addReg(TmpReg1).addReg(TmpReg1);
1709 }
1710 TmpReg2 = getReg(CI);
1711 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1712 return;
1713
Chris Lattner915e5e52004-02-12 17:53:22 +00001714 case Intrinsic::memcpy: {
1715 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1716 unsigned Align = 1;
1717 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1718 Align = AlignC->getRawValue();
1719 if (Align == 0) Align = 1;
1720 }
1721
1722 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001723 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001724 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001725 switch (Align & 3) {
1726 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001727 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1728 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1729 } else {
1730 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001731 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001732 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001733 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001734 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001735 break;
1736 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001737 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1738 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1739 } else {
1740 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001741 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001742 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001743 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001744 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001745 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001746 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001747 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001748 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001749 break;
1750 }
1751
1752 // No matter what the alignment is, we put the source in ESI, the
1753 // destination in EDI, and the count in ECX.
1754 TmpReg1 = getReg(CI.getOperand(1));
1755 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001756 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1757 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1758 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001759 BuildMI(BB, Opcode, 0);
1760 return;
1761 }
1762 case Intrinsic::memset: {
1763 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1764 unsigned Align = 1;
1765 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1766 Align = AlignC->getRawValue();
1767 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001768 }
1769
Chris Lattner2a0f2242004-02-14 04:46:05 +00001770 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001771 unsigned CountReg;
1772 unsigned Opcode;
1773 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1774 unsigned Val = ValC->getRawValue() & 255;
1775
1776 // If the value is a constant, then we can potentially use larger copies.
1777 switch (Align & 3) {
1778 case 2: // WORD aligned
1779 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001780 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001781 } else {
1782 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001783 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001784 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001785 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001786 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001787 Opcode = X86::REP_STOSW;
1788 break;
1789 case 0: // DWORD aligned
1790 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001791 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001792 } else {
1793 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001794 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001795 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001796 }
1797 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001798 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001799 Opcode = X86::REP_STOSD;
1800 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001801 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001802 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001803 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001804 Opcode = X86::REP_STOSB;
1805 break;
1806 }
1807 } else {
1808 // If it's not a constant value we are storing, just fall back. We could
1809 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1810 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001811 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001812 CountReg = getReg(CI.getOperand(3));
1813 Opcode = X86::REP_STOSB;
1814 }
1815
1816 // No matter what the alignment is, we put the source in ESI, the
1817 // destination in EDI, and the count in ECX.
1818 TmpReg1 = getReg(CI.getOperand(1));
1819 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001820 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1821 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001822 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001823 return;
1824 }
1825
Chris Lattner87e18de2004-04-13 17:20:37 +00001826 case Intrinsic::readport: {
1827 // First, determine that the size of the operand falls within the acceptable
1828 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001829 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001830 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001831 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001832 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001833 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001834
John Criswell4ffff9e2004-04-08 20:31:47 +00001835 // Now, move the I/O port address into the DX register and use the IN
1836 // instruction to get the input data.
1837 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001838 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1839 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001840
Chris Lattner87e18de2004-04-13 17:20:37 +00001841 // If the port is a single-byte constant, use the immediate form.
1842 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1843 if ((C->getRawValue() & 255) == C->getRawValue()) {
1844 switch (Class) {
1845 case cByte:
1846 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1847 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1848 return;
1849 case cShort:
1850 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1851 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1852 return;
1853 case cInt:
1854 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1855 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1856 return;
1857 }
1858 }
1859
1860 unsigned Reg = getReg(CI.getOperand(1));
1861 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1862 switch (Class) {
1863 case cByte:
1864 BuildMI(BB, X86::IN8rr, 0);
1865 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1866 break;
1867 case cShort:
1868 BuildMI(BB, X86::IN16rr, 0);
1869 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1870 break;
1871 case cInt:
1872 BuildMI(BB, X86::IN32rr, 0);
1873 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1874 break;
1875 default:
1876 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00001877 exit (1);
1878 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001879 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00001880 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001881
Chris Lattner87e18de2004-04-13 17:20:37 +00001882 case Intrinsic::writeport: {
1883 // First, determine that the size of the operand falls within the
1884 // acceptable range for this architecture.
1885 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1886 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1887 exit(1);
1888 }
1889
1890 unsigned Class = getClassB(CI.getOperand(1)->getType());
1891 unsigned ValReg = getReg(CI.getOperand(1));
1892 switch (Class) {
1893 case cByte:
1894 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1895 break;
1896 case cShort:
1897 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1898 break;
1899 case cInt:
1900 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1901 break;
1902 default:
1903 std::cerr << "llvm.writeport: invalid data type for X86 target";
1904 exit(1);
1905 }
1906
1907
1908 // If the port is a single-byte constant, use the immediate form.
1909 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1910 if ((C->getRawValue() & 255) == C->getRawValue()) {
1911 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1912 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1913 return;
1914 }
1915
1916 // Otherwise, move the I/O port address into the DX register and the value
1917 // to write into the AL/AX/EAX register.
1918 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1919 unsigned Reg = getReg(CI.getOperand(2));
1920 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1921 BuildMI(BB, Opc[Class], 0);
1922 return;
1923 }
1924
Chris Lattner44827152003-12-28 09:47:19 +00001925 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001926 }
1927}
1928
Chris Lattner7dee5da2004-03-08 01:58:35 +00001929static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1930 if (LI.getParent() != User.getParent())
1931 return false;
1932 BasicBlock::iterator It = &LI;
1933 // Check all of the instructions between the load and the user. We should
1934 // really use alias analysis here, but for now we just do something simple.
1935 for (++It; It != BasicBlock::iterator(&User); ++It) {
1936 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001937 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001938 case Instruction::Store:
1939 case Instruction::Call:
1940 case Instruction::Invoke:
1941 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00001942 case Instruction::Load:
1943 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1944 return false;
1945 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00001946 }
1947 }
1948 return true;
1949}
1950
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001951/// visitSimpleBinary - Implement simple binary operators for integral types...
1952/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1953/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001954///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001955void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1956 unsigned DestReg = getReg(B);
1957 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001958 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00001959 unsigned Class = getClassB(B.getType());
Chris Lattner721d2d42004-03-08 01:18:36 +00001960
Chris Lattner7dee5da2004-03-08 01:58:35 +00001961 // Special case: op Reg, load [mem]
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00001962 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
1963 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
Chris Lattner7dee5da2004-03-08 01:58:35 +00001964 if (!B.swapOperands())
1965 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1966
Chris Lattner95157f72004-04-11 22:05:45 +00001967 if (isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00001968 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1969
Chris Lattner95157f72004-04-11 22:05:45 +00001970 unsigned Opcode;
1971 if (Class != cFP) {
1972 static const unsigned OpcodeTab[][3] = {
1973 // Arithmetic operators
1974 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1975 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1976
1977 // Bitwise operators
1978 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1979 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1980 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1981 };
1982 Opcode = OpcodeTab[OperatorClass][Class];
1983 } else {
1984 static const unsigned OpcodeTab[][2] = {
1985 { X86::FADD32m, X86::FADD64m }, // ADD
1986 { X86::FSUB32m, X86::FSUB64m }, // SUB
1987 };
1988 const Type *Ty = Op0->getType();
1989 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1990 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
1991 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00001992
Chris Lattner7dee5da2004-03-08 01:58:35 +00001993 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00001994 if (AllocaInst *AI =
1995 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
1996 unsigned FI = getFixedSizedAllocaFI(AI);
1997 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
1998
1999 } else {
2000 unsigned BaseReg, Scale, IndexReg, Disp;
2001 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
2002 Scale, IndexReg, Disp);
2003
2004 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r),
2005 BaseReg, Scale, IndexReg, Disp);
2006 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002007 return;
2008 }
2009
Chris Lattner95157f72004-04-11 22:05:45 +00002010 // If this is a floating point subtract, check to see if we can fold the first
2011 // operand in.
2012 if (Class == cFP && OperatorClass == 1 &&
2013 isa<LoadInst>(Op0) &&
2014 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2015 const Type *Ty = Op0->getType();
2016 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2017 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2018
Chris Lattner95157f72004-04-11 22:05:45 +00002019 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002020 if (AllocaInst *AI =
2021 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2022 unsigned FI = getFixedSizedAllocaFI(AI);
2023 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2024 } else {
2025 unsigned BaseReg, Scale, IndexReg, Disp;
2026 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), BaseReg,
2027 Scale, IndexReg, Disp);
2028
2029 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r),
2030 BaseReg, Scale, IndexReg, Disp);
2031 }
Chris Lattner95157f72004-04-11 22:05:45 +00002032 return;
2033 }
2034
Chris Lattner721d2d42004-03-08 01:18:36 +00002035 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002036}
Chris Lattner3e130a22003-01-13 00:32:26 +00002037
Chris Lattner6621ed92004-04-11 21:23:56 +00002038
2039/// emitBinaryFPOperation - This method handles emission of floating point
2040/// Add (0), Sub (1), Mul (2), and Div (3) operations.
2041void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2042 MachineBasicBlock::iterator IP,
2043 Value *Op0, Value *Op1,
2044 unsigned OperatorClass, unsigned DestReg) {
2045
2046 // Special case: op Reg, <const fp>
2047 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2048 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2049 // Create a constant pool entry for this constant.
2050 MachineConstantPool *CP = F->getConstantPool();
2051 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2052 const Type *Ty = Op1->getType();
2053
2054 static const unsigned OpcodeTab[][4] = {
2055 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2056 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2057 };
2058
2059 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2060 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2061 unsigned Op0r = getReg(Op0, BB, IP);
2062 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2063 DestReg).addReg(Op0r), CPI);
2064 return;
2065 }
2066
Chris Lattner13c07fe2004-04-12 00:12:04 +00002067 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00002068 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2069 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2070 // -0.0 - X === -X
2071 unsigned op1Reg = getReg(Op1, BB, IP);
2072 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2073 return;
2074 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00002075 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00002076
2077 // Create a constant pool entry for this constant.
2078 MachineConstantPool *CP = F->getConstantPool();
2079 unsigned CPI = CP->getConstantPoolIndex(CFP);
2080 const Type *Ty = CFP->getType();
2081
2082 static const unsigned OpcodeTab[][4] = {
2083 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2084 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2085 };
2086
2087 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2088 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2089 unsigned Op1r = getReg(Op1, BB, IP);
2090 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2091 DestReg).addReg(Op1r), CPI);
2092 return;
2093 }
2094
2095 // General case.
2096 static const unsigned OpcodeTab[4] = {
2097 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2098 };
2099
2100 unsigned Opcode = OpcodeTab[OperatorClass];
2101 unsigned Op0r = getReg(Op0, BB, IP);
2102 unsigned Op1r = getReg(Op1, BB, IP);
2103 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2104}
2105
Chris Lattnerb2acc512003-10-19 21:09:10 +00002106/// emitSimpleBinaryOperation - Implement simple binary operators for integral
2107/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2108/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00002109///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002110/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2111/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002112///
2113void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002114 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002115 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002116 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002117 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002118
Chris Lattner6621ed92004-04-11 21:23:56 +00002119 if (Class == cFP) {
2120 assert(OperatorClass < 2 && "No logical ops for FP!");
2121 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2122 return;
2123 }
2124
Chris Lattnerb2acc512003-10-19 21:09:10 +00002125 // sub 0, X -> neg X
Chris Lattner48b0c972004-04-11 20:26:20 +00002126 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2127 if (OperatorClass == 1 && CI->isNullValue()) {
2128 unsigned op1Reg = getReg(Op1, MBB, IP);
2129 static unsigned const NEGTab[] = {
2130 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2131 };
2132 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2133
2134 if (Class == cLong) {
2135 // We just emitted: Dl = neg Sl
2136 // Now emit : T = addc Sh, 0
2137 // : Dh = neg T
2138 unsigned T = makeAnotherReg(Type::IntTy);
2139 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2140 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002141 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002142 return;
2143 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002144
Chris Lattner48b0c972004-04-11 20:26:20 +00002145 // Special case: op Reg, <const int>
2146 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002147 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002148
Chris Lattner721d2d42004-03-08 01:18:36 +00002149 // xor X, -1 -> not X
2150 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002151 static unsigned const NOTTab[] = {
2152 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2153 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002154 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002155 if (Class == cLong) // Invert the top part too
2156 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002157 return;
2158 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002159
Chris Lattner721d2d42004-03-08 01:18:36 +00002160 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002161 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2162 // Note that we can't use dec for 64-bit decrements, because it does not
2163 // set the carry flag!
2164 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002165 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2166 return;
2167 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002168
Chris Lattner721d2d42004-03-08 01:18:36 +00002169 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002170 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2171 // Note that we can't use inc for 64-bit increments, because it does not
2172 // set the carry flag!
2173 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002174 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002175 return;
2176 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002177
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002178 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002179 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002180 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2181 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002182
Chris Lattner721d2d42004-03-08 01:18:36 +00002183 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002184 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2185 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2186 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002187 };
2188
Chris Lattner721d2d42004-03-08 01:18:36 +00002189 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002190 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002191
Chris Lattner33f7fa32004-04-06 03:15:53 +00002192 if (Class != cLong) {
2193 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2194 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002195 }
2196
2197 // If this is a long value and the high or low bits have a special
2198 // property, emit some special cases.
2199 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2200
2201 // If the constant is zero in the low 32-bits, just copy the low part
2202 // across and apply the normal 32-bit operation to the high parts. There
2203 // will be no carry or borrow into the top.
2204 if (Op1l == 0) {
2205 if (OperatorClass != 2) // All but and...
2206 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2207 else
2208 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2209 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2210 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002211 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002212 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002213
2214 // If this is a logical operation and the top 32-bits are zero, just
2215 // operate on the lower 32.
2216 if (Op1h == 0 && OperatorClass > 1) {
2217 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2218 .addReg(Op0r).addImm(Op1l);
2219 if (OperatorClass != 2) // All but and
2220 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2221 else
2222 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2223 return;
2224 }
2225
2226 // TODO: We could handle lots of other special cases here, such as AND'ing
2227 // with 0xFFFFFFFF00000000 -> noop, etc.
2228
2229 // Otherwise, code generate the full operation with a constant.
2230 static const unsigned TopTab[] = {
2231 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2232 };
2233
2234 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2235 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2236 .addReg(Op0r+1).addImm(Op1h);
2237 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002238 }
2239
2240 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002241 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002242 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002243 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2244 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002245
Chris Lattnerb2acc512003-10-19 21:09:10 +00002246 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002247 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2248 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2249 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002250 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002251
Chris Lattnerb2acc512003-10-19 21:09:10 +00002252 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002253 unsigned Op0r = getReg(Op0, MBB, IP);
2254 unsigned Op1r = getReg(Op1, MBB, IP);
2255 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2256
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002257 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002258 static const unsigned TopTab[] = {
2259 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2260 };
2261 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2262 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2263 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002264}
2265
Chris Lattner3e130a22003-01-13 00:32:26 +00002266/// doMultiply - Emit appropriate instructions to multiply together the
2267/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2268/// result should be given as DestTy.
2269///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002270void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00002271 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00002272 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002273 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002274 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002275 case cInt:
2276 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002277 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002278 .addReg(op0Reg).addReg(op1Reg);
2279 return;
2280 case cByte:
2281 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002282 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2283 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2284 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002285 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002286 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002287 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002288 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002289}
2290
Chris Lattnerb2acc512003-10-19 21:09:10 +00002291// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2292// returns zero when the input is not exactly a power of two.
2293static unsigned ExactLog2(unsigned Val) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002294 if (Val == 0 || (Val & (Val-1))) return 0;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002295 unsigned Count = 0;
2296 while (Val != 1) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002297 Val >>= 1;
2298 ++Count;
2299 }
2300 return Count+1;
2301}
2302
Chris Lattner462fa822004-04-11 20:56:28 +00002303
2304/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2305/// 16, or 32-bit integer multiply by a constant.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002306void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002307 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002308 unsigned DestReg, const Type *DestTy,
2309 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002310 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2311 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002312 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
Chris Lattner6ab06d52004-04-06 04:55:43 +00002313
Chris Lattnerb2acc512003-10-19 21:09:10 +00002314 unsigned Class = getClass(DestTy);
2315
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002316 // Handle special cases here.
2317 switch (ConstRHS) {
2318 case 0:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002319 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2320 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002321 case 1:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002322 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2323 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002324 case 2:
2325 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2326 return;
2327 case 3:
2328 case 5:
2329 case 9:
2330 if (Class == cInt) {
2331 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg),
2332 op0Reg, ConstRHS-1, op0Reg, 0);
2333 return;
2334 }
Chris Lattner6ab06d52004-04-06 04:55:43 +00002335 }
2336
Chris Lattnerb2acc512003-10-19 21:09:10 +00002337 // If the element size is exactly a power of 2, use a shift to get it.
2338 if (unsigned Shift = ExactLog2(ConstRHS)) {
2339 switch (Class) {
2340 default: assert(0 && "Unknown class for this function!");
2341 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002342 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002343 return;
2344 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002345 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002346 return;
2347 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002348 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002349 return;
2350 }
2351 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002352
2353 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002354 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002355 return;
2356 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002357 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002358 return;
2359 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002360
2361 // Most general case, emit a normal multiply...
Chris Lattnerb2acc512003-10-19 21:09:10 +00002362 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002363 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002364
2365 // Emit a MUL to multiply the register holding the index by
2366 // elementSize, putting the result in OffsetReg.
2367 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2368}
2369
Chris Lattnerca9671d2002-11-02 20:28:58 +00002370/// visitMul - Multiplies are not simple binary operators because they must deal
2371/// with the EAX register explicitly.
2372///
2373void ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002374 unsigned ResultReg = getReg(I);
2375
Chris Lattner95157f72004-04-11 22:05:45 +00002376 Value *Op0 = I.getOperand(0);
2377 Value *Op1 = I.getOperand(1);
2378
2379 // Fold loads into floating point multiplies.
2380 if (getClass(Op0->getType()) == cFP) {
2381 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2382 if (!I.swapOperands())
2383 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2384 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2385 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2386 const Type *Ty = Op0->getType();
2387 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2388 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2389
Chris Lattner95157f72004-04-11 22:05:45 +00002390 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002391 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2392 unsigned FI = getFixedSizedAllocaFI(AI);
2393 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2394 } else {
2395 unsigned BaseReg, Scale, IndexReg, Disp;
2396 getAddressingMode(LI->getOperand(0), BaseReg,
2397 Scale, IndexReg, Disp);
2398
2399 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r),
2400 BaseReg, Scale, IndexReg, Disp);
2401 }
Chris Lattner95157f72004-04-11 22:05:45 +00002402 return;
2403 }
2404 }
2405
Chris Lattner462fa822004-04-11 20:56:28 +00002406 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002407 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002408}
2409
2410void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2411 Value *Op0, Value *Op1, unsigned DestReg) {
2412 MachineBasicBlock &BB = *MBB;
2413 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002414
2415 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002416 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002417 switch (Class) {
2418 case cByte:
2419 case cShort:
2420 case cInt:
2421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002422 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2423 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002424 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002425 unsigned Op1Reg = getReg(Op1, &BB, IP);
2426 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002427 }
Chris Lattner462fa822004-04-11 20:56:28 +00002428 return;
2429 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002430 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2431 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002432 case cLong:
2433 break;
2434 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002435
Chris Lattner462fa822004-04-11 20:56:28 +00002436 // Long value. We have to do things the hard way...
2437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2438 unsigned CLow = CI->getRawValue();
2439 unsigned CHi = CI->getRawValue() >> 32;
2440
2441 if (CLow == 0) {
2442 // If the low part of the constant is all zeros, things are simple.
2443 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2444 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2445 return;
2446 }
2447
2448 // Multiply the two low parts... capturing carry into EDX
2449 unsigned OverflowReg = 0;
2450 if (CLow == 1) {
2451 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002452 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002453 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2454 OverflowReg = makeAnotherReg(Type::UIntTy);
2455 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2456 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2457 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002458
Chris Lattner462fa822004-04-11 20:56:28 +00002459 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2460 BuildMI(BB, IP, X86::MOV32rr, 1,
2461 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2462 }
2463
2464 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2465 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2466
2467 unsigned AHBLplusOverflowReg;
2468 if (OverflowReg) {
2469 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2470 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002471 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002472 } else {
2473 AHBLplusOverflowReg = AHBLReg;
2474 }
2475
2476 if (CHi == 0) {
2477 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2478 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002479 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002480 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002481
Chris Lattner462fa822004-04-11 20:56:28 +00002482 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002483 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2484 }
Chris Lattner462fa822004-04-11 20:56:28 +00002485 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002486 }
Chris Lattner462fa822004-04-11 20:56:28 +00002487
2488 // General 64x64 multiply
2489
2490 unsigned Op1Reg = getReg(Op1, &BB, IP);
2491 // Multiply the two low parts... capturing carry into EDX
2492 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2493 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2494
2495 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2496 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2497 BuildMI(BB, IP, X86::MOV32rr, 1,
2498 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2499
2500 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2501 BuildMI(BB, IP, X86::IMUL32rr, 2,
2502 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2503
2504 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2505 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2506 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2507
2508 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2509 BuildMI(BB, IP, X86::IMUL32rr, 2,
2510 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2511
2512 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2513 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002514}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002515
Chris Lattner06925362002-11-17 21:56:38 +00002516
Chris Lattnerf01729e2002-11-02 20:54:46 +00002517/// visitDivRem - Handle division and remainder instructions... these
2518/// instruction both require the same instructions to be generated, they just
2519/// select the result from a different register. Note that both of these
2520/// instructions work differently for signed and unsigned operands.
2521///
2522void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002523 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2525
2526 // Fold loads into floating point divides.
2527 if (getClass(Op0->getType()) == cFP) {
2528 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2529 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2530 const Type *Ty = Op0->getType();
2531 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2532 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2533
Chris Lattner95157f72004-04-11 22:05:45 +00002534 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002535 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2536 unsigned FI = getFixedSizedAllocaFI(AI);
2537 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2538 } else {
2539 unsigned BaseReg, Scale, IndexReg, Disp;
2540 getAddressingMode(LI->getOperand(0), BaseReg,
2541 Scale, IndexReg, Disp);
2542
2543 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r),
2544 BaseReg, Scale, IndexReg, Disp);
2545 }
Chris Lattner95157f72004-04-11 22:05:45 +00002546 return;
2547 }
2548
2549 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2550 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2551 const Type *Ty = Op0->getType();
2552 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2553 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2554
Chris Lattner95157f72004-04-11 22:05:45 +00002555 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002556 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2557 unsigned FI = getFixedSizedAllocaFI(AI);
2558 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2559 } else {
2560 unsigned BaseReg, Scale, IndexReg, Disp;
2561 getAddressingMode(LI->getOperand(0), BaseReg, Scale, IndexReg, Disp);
2562 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r),
2563 BaseReg, Scale, IndexReg, Disp);
2564 }
Chris Lattner95157f72004-04-11 22:05:45 +00002565 return;
2566 }
2567 }
2568
Chris Lattner94af4142002-12-25 05:13:53 +00002569
Chris Lattnercadff442003-10-23 17:21:43 +00002570 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002571 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002572 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002573}
2574
2575void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002576 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +00002577 Value *Op0, Value *Op1, bool isDiv,
2578 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002579 const Type *Ty = Op0->getType();
2580 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002581 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002582 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002583 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002584 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2585 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002586 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002587 unsigned Op0Reg = getReg(Op0, BB, IP);
2588 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002589 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002590 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002591 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002592 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2593 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002594 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2595 }
Chris Lattner94af4142002-12-25 05:13:53 +00002596 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002597 case cLong: {
2598 static const char *FnName[] =
2599 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002600 unsigned Op0Reg = getReg(Op0, BB, IP);
2601 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002602 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002603 MachineInstr *TheCall =
2604 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2605
2606 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002607 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2608 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002609 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2610 return;
2611 }
2612 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002613 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002614 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002615 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002616
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002617 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002618 static const unsigned NEGOpcode[] = { X86::NEG8r, X86::NEG16r, X86::NEG32r };
2619 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2620 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2621 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2622
2623 // Special case signed division by power of 2.
2624 if (isDiv)
2625 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2626 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2627 int V = CI->getValue();
2628
2629 if (V == 1) { // X /s 1 => X
2630 unsigned Op0Reg = getReg(Op0, BB, IP);
2631 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2632 return;
2633 }
2634
2635 if (V == -1) { // X /s -1 => -X
2636 unsigned Op0Reg = getReg(Op0, BB, IP);
2637 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2638 return;
2639 }
2640
2641 bool isNeg = false;
2642 if (V < 0) { // Not a positive power of 2?
2643 V = -V;
2644 isNeg = true; // Maybe it's a negative power of 2.
2645 }
2646 if (unsigned Log = ExactLog2(V)) {
2647 --Log;
2648 unsigned Op0Reg = getReg(Op0, BB, IP);
2649 unsigned TmpReg = makeAnotherReg(Op0->getType());
2650 if (Log != 1)
2651 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2652 .addReg(Op0Reg).addImm(Log-1);
2653 else
2654 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg).addReg(Op0Reg);
2655 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2656 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2657 .addReg(TmpReg).addImm(32-Log);
2658 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2659 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2660 .addReg(Op0Reg).addReg(TmpReg2);
2661
2662 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2663 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2664 .addReg(Op0Reg).addImm(Log);
2665 if (isNeg)
2666 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2667 return;
2668 }
2669 }
2670
2671 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002672 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002673 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2674
2675 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002676 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2677 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002678 };
2679
Chris Lattnerf01729e2002-11-02 20:54:46 +00002680 unsigned Reg = Regs[Class];
2681 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002682
2683 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002684 unsigned Op0Reg = getReg(Op0, BB, IP);
2685 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002686 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002687
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002688 if (Ty->isSigned()) {
Chris Lattnerf01729e2002-11-02 20:54:46 +00002689 // Emit a sign extension instruction...
Chris Lattner462fa822004-04-11 20:56:28 +00002690 unsigned ShiftResult = makeAnotherReg(Op0->getType());
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002691 BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
Chris Lattneree352852004-02-29 07:22:16 +00002692 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002693
2694 // Emit the appropriate divide or remainder instruction...
2695 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002696 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002697 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002698 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002699
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002700 // Emit the appropriate divide or remainder instruction...
2701 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2702 }
Chris Lattner06925362002-11-17 21:56:38 +00002703
Chris Lattnerf01729e2002-11-02 20:54:46 +00002704 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002705 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002706
Chris Lattnerf01729e2002-11-02 20:54:46 +00002707 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002708 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002709}
Chris Lattnere2954c82002-11-02 20:04:26 +00002710
Chris Lattner06925362002-11-17 21:56:38 +00002711
Brian Gaekea1719c92002-10-31 23:03:59 +00002712/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2713/// for constant immediate shift values, and for constant immediate
2714/// shift values equal to 1. Even the general case is sort of special,
2715/// because the shift amount has to be in CL, not just any old register.
2716///
Chris Lattner3e130a22003-01-13 00:32:26 +00002717void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002718 MachineBasicBlock::iterator IP = BB->end ();
2719 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2720 I.getOpcode () == Instruction::Shl, I.getType (),
2721 getReg (I));
2722}
2723
2724/// emitShiftOperation - Common code shared between visitShiftInst and
2725/// constant expression support.
2726void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002727 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002728 Value *Op, Value *ShiftAmount, bool isLeftShift,
2729 const Type *ResultTy, unsigned DestReg) {
2730 unsigned SrcReg = getReg (Op, MBB, IP);
2731 bool isSigned = ResultTy->isSigned ();
2732 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002733
2734 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002735 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2736 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2737 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2738 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002739 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002740
Chris Lattner3e130a22003-01-13 00:32:26 +00002741 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002742 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2743 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2744 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2745 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002746 };
Chris Lattner796df732002-11-02 00:44:25 +00002747
Chris Lattner3e130a22003-01-13 00:32:26 +00002748 // Longs, as usual, are handled specially...
2749 if (Class == cLong) {
2750 // If we have a constant shift, we can generate much more efficient code
2751 // than otherwise...
2752 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002753 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002754 unsigned Amount = CUI->getValue();
2755 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002756 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2757 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00002758 BuildMI(*MBB, IP, Opc[3], 3,
2759 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2760 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002761 } else {
Chris Lattneree352852004-02-29 07:22:16 +00002762 BuildMI(*MBB, IP, Opc[3], 3,
2763 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2764 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002765 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002766 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002767 Amount -= 32;
2768 if (isLeftShift) {
Chris Lattner722070e2004-04-06 03:42:38 +00002769 if (Amount != 0) {
2770 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2771 DestReg + 1).addReg(SrcReg).addImm(Amount);
2772 } else {
2773 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2774 }
2775 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002776 } else {
Chris Lattner722070e2004-04-06 03:42:38 +00002777 if (Amount != 0) {
2778 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2779 DestReg).addReg(SrcReg+1).addImm(Amount);
2780 } else {
2781 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2782 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002783 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002784 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002785 }
2786 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00002787 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2788
2789 if (!isLeftShift && isSigned) {
2790 // If this is a SHR of a Long, then we need to do funny sign extension
2791 // stuff. TmpReg gets the value to use as the high-part if we are
2792 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002793 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00002794 } else {
2795 // Other shifts use a fixed zero value if the shift is more than 32
2796 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002797 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00002798 }
2799
2800 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002801 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002802 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002803
2804 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2805 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2806 if (isLeftShift) {
2807 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002808 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00002809 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002810 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002811 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002812
2813 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002814 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002815
2816 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002817 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002818 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2819 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002820 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002821 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002822 } else {
2823 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002824 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00002825 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00002826 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002827 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00002828 .addReg(SrcReg+1);
2829
2830 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002831 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002832
2833 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002834 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002835 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2836
2837 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002838 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002839 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2840 }
Brian Gaekea1719c92002-10-31 23:03:59 +00002841 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002842 return;
2843 }
Chris Lattnere9913f22002-11-02 01:41:55 +00002844
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002845 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002846 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2847 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002848
Chris Lattner3e130a22003-01-13 00:32:26 +00002849 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002850 BuildMI(*MBB, IP, Opc[Class], 2,
2851 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00002852 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002853 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002854 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002855
Chris Lattner3e130a22003-01-13 00:32:26 +00002856 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002857 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002858 }
2859}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002860
Chris Lattner3e130a22003-01-13 00:32:26 +00002861
Chris Lattner6fc3c522002-11-17 21:11:55 +00002862/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00002863/// instruction. The load and store instructions are the only place where we
2864/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00002865///
2866void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002867 // Check to see if this load instruction is going to be folded into a binary
2868 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2869 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00002870 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002871 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002872 Instruction *User = cast<Instruction>(I.use_back());
2873 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002874 case Instruction::Cast:
2875 // If this is a cast from a signed-integer type to a floating point type,
2876 // fold the cast here.
John Criswell6b5bd582004-06-09 15:18:51 +00002877 if (getClassB(User->getType()) == cFP &&
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002878 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
2879 I.getType() == Type::LongTy)) {
2880 unsigned DestReg = getReg(User);
2881 static const unsigned Opcode[] = {
2882 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
2883 };
Chris Lattner9f1b5312004-05-13 15:12:43 +00002884
2885 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2886 unsigned FI = getFixedSizedAllocaFI(AI);
2887 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
2888 } else {
2889 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2890 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2891 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg),
2892 BaseReg, Scale, IndexReg, Disp);
2893 }
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002894 return;
2895 } else {
2896 User = 0;
2897 }
2898 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00002899
Chris Lattner7dee5da2004-03-08 01:58:35 +00002900 case Instruction::Add:
2901 case Instruction::Sub:
2902 case Instruction::And:
2903 case Instruction::Or:
2904 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002905 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002906 break;
Chris Lattner95157f72004-04-11 22:05:45 +00002907 case Instruction::Mul:
2908 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00002909 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002910 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00002911 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002912 }
2913
2914 if (User) {
2915 // Okay, we found a user. If the load is the first operand and there is
2916 // no second operand load, reverse the operand ordering. Note that this
2917 // can fail for a subtract (ie, no change will be made).
2918 if (!isa<LoadInst>(User->getOperand(1)))
2919 cast<BinaryOperator>(User)->swapOperands();
2920
2921 // Okay, now that everything is set up, if this load is used by the second
2922 // operand, and if there are no instructions that invalidate the load
2923 // before the binary operator, eliminate the load.
2924 if (User->getOperand(1) == &I &&
2925 isSafeToFoldLoadIntoInstruction(I, *User))
2926 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00002927
2928 // If this is a floating point sub or div, we won't be able to swap the
2929 // operands, but we will still be able to eliminate the load.
2930 if (Class == cFP && User->getOperand(0) == &I &&
2931 !isa<LoadInst>(User->getOperand(1)) &&
2932 (User->getOpcode() == Instruction::Sub ||
2933 User->getOpcode() == Instruction::Div) &&
2934 isSafeToFoldLoadIntoInstruction(I, *User))
2935 return; // Eliminate the load!
Chris Lattner7dee5da2004-03-08 01:58:35 +00002936 }
2937 }
2938
Chris Lattner6ac1d712003-10-20 04:48:06 +00002939 static const unsigned Opcodes[] = {
Chris Lattner9f1b5312004-05-13 15:12:43 +00002940 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
Chris Lattner3e130a22003-01-13 00:32:26 +00002941 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002942 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002943 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00002944
2945 unsigned DestReg = getReg(I);
2946
2947 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2948 unsigned FI = getFixedSizedAllocaFI(AI);
2949 if (Class == cLong) {
2950 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
2951 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
2952 } else {
2953 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
2954 }
2955 } else {
2956 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2957 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2958
2959 if (Class == cLong) {
2960 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2961 BaseReg, Scale, IndexReg, Disp);
2962 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2963 BaseReg, Scale, IndexReg, Disp+4);
2964 } else {
2965 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2966 BaseReg, Scale, IndexReg, Disp);
2967 }
2968 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002969}
2970
Chris Lattner6fc3c522002-11-17 21:11:55 +00002971/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2972/// instruction.
2973///
2974void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00002975 unsigned BaseReg = ~0U, Scale = ~0U, IndexReg = ~0U, Disp = ~0U;
2976 unsigned AllocaFrameIdx = ~0U;
2977
2978 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(1)))
2979 AllocaFrameIdx = getFixedSizedAllocaFI(AI);
2980 else
2981 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002982
Chris Lattner6c09db22003-10-20 04:11:23 +00002983 const Type *ValTy = I.getOperand(0)->getType();
2984 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002985
Chris Lattner5a830962004-02-25 02:56:58 +00002986 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2987 uint64_t Val = CI->getRawValue();
2988 if (Class == cLong) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00002989 if (AllocaFrameIdx != ~0U) {
2990 addFrameReference(BuildMI(BB, X86::MOV32mi, 5),
2991 AllocaFrameIdx).addImm(Val & ~0U);
2992 addFrameReference(BuildMI(BB, X86::MOV32mi, 5),
2993 AllocaFrameIdx, 4).addImm(Val>>32);
2994 } else {
2995 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2996 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2997 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2998 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2999 }
Chris Lattner5a830962004-02-25 02:56:58 +00003000 } else {
3001 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003002 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00003003 };
3004 unsigned Opcode = Opcodes[Class];
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003005 if (AllocaFrameIdx != ~0U)
Chris Lattner9f1b5312004-05-13 15:12:43 +00003006 addFrameReference(BuildMI(BB, Opcode, 5), AllocaFrameIdx).addImm(Val);
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003007 else
Chris Lattner9f1b5312004-05-13 15:12:43 +00003008 addFullAddress(BuildMI(BB, Opcode, 5),
3009 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00003010 }
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003011 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
3012 if (AllocaFrameIdx != ~0U)
3013 addFrameReference(BuildMI(BB, X86::MOV32mi, 5), AllocaFrameIdx).addImm(0);
3014 else
3015 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
3016 BaseReg, Scale, IndexReg, Disp).addImm(0);
3017
Chris Lattner5a830962004-02-25 02:56:58 +00003018 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00003019 if (AllocaFrameIdx != ~0U)
3020 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
3021 AllocaFrameIdx).addImm(CB->getValue());
3022 else
3023 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
3024 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattnere7a31c92004-05-07 21:18:15 +00003025 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3026 // Store constant FP values with integer instructions to avoid having to
3027 // load the constants from the constant pool then do a store.
3028 if (CFP->getType() == Type::FloatTy) {
3029 union {
3030 unsigned I;
3031 float F;
3032 } V;
3033 V.F = CFP->getValue();
Chris Lattner9f1b5312004-05-13 15:12:43 +00003034 if (AllocaFrameIdx != ~0U)
3035 addFrameReference(BuildMI(BB, X86::MOV32mi, 5),
3036 AllocaFrameIdx).addImm(V.I);
3037 else
3038 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
3039 BaseReg, Scale, IndexReg, Disp).addImm(V.I);
Chris Lattner5a830962004-02-25 02:56:58 +00003040 } else {
Chris Lattnere7a31c92004-05-07 21:18:15 +00003041 union {
3042 uint64_t I;
3043 double F;
3044 } V;
3045 V.F = CFP->getValue();
Chris Lattner9f1b5312004-05-13 15:12:43 +00003046 if (AllocaFrameIdx != ~0U) {
3047 addFrameReference(BuildMI(BB, X86::MOV32mi, 5),
3048 AllocaFrameIdx).addImm((unsigned)V.I);
3049 addFrameReference(BuildMI(BB, X86::MOV32mi, 5),
3050 AllocaFrameIdx, 4).addImm(unsigned(V.I >> 32));
3051 } else {
3052 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
3053 BaseReg, Scale, IndexReg, Disp).addImm((unsigned)V.I);
3054 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
3055 BaseReg, Scale, IndexReg, Disp+4).addImm(
Chris Lattnere7a31c92004-05-07 21:18:15 +00003056 unsigned(V.I >> 32));
Chris Lattner9f1b5312004-05-13 15:12:43 +00003057 }
Chris Lattner5a830962004-02-25 02:56:58 +00003058 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00003059
3060 } else if (Class == cLong) {
3061 unsigned ValReg = getReg(I.getOperand(0));
Chris Lattner9f1b5312004-05-13 15:12:43 +00003062 if (AllocaFrameIdx != ~0U) {
3063 addFrameReference(BuildMI(BB, X86::MOV32mr, 5),
3064 AllocaFrameIdx).addReg(ValReg);
3065 addFrameReference(BuildMI(BB, X86::MOV32mr, 5),
3066 AllocaFrameIdx, 4).addReg(ValReg+1);
3067 } else {
3068 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
3069 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
3070 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
3071 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
3072 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00003073 } else {
3074 unsigned ValReg = getReg(I.getOperand(0));
3075 static const unsigned Opcodes[] = {
3076 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3077 };
3078 unsigned Opcode = Opcodes[Class];
3079 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003080
3081 if (AllocaFrameIdx != ~0U)
3082 addFrameReference(BuildMI(BB, Opcode, 5), AllocaFrameIdx).addReg(ValReg);
3083 else
3084 addFullAddress(BuildMI(BB, Opcode, 1+4),
3085 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003086 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00003087}
3088
3089
Misha Brukman538607f2004-03-01 23:53:11 +00003090/// visitCastInst - Here we have various kinds of copying with or without sign
3091/// extension going on.
3092///
Chris Lattner3e130a22003-01-13 00:32:26 +00003093void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003094 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00003095
Chris Lattner99382862004-04-12 00:23:04 +00003096 unsigned SrcClass = getClassB(Op->getType());
3097 unsigned DestClass = getClassB(CI.getType());
3098 // Noop casts are not emitted: getReg will return the source operand as the
3099 // register to use for any uses of the noop cast.
3100 if (DestClass == SrcClass)
Chris Lattner427aeb42004-04-11 19:21:59 +00003101 return;
3102
Chris Lattnerf5854472003-06-21 16:01:24 +00003103 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3104 // of the case are GEP instructions, then the cast does not need to be
3105 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00003106 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003107 bool AllUsesAreGEPs = true;
3108 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3109 if (!isa<GetElementPtrInst>(*I)) {
3110 AllUsesAreGEPs = false;
3111 break;
3112 }
3113
3114 // No need to codegen this cast if all users are getelementptr instrs...
3115 if (AllUsesAreGEPs) return;
3116 }
3117
Chris Lattner99382862004-04-12 00:23:04 +00003118 // If this cast converts a load from a short,int, or long integer to a FP
3119 // value, we will have folded this cast away.
3120 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3121 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3122 Op->getType() == Type::LongTy))
3123 return;
3124
3125
Chris Lattner548f61d2003-04-23 17:22:12 +00003126 unsigned DestReg = getReg(CI);
3127 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00003128 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00003129}
3130
Misha Brukman538607f2004-03-01 23:53:11 +00003131/// emitCastOperation - Common code shared between visitCastInst and constant
3132/// expression cast support.
3133///
Chris Lattner548f61d2003-04-23 17:22:12 +00003134void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003135 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00003136 Value *Src, const Type *DestTy,
3137 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003138 const Type *SrcTy = Src->getType();
3139 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00003140 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003141 unsigned SrcReg = getReg(Src, BB, IP);
3142
Chris Lattner3e130a22003-01-13 00:32:26 +00003143 // Implement casts to bool by using compare on the operand followed by set if
3144 // not zero on the result.
3145 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00003146 switch (SrcClass) {
3147 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003148 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003149 break;
3150 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003151 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003152 break;
3153 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003154 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003155 break;
3156 case cLong: {
3157 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003158 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00003159 break;
3160 }
3161 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00003162 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003163 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00003164 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00003165 break;
Chris Lattner20772542003-06-01 03:38:24 +00003166 }
3167
3168 // If the zero flag is not set, then the value is true, set the byte to
3169 // true.
Chris Lattneree352852004-02-29 07:22:16 +00003170 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003171 return;
3172 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003173
3174 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003175 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00003176 };
3177
3178 // Implement casts between values of the same type class (as determined by
3179 // getClass) by using a register-to-register move.
3180 if (SrcClass == DestClass) {
3181 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00003182 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003183 } else if (SrcClass == cFP) {
3184 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003185 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00003186 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003187 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003188 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3189 "Unknown cFP member!");
3190 // Truncate from double to float by storing to memory as short, then
3191 // reading it back.
3192 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00003193 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003194 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3195 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003196 }
3197 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003198 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3199 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003200 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00003201 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003202 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00003203 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003204 return;
3205 }
3206
3207 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3208 // or zero extension, depending on whether the source type was signed.
3209 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3210 SrcClass < DestClass) {
3211 bool isLong = DestClass == cLong;
3212 if (isLong) DestClass = cInt;
3213
3214 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003215 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3216 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00003217 };
3218
Chris Lattner96e3b422004-05-09 22:28:45 +00003219 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
Chris Lattneree352852004-02-29 07:22:16 +00003220 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00003221 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003222
3223 if (isLong) { // Handle upper 32 bits as appropriate...
3224 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003225 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00003226 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003227 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00003228 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003229 return;
3230 }
3231
3232 // Special case long -> int ...
3233 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003234 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003235 return;
3236 }
3237
3238 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3239 // move out of AX or AL.
3240 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3241 && SrcClass > DestClass) {
3242 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00003243 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3244 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00003245 return;
3246 }
3247
3248 // Handle casts from integer to floating point now...
3249 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003250 // Promote the integer to a type supported by FLD. We do this because there
3251 // are no unsigned FLD instructions, so we must promote an unsigned value to
3252 // a larger signed value, then use FLD on the larger value.
3253 //
3254 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00003255 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003256 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003257 switch (SrcTy->getPrimitiveID()) {
3258 case Type::BoolTyID:
3259 case Type::SByteTyID:
3260 // We don't have the facilities for directly loading byte sized data from
3261 // memory (even signed). Promote it to 16 bits.
3262 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003263 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003264 break;
3265 case Type::UByteTyID:
3266 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003267 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003268 break;
3269 case Type::UShortTyID:
3270 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003271 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003272 break;
3273 case Type::UIntTyID: {
3274 // Make a 64 bit temporary... and zero out the top of it...
3275 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003276 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
3277 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003278 SrcTy = Type::LongTy;
3279 SrcClass = cLong;
3280 SrcReg = TmpReg;
3281 break;
3282 }
3283 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003284 // Don't fild into the read destination.
3285 DestReg = makeAnotherReg(Type::DoubleTy);
3286 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003287 default: // No promotion needed...
3288 break;
3289 }
3290
3291 if (PromoteType) {
3292 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003293 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003294 SrcTy = PromoteType;
3295 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003296 SrcReg = TmpReg;
3297 }
3298
3299 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003300 int FrameIdx =
3301 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003302
3303 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003304 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003305 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003306 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003307 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003308 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003309 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003310 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3311 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003312 }
3313
3314 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003315 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003316 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003317
3318 // We need special handling for unsigned 64-bit integer sources. If the
3319 // input number has the "sign bit" set, then we loaded it incorrectly as a
3320 // negative 64-bit number. In this case, add an offset value.
3321 if (SrcTy == Type::ULongTy) {
3322 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003323 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003324
Chris Lattnerb6bac512004-02-25 06:13:04 +00003325 // If the sign bit is set, get a pointer to an offset, otherwise get a
3326 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003327 MachineConstantPool *CP = F->getConstantPool();
3328 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003329 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003330 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003331 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003332 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003333 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3334
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003335 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003336 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003337 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003338 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003339
3340 // Load the constant for an add. FIXME: this could make an 'fadd' that
3341 // reads directly from memory, but we don't support these yet.
3342 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003343 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003344
Chris Lattneree352852004-02-29 07:22:16 +00003345 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3346 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003347 }
3348
Chris Lattner3e130a22003-01-13 00:32:26 +00003349 return;
3350 }
3351
3352 // Handle casts from floating point to integer now...
3353 if (SrcClass == cFP) {
3354 // Change the floating point control register to use "round towards zero"
3355 // mode when truncating to an integer value.
3356 //
3357 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003358 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003359
3360 // Load the old value of the high byte of the control word...
3361 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003362 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003363 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003364
3365 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003366 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003367 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003368
3369 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003370 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003371
3372 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003373 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003374 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003375
3376 // We don't have the facilities for directly storing byte sized data to
3377 // memory. Promote it to 16 bits. We also must promote unsigned values to
3378 // larger classes because we only have signed FP stores.
3379 unsigned StoreClass = DestClass;
3380 const Type *StoreTy = DestTy;
3381 if (StoreClass == cByte || DestTy->isUnsigned())
3382 switch (StoreClass) {
3383 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3384 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3385 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003386 // The following treatment of cLong may not be perfectly right,
3387 // but it survives chains of casts of the form
3388 // double->ulong->double.
3389 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003390 default: assert(0 && "Unknown store class!");
3391 }
3392
3393 // Spill the integer to memory and reload it from there...
3394 int FrameIdx =
3395 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3396
3397 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003398 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003399 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3400 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003401
3402 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003403 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3404 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003405 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003406 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003407 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003408 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003409 }
3410
3411 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003412 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003413 return;
3414 }
3415
Brian Gaeked474e9c2002-12-06 10:49:33 +00003416 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003417 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003418 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003419}
Brian Gaekea1719c92002-10-31 23:03:59 +00003420
Chris Lattner73815062003-10-18 05:56:40 +00003421/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003422///
Chris Lattner73815062003-10-18 05:56:40 +00003423void ISel::visitVANextInst(VANextInst &I) {
3424 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003425 unsigned DestReg = getReg(I);
3426
Chris Lattnereca195e2003-05-08 19:44:13 +00003427 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00003428 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003429 default:
3430 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003431 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003432 return;
3433 case Type::PointerTyID:
3434 case Type::UIntTyID:
3435 case Type::IntTyID:
3436 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003437 break;
3438 case Type::ULongTyID:
3439 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003440 case Type::DoubleTyID:
3441 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003442 break;
3443 }
3444
3445 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003446 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003447}
Chris Lattnereca195e2003-05-08 19:44:13 +00003448
Chris Lattner73815062003-10-18 05:56:40 +00003449void ISel::visitVAArgInst(VAArgInst &I) {
3450 unsigned VAList = getReg(I.getOperand(0));
3451 unsigned DestReg = getReg(I);
3452
3453 switch (I.getType()->getPrimitiveID()) {
3454 default:
3455 std::cerr << I;
3456 assert(0 && "Error: bad type for va_next instruction!");
3457 return;
3458 case Type::PointerTyID:
3459 case Type::UIntTyID:
3460 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003461 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003462 break;
3463 case Type::ULongTyID:
3464 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003465 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3466 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003467 break;
3468 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003469 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003470 break;
3471 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003472}
3473
Misha Brukman538607f2004-03-01 23:53:11 +00003474/// visitGetElementPtrInst - instruction-select GEP instructions
3475///
Chris Lattner3e130a22003-01-13 00:32:26 +00003476void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003477 // If this GEP instruction will be folded into all of its users, we don't need
3478 // to explicitly calculate it!
3479 unsigned A, B, C, D;
3480 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
3481 // Check all of the users of the instruction to see if they are loads and
3482 // stores.
3483 bool AllWillFold = true;
3484 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3485 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3486 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3487 cast<Instruction>(*UI)->getOperand(0) == &I) {
3488 AllWillFold = false;
3489 break;
3490 }
3491
3492 // If the instruction is foldable, and will be folded into all users, don't
3493 // emit it!
3494 if (AllWillFold) return;
3495 }
3496
Chris Lattner3e130a22003-01-13 00:32:26 +00003497 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003498 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003499 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003500}
3501
Chris Lattner985fe3d2004-02-25 03:45:50 +00003502/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3503/// GEPTypes (the derived types being stepped through at each level). On return
3504/// from this function, if some indexes of the instruction are representable as
3505/// an X86 lea instruction, the machine operands are put into the Ops
3506/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3507/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3508/// addressing mode that only partially consumes the input, the BaseReg input of
3509/// the addressing mode must be left free.
3510///
3511/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3512///
Chris Lattnerb6bac512004-02-25 06:13:04 +00003513void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
3514 std::vector<Value*> &GEPOps,
3515 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
3516 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3517 const TargetData &TD = TM.getTargetData();
3518
Chris Lattner985fe3d2004-02-25 03:45:50 +00003519 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003520 BaseReg = 0; // No base register
3521 Scale = 1; // Unit scale
3522 IndexReg = 0; // No index register
3523 Disp = 0; // No displacement
3524
Chris Lattner985fe3d2004-02-25 03:45:50 +00003525 // While there are GEP indexes that can be folded into the current address,
3526 // keep processing them.
3527 while (!GEPTypes.empty()) {
3528 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3529 // It's a struct access. CUI is the index into the structure,
3530 // which names the field. This index must have unsigned type.
3531 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3532
3533 // Use the TargetData structure to pick out what the layout of the
3534 // structure is in memory. Since the structure index must be constant, we
3535 // can get its value and use it to find the right byte offset from the
3536 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003537 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003538 GEPOps.pop_back(); // Consume a GEP operand
3539 GEPTypes.pop_back();
3540 } else {
3541 // It's an array or pointer access: [ArraySize x ElementType].
3542 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3543 Value *idx = GEPOps.back();
3544
3545 // idx is the index into the array. Unlike with structure
3546 // indices, we may not know its actual value at code-generation
3547 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003548
3549 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003550 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003551 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003552 Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003553 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3554 Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003555 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003556 // If the index reg is already taken, we can't handle this index.
3557 if (IndexReg) return;
3558
3559 // If this is a size that we can handle, then add the index as
3560 switch (TypeSize) {
3561 case 1: case 2: case 4: case 8:
3562 // These are all acceptable scales on X86.
3563 Scale = TypeSize;
3564 break;
3565 default:
3566 // Otherwise, we can't handle this scale
3567 return;
3568 }
3569
3570 if (CastInst *CI = dyn_cast<CastInst>(idx))
3571 if (CI->getOperand(0)->getType() == Type::IntTy ||
3572 CI->getOperand(0)->getType() == Type::UIntTy)
3573 idx = CI->getOperand(0);
3574
3575 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003576 }
3577
3578 GEPOps.pop_back(); // Consume a GEP operand
3579 GEPTypes.pop_back();
3580 }
3581 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003582
Chris Lattnerdf040972004-05-23 21:23:12 +00003583 // GEPTypes is empty, which means we have a single operand left. Set it as
3584 // the base register.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003585 //
Chris Lattnerb6bac512004-02-25 06:13:04 +00003586 assert(BaseReg == 0);
Chris Lattnerdf040972004-05-23 21:23:12 +00003587
3588#if 0 // FIXME: TODO!
3589 if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
3590 // FIXME: When we can add FrameIndex values as the first operand, we can
3591 // make GEP's of allocas MUCH more efficient!
3592 unsigned FI = getFixedSizedAllocaFI(AI);
3593 GEPOps.pop_back();
3594 return;
3595 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3596 // FIXME: When addressing modes are more powerful/correct, we could load
3597 // global addresses directly as 32-bit immediates.
3598 }
3599#endif
3600
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003601 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003602 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003603}
3604
3605
Chris Lattnerb6bac512004-02-25 06:13:04 +00003606/// isGEPFoldable - Return true if the specified GEP can be completely
3607/// folded into the addressing mode of a load/store or lea instruction.
3608bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3609 Value *Src, User::op_iterator IdxBegin,
3610 User::op_iterator IdxEnd, unsigned &BaseReg,
3611 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003612 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3613 Src = CPR->getValue();
3614
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003615 std::vector<Value*> GEPOps;
3616 GEPOps.resize(IdxEnd-IdxBegin+1);
3617 GEPOps[0] = Src;
3618 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3619
Chris Lattnerdf040972004-05-23 21:23:12 +00003620 std::vector<const Type*>
3621 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3622 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003623
Chris Lattnerb6bac512004-02-25 06:13:04 +00003624 MachineBasicBlock::iterator IP;
3625 if (MBB) IP = MBB->end();
3626 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3627
3628 // We can fold it away iff the getGEPIndex call eliminated all operands.
3629 return GEPOps.empty();
3630}
3631
3632void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3633 MachineBasicBlock::iterator IP,
3634 Value *Src, User::op_iterator IdxBegin,
3635 User::op_iterator IdxEnd, unsigned TargetReg) {
3636 const TargetData &TD = TM.getTargetData();
3637 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3638 Src = CPR->getValue();
3639
3640 std::vector<Value*> GEPOps;
3641 GEPOps.resize(IdxEnd-IdxBegin+1);
3642 GEPOps[0] = Src;
3643 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3644
3645 std::vector<const Type*> GEPTypes;
3646 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3647 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003648
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003649 // Keep emitting instructions until we consume the entire GEP instruction.
3650 while (!GEPOps.empty()) {
3651 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003652 unsigned BaseReg, Scale, IndexReg, Disp;
3653 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003654
Chris Lattner985fe3d2004-02-25 03:45:50 +00003655 if (GEPOps.size() != OldSize) {
3656 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003657 unsigned NextTarget = 0;
3658 if (!GEPOps.empty()) {
3659 assert(BaseReg == 0 &&
3660 "getGEPIndex should have left the base register open for chaining!");
3661 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003662 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003663
3664 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003665 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003666 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003667 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003668 BaseReg, Scale, IndexReg, Disp);
3669 --IP;
3670 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003671 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003672 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3673 // all operands are consumed but the base pointer. If so, just load it
3674 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003675 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003676 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003677 } else {
3678 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003679 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003680 }
3681 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003682
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003683 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003684 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003685 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3686 Value *idx = GEPOps.back();
3687 GEPOps.pop_back(); // Consume a GEP operand
3688 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003689
Chris Lattner28977af2004-04-05 01:30:19 +00003690 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003691 // operand on X86. Handle this case directly now...
3692 if (CastInst *CI = dyn_cast<CastInst>(idx))
3693 if (CI->getOperand(0)->getType() == Type::IntTy ||
3694 CI->getOperand(0)->getType() == Type::UIntTy)
3695 idx = CI->getOperand(0);
3696
Chris Lattner3e130a22003-01-13 00:32:26 +00003697 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003698 // must find the size of the pointed-to type (Not coincidentally, the next
3699 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003700 const Type *ElTy = SqTy->getElementType();
3701 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003702
3703 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003704 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003705 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003706 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003707 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003708 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003709 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003710 --IP; // Insert the next instruction before this one.
3711 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003712 }
3713 } else if (elementSize == 1) {
3714 // If the element size is 1, we don't have to multiply, just add
3715 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003716 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003717 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003718 --IP; // Insert the next instruction before this one.
3719 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003720 } else {
3721 unsigned idxReg = getReg(idx, MBB, IP);
3722 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003723
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003724 // Make sure we can back the iterator up to point to the first
3725 // instruction emitted.
3726 MachineBasicBlock::iterator BeforeIt = IP;
3727 if (IP == MBB->begin())
3728 BeforeIt = MBB->end();
3729 else
3730 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003731 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3732
Chris Lattner8a307e82002-12-16 19:32:50 +00003733 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003734 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003735 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003736 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003737
3738 // Step to the first instruction of the multiply.
3739 if (BeforeIt == MBB->end())
3740 IP = MBB->begin();
3741 else
3742 IP = ++BeforeIt;
3743
3744 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003745 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003746 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003747 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003748}
3749
Chris Lattner065faeb2002-12-28 20:24:02 +00003750/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3751/// frame manager, otherwise do it the hard way.
3752///
3753void ISel::visitAllocaInst(AllocaInst &I) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00003754 // If this is a fixed size alloca in the entry block for the function, we
3755 // statically stack allocate the space, so we don't need to do anything here.
3756 //
Chris Lattnercb2fd552004-05-13 07:40:27 +00003757 if (dyn_castFixedAlloca(&I)) return;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003758
Brian Gaekee48ec012002-12-13 06:46:31 +00003759 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00003760 const Type *Ty = I.getAllocatedType();
3761 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3762
Chris Lattner065faeb2002-12-28 20:24:02 +00003763 // Create a register to hold the temporary result of multiplying the type size
3764 // constant by the variable amount.
3765 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3766 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00003767
3768 // TotalSizeReg = mul <numelements>, <TypeSize>
3769 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003770 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003771
3772 // AddedSize = add <TotalSizeReg>, 15
3773 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003774 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003775
3776 // AlignedSize = and <AddedSize>, ~15
3777 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003778 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003779
Brian Gaekee48ec012002-12-13 06:46:31 +00003780 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003781 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003782
Brian Gaekee48ec012002-12-13 06:46:31 +00003783 // Put a pointer to the space into the result register, by copying
3784 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003785 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00003786
Misha Brukman48196b32003-05-03 02:18:17 +00003787 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00003788 // object.
3789 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00003790}
Chris Lattner3e130a22003-01-13 00:32:26 +00003791
3792/// visitMallocInst - Malloc instructions are code generated into direct calls
3793/// to the library malloc.
3794///
3795void ISel::visitMallocInst(MallocInst &I) {
3796 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3797 unsigned Arg;
3798
3799 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3800 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3801 } else {
3802 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003803 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00003804 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003805 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00003806 }
3807
3808 std::vector<ValueRecord> Args;
3809 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3810 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003811 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003812 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3813}
3814
3815
3816/// visitFreeInst - Free instructions are code gen'd to call the free libc
3817/// function.
3818///
3819void ISel::visitFreeInst(FreeInst &I) {
3820 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00003821 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00003822 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003823 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003824 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3825}
3826
Chris Lattnerd281de22003-07-26 23:49:58 +00003827/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00003828/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00003829/// generated code sucks but the implementation is nice and simple.
3830///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00003831FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3832 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00003833}