blob: a9befc6069dfce51b606362e35d0af46c053a7b8 [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 Lattnerf70e0c22003-12-28 21:23:38 +000089 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000090
91 /// runOnFunction - Top level implementation of instruction selection for
92 /// the entire function.
93 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000094 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000095 // First pass over the function, lower any unknown intrinsic functions
96 // with the IntrinsicLowering class.
97 LowerUnknownIntrinsicFunctionCalls(Fn);
98
Chris Lattner36b36032002-10-29 23:40:58 +000099 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000100
Chris Lattner065faeb2002-12-28 20:24:02 +0000101 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000102 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
103 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
104
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000105 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000106
Chris Lattner0e5b79c2004-02-15 01:04:03 +0000107 // Set up a frame object for the return address. This is used by the
108 // llvm.returnaddress & llvm.frameaddress intrinisics.
109 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
110
Chris Lattnerdbd73722003-05-06 21:32:22 +0000111 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000112 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000113
Chris Lattner333b2fa2002-12-13 10:09:43 +0000114 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000115 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000116
117 // Select the PHI nodes
118 SelectPHINodes();
119
Chris Lattner986618e2004-02-22 19:47:26 +0000120 // Insert the FP_REG_KILL instructions into blocks that need them.
121 InsertFPRegKills();
122
Chris Lattner72614082002-10-25 22:55:53 +0000123 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000124 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000125 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000126 // We always build a machine code representation for the function
127 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000128 }
129
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000130 virtual const char *getPassName() const {
131 return "X86 Simple Instruction Selection";
132 }
133
Chris Lattner72614082002-10-25 22:55:53 +0000134 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000135 /// block. This simply creates a new MachineBasicBlock to emit code into
136 /// and adds it to the current MachineFunction. Subsequent visit* for
137 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000138 ///
139 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000140 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000141 }
142
Chris Lattner44827152003-12-28 09:47:19 +0000143 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
144 /// function, lowering any calls to unknown intrinsic functions into the
145 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000146 ///
Chris Lattner44827152003-12-28 09:47:19 +0000147 void LowerUnknownIntrinsicFunctionCalls(Function &F);
148
Chris Lattner065faeb2002-12-28 20:24:02 +0000149 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
150 /// from the stack into virtual registers.
151 ///
152 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000153
154 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
155 /// because we have to generate our sources into the source basic blocks,
156 /// not the current one.
157 ///
158 void SelectPHINodes();
159
Chris Lattner986618e2004-02-22 19:47:26 +0000160 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
161 /// that need them. This only occurs due to the floating point stackifier
162 /// not being aggressive enough to handle arbitrary global stackification.
163 ///
164 void InsertFPRegKills();
165
Chris Lattner72614082002-10-25 22:55:53 +0000166 // Visitation methods for various instructions. These methods simply emit
167 // fixed X86 code for each instruction.
168 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000169
170 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000171 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000172 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000173
174 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000175 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000176 unsigned Reg;
177 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000178 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
179 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000180 };
181 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000182 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000183 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000184 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000185
186 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000187 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000188 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
189 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerca9671d2002-11-02 20:28:58 +0000190 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000191
Chris Lattnerf01729e2002-11-02 20:54:46 +0000192 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
193 void visitRem(BinaryOperator &B) { visitDivRem(B); }
194 void visitDivRem(BinaryOperator &B);
195
Chris Lattnere2954c82002-11-02 20:04:26 +0000196 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000197 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
198 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
199 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000200
Chris Lattner6d40c192003-01-16 16:43:00 +0000201 // Comparison operators...
202 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000203 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
204 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000205 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000206 void visitSelectInst(SelectInst &SI);
207
Chris Lattnerb2acc512003-10-19 21:09:10 +0000208
Chris Lattner6fc3c522002-11-17 21:11:55 +0000209 // Memory Instructions
210 void visitLoadInst(LoadInst &I);
211 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000212 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000213 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000214 void visitMallocInst(MallocInst &I);
215 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000216
Chris Lattnere2954c82002-11-02 20:04:26 +0000217 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000218 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000219 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000220 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000221 void visitVANextInst(VANextInst &I);
222 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000223
224 void visitInstruction(Instruction &I) {
225 std::cerr << "Cannot instruction select: " << I;
226 abort();
227 }
228
Brian Gaeke95780cc2002-12-13 07:56:18 +0000229 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000230 ///
231 void promote32(unsigned targetReg, const ValueRecord &VR);
232
Chris Lattner721d2d42004-03-08 01:18:36 +0000233 /// getAddressingMode - Get the addressing mode to use to address the
234 /// specified value. The returned value should be used with addFullAddress.
235 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
236 unsigned &IndexReg, unsigned &Disp);
237
238
239 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
240 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000241 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
242 std::vector<Value*> &GEPOps,
243 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
244 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
245
246 /// isGEPFoldable - Return true if the specified GEP can be completely
247 /// folded into the addressing mode of a load/store or lea instruction.
248 bool isGEPFoldable(MachineBasicBlock *MBB,
249 Value *Src, User::op_iterator IdxBegin,
250 User::op_iterator IdxEnd, unsigned &BaseReg,
251 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
252
Chris Lattner3e130a22003-01-13 00:32:26 +0000253 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
254 /// constant expression GEP support.
255 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000256 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000257 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000258 User::op_iterator IdxEnd, unsigned TargetReg);
259
Chris Lattner548f61d2003-04-23 17:22:12 +0000260 /// emitCastOperation - Common code shared between visitCastInst and
261 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000262 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000263 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000264 Value *Src, const Type *DestTy, unsigned TargetReg);
265
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000266 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
267 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000268 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000269 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000270 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000271 Value *Op0, Value *Op1,
272 unsigned OperatorClass, unsigned TargetReg);
273
Chris Lattner6621ed92004-04-11 21:23:56 +0000274 /// emitBinaryFPOperation - This method handles emission of floating point
275 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
276 void emitBinaryFPOperation(MachineBasicBlock *BB,
277 MachineBasicBlock::iterator IP,
278 Value *Op0, Value *Op1,
279 unsigned OperatorClass, unsigned TargetReg);
280
Chris Lattner462fa822004-04-11 20:56:28 +0000281 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
282 Value *Op0, Value *Op1, unsigned TargetReg);
283
284 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
285 unsigned DestReg, const Type *DestTy,
286 unsigned Op0Reg, unsigned Op1Reg);
287 void doMultiplyConst(MachineBasicBlock *MBB,
288 MachineBasicBlock::iterator MBBI,
289 unsigned DestReg, const Type *DestTy,
290 unsigned Op0Reg, unsigned Op1Val);
291
Chris Lattnercadff442003-10-23 17:21:43 +0000292 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000293 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +0000294 Value *Op0, Value *Op1, bool isDiv,
295 unsigned TargetReg);
Chris Lattnercadff442003-10-23 17:21:43 +0000296
Chris Lattner58c41fe2003-08-24 19:19:47 +0000297 /// emitSetCCOperation - Common code shared between visitSetCondInst and
298 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000299 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000300 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000301 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000302 Value *Op0, Value *Op1, unsigned Opcode,
303 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000304
305 /// emitShiftOperation - Common code shared between visitShiftInst and
306 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000307 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000308 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000309 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000310 Value *Op, Value *ShiftAmount, bool isLeftShift,
311 const Type *ResultTy, unsigned DestReg);
312
Chris Lattner12d96a02004-03-30 21:22:00 +0000313 /// emitSelectOperation - Common code shared between visitSelectInst and the
314 /// constant expression support.
315 void emitSelectOperation(MachineBasicBlock *MBB,
316 MachineBasicBlock::iterator IP,
317 Value *Cond, Value *TrueVal, Value *FalseVal,
318 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000319
Chris Lattnerc5291f52002-10-27 21:16:59 +0000320 /// copyConstantToRegister - Output the instructions required to put the
321 /// specified constant into the specified register.
322 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000323 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000324 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000325 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000326
Chris Lattner3e130a22003-01-13 00:32:26 +0000327 /// makeAnotherReg - This method returns the next register number we haven't
328 /// yet used.
329 ///
330 /// Long values are handled somewhat specially. They are always allocated
331 /// as pairs of 32 bit integer values. The register number returned is the
332 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
333 /// of the long value.
334 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000335 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000336 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
337 "Current target doesn't have X86 reg info??");
338 const X86RegisterInfo *MRI =
339 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000340 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000341 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
342 // Create the lower part
343 F->getSSARegMap()->createVirtualRegister(RC);
344 // Create the upper part.
345 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000346 }
347
Chris Lattnerc0812d82002-12-13 06:56:29 +0000348 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000349 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000350 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000351 }
352
Chris Lattner72614082002-10-25 22:55:53 +0000353 /// getReg - This method turns an LLVM value into a register number. This
354 /// is guaranteed to produce the same register number for a particular value
355 /// every time it is queried.
356 ///
357 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000358 unsigned getReg(Value *V) {
359 // Just append to the end of the current bb.
360 MachineBasicBlock::iterator It = BB->end();
361 return getReg(V, BB, It);
362 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000363 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000364 MachineBasicBlock::iterator IPt) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000365 // If this operand is a constant, emit the code to copy the constant into
366 // the register here...
367 //
368 if (Constant *C = dyn_cast<Constant>(V)) {
369 unsigned Reg = makeAnotherReg(V->getType());
370 copyConstantToRegister(MBB, IPt, C, Reg);
371 return Reg;
372 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
373 unsigned Reg = makeAnotherReg(V->getType());
374 // Move the address of the global into the register
375 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
376 return Reg;
377 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
378 // Do not emit noop casts at all.
379 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
380 return getReg(CI->getOperand(0), MBB, IPt);
381 }
382
Chris Lattner72614082002-10-25 22:55:53 +0000383 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000384 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000385 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000386 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000387 }
Chris Lattner72614082002-10-25 22:55:53 +0000388
Chris Lattner72614082002-10-25 22:55:53 +0000389 return Reg;
390 }
Chris Lattner72614082002-10-25 22:55:53 +0000391 };
392}
393
Chris Lattnerc5291f52002-10-27 21:16:59 +0000394/// copyConstantToRegister - Output the instructions required to put the
395/// specified constant into the specified register.
396///
Chris Lattner8a307e82002-12-16 19:32:50 +0000397void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000398 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000399 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000401 unsigned Class = 0;
402 switch (CE->getOpcode()) {
403 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000404 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000405 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000406 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000407 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000408 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000409 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000410
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000411 case Instruction::Xor: ++Class; // FALL THROUGH
412 case Instruction::Or: ++Class; // FALL THROUGH
413 case Instruction::And: ++Class; // FALL THROUGH
414 case Instruction::Sub: ++Class; // FALL THROUGH
415 case Instruction::Add:
416 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
417 Class, R);
418 return;
419
Chris Lattner462fa822004-04-11 20:56:28 +0000420 case Instruction::Mul:
421 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
Chris Lattnercadff442003-10-23 17:21:43 +0000422 return;
Chris Lattner462fa822004-04-11 20:56:28 +0000423
Chris Lattnercadff442003-10-23 17:21:43 +0000424 case Instruction::Div:
Chris Lattner462fa822004-04-11 20:56:28 +0000425 case Instruction::Rem:
426 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
427 CE->getOpcode() == Instruction::Div, R);
Chris Lattnercadff442003-10-23 17:21:43 +0000428 return;
Chris Lattnercadff442003-10-23 17:21:43 +0000429
Chris Lattner58c41fe2003-08-24 19:19:47 +0000430 case Instruction::SetNE:
431 case Instruction::SetEQ:
432 case Instruction::SetLT:
433 case Instruction::SetGT:
434 case Instruction::SetLE:
435 case Instruction::SetGE:
436 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
437 CE->getOpcode(), R);
438 return;
439
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000440 case Instruction::Shl:
441 case Instruction::Shr:
442 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000443 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
444 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000445
Chris Lattner12d96a02004-03-30 21:22:00 +0000446 case Instruction::Select:
447 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
448 CE->getOperand(2), R);
449 return;
450
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000451 default:
452 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000453 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000454 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000455 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000456
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000457 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000458 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000459
460 if (Class == cLong) {
461 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000462 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000463 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
464 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000465 return;
466 }
467
Chris Lattner94af4142002-12-25 05:13:53 +0000468 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000469
470 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000471 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000472 };
473
Chris Lattner6b993cc2002-12-15 08:02:15 +0000474 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000475 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000476 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000477 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000478 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000479 }
Chris Lattner94af4142002-12-25 05:13:53 +0000480 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000481 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000482 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000483 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000484 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000485 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000486 // Otherwise we need to spill the constant to memory...
487 MachineConstantPool *CP = F->getConstantPool();
488 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000489 const Type *Ty = CFP->getType();
490
491 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000492 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000493 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000494 }
495
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000496 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000497 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000498 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000499 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000500 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000501 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000502 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000503 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000504 }
505}
506
Chris Lattner065faeb2002-12-28 20:24:02 +0000507/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
508/// the stack into virtual registers.
509///
510void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
511 // Emit instructions to load the arguments... On entry to a function on the
512 // X86, the stack frame looks like this:
513 //
514 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000515 // [ESP + 4] -- first argument (leftmost lexically)
516 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000517 // ...
518 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000519 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000520 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000521
522 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000523 bool ArgLive = !I->use_empty();
524 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000525 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000526
Chris Lattner065faeb2002-12-28 20:24:02 +0000527 switch (getClassB(I->getType())) {
528 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000529 if (ArgLive) {
530 FI = MFI->CreateFixedObject(1, ArgOffset);
531 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
532 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000533 break;
534 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000535 if (ArgLive) {
536 FI = MFI->CreateFixedObject(2, ArgOffset);
537 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
538 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000539 break;
540 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000541 if (ArgLive) {
542 FI = MFI->CreateFixedObject(4, ArgOffset);
543 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
544 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000545 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000546 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000547 if (ArgLive) {
548 FI = MFI->CreateFixedObject(8, ArgOffset);
549 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
550 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
551 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000552 ArgOffset += 4; // longs require 4 additional bytes
553 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000554 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000555 if (ArgLive) {
556 unsigned Opcode;
557 if (I->getType() == Type::FloatTy) {
558 Opcode = X86::FLD32m;
559 FI = MFI->CreateFixedObject(4, ArgOffset);
560 } else {
561 Opcode = X86::FLD64m;
562 FI = MFI->CreateFixedObject(8, ArgOffset);
563 }
564 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000565 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000566 if (I->getType() == Type::DoubleTy)
567 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000568 break;
569 default:
570 assert(0 && "Unhandled argument type!");
571 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000572 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000573 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000574
575 // If the function takes variable number of arguments, add a frame offset for
576 // the start of the first vararg value... this is used to expand
577 // llvm.va_start.
578 if (Fn.getFunctionType()->isVarArg())
579 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000580}
581
582
Chris Lattner333b2fa2002-12-13 10:09:43 +0000583/// SelectPHINodes - Insert machine code to generate phis. This is tricky
584/// because we have to generate our sources into the source basic blocks, not
585/// the current one.
586///
587void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000588 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000589 const Function &LF = *F->getFunction(); // The LLVM function...
590 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
591 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000592 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000593
594 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000595 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000596 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000597 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000598
Chris Lattner333b2fa2002-12-13 10:09:43 +0000599 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000600 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000601 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
602 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000603
604 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000605 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
606 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
607 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000608
Chris Lattnera6e73f12003-05-12 14:22:21 +0000609 // PHIValues - Map of blocks to incoming virtual registers. We use this
610 // so that we only initialize one incoming value for a particular block,
611 // even if the block has multiple entries in the PHI node.
612 //
613 std::map<MachineBasicBlock*, unsigned> PHIValues;
614
Chris Lattner333b2fa2002-12-13 10:09:43 +0000615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
616 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000617 unsigned ValReg;
618 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
619 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000620
Chris Lattnera6e73f12003-05-12 14:22:21 +0000621 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
622 // We already inserted an initialization of the register for this
623 // predecessor. Recycle it.
624 ValReg = EntryIt->second;
625
626 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000627 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000628 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000629 Value *Val = PN->getIncomingValue(i);
630
631 // If this is a constant or GlobalValue, we may have to insert code
632 // into the basic block to compute it into a virtual register.
633 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
Chris Lattner6f2ab042004-03-30 19:10:12 +0000634 if (isa<ConstantExpr>(Val)) {
635 // Because we don't want to clobber any values which might be in
636 // physical registers with the computation of this constant (which
637 // might be arbitrarily complex if it is a constant expression),
638 // just insert the computation at the top of the basic block.
639 MachineBasicBlock::iterator PI = PredMBB->begin();
640
641 // Skip over any PHI nodes though!
642 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
643 ++PI;
644
645 ValReg = getReg(Val, PredMBB, PI);
646 } else {
647 // Simple constants get emitted at the end of the basic block,
648 // before any terminator instructions. We "know" that the code to
649 // move a constant into a register will never clobber any flags.
650 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
651 }
Chris Lattnera81fc682003-10-19 00:26:11 +0000652 } else {
653 ValReg = getReg(Val);
654 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000655
656 // Remember that we inserted a value for this PHI for this predecessor
657 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
658 }
659
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000660 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000661 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000662 if (LongPhiMI) {
663 LongPhiMI->addRegOperand(ValReg+1);
664 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
665 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000666 }
Chris Lattner168aa902004-02-29 07:10:16 +0000667
668 // Now that we emitted all of the incoming values for the PHI node, make
669 // sure to reposition the InsertPoint after the PHI that we just added.
670 // This is needed because we might have inserted a constant into this
671 // block, right after the PHI's which is before the old insert point!
672 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
673 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000674 }
675 }
676}
677
Chris Lattner986618e2004-02-22 19:47:26 +0000678/// RequiresFPRegKill - The floating point stackifier pass cannot insert
679/// compensation code on critical edges. As such, it requires that we kill all
680/// FP registers on the exit from any blocks that either ARE critical edges, or
681/// branch to a block that has incoming critical edges.
682///
683/// Note that this kill instruction will eventually be eliminated when
684/// restrictions in the stackifier are relaxed.
685///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000686static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000687#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000688 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000689 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
690 const BasicBlock *Succ = *SI;
691 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
692 ++PI; // Block have at least one predecessory
693 if (PI != PE) { // If it has exactly one, this isn't crit edge
694 // If this block has more than one predecessor, check all of the
695 // predecessors to see if they have multiple successors. If so, then the
696 // block we are analyzing needs an FPRegKill.
697 for (PI = pred_begin(Succ); PI != PE; ++PI) {
698 const BasicBlock *Pred = *PI;
699 succ_const_iterator SI2 = succ_begin(Pred);
700 ++SI2; // There must be at least one successor of this block.
701 if (SI2 != succ_end(Pred))
702 return true; // Yes, we must insert the kill on this edge.
703 }
704 }
705 }
706 // If we got this far, there is no need to insert the kill instruction.
707 return false;
708#else
709 return true;
710#endif
711}
712
713// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
714// need them. This only occurs due to the floating point stackifier not being
715// aggressive enough to handle arbitrary global stackification.
716//
717// Currently we insert an FP_REG_KILL instruction into each block that uses or
718// defines a floating point virtual register.
719//
720// When the global register allocators (like linear scan) finally update live
721// variable analysis, we can keep floating point values in registers across
722// portions of the CFG that do not involve critical edges. This will be a big
723// win, but we are waiting on the global allocators before we can do this.
724//
725// With a bit of work, the floating point stackifier pass can be enhanced to
726// break critical edges as needed (to make a place to put compensation code),
727// but this will require some infrastructure improvements as well.
728//
729void ISel::InsertFPRegKills() {
730 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000731
732 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000733 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000734 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
735 MachineOperand& MO = I->getOperand(i);
736 if (MO.isRegister() && MO.getReg()) {
737 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000738 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000739 if (RegMap.getRegClass(Reg)->getSize() == 10)
740 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000741 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000742 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000743 // If we haven't found an FP register use or def in this basic block, check
744 // to see if any of our successors has an FP PHI node, which will cause a
745 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000746 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
747 SE = BB->succ_end(); SI != SE; ++SI) {
748 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000749 for (MachineBasicBlock::iterator I = SBB->begin();
750 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
751 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
752 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000753 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000754 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000755 continue;
756 UsesFPReg:
757 // Okay, this block uses an FP register. If the block has successors (ie,
758 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Brian Gaeke1afe7732004-04-28 04:45:55 +0000759 if (BB->succ_size () && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000760 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000761 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000762 }
763 }
764}
765
766
Chris Lattner307ecba2004-03-30 22:39:09 +0000767// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
768// it into the conditional branch or select instruction which is the only user
769// of the cc instruction. This is the case if the conditional branch is the
770// only user of the setcc, and if the setcc is in the same basic block as the
771// conditional branch. We also don't handle long arguments below, so we reject
772// them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000773//
Chris Lattner307ecba2004-03-30 22:39:09 +0000774static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000775 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000776 if (SCI->hasOneUse()) {
777 Instruction *User = cast<Instruction>(SCI->use_back());
778 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
779 SCI->getParent() == User->getParent() &&
Chris Lattner48c937e2004-04-06 17:34:50 +0000780 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
781 SCI->getOpcode() == Instruction::SetEQ ||
782 SCI->getOpcode() == Instruction::SetNE))
Chris Lattner6d40c192003-01-16 16:43:00 +0000783 return SCI;
784 }
785 return 0;
786}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000787
Chris Lattner6d40c192003-01-16 16:43:00 +0000788// Return a fixed numbering for setcc instructions which does not depend on the
789// order of the opcodes.
790//
791static unsigned getSetCCNumber(unsigned Opcode) {
792 switch(Opcode) {
793 default: assert(0 && "Unknown setcc instruction!");
794 case Instruction::SetEQ: return 0;
795 case Instruction::SetNE: return 1;
796 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000797 case Instruction::SetGE: return 3;
798 case Instruction::SetGT: return 4;
799 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000800 }
801}
Chris Lattner06925362002-11-17 21:56:38 +0000802
Chris Lattner6d40c192003-01-16 16:43:00 +0000803// LLVM -> X86 signed X86 unsigned
804// ----- ---------- ------------
805// seteq -> sete sete
806// setne -> setne setne
807// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000808// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000809// setgt -> setg seta
810// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000811// ----
812// sets // Used by comparison with 0 optimization
813// setns
814static const unsigned SetCCOpcodeTab[2][8] = {
815 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
816 0, 0 },
817 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
818 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000819};
820
Chris Lattnerb2acc512003-10-19 21:09:10 +0000821// EmitComparison - This function emits a comparison of the two operands,
822// returning the extended setcc code to use.
823unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
824 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000825 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000826 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000827 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000828 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000829 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000830
831 // Special case handling of: cmp R, i
Chris Lattnere80e6372004-04-06 16:02:27 +0000832 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
833 if (Class == cByte || Class == cShort || Class == cInt) {
834 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000835
Chris Lattner333864d2003-06-05 19:30:30 +0000836 // Mask off any upper bits of the constant, if there are any...
837 Op1v &= (1ULL << (8 << Class)) - 1;
838
Chris Lattnerb2acc512003-10-19 21:09:10 +0000839 // If this is a comparison against zero, emit more efficient code. We
840 // can't handle unsigned comparisons against zero unless they are == or
841 // !=. These should have been strength reduced already anyway.
842 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
843 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000844 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000845 };
Chris Lattneree352852004-02-29 07:22:16 +0000846 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000847
848 if (OpNum == 2) return 6; // Map jl -> js
849 if (OpNum == 3) return 7; // Map jg -> jns
850 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000851 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000852
853 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000854 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000855 };
856
Chris Lattneree352852004-02-29 07:22:16 +0000857 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000858 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000859 } else {
860 assert(Class == cLong && "Unknown integer class!");
861 unsigned LowCst = CI->getRawValue();
862 unsigned HiCst = CI->getRawValue() >> 32;
863 if (OpNum < 2) { // seteq, setne
864 unsigned LoTmp = Op0r;
865 if (LowCst != 0) {
866 LoTmp = makeAnotherReg(Type::IntTy);
867 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
868 }
869 unsigned HiTmp = Op0r+1;
870 if (HiCst != 0) {
871 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +0000872 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +0000873 }
874 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
875 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
876 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +0000877 } else {
878 // Emit a sequence of code which compares the high and low parts once
879 // each, then uses a conditional move to handle the overflow case. For
880 // example, a setlt for long would generate code like this:
881 //
882 // AL = lo(op1) < lo(op2) // Signedness depends on operands
883 // BL = hi(op1) < hi(op2) // Always unsigned comparison
884 // dest = hi(op1) == hi(op2) ? AL : BL;
885 //
886
887 // FIXME: This would be much better if we had hierarchical register
888 // classes! Until then, hardcode registers so that we can deal with
889 // their aliases (because we don't have conditional byte moves).
890 //
891 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
892 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
893 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
894 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
895 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
896 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
897 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
898 .addReg(X86::AX);
899 // NOTE: visitSetCondInst knows that the value is dumped into the BL
900 // register at this point for long values...
901 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000902 }
Chris Lattner333864d2003-06-05 19:30:30 +0000903 }
Chris Lattnere80e6372004-04-06 16:02:27 +0000904 }
Chris Lattner333864d2003-06-05 19:30:30 +0000905
Chris Lattner9f08a922004-02-03 18:54:04 +0000906 // Special case handling of comparison against +/- 0.0
907 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
908 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000909 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000910 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000911 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000912 return OpNum;
913 }
914
Chris Lattner58c41fe2003-08-24 19:19:47 +0000915 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000916 switch (Class) {
917 default: assert(0 && "Unknown type class!");
918 // Emit: cmp <var1>, <var2> (do the comparison). We can
919 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
920 // 32-bit.
921 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000922 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000923 break;
924 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000925 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000926 break;
927 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000928 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000929 break;
930 case cFP:
Chris Lattner8d2822e2004-04-12 01:43:36 +0000931 if (0) { // for processors prior to the P6
932 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
933 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
934 BuildMI(*MBB, IP, X86::SAHF, 1);
935 } else {
Chris Lattner133dbb12004-04-12 03:02:48 +0000936 BuildMI(*MBB, IP, X86::FpUCOMI, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner8d2822e2004-04-12 01:43:36 +0000937 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000938 break;
939
940 case cLong:
941 if (OpNum < 2) { // seteq, setne
942 unsigned LoTmp = makeAnotherReg(Type::IntTy);
943 unsigned HiTmp = makeAnotherReg(Type::IntTy);
944 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000945 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
946 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
947 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +0000948 break; // Allow the sete or setne to be generated from flags set by OR
949 } else {
950 // Emit a sequence of code which compares the high and low parts once
951 // each, then uses a conditional move to handle the overflow case. For
952 // example, a setlt for long would generate code like this:
953 //
954 // AL = lo(op1) < lo(op2) // Signedness depends on operands
955 // BL = hi(op1) < hi(op2) // Always unsigned comparison
956 // dest = hi(op1) == hi(op2) ? AL : BL;
957 //
958
Chris Lattner6d40c192003-01-16 16:43:00 +0000959 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000960 // classes! Until then, hardcode registers so that we can deal with their
961 // aliases (because we don't have conditional byte moves).
962 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000963 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +0000964 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000965 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +0000966 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
967 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
968 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000969 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +0000970 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000971 // NOTE: visitSetCondInst knows that the value is dumped into the BL
972 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +0000973 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +0000974 }
975 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000976 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +0000977}
Chris Lattner3e130a22003-01-13 00:32:26 +0000978
Chris Lattner6d40c192003-01-16 16:43:00 +0000979/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
980/// register, then move it to wherever the result should be.
981///
982void ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +0000983 if (canFoldSetCCIntoBranchOrSelect(&I))
984 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +0000985
Chris Lattner6d40c192003-01-16 16:43:00 +0000986 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000987 MachineBasicBlock::iterator MII = BB->end();
988 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
989 DestReg);
990}
Chris Lattner6d40c192003-01-16 16:43:00 +0000991
Chris Lattner58c41fe2003-08-24 19:19:47 +0000992/// emitSetCCOperation - Common code shared between visitSetCondInst and
993/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000994///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000995void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000996 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000997 Value *Op0, Value *Op1, unsigned Opcode,
998 unsigned TargetReg) {
999 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001000 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001001
Chris Lattnerb2acc512003-10-19 21:09:10 +00001002 const Type *CompTy = Op0->getType();
1003 unsigned CompClass = getClassB(CompTy);
1004 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1005
1006 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +00001007 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001008 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +00001009 } else {
1010 // Handle long comparisons by copying the value which is already in BL into
1011 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001012 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +00001013 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001014}
Chris Lattner51b49a92002-11-02 19:45:49 +00001015
Chris Lattner12d96a02004-03-30 21:22:00 +00001016void ISel::visitSelectInst(SelectInst &SI) {
1017 unsigned DestReg = getReg(SI);
1018 MachineBasicBlock::iterator MII = BB->end();
1019 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1020 SI.getFalseValue(), DestReg);
1021}
1022
1023/// emitSelect - Common code shared between visitSelectInst and the constant
1024/// expression support.
1025void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1026 MachineBasicBlock::iterator IP,
1027 Value *Cond, Value *TrueVal, Value *FalseVal,
1028 unsigned DestReg) {
1029 unsigned SelectClass = getClassB(TrueVal->getType());
1030
1031 // We don't support 8-bit conditional moves. If we have incoming constants,
1032 // transform them into 16-bit constants to avoid having a run-time conversion.
1033 if (SelectClass == cByte) {
1034 if (Constant *T = dyn_cast<Constant>(TrueVal))
1035 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1036 if (Constant *F = dyn_cast<Constant>(FalseVal))
1037 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1038 }
1039
Chris Lattner82c5a992004-04-13 21:56:09 +00001040 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1041 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1042 if (TrueReg == FalseReg) {
1043 static const unsigned Opcode[] = {
1044 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1045 };
1046 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1047 if (SelectClass == cLong)
1048 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1049 return;
1050 }
1051
Chris Lattner307ecba2004-03-30 22:39:09 +00001052 unsigned Opcode;
1053 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1054 // We successfully folded the setcc into the select instruction.
1055
1056 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1057 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1058 IP);
1059
1060 const Type *CompTy = SCI->getOperand(0)->getType();
1061 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1062
1063 // LLVM -> X86 signed X86 unsigned
1064 // ----- ---------- ------------
1065 // seteq -> cmovNE cmovNE
1066 // setne -> cmovE cmovE
1067 // setlt -> cmovGE cmovAE
1068 // setge -> cmovL cmovB
1069 // setgt -> cmovLE cmovBE
1070 // setle -> cmovG cmovA
1071 // ----
1072 // cmovNS // Used by comparison with 0 optimization
1073 // cmovS
1074
1075 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001076 default: assert(0 && "Unknown value class!");
1077 case cFP: {
1078 // Annoyingly, we don't have a full set of floating point conditional
1079 // moves. :(
1080 static const unsigned OpcodeTab[2][8] = {
1081 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1082 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1083 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1084 };
1085 Opcode = OpcodeTab[isSigned][OpNum];
1086
1087 // If opcode == 0, we hit a case that we don't support. Output a setcc
1088 // and compare the result against zero.
1089 if (Opcode == 0) {
1090 unsigned CompClass = getClassB(CompTy);
1091 unsigned CondReg;
1092 if (CompClass != cLong || OpNum < 2) {
1093 CondReg = makeAnotherReg(Type::BoolTy);
1094 // Handle normal comparisons with a setcc instruction...
1095 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1096 } else {
1097 // Long comparisons end up in the BL register.
1098 CondReg = X86::BL;
1099 }
1100
Chris Lattner68626c22004-03-31 22:22:36 +00001101 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001102 Opcode = X86::FCMOVE;
1103 }
1104 break;
1105 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001106 case cByte:
1107 case cShort: {
1108 static const unsigned OpcodeTab[2][8] = {
1109 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1110 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1111 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1112 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1113 };
1114 Opcode = OpcodeTab[isSigned][OpNum];
1115 break;
1116 }
1117 case cInt:
1118 case cLong: {
1119 static const unsigned OpcodeTab[2][8] = {
1120 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1121 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1122 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1123 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1124 };
1125 Opcode = OpcodeTab[isSigned][OpNum];
1126 break;
1127 }
1128 }
1129 } else {
1130 // Get the value being branched on, and use it to set the condition codes.
1131 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001132 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001133 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001134 default: assert(0 && "Unknown value class!");
1135 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001136 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001137 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001138 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001139 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001140 }
1141 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001142
Chris Lattner12d96a02004-03-30 21:22:00 +00001143 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001144
Chris Lattner12d96a02004-03-30 21:22:00 +00001145
1146 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1147 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1148 // cmove, then truncate the result.
1149 if (SelectClass == cByte) {
1150 DestReg = makeAnotherReg(Type::ShortTy);
1151 if (getClassB(TrueVal->getType()) == cByte) {
1152 // Promote the true value, by storing it into AL, and reading from AX.
1153 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1154 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1155 TrueReg = makeAnotherReg(Type::ShortTy);
1156 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1157 }
1158 if (getClassB(FalseVal->getType()) == cByte) {
1159 // Promote the true value, by storing it into CL, and reading from CX.
1160 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1161 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1162 FalseReg = makeAnotherReg(Type::ShortTy);
1163 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1164 }
1165 }
1166
1167 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1168
1169 switch (SelectClass) {
1170 case cByte:
1171 // We did the computation with 16-bit registers. Truncate back to our
1172 // result by copying into AX then copying out AL.
1173 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1174 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1175 break;
1176 case cLong:
1177 // Move the upper half of the value as well.
1178 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1179 break;
1180 }
1181}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001182
1183
1184
Brian Gaekec2505982002-11-30 11:57:28 +00001185/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1186/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001187///
Chris Lattner3e130a22003-01-13 00:32:26 +00001188void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1189 bool isUnsigned = VR.Ty->isUnsigned();
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001190
Chris Lattner29bf0622004-04-06 01:21:00 +00001191 Value *Val = VR.Val;
1192 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001193 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001194 if (Constant *C = dyn_cast<Constant>(Val)) {
1195 Val = ConstantExpr::getCast(C, Type::IntTy);
1196 Ty = Type::IntTy;
1197 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001198
Chris Lattner502e36c2004-04-06 01:25:33 +00001199 // If this is a simple constant, just emit a MOVri directly to avoid the
1200 // copy.
1201 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1202 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1203 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1204 return;
1205 }
1206 }
1207
Chris Lattner29bf0622004-04-06 01:21:00 +00001208 // Make sure we have the register number for this value...
1209 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1210
1211 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001212 case cByte:
1213 // Extend value into target register (8->32)
1214 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001215 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001216 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001217 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001218 break;
1219 case cShort:
1220 // Extend value into target register (16->32)
1221 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001222 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001223 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001224 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001225 break;
1226 case cInt:
1227 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001228 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001229 break;
1230 default:
1231 assert(0 && "Unpromotable operand class in promote32");
1232 }
Brian Gaekec2505982002-11-30 11:57:28 +00001233}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001234
Chris Lattner72614082002-10-25 22:55:53 +00001235/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1236/// we have the following possibilities:
1237///
1238/// ret void: No return value, simply emit a 'ret' instruction
1239/// ret sbyte, ubyte : Extend value into EAX and return
1240/// ret short, ushort: Extend value into EAX and return
1241/// ret int, uint : Move value into EAX and return
1242/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001243/// ret long, ulong : Move value into EAX/EDX and return
1244/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001245///
Chris Lattner3e130a22003-01-13 00:32:26 +00001246void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001247 if (I.getNumOperands() == 0) {
1248 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1249 return;
1250 }
1251
1252 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001253 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001254 case cByte: // integral return values: extend or move into EAX and return
1255 case cShort:
1256 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001257 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001258 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001259 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001260 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001261 case cFP: { // Floats & Doubles: Return in ST(0)
1262 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001263 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001264 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001265 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001266 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001267 }
1268 case cLong: {
1269 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001270 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1271 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001272 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001273 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1274 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001275 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001276 }
Chris Lattner94af4142002-12-25 05:13:53 +00001277 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001278 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001279 }
Chris Lattner43189d12002-11-17 20:07:45 +00001280 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001281 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001282}
1283
Chris Lattner55f6fab2003-01-16 18:07:23 +00001284// getBlockAfter - Return the basic block which occurs lexically after the
1285// specified one.
1286static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1287 Function::iterator I = BB; ++I; // Get iterator to next block
1288 return I != BB->getParent()->end() ? &*I : 0;
1289}
1290
Chris Lattner51b49a92002-11-02 19:45:49 +00001291/// visitBranchInst - Handle conditional and unconditional branches here. Note
1292/// that since code layout is frozen at this point, that if we are trying to
1293/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001294/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001295///
Chris Lattner94af4142002-12-25 05:13:53 +00001296void ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001297 // Update machine-CFG edges
1298 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1299 if (BI.isConditional())
1300 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1301
Chris Lattner55f6fab2003-01-16 18:07:23 +00001302 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1303
1304 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001305 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001306 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001307 return;
1308 }
1309
1310 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001311 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001312 if (SCI == 0) {
1313 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1314 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001315 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001316 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001317 if (BI.getSuccessor(1) == NextBB) {
1318 if (BI.getSuccessor(0) != NextBB)
1319 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1320 } else {
1321 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1322
1323 if (BI.getSuccessor(0) != NextBB)
1324 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1325 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001326 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001327 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001328
1329 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001330 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001331 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001332
1333 const Type *CompTy = SCI->getOperand(0)->getType();
1334 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001335
Chris Lattnerb2acc512003-10-19 21:09:10 +00001336
Chris Lattner6d40c192003-01-16 16:43:00 +00001337 // LLVM -> X86 signed X86 unsigned
1338 // ----- ---------- ------------
1339 // seteq -> je je
1340 // setne -> jne jne
1341 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001342 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001343 // setgt -> jg ja
1344 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001345 // ----
1346 // js // Used by comparison with 0 optimization
1347 // jns
1348
1349 static const unsigned OpcodeTab[2][8] = {
1350 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1351 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1352 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001353 };
1354
Chris Lattner55f6fab2003-01-16 18:07:23 +00001355 if (BI.getSuccessor(0) != NextBB) {
1356 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1357 if (BI.getSuccessor(1) != NextBB)
1358 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1359 } else {
1360 // Change to the inverse condition...
1361 if (BI.getSuccessor(1) != NextBB) {
1362 OpNum ^= 1;
1363 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1364 }
1365 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001366}
1367
Chris Lattner3e130a22003-01-13 00:32:26 +00001368
1369/// doCall - This emits an abstract call instruction, setting up the arguments
1370/// and the return value as appropriate. For the actual function call itself,
1371/// it inserts the specified CallMI instruction into the stream.
1372///
1373void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001374 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001375
Chris Lattner065faeb2002-12-28 20:24:02 +00001376 // Count how many bytes are to be pushed on the stack...
1377 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001378
Chris Lattner3e130a22003-01-13 00:32:26 +00001379 if (!Args.empty()) {
1380 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1381 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001382 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001383 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001384 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001385 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001386 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001387 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1388 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001389 default: assert(0 && "Unknown class!");
1390 }
1391
1392 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001393 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001394
1395 // Arguments go on the stack in reverse order, as specified by the ABI.
1396 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001397 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001398 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001399 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001400 case cByte:
Chris Lattner21585222004-03-01 02:42:43 +00001401 case cShort:
1402 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1403 // Zero/Sign extend constant, then stuff into memory.
1404 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1405 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1406 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1407 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1408 } else {
1409 // Promote arg to 32 bits wide into a temporary register...
1410 ArgReg = makeAnotherReg(Type::UIntTy);
1411 promote32(ArgReg, Args[i]);
1412 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1413 X86::ESP, ArgOffset).addReg(ArgReg);
1414 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001415 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001416 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001417 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1418 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1419 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1420 X86::ESP, ArgOffset).addImm(Val);
1421 } else {
1422 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1423 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1424 X86::ESP, ArgOffset).addReg(ArgReg);
1425 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001426 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001427 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001428 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1429 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1430 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1431 X86::ESP, ArgOffset).addImm(Val & ~0U);
1432 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1433 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1434 } else {
1435 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1436 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1437 X86::ESP, ArgOffset).addReg(ArgReg);
1438 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1439 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1440 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001441 ArgOffset += 4; // 8 byte entry, not 4.
1442 break;
1443
Chris Lattner065faeb2002-12-28 20:24:02 +00001444 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001445 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001446 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001447 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001448 X86::ESP, ArgOffset).addReg(ArgReg);
1449 } else {
1450 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001451 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001452 X86::ESP, ArgOffset).addReg(ArgReg);
1453 ArgOffset += 4; // 8 byte entry, not 4.
1454 }
1455 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001456
Chris Lattner3e130a22003-01-13 00:32:26 +00001457 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001458 }
1459 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001460 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001461 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001462 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001463 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001464
Chris Lattner3e130a22003-01-13 00:32:26 +00001465 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001466
Chris Lattneree352852004-02-29 07:22:16 +00001467 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001468
1469 // If there is a return value, scavenge the result from the location the call
1470 // leaves it in...
1471 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001472 if (Ret.Ty != Type::VoidTy) {
1473 unsigned DestClass = getClassB(Ret.Ty);
1474 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001475 case cByte:
1476 case cShort:
1477 case cInt: {
1478 // Integral results are in %eax, or the appropriate portion
1479 // thereof.
1480 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001481 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001482 };
1483 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001484 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001485 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001486 }
Chris Lattner94af4142002-12-25 05:13:53 +00001487 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001488 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001489 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001490 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001491 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1492 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001493 break;
1494 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001495 }
Chris Lattnera3243642002-12-04 23:45:28 +00001496 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001497}
Chris Lattner2df035b2002-11-02 19:27:56 +00001498
Chris Lattner3e130a22003-01-13 00:32:26 +00001499
1500/// visitCallInst - Push args on stack and do a procedure call instruction.
1501void ISel::visitCallInst(CallInst &CI) {
1502 MachineInstr *TheCall;
1503 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001504 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001505 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001506 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1507 return;
1508 }
1509
Chris Lattner3e130a22003-01-13 00:32:26 +00001510 // Emit a CALL instruction with PC-relative displacement.
1511 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1512 } else { // Emit an indirect call...
1513 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001514 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001515 }
1516
1517 std::vector<ValueRecord> Args;
1518 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001519 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001520
1521 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1522 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001523}
Chris Lattner3e130a22003-01-13 00:32:26 +00001524
Chris Lattneraeb54b82003-08-28 21:23:43 +00001525
Chris Lattner44827152003-12-28 09:47:19 +00001526/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1527/// function, lowering any calls to unknown intrinsic functions into the
1528/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001529///
Chris Lattner44827152003-12-28 09:47:19 +00001530void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1531 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1532 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1533 if (CallInst *CI = dyn_cast<CallInst>(I++))
1534 if (Function *F = CI->getCalledFunction())
1535 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001536 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001537 case Intrinsic::vastart:
1538 case Intrinsic::vacopy:
1539 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001540 case Intrinsic::returnaddress:
1541 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001542 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001543 case Intrinsic::memset:
John Criswell4ffff9e2004-04-08 20:31:47 +00001544 case Intrinsic::readport:
1545 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001546 // We directly implement these intrinsics
1547 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001548 case Intrinsic::readio: {
1549 // On X86, memory operations are in-order. Lower this intrinsic
1550 // into a volatile load.
1551 Instruction *Before = CI->getPrev();
1552 LoadInst * LI = new LoadInst (CI->getOperand(1), "", true, CI);
1553 CI->replaceAllUsesWith (LI);
1554 BB->getInstList().erase (CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001555 break;
1556 }
1557 case Intrinsic::writeio: {
1558 // On X86, memory operations are in-order. Lower this intrinsic
1559 // into a volatile store.
1560 Instruction *Before = CI->getPrev();
1561 StoreInst * LI = new StoreInst (CI->getOperand(1),
1562 CI->getOperand(2), true, CI);
1563 CI->replaceAllUsesWith (LI);
1564 BB->getInstList().erase (CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001565 break;
1566 }
Chris Lattner44827152003-12-28 09:47:19 +00001567 default:
1568 // All other intrinsic calls we must lower.
1569 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001570 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001571 if (Before) { // Move iterator to instruction after call
1572 I = Before; ++I;
1573 } else {
1574 I = BB->begin();
1575 }
1576 }
1577
1578}
1579
Brian Gaeked0fde302003-11-11 22:41:34 +00001580void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001581 unsigned TmpReg1, TmpReg2;
1582 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001583 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001584 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001585 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001586 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001587 return;
1588
Chris Lattner5634b9f2004-03-13 00:24:52 +00001589 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001590 TmpReg1 = getReg(CI);
1591 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001592 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001593 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001594 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001595
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001596 case Intrinsic::returnaddress:
1597 case Intrinsic::frameaddress:
1598 TmpReg1 = getReg(CI);
1599 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1600 if (ID == Intrinsic::returnaddress) {
1601 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001602 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001603 ReturnAddressIndex);
1604 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001605 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001606 ReturnAddressIndex, -4);
1607 }
1608 } else {
1609 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001610 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001611 }
1612 return;
1613
Chris Lattner915e5e52004-02-12 17:53:22 +00001614 case Intrinsic::memcpy: {
1615 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1616 unsigned Align = 1;
1617 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1618 Align = AlignC->getRawValue();
1619 if (Align == 0) Align = 1;
1620 }
1621
1622 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001623 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001624 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001625 switch (Align & 3) {
1626 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001627 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1628 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1629 } else {
1630 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001631 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001632 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001633 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001634 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001635 break;
1636 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001637 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1638 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1639 } else {
1640 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001641 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001642 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001643 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001644 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001645 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001646 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001647 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001648 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001649 break;
1650 }
1651
1652 // No matter what the alignment is, we put the source in ESI, the
1653 // destination in EDI, and the count in ECX.
1654 TmpReg1 = getReg(CI.getOperand(1));
1655 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001656 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1657 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1658 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001659 BuildMI(BB, Opcode, 0);
1660 return;
1661 }
1662 case Intrinsic::memset: {
1663 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1664 unsigned Align = 1;
1665 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1666 Align = AlignC->getRawValue();
1667 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001668 }
1669
Chris Lattner2a0f2242004-02-14 04:46:05 +00001670 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001671 unsigned CountReg;
1672 unsigned Opcode;
1673 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1674 unsigned Val = ValC->getRawValue() & 255;
1675
1676 // If the value is a constant, then we can potentially use larger copies.
1677 switch (Align & 3) {
1678 case 2: // WORD aligned
1679 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001680 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001681 } else {
1682 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001683 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001684 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001685 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001686 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001687 Opcode = X86::REP_STOSW;
1688 break;
1689 case 0: // DWORD aligned
1690 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001691 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001692 } else {
1693 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001694 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001695 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001696 }
1697 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001698 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001699 Opcode = X86::REP_STOSD;
1700 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001701 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001702 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001703 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001704 Opcode = X86::REP_STOSB;
1705 break;
1706 }
1707 } else {
1708 // If it's not a constant value we are storing, just fall back. We could
1709 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1710 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001711 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001712 CountReg = getReg(CI.getOperand(3));
1713 Opcode = X86::REP_STOSB;
1714 }
1715
1716 // No matter what the alignment is, we put the source in ESI, the
1717 // destination in EDI, and the count in ECX.
1718 TmpReg1 = getReg(CI.getOperand(1));
1719 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001720 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1721 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001722 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001723 return;
1724 }
1725
Chris Lattner87e18de2004-04-13 17:20:37 +00001726 case Intrinsic::readport: {
1727 // First, determine that the size of the operand falls within the acceptable
1728 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001729 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001730 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001731 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001732 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001733 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001734
John Criswell4ffff9e2004-04-08 20:31:47 +00001735 // Now, move the I/O port address into the DX register and use the IN
1736 // instruction to get the input data.
1737 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001738 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1739 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001740
Chris Lattner87e18de2004-04-13 17:20:37 +00001741 // If the port is a single-byte constant, use the immediate form.
1742 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1743 if ((C->getRawValue() & 255) == C->getRawValue()) {
1744 switch (Class) {
1745 case cByte:
1746 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1747 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1748 return;
1749 case cShort:
1750 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1751 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1752 return;
1753 case cInt:
1754 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1755 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1756 return;
1757 }
1758 }
1759
1760 unsigned Reg = getReg(CI.getOperand(1));
1761 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1762 switch (Class) {
1763 case cByte:
1764 BuildMI(BB, X86::IN8rr, 0);
1765 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1766 break;
1767 case cShort:
1768 BuildMI(BB, X86::IN16rr, 0);
1769 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1770 break;
1771 case cInt:
1772 BuildMI(BB, X86::IN32rr, 0);
1773 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1774 break;
1775 default:
1776 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00001777 exit (1);
1778 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001779 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00001780 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001781
Chris Lattner87e18de2004-04-13 17:20:37 +00001782 case Intrinsic::writeport: {
1783 // First, determine that the size of the operand falls within the
1784 // acceptable range for this architecture.
1785 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1786 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1787 exit(1);
1788 }
1789
1790 unsigned Class = getClassB(CI.getOperand(1)->getType());
1791 unsigned ValReg = getReg(CI.getOperand(1));
1792 switch (Class) {
1793 case cByte:
1794 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1795 break;
1796 case cShort:
1797 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1798 break;
1799 case cInt:
1800 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1801 break;
1802 default:
1803 std::cerr << "llvm.writeport: invalid data type for X86 target";
1804 exit(1);
1805 }
1806
1807
1808 // If the port is a single-byte constant, use the immediate form.
1809 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1810 if ((C->getRawValue() & 255) == C->getRawValue()) {
1811 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1812 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1813 return;
1814 }
1815
1816 // Otherwise, move the I/O port address into the DX register and the value
1817 // to write into the AL/AX/EAX register.
1818 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1819 unsigned Reg = getReg(CI.getOperand(2));
1820 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1821 BuildMI(BB, Opc[Class], 0);
1822 return;
1823 }
1824
Chris Lattner44827152003-12-28 09:47:19 +00001825 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001826 }
1827}
1828
Chris Lattner7dee5da2004-03-08 01:58:35 +00001829static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1830 if (LI.getParent() != User.getParent())
1831 return false;
1832 BasicBlock::iterator It = &LI;
1833 // Check all of the instructions between the load and the user. We should
1834 // really use alias analysis here, but for now we just do something simple.
1835 for (++It; It != BasicBlock::iterator(&User); ++It) {
1836 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001837 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001838 case Instruction::Store:
1839 case Instruction::Call:
1840 case Instruction::Invoke:
1841 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00001842 case Instruction::Load:
1843 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1844 return false;
1845 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00001846 }
1847 }
1848 return true;
1849}
1850
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001851/// visitSimpleBinary - Implement simple binary operators for integral types...
1852/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1853/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001854///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001855void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1856 unsigned DestReg = getReg(B);
1857 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001858 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1859
Chris Lattner7dee5da2004-03-08 01:58:35 +00001860 // Special case: op Reg, load [mem]
1861 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1862 if (!B.swapOperands())
1863 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1864
1865 unsigned Class = getClassB(B.getType());
Chris Lattner95157f72004-04-11 22:05:45 +00001866 if (isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00001867 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1868
Chris Lattner95157f72004-04-11 22:05:45 +00001869 unsigned Opcode;
1870 if (Class != cFP) {
1871 static const unsigned OpcodeTab[][3] = {
1872 // Arithmetic operators
1873 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1874 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1875
1876 // Bitwise operators
1877 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1878 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1879 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1880 };
1881 Opcode = OpcodeTab[OperatorClass][Class];
1882 } else {
1883 static const unsigned OpcodeTab[][2] = {
1884 { X86::FADD32m, X86::FADD64m }, // ADD
1885 { X86::FSUB32m, X86::FSUB64m }, // SUB
1886 };
1887 const Type *Ty = Op0->getType();
1888 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1889 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
1890 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00001891
1892 unsigned BaseReg, Scale, IndexReg, Disp;
1893 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1894 Scale, IndexReg, Disp);
1895
1896 unsigned Op0r = getReg(Op0);
1897 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1898 BaseReg, Scale, IndexReg, Disp);
1899 return;
1900 }
1901
Chris Lattner95157f72004-04-11 22:05:45 +00001902 // If this is a floating point subtract, check to see if we can fold the first
1903 // operand in.
1904 if (Class == cFP && OperatorClass == 1 &&
1905 isa<LoadInst>(Op0) &&
1906 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
1907 const Type *Ty = Op0->getType();
1908 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1909 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
1910
1911 unsigned BaseReg, Scale, IndexReg, Disp;
1912 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), BaseReg,
1913 Scale, IndexReg, Disp);
1914
1915 unsigned Op1r = getReg(Op1);
1916 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op1r),
1917 BaseReg, Scale, IndexReg, Disp);
1918 return;
1919 }
1920
Chris Lattner721d2d42004-03-08 01:18:36 +00001921 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001922}
Chris Lattner3e130a22003-01-13 00:32:26 +00001923
Chris Lattner6621ed92004-04-11 21:23:56 +00001924
1925/// emitBinaryFPOperation - This method handles emission of floating point
1926/// Add (0), Sub (1), Mul (2), and Div (3) operations.
1927void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1928 MachineBasicBlock::iterator IP,
1929 Value *Op0, Value *Op1,
1930 unsigned OperatorClass, unsigned DestReg) {
1931
1932 // Special case: op Reg, <const fp>
1933 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
1934 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
1935 // Create a constant pool entry for this constant.
1936 MachineConstantPool *CP = F->getConstantPool();
1937 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1938 const Type *Ty = Op1->getType();
1939
1940 static const unsigned OpcodeTab[][4] = {
1941 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
1942 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
1943 };
1944
1945 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1946 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1947 unsigned Op0r = getReg(Op0, BB, IP);
1948 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
1949 DestReg).addReg(Op0r), CPI);
1950 return;
1951 }
1952
Chris Lattner13c07fe2004-04-12 00:12:04 +00001953 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00001954 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1955 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
1956 // -0.0 - X === -X
1957 unsigned op1Reg = getReg(Op1, BB, IP);
1958 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1959 return;
1960 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00001961 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00001962
1963 // Create a constant pool entry for this constant.
1964 MachineConstantPool *CP = F->getConstantPool();
1965 unsigned CPI = CP->getConstantPoolIndex(CFP);
1966 const Type *Ty = CFP->getType();
1967
1968 static const unsigned OpcodeTab[][4] = {
1969 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
1970 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
1971 };
1972
1973 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
1974 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1975 unsigned Op1r = getReg(Op1, BB, IP);
1976 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
1977 DestReg).addReg(Op1r), CPI);
1978 return;
1979 }
1980
1981 // General case.
1982 static const unsigned OpcodeTab[4] = {
1983 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
1984 };
1985
1986 unsigned Opcode = OpcodeTab[OperatorClass];
1987 unsigned Op0r = getReg(Op0, BB, IP);
1988 unsigned Op1r = getReg(Op1, BB, IP);
1989 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1990}
1991
Chris Lattnerb2acc512003-10-19 21:09:10 +00001992/// emitSimpleBinaryOperation - Implement simple binary operators for integral
1993/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1994/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00001995///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001996/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1997/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00001998///
1999void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002000 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002001 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002002 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002003 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002004
Chris Lattner6621ed92004-04-11 21:23:56 +00002005 if (Class == cFP) {
2006 assert(OperatorClass < 2 && "No logical ops for FP!");
2007 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2008 return;
2009 }
2010
Chris Lattnerb2acc512003-10-19 21:09:10 +00002011 // sub 0, X -> neg X
Chris Lattner48b0c972004-04-11 20:26:20 +00002012 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2013 if (OperatorClass == 1 && CI->isNullValue()) {
2014 unsigned op1Reg = getReg(Op1, MBB, IP);
2015 static unsigned const NEGTab[] = {
2016 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2017 };
2018 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2019
2020 if (Class == cLong) {
2021 // We just emitted: Dl = neg Sl
2022 // Now emit : T = addc Sh, 0
2023 // : Dh = neg T
2024 unsigned T = makeAnotherReg(Type::IntTy);
2025 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2026 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002027 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002028 return;
2029 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002030
Chris Lattner48b0c972004-04-11 20:26:20 +00002031 // Special case: op Reg, <const int>
2032 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002033 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002034
Chris Lattner721d2d42004-03-08 01:18:36 +00002035 // xor X, -1 -> not X
2036 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002037 static unsigned const NOTTab[] = {
2038 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2039 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002040 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002041 if (Class == cLong) // Invert the top part too
2042 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002043 return;
2044 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002045
Chris Lattner721d2d42004-03-08 01:18:36 +00002046 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002047 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2048 // Note that we can't use dec for 64-bit decrements, because it does not
2049 // set the carry flag!
2050 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002051 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2052 return;
2053 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002054
Chris Lattner721d2d42004-03-08 01:18:36 +00002055 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002056 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2057 // Note that we can't use inc for 64-bit increments, because it does not
2058 // set the carry flag!
2059 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002060 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002061 return;
2062 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002063
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002064 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002065 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002066 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2067 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002068
Chris Lattner721d2d42004-03-08 01:18:36 +00002069 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002070 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2071 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2072 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002073 };
2074
Chris Lattner721d2d42004-03-08 01:18:36 +00002075 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002076 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002077
Chris Lattner33f7fa32004-04-06 03:15:53 +00002078 if (Class != cLong) {
2079 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2080 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002081 }
2082
2083 // If this is a long value and the high or low bits have a special
2084 // property, emit some special cases.
2085 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2086
2087 // If the constant is zero in the low 32-bits, just copy the low part
2088 // across and apply the normal 32-bit operation to the high parts. There
2089 // will be no carry or borrow into the top.
2090 if (Op1l == 0) {
2091 if (OperatorClass != 2) // All but and...
2092 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2093 else
2094 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2095 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2096 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002097 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002098 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002099
2100 // If this is a logical operation and the top 32-bits are zero, just
2101 // operate on the lower 32.
2102 if (Op1h == 0 && OperatorClass > 1) {
2103 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2104 .addReg(Op0r).addImm(Op1l);
2105 if (OperatorClass != 2) // All but and
2106 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2107 else
2108 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2109 return;
2110 }
2111
2112 // TODO: We could handle lots of other special cases here, such as AND'ing
2113 // with 0xFFFFFFFF00000000 -> noop, etc.
2114
2115 // Otherwise, code generate the full operation with a constant.
2116 static const unsigned TopTab[] = {
2117 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2118 };
2119
2120 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2121 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2122 .addReg(Op0r+1).addImm(Op1h);
2123 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002124 }
2125
2126 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002127 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002128 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002129 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2130 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002131
Chris Lattnerb2acc512003-10-19 21:09:10 +00002132 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002133 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2134 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2135 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002136 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002137
Chris Lattnerb2acc512003-10-19 21:09:10 +00002138 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002139 unsigned Op0r = getReg(Op0, MBB, IP);
2140 unsigned Op1r = getReg(Op1, MBB, IP);
2141 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2142
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002143 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002144 static const unsigned TopTab[] = {
2145 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2146 };
2147 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2148 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2149 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002150}
2151
Chris Lattner3e130a22003-01-13 00:32:26 +00002152/// doMultiply - Emit appropriate instructions to multiply together the
2153/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2154/// result should be given as DestTy.
2155///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002156void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00002157 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00002158 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002159 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002160 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002161 case cInt:
2162 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002163 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002164 .addReg(op0Reg).addReg(op1Reg);
2165 return;
2166 case cByte:
2167 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002168 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2169 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2170 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002171 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002172 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002173 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002174 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002175}
2176
Chris Lattnerb2acc512003-10-19 21:09:10 +00002177// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2178// returns zero when the input is not exactly a power of two.
2179static unsigned ExactLog2(unsigned Val) {
2180 if (Val == 0) return 0;
2181 unsigned Count = 0;
2182 while (Val != 1) {
2183 if (Val & 1) return 0;
2184 Val >>= 1;
2185 ++Count;
2186 }
2187 return Count+1;
2188}
2189
Chris Lattner462fa822004-04-11 20:56:28 +00002190
2191/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2192/// 16, or 32-bit integer multiply by a constant.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002193void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002194 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002195 unsigned DestReg, const Type *DestTy,
2196 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002197 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2198 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2199
Chris Lattnerb2acc512003-10-19 21:09:10 +00002200 unsigned Class = getClass(DestTy);
2201
Chris Lattner6ab06d52004-04-06 04:55:43 +00002202 if (ConstRHS == 0) {
2203 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2204 return;
2205 } else if (ConstRHS == 1) {
2206 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2207 return;
2208 }
2209
Chris Lattnerb2acc512003-10-19 21:09:10 +00002210 // If the element size is exactly a power of 2, use a shift to get it.
2211 if (unsigned Shift = ExactLog2(ConstRHS)) {
2212 switch (Class) {
2213 default: assert(0 && "Unknown class for this function!");
2214 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002215 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002216 return;
2217 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002218 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002219 return;
2220 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002221 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002222 return;
2223 }
2224 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002225
2226 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002227 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002228 return;
2229 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002230 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002231 return;
2232 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002233
2234 // Most general case, emit a normal multiply...
Chris Lattnerb2acc512003-10-19 21:09:10 +00002235 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002236 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002237
2238 // Emit a MUL to multiply the register holding the index by
2239 // elementSize, putting the result in OffsetReg.
2240 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2241}
2242
Chris Lattnerca9671d2002-11-02 20:28:58 +00002243/// visitMul - Multiplies are not simple binary operators because they must deal
2244/// with the EAX register explicitly.
2245///
2246void ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002247 unsigned ResultReg = getReg(I);
2248
Chris Lattner95157f72004-04-11 22:05:45 +00002249 Value *Op0 = I.getOperand(0);
2250 Value *Op1 = I.getOperand(1);
2251
2252 // Fold loads into floating point multiplies.
2253 if (getClass(Op0->getType()) == cFP) {
2254 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2255 if (!I.swapOperands())
2256 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2257 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2258 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2259 const Type *Ty = Op0->getType();
2260 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2261 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2262
2263 unsigned BaseReg, Scale, IndexReg, Disp;
2264 getAddressingMode(LI->getOperand(0), BaseReg,
2265 Scale, IndexReg, Disp);
2266
2267 unsigned Op0r = getReg(Op0);
2268 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2269 BaseReg, Scale, IndexReg, Disp);
2270 return;
2271 }
2272 }
2273
Chris Lattner462fa822004-04-11 20:56:28 +00002274 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002275 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002276}
2277
2278void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2279 Value *Op0, Value *Op1, unsigned DestReg) {
2280 MachineBasicBlock &BB = *MBB;
2281 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002282
2283 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002284 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002285 switch (Class) {
2286 case cByte:
2287 case cShort:
2288 case cInt:
2289 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002290 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2291 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002292 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002293 unsigned Op1Reg = getReg(Op1, &BB, IP);
2294 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002295 }
Chris Lattner462fa822004-04-11 20:56:28 +00002296 return;
2297 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002298 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2299 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002300 case cLong:
2301 break;
2302 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002303
Chris Lattner462fa822004-04-11 20:56:28 +00002304 // Long value. We have to do things the hard way...
2305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2306 unsigned CLow = CI->getRawValue();
2307 unsigned CHi = CI->getRawValue() >> 32;
2308
2309 if (CLow == 0) {
2310 // If the low part of the constant is all zeros, things are simple.
2311 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2312 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2313 return;
2314 }
2315
2316 // Multiply the two low parts... capturing carry into EDX
2317 unsigned OverflowReg = 0;
2318 if (CLow == 1) {
2319 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002320 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002321 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2322 OverflowReg = makeAnotherReg(Type::UIntTy);
2323 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2324 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2325 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002326
Chris Lattner462fa822004-04-11 20:56:28 +00002327 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2328 BuildMI(BB, IP, X86::MOV32rr, 1,
2329 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2330 }
2331
2332 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2333 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2334
2335 unsigned AHBLplusOverflowReg;
2336 if (OverflowReg) {
2337 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2338 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002339 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002340 } else {
2341 AHBLplusOverflowReg = AHBLReg;
2342 }
2343
2344 if (CHi == 0) {
2345 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2346 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002347 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002348 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002349
Chris Lattner462fa822004-04-11 20:56:28 +00002350 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002351 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2352 }
Chris Lattner462fa822004-04-11 20:56:28 +00002353 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002354 }
Chris Lattner462fa822004-04-11 20:56:28 +00002355
2356 // General 64x64 multiply
2357
2358 unsigned Op1Reg = getReg(Op1, &BB, IP);
2359 // Multiply the two low parts... capturing carry into EDX
2360 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2361 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2362
2363 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2364 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2365 BuildMI(BB, IP, X86::MOV32rr, 1,
2366 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2367
2368 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2369 BuildMI(BB, IP, X86::IMUL32rr, 2,
2370 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2371
2372 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2373 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2374 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2375
2376 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2377 BuildMI(BB, IP, X86::IMUL32rr, 2,
2378 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2379
2380 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2381 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002382}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002383
Chris Lattner06925362002-11-17 21:56:38 +00002384
Chris Lattnerf01729e2002-11-02 20:54:46 +00002385/// visitDivRem - Handle division and remainder instructions... these
2386/// instruction both require the same instructions to be generated, they just
2387/// select the result from a different register. Note that both of these
2388/// instructions work differently for signed and unsigned operands.
2389///
2390void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002391 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002392 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2393
2394 // Fold loads into floating point divides.
2395 if (getClass(Op0->getType()) == cFP) {
2396 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2397 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2398 const Type *Ty = Op0->getType();
2399 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2400 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2401
2402 unsigned BaseReg, Scale, IndexReg, Disp;
2403 getAddressingMode(LI->getOperand(0), BaseReg,
2404 Scale, IndexReg, Disp);
2405
2406 unsigned Op0r = getReg(Op0);
2407 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2408 BaseReg, Scale, IndexReg, Disp);
2409 return;
2410 }
2411
2412 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2413 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2414 const Type *Ty = Op0->getType();
2415 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2416 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2417
2418 unsigned BaseReg, Scale, IndexReg, Disp;
2419 getAddressingMode(LI->getOperand(0), BaseReg,
2420 Scale, IndexReg, Disp);
2421
2422 unsigned Op1r = getReg(Op1);
2423 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op1r),
2424 BaseReg, Scale, IndexReg, Disp);
2425 return;
2426 }
2427 }
2428
Chris Lattner94af4142002-12-25 05:13:53 +00002429
Chris Lattnercadff442003-10-23 17:21:43 +00002430 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002431 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002432 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002433}
2434
2435void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002436 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +00002437 Value *Op0, Value *Op1, bool isDiv,
2438 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002439 const Type *Ty = Op0->getType();
2440 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002441 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002442 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002443 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002444 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2445 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002446 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002447 unsigned Op0Reg = getReg(Op0, BB, IP);
2448 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002449 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002450 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002451 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002452 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2453 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002454 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2455 }
Chris Lattner94af4142002-12-25 05:13:53 +00002456 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002457 case cLong: {
2458 static const char *FnName[] =
2459 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002460 unsigned Op0Reg = getReg(Op0, BB, IP);
2461 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002462 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002463 MachineInstr *TheCall =
2464 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2465
2466 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002467 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2468 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002469 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2470 return;
2471 }
2472 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002473 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002474 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002475 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002476
2477 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002478 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2479 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2480 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002481 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2482
2483 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002484 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2485 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002486 };
2487
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002488 bool isSigned = Ty->isSigned();
Chris Lattnerf01729e2002-11-02 20:54:46 +00002489 unsigned Reg = Regs[Class];
2490 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002491
2492 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002493 unsigned Op0Reg = getReg(Op0, BB, IP);
2494 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002495 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002496
2497 if (isSigned) {
2498 // Emit a sign extension instruction...
Chris Lattner462fa822004-04-11 20:56:28 +00002499 unsigned ShiftResult = makeAnotherReg(Op0->getType());
Chris Lattneree352852004-02-29 07:22:16 +00002500 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2501 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002502 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002503 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002504 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002505 }
2506
Chris Lattner06925362002-11-17 21:56:38 +00002507 // Emit the appropriate divide or remainder instruction...
Chris Lattneree352852004-02-29 07:22:16 +00002508 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00002509
Chris Lattnerf01729e2002-11-02 20:54:46 +00002510 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002511 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002512
Chris Lattnerf01729e2002-11-02 20:54:46 +00002513 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002514 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002515}
Chris Lattnere2954c82002-11-02 20:04:26 +00002516
Chris Lattner06925362002-11-17 21:56:38 +00002517
Brian Gaekea1719c92002-10-31 23:03:59 +00002518/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2519/// for constant immediate shift values, and for constant immediate
2520/// shift values equal to 1. Even the general case is sort of special,
2521/// because the shift amount has to be in CL, not just any old register.
2522///
Chris Lattner3e130a22003-01-13 00:32:26 +00002523void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002524 MachineBasicBlock::iterator IP = BB->end ();
2525 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2526 I.getOpcode () == Instruction::Shl, I.getType (),
2527 getReg (I));
2528}
2529
2530/// emitShiftOperation - Common code shared between visitShiftInst and
2531/// constant expression support.
2532void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002533 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002534 Value *Op, Value *ShiftAmount, bool isLeftShift,
2535 const Type *ResultTy, unsigned DestReg) {
2536 unsigned SrcReg = getReg (Op, MBB, IP);
2537 bool isSigned = ResultTy->isSigned ();
2538 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002539
2540 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002541 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2542 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2543 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2544 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002545 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002546
Chris Lattner3e130a22003-01-13 00:32:26 +00002547 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002548 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2549 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2550 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2551 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002552 };
Chris Lattner796df732002-11-02 00:44:25 +00002553
Chris Lattner3e130a22003-01-13 00:32:26 +00002554 // Longs, as usual, are handled specially...
2555 if (Class == cLong) {
2556 // If we have a constant shift, we can generate much more efficient code
2557 // than otherwise...
2558 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002559 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002560 unsigned Amount = CUI->getValue();
2561 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002562 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2563 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00002564 BuildMI(*MBB, IP, Opc[3], 3,
2565 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2566 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002567 } else {
Chris Lattneree352852004-02-29 07:22:16 +00002568 BuildMI(*MBB, IP, Opc[3], 3,
2569 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2570 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002571 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002572 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002573 Amount -= 32;
2574 if (isLeftShift) {
Chris Lattner722070e2004-04-06 03:42:38 +00002575 if (Amount != 0) {
2576 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2577 DestReg + 1).addReg(SrcReg).addImm(Amount);
2578 } else {
2579 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2580 }
2581 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002582 } else {
Chris Lattner722070e2004-04-06 03:42:38 +00002583 if (Amount != 0) {
2584 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2585 DestReg).addReg(SrcReg+1).addImm(Amount);
2586 } else {
2587 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2588 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002589 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002590 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002591 }
2592 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00002593 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2594
2595 if (!isLeftShift && isSigned) {
2596 // If this is a SHR of a Long, then we need to do funny sign extension
2597 // stuff. TmpReg gets the value to use as the high-part if we are
2598 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002599 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00002600 } else {
2601 // Other shifts use a fixed zero value if the shift is more than 32
2602 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002603 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00002604 }
2605
2606 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002607 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002608 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002609
2610 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2611 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2612 if (isLeftShift) {
2613 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002614 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00002615 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002616 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002617 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002618
2619 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002620 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002621
2622 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002623 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002624 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2625 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002626 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002627 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002628 } else {
2629 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002630 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00002631 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00002632 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002633 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00002634 .addReg(SrcReg+1);
2635
2636 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002637 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002638
2639 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002640 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002641 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2642
2643 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002644 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002645 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2646 }
Brian Gaekea1719c92002-10-31 23:03:59 +00002647 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002648 return;
2649 }
Chris Lattnere9913f22002-11-02 01:41:55 +00002650
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002651 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002652 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2653 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002654
Chris Lattner3e130a22003-01-13 00:32:26 +00002655 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002656 BuildMI(*MBB, IP, Opc[Class], 2,
2657 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00002658 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002659 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002660 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002661
Chris Lattner3e130a22003-01-13 00:32:26 +00002662 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002663 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002664 }
2665}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002666
Chris Lattner3e130a22003-01-13 00:32:26 +00002667
Chris Lattner721d2d42004-03-08 01:18:36 +00002668void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2669 unsigned &IndexReg, unsigned &Disp) {
2670 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2671 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2672 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2673 BaseReg, Scale, IndexReg, Disp))
2674 return;
2675 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2676 if (CE->getOpcode() == Instruction::GetElementPtr)
2677 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2678 BaseReg, Scale, IndexReg, Disp))
2679 return;
2680 }
2681
2682 // If it's not foldable, reset addr mode.
2683 BaseReg = getReg(Addr);
2684 Scale = 1; IndexReg = 0; Disp = 0;
2685}
2686
2687
Chris Lattner6fc3c522002-11-17 21:11:55 +00002688/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00002689/// instruction. The load and store instructions are the only place where we
2690/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00002691///
2692void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002693 // Check to see if this load instruction is going to be folded into a binary
2694 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2695 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00002696 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002697 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002698 Instruction *User = cast<Instruction>(I.use_back());
2699 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002700 case Instruction::Cast:
2701 // If this is a cast from a signed-integer type to a floating point type,
2702 // fold the cast here.
2703 if (getClass(User->getType()) == cFP &&
2704 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
2705 I.getType() == Type::LongTy)) {
2706 unsigned DestReg = getReg(User);
2707 static const unsigned Opcode[] = {
2708 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
2709 };
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002710 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2711 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2712 addFullAddress(BuildMI(BB, Opcode[Class], 5, DestReg),
2713 BaseReg, Scale, IndexReg, Disp);
2714 return;
2715 } else {
2716 User = 0;
2717 }
2718 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00002719
Chris Lattner7dee5da2004-03-08 01:58:35 +00002720 case Instruction::Add:
2721 case Instruction::Sub:
2722 case Instruction::And:
2723 case Instruction::Or:
2724 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002725 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002726 break;
Chris Lattner95157f72004-04-11 22:05:45 +00002727 case Instruction::Mul:
2728 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00002729 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002730 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00002731 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002732 }
2733
2734 if (User) {
2735 // Okay, we found a user. If the load is the first operand and there is
2736 // no second operand load, reverse the operand ordering. Note that this
2737 // can fail for a subtract (ie, no change will be made).
2738 if (!isa<LoadInst>(User->getOperand(1)))
2739 cast<BinaryOperator>(User)->swapOperands();
2740
2741 // Okay, now that everything is set up, if this load is used by the second
2742 // operand, and if there are no instructions that invalidate the load
2743 // before the binary operator, eliminate the load.
2744 if (User->getOperand(1) == &I &&
2745 isSafeToFoldLoadIntoInstruction(I, *User))
2746 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00002747
2748 // If this is a floating point sub or div, we won't be able to swap the
2749 // operands, but we will still be able to eliminate the load.
2750 if (Class == cFP && User->getOperand(0) == &I &&
2751 !isa<LoadInst>(User->getOperand(1)) &&
2752 (User->getOpcode() == Instruction::Sub ||
2753 User->getOpcode() == Instruction::Div) &&
2754 isSafeToFoldLoadIntoInstruction(I, *User))
2755 return; // Eliminate the load!
Chris Lattner7dee5da2004-03-08 01:58:35 +00002756 }
2757 }
2758
Chris Lattner94af4142002-12-25 05:13:53 +00002759 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002760 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
Chris Lattner721d2d42004-03-08 01:18:36 +00002761 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
Chris Lattnere8f0d922002-12-24 00:03:11 +00002762
Chris Lattner6ac1d712003-10-20 04:48:06 +00002763 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002764 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002765 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002766 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002767 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00002768 return;
2769 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002770
Chris Lattner6ac1d712003-10-20 04:48:06 +00002771 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002772 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00002773 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002774 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002775 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002776 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2777 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00002778}
2779
Chris Lattner6fc3c522002-11-17 21:11:55 +00002780/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2781/// instruction.
2782///
2783void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002784 unsigned BaseReg, Scale, IndexReg, Disp;
2785 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002786
Chris Lattner6c09db22003-10-20 04:11:23 +00002787 const Type *ValTy = I.getOperand(0)->getType();
2788 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002789
Chris Lattner5a830962004-02-25 02:56:58 +00002790 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2791 uint64_t Val = CI->getRawValue();
2792 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002793 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002794 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002795 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002796 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00002797 } else {
2798 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002799 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00002800 };
2801 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00002802 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002803 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00002804 }
2805 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002806 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002807 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattner5a830962004-02-25 02:56:58 +00002808 } else {
2809 if (Class == cLong) {
2810 unsigned ValReg = getReg(I.getOperand(0));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002811 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002812 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002813 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002814 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
Chris Lattner5a830962004-02-25 02:56:58 +00002815 } else {
2816 unsigned ValReg = getReg(I.getOperand(0));
2817 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002818 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
Chris Lattner5a830962004-02-25 02:56:58 +00002819 };
2820 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002821 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002822 addFullAddress(BuildMI(BB, Opcode, 1+4),
2823 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner5a830962004-02-25 02:56:58 +00002824 }
Chris Lattner94af4142002-12-25 05:13:53 +00002825 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002826}
2827
2828
Misha Brukman538607f2004-03-01 23:53:11 +00002829/// visitCastInst - Here we have various kinds of copying with or without sign
2830/// extension going on.
2831///
Chris Lattner3e130a22003-01-13 00:32:26 +00002832void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002833 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00002834
Chris Lattner99382862004-04-12 00:23:04 +00002835 unsigned SrcClass = getClassB(Op->getType());
2836 unsigned DestClass = getClassB(CI.getType());
2837 // Noop casts are not emitted: getReg will return the source operand as the
2838 // register to use for any uses of the noop cast.
2839 if (DestClass == SrcClass)
Chris Lattner427aeb42004-04-11 19:21:59 +00002840 return;
2841
Chris Lattnerf5854472003-06-21 16:01:24 +00002842 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2843 // of the case are GEP instructions, then the cast does not need to be
2844 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00002845 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002846 bool AllUsesAreGEPs = true;
2847 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2848 if (!isa<GetElementPtrInst>(*I)) {
2849 AllUsesAreGEPs = false;
2850 break;
2851 }
2852
2853 // No need to codegen this cast if all users are getelementptr instrs...
2854 if (AllUsesAreGEPs) return;
2855 }
2856
Chris Lattner99382862004-04-12 00:23:04 +00002857 // If this cast converts a load from a short,int, or long integer to a FP
2858 // value, we will have folded this cast away.
2859 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
2860 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
2861 Op->getType() == Type::LongTy))
2862 return;
2863
2864
Chris Lattner548f61d2003-04-23 17:22:12 +00002865 unsigned DestReg = getReg(CI);
2866 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00002867 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00002868}
2869
Misha Brukman538607f2004-03-01 23:53:11 +00002870/// emitCastOperation - Common code shared between visitCastInst and constant
2871/// expression cast support.
2872///
Chris Lattner548f61d2003-04-23 17:22:12 +00002873void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002874 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00002875 Value *Src, const Type *DestTy,
2876 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002877 const Type *SrcTy = Src->getType();
2878 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002879 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002880 unsigned SrcReg = getReg(Src, BB, IP);
2881
Chris Lattner3e130a22003-01-13 00:32:26 +00002882 // Implement casts to bool by using compare on the operand followed by set if
2883 // not zero on the result.
2884 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00002885 switch (SrcClass) {
2886 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002887 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002888 break;
2889 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002890 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002891 break;
2892 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002893 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002894 break;
2895 case cLong: {
2896 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002897 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00002898 break;
2899 }
2900 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00002901 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002902 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00002903 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00002904 break;
Chris Lattner20772542003-06-01 03:38:24 +00002905 }
2906
2907 // If the zero flag is not set, then the value is true, set the byte to
2908 // true.
Chris Lattneree352852004-02-29 07:22:16 +00002909 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002910 return;
2911 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002912
2913 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002914 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00002915 };
2916
2917 // Implement casts between values of the same type class (as determined by
2918 // getClass) by using a register-to-register move.
2919 if (SrcClass == DestClass) {
2920 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00002921 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002922 } else if (SrcClass == cFP) {
2923 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002924 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00002925 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002926 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002927 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2928 "Unknown cFP member!");
2929 // Truncate from double to float by storing to memory as short, then
2930 // reading it back.
2931 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00002932 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002933 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2934 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002935 }
2936 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002937 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2938 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002939 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00002940 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002941 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00002942 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002943 return;
2944 }
2945
2946 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2947 // or zero extension, depending on whether the source type was signed.
2948 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2949 SrcClass < DestClass) {
2950 bool isLong = DestClass == cLong;
2951 if (isLong) DestClass = cInt;
2952
2953 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002954 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2955 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00002956 };
2957
2958 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattneree352852004-02-29 07:22:16 +00002959 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00002960 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002961
2962 if (isLong) { // Handle upper 32 bits as appropriate...
2963 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002964 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00002965 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002966 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00002967 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002968 return;
2969 }
2970
2971 // Special case long -> int ...
2972 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002973 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002974 return;
2975 }
2976
2977 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2978 // move out of AX or AL.
2979 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2980 && SrcClass > DestClass) {
2981 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00002982 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2983 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00002984 return;
2985 }
2986
2987 // Handle casts from integer to floating point now...
2988 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002989 // Promote the integer to a type supported by FLD. We do this because there
2990 // are no unsigned FLD instructions, so we must promote an unsigned value to
2991 // a larger signed value, then use FLD on the larger value.
2992 //
2993 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00002994 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002995 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002996 switch (SrcTy->getPrimitiveID()) {
2997 case Type::BoolTyID:
2998 case Type::SByteTyID:
2999 // We don't have the facilities for directly loading byte sized data from
3000 // memory (even signed). Promote it to 16 bits.
3001 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003002 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003003 break;
3004 case Type::UByteTyID:
3005 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003006 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003007 break;
3008 case Type::UShortTyID:
3009 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003010 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003011 break;
3012 case Type::UIntTyID: {
3013 // Make a 64 bit temporary... and zero out the top of it...
3014 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003015 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
3016 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003017 SrcTy = Type::LongTy;
3018 SrcClass = cLong;
3019 SrcReg = TmpReg;
3020 break;
3021 }
3022 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003023 // Don't fild into the read destination.
3024 DestReg = makeAnotherReg(Type::DoubleTy);
3025 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003026 default: // No promotion needed...
3027 break;
3028 }
3029
3030 if (PromoteType) {
3031 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003032 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003033 SrcTy = PromoteType;
3034 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003035 SrcReg = TmpReg;
3036 }
3037
3038 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003039 int FrameIdx =
3040 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003041
3042 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003043 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003044 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003045 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003046 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003047 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003048 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003049 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3050 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003051 }
3052
3053 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003054 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003055 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003056
3057 // We need special handling for unsigned 64-bit integer sources. If the
3058 // input number has the "sign bit" set, then we loaded it incorrectly as a
3059 // negative 64-bit number. In this case, add an offset value.
3060 if (SrcTy == Type::ULongTy) {
3061 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003062 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003063
Chris Lattnerb6bac512004-02-25 06:13:04 +00003064 // If the sign bit is set, get a pointer to an offset, otherwise get a
3065 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003066 MachineConstantPool *CP = F->getConstantPool();
3067 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003068 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003069 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003070 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003071 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003072 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3073
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003074 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003075 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003076 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003077 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003078
3079 // Load the constant for an add. FIXME: this could make an 'fadd' that
3080 // reads directly from memory, but we don't support these yet.
3081 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003082 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003083
Chris Lattneree352852004-02-29 07:22:16 +00003084 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3085 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003086 }
3087
Chris Lattner3e130a22003-01-13 00:32:26 +00003088 return;
3089 }
3090
3091 // Handle casts from floating point to integer now...
3092 if (SrcClass == cFP) {
3093 // Change the floating point control register to use "round towards zero"
3094 // mode when truncating to an integer value.
3095 //
3096 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003097 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003098
3099 // Load the old value of the high byte of the control word...
3100 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003101 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003102 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003103
3104 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003105 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003106 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003107
3108 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003109 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003110
3111 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003112 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003113 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003114
3115 // We don't have the facilities for directly storing byte sized data to
3116 // memory. Promote it to 16 bits. We also must promote unsigned values to
3117 // larger classes because we only have signed FP stores.
3118 unsigned StoreClass = DestClass;
3119 const Type *StoreTy = DestTy;
3120 if (StoreClass == cByte || DestTy->isUnsigned())
3121 switch (StoreClass) {
3122 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3123 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3124 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003125 // The following treatment of cLong may not be perfectly right,
3126 // but it survives chains of casts of the form
3127 // double->ulong->double.
3128 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003129 default: assert(0 && "Unknown store class!");
3130 }
3131
3132 // Spill the integer to memory and reload it from there...
3133 int FrameIdx =
3134 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3135
3136 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003137 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003138 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3139 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003140
3141 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003142 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3143 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003144 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003145 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003146 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003147 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003148 }
3149
3150 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003151 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003152 return;
3153 }
3154
Brian Gaeked474e9c2002-12-06 10:49:33 +00003155 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003156 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003157 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003158}
Brian Gaekea1719c92002-10-31 23:03:59 +00003159
Chris Lattner73815062003-10-18 05:56:40 +00003160/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003161///
Chris Lattner73815062003-10-18 05:56:40 +00003162void ISel::visitVANextInst(VANextInst &I) {
3163 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003164 unsigned DestReg = getReg(I);
3165
Chris Lattnereca195e2003-05-08 19:44:13 +00003166 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00003167 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003168 default:
3169 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003170 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003171 return;
3172 case Type::PointerTyID:
3173 case Type::UIntTyID:
3174 case Type::IntTyID:
3175 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003176 break;
3177 case Type::ULongTyID:
3178 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003179 case Type::DoubleTyID:
3180 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003181 break;
3182 }
3183
3184 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003185 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003186}
Chris Lattnereca195e2003-05-08 19:44:13 +00003187
Chris Lattner73815062003-10-18 05:56:40 +00003188void ISel::visitVAArgInst(VAArgInst &I) {
3189 unsigned VAList = getReg(I.getOperand(0));
3190 unsigned DestReg = getReg(I);
3191
3192 switch (I.getType()->getPrimitiveID()) {
3193 default:
3194 std::cerr << I;
3195 assert(0 && "Error: bad type for va_next instruction!");
3196 return;
3197 case Type::PointerTyID:
3198 case Type::UIntTyID:
3199 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003200 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003201 break;
3202 case Type::ULongTyID:
3203 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003204 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3205 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003206 break;
3207 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003208 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003209 break;
3210 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003211}
3212
Misha Brukman538607f2004-03-01 23:53:11 +00003213/// visitGetElementPtrInst - instruction-select GEP instructions
3214///
Chris Lattner3e130a22003-01-13 00:32:26 +00003215void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003216 // If this GEP instruction will be folded into all of its users, we don't need
3217 // to explicitly calculate it!
3218 unsigned A, B, C, D;
3219 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
3220 // Check all of the users of the instruction to see if they are loads and
3221 // stores.
3222 bool AllWillFold = true;
3223 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3224 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3225 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3226 cast<Instruction>(*UI)->getOperand(0) == &I) {
3227 AllWillFold = false;
3228 break;
3229 }
3230
3231 // If the instruction is foldable, and will be folded into all users, don't
3232 // emit it!
3233 if (AllWillFold) return;
3234 }
3235
Chris Lattner3e130a22003-01-13 00:32:26 +00003236 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003237 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003238 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003239}
3240
Chris Lattner985fe3d2004-02-25 03:45:50 +00003241/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3242/// GEPTypes (the derived types being stepped through at each level). On return
3243/// from this function, if some indexes of the instruction are representable as
3244/// an X86 lea instruction, the machine operands are put into the Ops
3245/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3246/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3247/// addressing mode that only partially consumes the input, the BaseReg input of
3248/// the addressing mode must be left free.
3249///
3250/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3251///
Chris Lattnerb6bac512004-02-25 06:13:04 +00003252void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
3253 std::vector<Value*> &GEPOps,
3254 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
3255 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3256 const TargetData &TD = TM.getTargetData();
3257
Chris Lattner985fe3d2004-02-25 03:45:50 +00003258 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003259 BaseReg = 0; // No base register
3260 Scale = 1; // Unit scale
3261 IndexReg = 0; // No index register
3262 Disp = 0; // No displacement
3263
Chris Lattner985fe3d2004-02-25 03:45:50 +00003264 // While there are GEP indexes that can be folded into the current address,
3265 // keep processing them.
3266 while (!GEPTypes.empty()) {
3267 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3268 // It's a struct access. CUI is the index into the structure,
3269 // which names the field. This index must have unsigned type.
3270 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3271
3272 // Use the TargetData structure to pick out what the layout of the
3273 // structure is in memory. Since the structure index must be constant, we
3274 // can get its value and use it to find the right byte offset from the
3275 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003276 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003277 GEPOps.pop_back(); // Consume a GEP operand
3278 GEPTypes.pop_back();
3279 } else {
3280 // It's an array or pointer access: [ArraySize x ElementType].
3281 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3282 Value *idx = GEPOps.back();
3283
3284 // idx is the index into the array. Unlike with structure
3285 // indices, we may not know its actual value at code-generation
3286 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003287
3288 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003289 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003290 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003291 Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003292 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3293 Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003294 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003295 // If the index reg is already taken, we can't handle this index.
3296 if (IndexReg) return;
3297
3298 // If this is a size that we can handle, then add the index as
3299 switch (TypeSize) {
3300 case 1: case 2: case 4: case 8:
3301 // These are all acceptable scales on X86.
3302 Scale = TypeSize;
3303 break;
3304 default:
3305 // Otherwise, we can't handle this scale
3306 return;
3307 }
3308
3309 if (CastInst *CI = dyn_cast<CastInst>(idx))
3310 if (CI->getOperand(0)->getType() == Type::IntTy ||
3311 CI->getOperand(0)->getType() == Type::UIntTy)
3312 idx = CI->getOperand(0);
3313
3314 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003315 }
3316
3317 GEPOps.pop_back(); // Consume a GEP operand
3318 GEPTypes.pop_back();
3319 }
3320 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003321
3322 // GEPTypes is empty, which means we have a single operand left. See if we
3323 // can set it as the base register.
3324 //
3325 // FIXME: When addressing modes are more powerful/correct, we could load
3326 // global addresses directly as 32-bit immediates.
3327 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003328 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003329 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003330}
3331
3332
Chris Lattnerb6bac512004-02-25 06:13:04 +00003333/// isGEPFoldable - Return true if the specified GEP can be completely
3334/// folded into the addressing mode of a load/store or lea instruction.
3335bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3336 Value *Src, User::op_iterator IdxBegin,
3337 User::op_iterator IdxEnd, unsigned &BaseReg,
3338 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003339 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3340 Src = CPR->getValue();
3341
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003342 std::vector<Value*> GEPOps;
3343 GEPOps.resize(IdxEnd-IdxBegin+1);
3344 GEPOps[0] = Src;
3345 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3346
3347 std::vector<const Type*> GEPTypes;
3348 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3349 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3350
Chris Lattnerb6bac512004-02-25 06:13:04 +00003351 MachineBasicBlock::iterator IP;
3352 if (MBB) IP = MBB->end();
3353 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3354
3355 // We can fold it away iff the getGEPIndex call eliminated all operands.
3356 return GEPOps.empty();
3357}
3358
3359void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3360 MachineBasicBlock::iterator IP,
3361 Value *Src, User::op_iterator IdxBegin,
3362 User::op_iterator IdxEnd, unsigned TargetReg) {
3363 const TargetData &TD = TM.getTargetData();
3364 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3365 Src = CPR->getValue();
3366
3367 std::vector<Value*> GEPOps;
3368 GEPOps.resize(IdxEnd-IdxBegin+1);
3369 GEPOps[0] = Src;
3370 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3371
3372 std::vector<const Type*> GEPTypes;
3373 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3374 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003375
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003376 // Keep emitting instructions until we consume the entire GEP instruction.
3377 while (!GEPOps.empty()) {
3378 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003379 unsigned BaseReg, Scale, IndexReg, Disp;
3380 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003381
Chris Lattner985fe3d2004-02-25 03:45:50 +00003382 if (GEPOps.size() != OldSize) {
3383 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003384 unsigned NextTarget = 0;
3385 if (!GEPOps.empty()) {
3386 assert(BaseReg == 0 &&
3387 "getGEPIndex should have left the base register open for chaining!");
3388 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003389 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003390
3391 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003392 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003393 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003394 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003395 BaseReg, Scale, IndexReg, Disp);
3396 --IP;
3397 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003398 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003399 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3400 // all operands are consumed but the base pointer. If so, just load it
3401 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003402 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003403 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003404 } else {
3405 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003406 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003407 }
3408 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003409
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003410 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003411 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003412 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3413 Value *idx = GEPOps.back();
3414 GEPOps.pop_back(); // Consume a GEP operand
3415 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003416
Chris Lattner28977af2004-04-05 01:30:19 +00003417 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003418 // operand on X86. Handle this case directly now...
3419 if (CastInst *CI = dyn_cast<CastInst>(idx))
3420 if (CI->getOperand(0)->getType() == Type::IntTy ||
3421 CI->getOperand(0)->getType() == Type::UIntTy)
3422 idx = CI->getOperand(0);
3423
Chris Lattner3e130a22003-01-13 00:32:26 +00003424 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003425 // must find the size of the pointed-to type (Not coincidentally, the next
3426 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003427 const Type *ElTy = SqTy->getElementType();
3428 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003429
3430 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003431 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003432 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003433 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003434 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003435 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003436 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003437 --IP; // Insert the next instruction before this one.
3438 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003439 }
3440 } else if (elementSize == 1) {
3441 // If the element size is 1, we don't have to multiply, just add
3442 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003443 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003444 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003445 --IP; // Insert the next instruction before this one.
3446 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003447 } else {
3448 unsigned idxReg = getReg(idx, MBB, IP);
3449 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003450
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003451 // Make sure we can back the iterator up to point to the first
3452 // instruction emitted.
3453 MachineBasicBlock::iterator BeforeIt = IP;
3454 if (IP == MBB->begin())
3455 BeforeIt = MBB->end();
3456 else
3457 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003458 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3459
Chris Lattner8a307e82002-12-16 19:32:50 +00003460 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003461 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003462 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003463 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003464
3465 // Step to the first instruction of the multiply.
3466 if (BeforeIt == MBB->end())
3467 IP = MBB->begin();
3468 else
3469 IP = ++BeforeIt;
3470
3471 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003472 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003473 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003474 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003475}
3476
3477
Chris Lattner065faeb2002-12-28 20:24:02 +00003478/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3479/// frame manager, otherwise do it the hard way.
3480///
3481void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00003482 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00003483 const Type *Ty = I.getAllocatedType();
3484 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3485
3486 // If this is a fixed size alloca in the entry block for the function,
3487 // statically stack allocate the space.
3488 //
3489 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
3490 if (I.getParent() == I.getParent()->getParent()->begin()) {
3491 TySize *= CUI->getValue(); // Get total allocated size...
3492 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
3493
3494 // Create a new stack object using the frame manager...
3495 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003496 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
Chris Lattner065faeb2002-12-28 20:24:02 +00003497 return;
3498 }
3499 }
3500
3501 // Create a register to hold the temporary result of multiplying the type size
3502 // constant by the variable amount.
3503 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3504 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00003505
3506 // TotalSizeReg = mul <numelements>, <TypeSize>
3507 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003508 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003509
3510 // AddedSize = add <TotalSizeReg>, 15
3511 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003512 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003513
3514 // AlignedSize = and <AddedSize>, ~15
3515 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003516 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003517
Brian Gaekee48ec012002-12-13 06:46:31 +00003518 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003519 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003520
Brian Gaekee48ec012002-12-13 06:46:31 +00003521 // Put a pointer to the space into the result register, by copying
3522 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003523 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00003524
Misha Brukman48196b32003-05-03 02:18:17 +00003525 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00003526 // object.
3527 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00003528}
Chris Lattner3e130a22003-01-13 00:32:26 +00003529
3530/// visitMallocInst - Malloc instructions are code generated into direct calls
3531/// to the library malloc.
3532///
3533void ISel::visitMallocInst(MallocInst &I) {
3534 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3535 unsigned Arg;
3536
3537 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3538 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3539 } else {
3540 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003541 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00003542 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003543 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00003544 }
3545
3546 std::vector<ValueRecord> Args;
3547 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3548 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003549 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003550 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3551}
3552
3553
3554/// visitFreeInst - Free instructions are code gen'd to call the free libc
3555/// function.
3556///
3557void ISel::visitFreeInst(FreeInst &I) {
3558 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00003559 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00003560 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003561 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003562 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3563}
3564
Chris Lattnerd281de22003-07-26 23:49:58 +00003565/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00003566/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00003567/// generated code sucks but the implementation is nice and simple.
3568///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00003569FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3570 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00003571}