blob: 6ab950459734d45332cb8ec3f3a57516daf1603f [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 Lattnercf93cdd2004-01-30 22:13:44 +000031#include "llvm/Support/CFG.h"
Chris Lattner986618e2004-02-22 19:47:26 +000032#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner986618e2004-02-22 19:47:26 +000035namespace {
36 Statistic<>
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000039
Chris Lattner72614082002-10-25 22:55:53 +000040namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000041 struct ISel : public FunctionPass, InstVisitor<ISel> {
42 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000043 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000046 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000047
Chris Lattner72614082002-10-25 22:55:53 +000048 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
49
Chris Lattner333b2fa2002-12-13 10:09:43 +000050 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
52
Chris Lattnerf70e0c22003-12-28 21:23:38 +000053 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000054
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
57 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000058 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000059 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
62
Chris Lattner36b36032002-10-29 23:40:58 +000063 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000064
Chris Lattner065faeb2002-12-28 20:24:02 +000065 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000066 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
68
Chris Lattner14aa7fe2002-12-16 22:54:46 +000069 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000070
Chris Lattner0e5b79c2004-02-15 01:04:03 +000071 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
74
Chris Lattnerdbd73722003-05-06 21:32:22 +000075 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000076 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000077
Chris Lattner333b2fa2002-12-13 10:09:43 +000078 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000079 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000080
81 // Select the PHI nodes
82 SelectPHINodes();
83
Chris Lattner986618e2004-02-22 19:47:26 +000084 // Insert the FP_REG_KILL instructions into blocks that need them.
85 InsertFPRegKills();
86
Chris Lattner72614082002-10-25 22:55:53 +000087 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000088 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000089 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +000090 // We always build a machine code representation for the function
91 return true;
Chris Lattner72614082002-10-25 22:55:53 +000092 }
93
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000094 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
96 }
97
Chris Lattner72614082002-10-25 22:55:53 +000098 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000099 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000102 ///
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000105 }
106
Chris Lattner44827152003-12-28 09:47:19 +0000107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000110 ///
Chris Lattner44827152003-12-28 09:47:19 +0000111 void LowerUnknownIntrinsicFunctionCalls(Function &F);
112
Chris Lattner065faeb2002-12-28 20:24:02 +0000113 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
114 /// from the stack into virtual registers.
115 ///
116 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000117
118 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
119 /// because we have to generate our sources into the source basic blocks,
120 /// not the current one.
121 ///
122 void SelectPHINodes();
123
Chris Lattner986618e2004-02-22 19:47:26 +0000124 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
125 /// that need them. This only occurs due to the floating point stackifier
126 /// not being aggressive enough to handle arbitrary global stackification.
127 ///
128 void InsertFPRegKills();
129
Chris Lattner72614082002-10-25 22:55:53 +0000130 // Visitation methods for various instructions. These methods simply emit
131 // fixed X86 code for each instruction.
132 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000133
134 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000135 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000136 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000137
138 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000139 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000140 unsigned Reg;
141 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000142 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
143 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000144 };
145 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000146 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000147 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000148 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000149
150 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000151 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000152 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
153 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000154 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000155 unsigned DestReg, const Type *DestTy,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000156 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000157 void doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000158 MachineBasicBlock::iterator MBBI,
Chris Lattnerb2acc512003-10-19 21:09:10 +0000159 unsigned DestReg, const Type *DestTy,
160 unsigned Op0Reg, unsigned Op1Val);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000161 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000162
Chris Lattnerf01729e2002-11-02 20:54:46 +0000163 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
164 void visitRem(BinaryOperator &B) { visitDivRem(B); }
165 void visitDivRem(BinaryOperator &B);
166
Chris Lattnere2954c82002-11-02 20:04:26 +0000167 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000168 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
169 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
170 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000171
Chris Lattner6d40c192003-01-16 16:43:00 +0000172 // Comparison operators...
173 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000174 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
175 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000176 MachineBasicBlock::iterator MBBI);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000177
Chris Lattner6fc3c522002-11-17 21:11:55 +0000178 // Memory Instructions
179 void visitLoadInst(LoadInst &I);
180 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000181 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000182 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000183 void visitMallocInst(MallocInst &I);
184 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000185
Chris Lattnere2954c82002-11-02 20:04:26 +0000186 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000187 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000188 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000189 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000190 void visitVANextInst(VANextInst &I);
191 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000192
193 void visitInstruction(Instruction &I) {
194 std::cerr << "Cannot instruction select: " << I;
195 abort();
196 }
197
Brian Gaeke95780cc2002-12-13 07:56:18 +0000198 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000199 ///
200 void promote32(unsigned targetReg, const ValueRecord &VR);
201
Chris Lattner721d2d42004-03-08 01:18:36 +0000202 /// getAddressingMode - Get the addressing mode to use to address the
203 /// specified value. The returned value should be used with addFullAddress.
204 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
205 unsigned &IndexReg, unsigned &Disp);
206
207
208 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
209 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000210 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
211 std::vector<Value*> &GEPOps,
212 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
213 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
214
215 /// isGEPFoldable - Return true if the specified GEP can be completely
216 /// folded into the addressing mode of a load/store or lea instruction.
217 bool isGEPFoldable(MachineBasicBlock *MBB,
218 Value *Src, User::op_iterator IdxBegin,
219 User::op_iterator IdxEnd, unsigned &BaseReg,
220 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
221
Chris Lattner3e130a22003-01-13 00:32:26 +0000222 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
223 /// constant expression GEP support.
224 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000225 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000226 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000227 User::op_iterator IdxEnd, unsigned TargetReg);
228
Chris Lattner548f61d2003-04-23 17:22:12 +0000229 /// emitCastOperation - Common code shared between visitCastInst and
230 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000231 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000232 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000233 Value *Src, const Type *DestTy, unsigned TargetReg);
234
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000235 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
236 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000237 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000238 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000239 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000240 Value *Op0, Value *Op1,
241 unsigned OperatorClass, unsigned TargetReg);
242
Chris Lattnercadff442003-10-23 17:21:43 +0000243 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000244 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +0000245 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
246 const Type *Ty, unsigned TargetReg);
247
Chris Lattner58c41fe2003-08-24 19:19:47 +0000248 /// emitSetCCOperation - Common code shared between visitSetCondInst and
249 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000250 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000251 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000252 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000253 Value *Op0, Value *Op1, unsigned Opcode,
254 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000255
256 /// emitShiftOperation - Common code shared between visitShiftInst and
257 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000258 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000259 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000260 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000261 Value *Op, Value *ShiftAmount, bool isLeftShift,
262 const Type *ResultTy, unsigned DestReg);
263
Chris Lattner58c41fe2003-08-24 19:19:47 +0000264
Chris Lattnerc5291f52002-10-27 21:16:59 +0000265 /// copyConstantToRegister - Output the instructions required to put the
266 /// specified constant into the specified register.
267 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000268 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000269 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000270 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000271
Chris Lattner3e130a22003-01-13 00:32:26 +0000272 /// makeAnotherReg - This method returns the next register number we haven't
273 /// yet used.
274 ///
275 /// Long values are handled somewhat specially. They are always allocated
276 /// as pairs of 32 bit integer values. The register number returned is the
277 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
278 /// of the long value.
279 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000280 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000281 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
282 "Current target doesn't have X86 reg info??");
283 const X86RegisterInfo *MRI =
284 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000285 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000286 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
287 // Create the lower part
288 F->getSSARegMap()->createVirtualRegister(RC);
289 // Create the upper part.
290 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000291 }
292
Chris Lattnerc0812d82002-12-13 06:56:29 +0000293 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000294 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000295 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000296 }
297
Chris Lattner72614082002-10-25 22:55:53 +0000298 /// getReg - This method turns an LLVM value into a register number. This
299 /// is guaranteed to produce the same register number for a particular value
300 /// every time it is queried.
301 ///
302 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000303 unsigned getReg(Value *V) {
304 // Just append to the end of the current bb.
305 MachineBasicBlock::iterator It = BB->end();
306 return getReg(V, BB, It);
307 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000308 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000309 MachineBasicBlock::iterator IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000310 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000311 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000312 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000313 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000314 }
Chris Lattner72614082002-10-25 22:55:53 +0000315
Chris Lattner6f8fd252002-10-27 21:23:43 +0000316 // If this operand is a constant, emit the code to copy the constant into
317 // the register here...
318 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000319 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000320 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000321 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000322 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
323 // Move the address of the global into the register
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000324 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000325 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000326 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000327
Chris Lattner72614082002-10-25 22:55:53 +0000328 return Reg;
329 }
Chris Lattner72614082002-10-25 22:55:53 +0000330 };
331}
332
Chris Lattner43189d12002-11-17 20:07:45 +0000333/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
334/// Representation.
335///
336enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000337 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000338};
339
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000340/// getClass - Turn a primitive type into a "class" number which is based on the
341/// size of the type, and whether or not it is floating point.
342///
Chris Lattner43189d12002-11-17 20:07:45 +0000343static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000344 switch (Ty->getPrimitiveID()) {
345 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000346 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000347 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000348 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000349 case Type::IntTyID:
350 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000351 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000352
Chris Lattner94af4142002-12-25 05:13:53 +0000353 case Type::FloatTyID:
354 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000355
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000356 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000357 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000358 default:
359 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000360 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000361 }
362}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000363
Chris Lattner6b993cc2002-12-15 08:02:15 +0000364// getClassB - Just like getClass, but treat boolean values as bytes.
365static inline TypeClass getClassB(const Type *Ty) {
366 if (Ty == Type::BoolTy) return cByte;
367 return getClass(Ty);
368}
369
Chris Lattner06925362002-11-17 21:56:38 +0000370
Chris Lattnerc5291f52002-10-27 21:16:59 +0000371/// copyConstantToRegister - Output the instructions required to put the
372/// specified constant into the specified register.
373///
Chris Lattner8a307e82002-12-16 19:32:50 +0000374void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000375 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000376 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000378 unsigned Class = 0;
379 switch (CE->getOpcode()) {
380 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000381 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000382 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000383 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000384 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000385 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000386 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000387
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000388 case Instruction::Xor: ++Class; // FALL THROUGH
389 case Instruction::Or: ++Class; // FALL THROUGH
390 case Instruction::And: ++Class; // FALL THROUGH
391 case Instruction::Sub: ++Class; // FALL THROUGH
392 case Instruction::Add:
393 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
394 Class, R);
395 return;
396
Chris Lattnercadff442003-10-23 17:21:43 +0000397 case Instruction::Mul: {
398 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
399 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
400 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
401 return;
402 }
403 case Instruction::Div:
404 case Instruction::Rem: {
405 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
406 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
407 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
408 CE->getOpcode() == Instruction::Div,
409 CE->getType(), R);
410 return;
411 }
412
Chris Lattner58c41fe2003-08-24 19:19:47 +0000413 case Instruction::SetNE:
414 case Instruction::SetEQ:
415 case Instruction::SetLT:
416 case Instruction::SetGT:
417 case Instruction::SetLE:
418 case Instruction::SetGE:
419 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
420 CE->getOpcode(), R);
421 return;
422
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000423 case Instruction::Shl:
424 case Instruction::Shr:
425 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000426 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
427 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000428
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000429 default:
430 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000431 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000432 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000433 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000434
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000435 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000436 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000437
438 if (Class == cLong) {
439 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000440 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000441 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
442 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000443 return;
444 }
445
Chris Lattner94af4142002-12-25 05:13:53 +0000446 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000447
448 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000449 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000450 };
451
Chris Lattner6b993cc2002-12-15 08:02:15 +0000452 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000453 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000454 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000455 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000456 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000457 }
Chris Lattner94af4142002-12-25 05:13:53 +0000458 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000459 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000460 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000461 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000462 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000463 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000464 // Otherwise we need to spill the constant to memory...
465 MachineConstantPool *CP = F->getConstantPool();
466 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000467 const Type *Ty = CFP->getType();
468
469 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000470 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000471 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000472 }
473
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000474 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000475 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000476 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000477 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000478 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000479 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000480 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000481 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000482 }
483}
484
Chris Lattner065faeb2002-12-28 20:24:02 +0000485/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
486/// the stack into virtual registers.
487///
488void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
489 // Emit instructions to load the arguments... On entry to a function on the
490 // X86, the stack frame looks like this:
491 //
492 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000493 // [ESP + 4] -- first argument (leftmost lexically)
494 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000495 // ...
496 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000497 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000498 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000499
500 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
501 unsigned Reg = getReg(*I);
502
Chris Lattner065faeb2002-12-28 20:24:02 +0000503 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000504 switch (getClassB(I->getType())) {
505 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000506 FI = MFI->CreateFixedObject(1, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000507 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000508 break;
509 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000510 FI = MFI->CreateFixedObject(2, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000511 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000512 break;
513 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000514 FI = MFI->CreateFixedObject(4, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000515 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000516 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000517 case cLong:
518 FI = MFI->CreateFixedObject(8, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000519 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
520 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +0000521 ArgOffset += 4; // longs require 4 additional bytes
522 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000523 case cFP:
524 unsigned Opcode;
525 if (I->getType() == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000526 Opcode = X86::FLD32m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000527 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000528 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000529 Opcode = X86::FLD64m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000530 FI = MFI->CreateFixedObject(8, ArgOffset);
531 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000532 }
533 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
534 break;
535 default:
536 assert(0 && "Unhandled argument type!");
537 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000538 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000539 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000540
541 // If the function takes variable number of arguments, add a frame offset for
542 // the start of the first vararg value... this is used to expand
543 // llvm.va_start.
544 if (Fn.getFunctionType()->isVarArg())
545 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000546}
547
548
Chris Lattner333b2fa2002-12-13 10:09:43 +0000549/// SelectPHINodes - Insert machine code to generate phis. This is tricky
550/// because we have to generate our sources into the source basic blocks, not
551/// the current one.
552///
553void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000554 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000555 const Function &LF = *F->getFunction(); // The LLVM function...
556 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
557 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000558 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000559
560 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000561 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000562 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000563 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000564
Chris Lattner333b2fa2002-12-13 10:09:43 +0000565 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000566 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000567 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
568 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000569
570 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000571 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
572 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
573 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000574
Chris Lattnera6e73f12003-05-12 14:22:21 +0000575 // PHIValues - Map of blocks to incoming virtual registers. We use this
576 // so that we only initialize one incoming value for a particular block,
577 // even if the block has multiple entries in the PHI node.
578 //
579 std::map<MachineBasicBlock*, unsigned> PHIValues;
580
Chris Lattner333b2fa2002-12-13 10:09:43 +0000581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
582 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000583 unsigned ValReg;
584 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
585 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000586
Chris Lattnera6e73f12003-05-12 14:22:21 +0000587 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
588 // We already inserted an initialization of the register for this
589 // predecessor. Recycle it.
590 ValReg = EntryIt->second;
591
592 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000593 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000594 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000595 Value *Val = PN->getIncomingValue(i);
596
597 // If this is a constant or GlobalValue, we may have to insert code
598 // into the basic block to compute it into a virtual register.
599 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
600 // Because we don't want to clobber any values which might be in
601 // physical registers with the computation of this constant (which
602 // might be arbitrarily complex if it is a constant expression),
603 // just insert the computation at the top of the basic block.
604 MachineBasicBlock::iterator PI = PredMBB->begin();
605
606 // Skip over any PHI nodes though!
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000607 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
Chris Lattnera81fc682003-10-19 00:26:11 +0000608 ++PI;
609
610 ValReg = getReg(Val, PredMBB, PI);
611 } else {
612 ValReg = getReg(Val);
613 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000614
615 // Remember that we inserted a value for this PHI for this predecessor
616 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
617 }
618
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000619 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000620 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000621 if (LongPhiMI) {
622 LongPhiMI->addRegOperand(ValReg+1);
623 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
624 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000625 }
Chris Lattner168aa902004-02-29 07:10:16 +0000626
627 // Now that we emitted all of the incoming values for the PHI node, make
628 // sure to reposition the InsertPoint after the PHI that we just added.
629 // This is needed because we might have inserted a constant into this
630 // block, right after the PHI's which is before the old insert point!
631 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
632 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000633 }
634 }
635}
636
Chris Lattner986618e2004-02-22 19:47:26 +0000637/// RequiresFPRegKill - The floating point stackifier pass cannot insert
638/// compensation code on critical edges. As such, it requires that we kill all
639/// FP registers on the exit from any blocks that either ARE critical edges, or
640/// branch to a block that has incoming critical edges.
641///
642/// Note that this kill instruction will eventually be eliminated when
643/// restrictions in the stackifier are relaxed.
644///
645static bool RequiresFPRegKill(const BasicBlock *BB) {
646#if 0
647 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
648 const BasicBlock *Succ = *SI;
649 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
650 ++PI; // Block have at least one predecessory
651 if (PI != PE) { // If it has exactly one, this isn't crit edge
652 // If this block has more than one predecessor, check all of the
653 // predecessors to see if they have multiple successors. If so, then the
654 // block we are analyzing needs an FPRegKill.
655 for (PI = pred_begin(Succ); PI != PE; ++PI) {
656 const BasicBlock *Pred = *PI;
657 succ_const_iterator SI2 = succ_begin(Pred);
658 ++SI2; // There must be at least one successor of this block.
659 if (SI2 != succ_end(Pred))
660 return true; // Yes, we must insert the kill on this edge.
661 }
662 }
663 }
664 // If we got this far, there is no need to insert the kill instruction.
665 return false;
666#else
667 return true;
668#endif
669}
670
671// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
672// need them. This only occurs due to the floating point stackifier not being
673// aggressive enough to handle arbitrary global stackification.
674//
675// Currently we insert an FP_REG_KILL instruction into each block that uses or
676// defines a floating point virtual register.
677//
678// When the global register allocators (like linear scan) finally update live
679// variable analysis, we can keep floating point values in registers across
680// portions of the CFG that do not involve critical edges. This will be a big
681// win, but we are waiting on the global allocators before we can do this.
682//
683// With a bit of work, the floating point stackifier pass can be enhanced to
684// break critical edges as needed (to make a place to put compensation code),
685// but this will require some infrastructure improvements as well.
686//
687void ISel::InsertFPRegKills() {
688 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000689
690 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000691 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000692 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
693 MachineOperand& MO = I->getOperand(i);
694 if (MO.isRegister() && MO.getReg()) {
695 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000696 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000697 if (RegMap.getRegClass(Reg)->getSize() == 10)
698 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000699 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000700 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000701 // If we haven't found an FP register use or def in this basic block, check
702 // to see if any of our successors has an FP PHI node, which will cause a
703 // copy to be inserted into this block.
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000704 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
705 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
706 MachineBasicBlock *SBB = MBBMap[*SI];
707 for (MachineBasicBlock::iterator I = SBB->begin();
708 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
709 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
710 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000711 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000712 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000713 continue;
714 UsesFPReg:
715 // Okay, this block uses an FP register. If the block has successors (ie,
716 // it's not an unwind/return), insert the FP_REG_KILL instruction.
717 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
718 RequiresFPRegKill(BB->getBasicBlock())) {
Chris Lattneree352852004-02-29 07:22:16 +0000719 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000720 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000721 }
722 }
723}
724
725
Chris Lattner6d40c192003-01-16 16:43:00 +0000726// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
727// the conditional branch instruction which is the only user of the cc
728// instruction. This is the case if the conditional branch is the only user of
729// the setcc, and if the setcc is in the same basic block as the conditional
730// branch. We also don't handle long arguments below, so we reject them here as
731// well.
732//
733static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
734 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattnerfd059242003-10-15 16:48:29 +0000735 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
Chris Lattner6d40c192003-01-16 16:43:00 +0000736 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
737 const Type *Ty = SCI->getOperand(0)->getType();
738 if (Ty != Type::LongTy && Ty != Type::ULongTy)
739 return SCI;
740 }
741 return 0;
742}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000743
Chris Lattner6d40c192003-01-16 16:43:00 +0000744// Return a fixed numbering for setcc instructions which does not depend on the
745// order of the opcodes.
746//
747static unsigned getSetCCNumber(unsigned Opcode) {
748 switch(Opcode) {
749 default: assert(0 && "Unknown setcc instruction!");
750 case Instruction::SetEQ: return 0;
751 case Instruction::SetNE: return 1;
752 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000753 case Instruction::SetGE: return 3;
754 case Instruction::SetGT: return 4;
755 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000756 }
757}
Chris Lattner06925362002-11-17 21:56:38 +0000758
Chris Lattner6d40c192003-01-16 16:43:00 +0000759// LLVM -> X86 signed X86 unsigned
760// ----- ---------- ------------
761// seteq -> sete sete
762// setne -> setne setne
763// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000764// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000765// setgt -> setg seta
766// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000767// ----
768// sets // Used by comparison with 0 optimization
769// setns
770static const unsigned SetCCOpcodeTab[2][8] = {
771 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
772 0, 0 },
773 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
774 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000775};
776
Chris Lattnerb2acc512003-10-19 21:09:10 +0000777// EmitComparison - This function emits a comparison of the two operands,
778// returning the extended setcc code to use.
779unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
780 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000781 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000782 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000783 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000784 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000785 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000786
787 // Special case handling of: cmp R, i
788 if (Class == cByte || Class == cShort || Class == cInt)
789 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000790 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
791
Chris Lattner333864d2003-06-05 19:30:30 +0000792 // Mask off any upper bits of the constant, if there are any...
793 Op1v &= (1ULL << (8 << Class)) - 1;
794
Chris Lattnerb2acc512003-10-19 21:09:10 +0000795 // If this is a comparison against zero, emit more efficient code. We
796 // can't handle unsigned comparisons against zero unless they are == or
797 // !=. These should have been strength reduced already anyway.
798 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
799 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000800 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000801 };
Chris Lattneree352852004-02-29 07:22:16 +0000802 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000803
804 if (OpNum == 2) return 6; // Map jl -> js
805 if (OpNum == 3) return 7; // Map jg -> jns
806 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000807 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000808
809 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000810 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000811 };
812
Chris Lattneree352852004-02-29 07:22:16 +0000813 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000814 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000815 }
816
Chris Lattner9f08a922004-02-03 18:54:04 +0000817 // Special case handling of comparison against +/- 0.0
818 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
819 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000820 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000821 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000822 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000823 return OpNum;
824 }
825
Chris Lattner58c41fe2003-08-24 19:19:47 +0000826 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000827 switch (Class) {
828 default: assert(0 && "Unknown type class!");
829 // Emit: cmp <var1>, <var2> (do the comparison). We can
830 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
831 // 32-bit.
832 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000833 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000834 break;
835 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000836 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000837 break;
838 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000839 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000840 break;
841 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +0000842 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000843 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000844 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +0000845 break;
846
847 case cLong:
848 if (OpNum < 2) { // seteq, setne
849 unsigned LoTmp = makeAnotherReg(Type::IntTy);
850 unsigned HiTmp = makeAnotherReg(Type::IntTy);
851 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000852 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
853 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
854 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +0000855 break; // Allow the sete or setne to be generated from flags set by OR
856 } else {
857 // Emit a sequence of code which compares the high and low parts once
858 // each, then uses a conditional move to handle the overflow case. For
859 // example, a setlt for long would generate code like this:
860 //
861 // AL = lo(op1) < lo(op2) // Signedness depends on operands
862 // BL = hi(op1) < hi(op2) // Always unsigned comparison
863 // dest = hi(op1) == hi(op2) ? AL : BL;
864 //
865
Chris Lattner6d40c192003-01-16 16:43:00 +0000866 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000867 // classes! Until then, hardcode registers so that we can deal with their
868 // aliases (because we don't have conditional byte moves).
869 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000870 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +0000871 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000872 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +0000873 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
874 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
875 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000876 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +0000877 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000878 // NOTE: visitSetCondInst knows that the value is dumped into the BL
879 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +0000880 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +0000881 }
882 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000883 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +0000884}
Chris Lattner3e130a22003-01-13 00:32:26 +0000885
Chris Lattner6d40c192003-01-16 16:43:00 +0000886
887/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
888/// register, then move it to wherever the result should be.
889///
890void ISel::visitSetCondInst(SetCondInst &I) {
891 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
892
Chris Lattner6d40c192003-01-16 16:43:00 +0000893 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000894 MachineBasicBlock::iterator MII = BB->end();
895 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
896 DestReg);
897}
Chris Lattner6d40c192003-01-16 16:43:00 +0000898
Chris Lattner58c41fe2003-08-24 19:19:47 +0000899/// emitSetCCOperation - Common code shared between visitSetCondInst and
900/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000901///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000902void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000903 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000904 Value *Op0, Value *Op1, unsigned Opcode,
905 unsigned TargetReg) {
906 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000907 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000908
Chris Lattnerb2acc512003-10-19 21:09:10 +0000909 const Type *CompTy = Op0->getType();
910 unsigned CompClass = getClassB(CompTy);
911 bool isSigned = CompTy->isSigned() && CompClass != cFP;
912
913 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000914 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +0000915 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +0000916 } else {
917 // Handle long comparisons by copying the value which is already in BL into
918 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000919 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +0000920 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000921}
Chris Lattner51b49a92002-11-02 19:45:49 +0000922
Chris Lattner58c41fe2003-08-24 19:19:47 +0000923
924
925
Brian Gaekec2505982002-11-30 11:57:28 +0000926/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
927/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +0000928///
Chris Lattner3e130a22003-01-13 00:32:26 +0000929void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
930 bool isUnsigned = VR.Ty->isUnsigned();
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000931
932 // Make sure we have the register number for this value...
933 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
934
Chris Lattner3e130a22003-01-13 00:32:26 +0000935 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000936 case cByte:
937 // Extend value into target register (8->32)
938 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000939 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000940 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000941 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000942 break;
943 case cShort:
944 // Extend value into target register (16->32)
945 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000946 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000947 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000948 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000949 break;
950 case cInt:
951 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000952 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000953 break;
954 default:
955 assert(0 && "Unpromotable operand class in promote32");
956 }
Brian Gaekec2505982002-11-30 11:57:28 +0000957}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000958
Chris Lattner72614082002-10-25 22:55:53 +0000959/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
960/// we have the following possibilities:
961///
962/// ret void: No return value, simply emit a 'ret' instruction
963/// ret sbyte, ubyte : Extend value into EAX and return
964/// ret short, ushort: Extend value into EAX and return
965/// ret int, uint : Move value into EAX and return
966/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000967/// ret long, ulong : Move value into EAX/EDX and return
968/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000969///
Chris Lattner3e130a22003-01-13 00:32:26 +0000970void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000971 if (I.getNumOperands() == 0) {
972 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
973 return;
974 }
975
976 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000977 unsigned RetReg = getReg(RetVal);
978 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000979 case cByte: // integral return values: extend or move into EAX and return
980 case cShort:
981 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000982 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattnerdbd73722003-05-06 21:32:22 +0000983 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000984 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000985 break;
986 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000987 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000988 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000989 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000990 break;
991 case cLong:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000992 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
993 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000994 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000995 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
996 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000997 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000998 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000999 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001000 }
Chris Lattner43189d12002-11-17 20:07:45 +00001001 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001002 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001003}
1004
Chris Lattner55f6fab2003-01-16 18:07:23 +00001005// getBlockAfter - Return the basic block which occurs lexically after the
1006// specified one.
1007static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1008 Function::iterator I = BB; ++I; // Get iterator to next block
1009 return I != BB->getParent()->end() ? &*I : 0;
1010}
1011
Chris Lattner51b49a92002-11-02 19:45:49 +00001012/// visitBranchInst - Handle conditional and unconditional branches here. Note
1013/// that since code layout is frozen at this point, that if we are trying to
1014/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001015/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001016///
Chris Lattner94af4142002-12-25 05:13:53 +00001017void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +00001018 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1019
1020 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001021 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001022 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001023 return;
1024 }
1025
1026 // See if we can fold the setcc into the branch itself...
1027 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1028 if (SCI == 0) {
1029 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1030 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001031 unsigned condReg = getReg(BI.getCondition());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001032 BuildMI(BB, X86::CMP8ri, 2).addReg(condReg).addImm(0);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001033 if (BI.getSuccessor(1) == NextBB) {
1034 if (BI.getSuccessor(0) != NextBB)
1035 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1036 } else {
1037 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1038
1039 if (BI.getSuccessor(0) != NextBB)
1040 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1041 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001042 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001043 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001044
1045 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001046 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001047 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001048
1049 const Type *CompTy = SCI->getOperand(0)->getType();
1050 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001051
Chris Lattnerb2acc512003-10-19 21:09:10 +00001052
Chris Lattner6d40c192003-01-16 16:43:00 +00001053 // LLVM -> X86 signed X86 unsigned
1054 // ----- ---------- ------------
1055 // seteq -> je je
1056 // setne -> jne jne
1057 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001058 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001059 // setgt -> jg ja
1060 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001061 // ----
1062 // js // Used by comparison with 0 optimization
1063 // jns
1064
1065 static const unsigned OpcodeTab[2][8] = {
1066 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1067 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1068 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001069 };
1070
Chris Lattner55f6fab2003-01-16 18:07:23 +00001071 if (BI.getSuccessor(0) != NextBB) {
1072 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1073 if (BI.getSuccessor(1) != NextBB)
1074 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1075 } else {
1076 // Change to the inverse condition...
1077 if (BI.getSuccessor(1) != NextBB) {
1078 OpNum ^= 1;
1079 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1080 }
1081 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001082}
1083
Chris Lattner3e130a22003-01-13 00:32:26 +00001084
1085/// doCall - This emits an abstract call instruction, setting up the arguments
1086/// and the return value as appropriate. For the actual function call itself,
1087/// it inserts the specified CallMI instruction into the stream.
1088///
1089void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001090 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001091
Chris Lattner065faeb2002-12-28 20:24:02 +00001092 // Count how many bytes are to be pushed on the stack...
1093 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001094
Chris Lattner3e130a22003-01-13 00:32:26 +00001095 if (!Args.empty()) {
1096 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1097 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001098 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001099 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001100 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001101 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001102 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001103 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1104 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001105 default: assert(0 && "Unknown class!");
1106 }
1107
1108 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001109 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001110
1111 // Arguments go on the stack in reverse order, as specified by the ABI.
1112 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001113 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001114 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001115 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001116 case cByte:
Chris Lattner21585222004-03-01 02:42:43 +00001117 case cShort:
1118 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1119 // Zero/Sign extend constant, then stuff into memory.
1120 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1121 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1122 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1123 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1124 } else {
1125 // Promote arg to 32 bits wide into a temporary register...
1126 ArgReg = makeAnotherReg(Type::UIntTy);
1127 promote32(ArgReg, Args[i]);
1128 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1129 X86::ESP, ArgOffset).addReg(ArgReg);
1130 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001131 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001132 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001133 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1134 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1135 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1136 X86::ESP, ArgOffset).addImm(Val);
1137 } else {
1138 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1139 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1140 X86::ESP, ArgOffset).addReg(ArgReg);
1141 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001142 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001143 case cLong:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001144 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001145 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001146 X86::ESP, ArgOffset).addReg(ArgReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001147 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001148 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1149 ArgOffset += 4; // 8 byte entry, not 4.
1150 break;
1151
Chris Lattner065faeb2002-12-28 20:24:02 +00001152 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001153 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001154 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001155 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001156 X86::ESP, ArgOffset).addReg(ArgReg);
1157 } else {
1158 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001159 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001160 X86::ESP, ArgOffset).addReg(ArgReg);
1161 ArgOffset += 4; // 8 byte entry, not 4.
1162 }
1163 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001164
Chris Lattner3e130a22003-01-13 00:32:26 +00001165 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001166 }
1167 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001168 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001169 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001170 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001171 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001172
Chris Lattner3e130a22003-01-13 00:32:26 +00001173 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001174
Chris Lattneree352852004-02-29 07:22:16 +00001175 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001176
1177 // If there is a return value, scavenge the result from the location the call
1178 // leaves it in...
1179 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001180 if (Ret.Ty != Type::VoidTy) {
1181 unsigned DestClass = getClassB(Ret.Ty);
1182 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001183 case cByte:
1184 case cShort:
1185 case cInt: {
1186 // Integral results are in %eax, or the appropriate portion
1187 // thereof.
1188 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001189 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001190 };
1191 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001192 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001193 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001194 }
Chris Lattner94af4142002-12-25 05:13:53 +00001195 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001196 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001197 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001198 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001199 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1200 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001201 break;
1202 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001203 }
Chris Lattnera3243642002-12-04 23:45:28 +00001204 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001205}
Chris Lattner2df035b2002-11-02 19:27:56 +00001206
Chris Lattner3e130a22003-01-13 00:32:26 +00001207
1208/// visitCallInst - Push args on stack and do a procedure call instruction.
1209void ISel::visitCallInst(CallInst &CI) {
1210 MachineInstr *TheCall;
1211 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001212 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001213 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001214 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1215 return;
1216 }
1217
Chris Lattner3e130a22003-01-13 00:32:26 +00001218 // Emit a CALL instruction with PC-relative displacement.
1219 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1220 } else { // Emit an indirect call...
1221 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001222 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001223 }
1224
1225 std::vector<ValueRecord> Args;
1226 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001227 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001228
1229 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1230 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001231}
Chris Lattner3e130a22003-01-13 00:32:26 +00001232
Chris Lattneraeb54b82003-08-28 21:23:43 +00001233
Chris Lattner44827152003-12-28 09:47:19 +00001234/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1235/// function, lowering any calls to unknown intrinsic functions into the
1236/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001237///
Chris Lattner44827152003-12-28 09:47:19 +00001238void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1241 if (CallInst *CI = dyn_cast<CallInst>(I++))
1242 if (Function *F = CI->getCalledFunction())
1243 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001244 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001245 case Intrinsic::vastart:
1246 case Intrinsic::vacopy:
1247 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001248 case Intrinsic::returnaddress:
1249 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001250 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001251 case Intrinsic::memset:
Chris Lattner44827152003-12-28 09:47:19 +00001252 // We directly implement these intrinsics
1253 break;
1254 default:
1255 // All other intrinsic calls we must lower.
1256 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001257 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001258 if (Before) { // Move iterator to instruction after call
1259 I = Before; ++I;
1260 } else {
1261 I = BB->begin();
1262 }
1263 }
1264
1265}
1266
Brian Gaeked0fde302003-11-11 22:41:34 +00001267void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001268 unsigned TmpReg1, TmpReg2;
1269 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001270 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001271 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001272 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001273 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001274 return;
1275
Chris Lattner5634b9f2004-03-13 00:24:52 +00001276 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001277 TmpReg1 = getReg(CI);
1278 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001279 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001280 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001281 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001282
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001283 case Intrinsic::returnaddress:
1284 case Intrinsic::frameaddress:
1285 TmpReg1 = getReg(CI);
1286 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1287 if (ID == Intrinsic::returnaddress) {
1288 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001289 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001290 ReturnAddressIndex);
1291 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001292 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001293 ReturnAddressIndex, -4);
1294 }
1295 } else {
1296 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001297 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001298 }
1299 return;
1300
Chris Lattner915e5e52004-02-12 17:53:22 +00001301 case Intrinsic::memcpy: {
1302 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1303 unsigned Align = 1;
1304 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1305 Align = AlignC->getRawValue();
1306 if (Align == 0) Align = 1;
1307 }
1308
1309 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001310 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001311 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001312 switch (Align & 3) {
1313 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001314 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1315 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1316 } else {
1317 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001318 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001319 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001320 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001321 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001322 break;
1323 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001324 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1325 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1326 } else {
1327 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001328 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001329 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001330 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001331 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001332 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001333 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001334 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001335 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001336 break;
1337 }
1338
1339 // No matter what the alignment is, we put the source in ESI, the
1340 // destination in EDI, and the count in ECX.
1341 TmpReg1 = getReg(CI.getOperand(1));
1342 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001343 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1344 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1345 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001346 BuildMI(BB, Opcode, 0);
1347 return;
1348 }
1349 case Intrinsic::memset: {
1350 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1351 unsigned Align = 1;
1352 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1353 Align = AlignC->getRawValue();
1354 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001355 }
1356
Chris Lattner2a0f2242004-02-14 04:46:05 +00001357 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001358 unsigned CountReg;
1359 unsigned Opcode;
1360 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1361 unsigned Val = ValC->getRawValue() & 255;
1362
1363 // If the value is a constant, then we can potentially use larger copies.
1364 switch (Align & 3) {
1365 case 2: // WORD aligned
1366 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001367 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001368 } else {
1369 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001370 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001371 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001372 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001373 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001374 Opcode = X86::REP_STOSW;
1375 break;
1376 case 0: // DWORD aligned
1377 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001378 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001379 } else {
1380 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001381 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001382 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001383 }
1384 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001385 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001386 Opcode = X86::REP_STOSD;
1387 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001388 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001389 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001390 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001391 Opcode = X86::REP_STOSB;
1392 break;
1393 }
1394 } else {
1395 // If it's not a constant value we are storing, just fall back. We could
1396 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1397 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001398 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001399 CountReg = getReg(CI.getOperand(3));
1400 Opcode = X86::REP_STOSB;
1401 }
1402
1403 // No matter what the alignment is, we put the source in ESI, the
1404 // destination in EDI, and the count in ECX.
1405 TmpReg1 = getReg(CI.getOperand(1));
1406 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001407 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1408 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001409 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001410 return;
1411 }
1412
Chris Lattner44827152003-12-28 09:47:19 +00001413 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001414 }
1415}
1416
Chris Lattner7dee5da2004-03-08 01:58:35 +00001417static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1418 if (LI.getParent() != User.getParent())
1419 return false;
1420 BasicBlock::iterator It = &LI;
1421 // Check all of the instructions between the load and the user. We should
1422 // really use alias analysis here, but for now we just do something simple.
1423 for (++It; It != BasicBlock::iterator(&User); ++It) {
1424 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001425 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001426 case Instruction::Store:
1427 case Instruction::Call:
1428 case Instruction::Invoke:
1429 return false;
1430 }
1431 }
1432 return true;
1433}
1434
Chris Lattnereca195e2003-05-08 19:44:13 +00001435
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001436/// visitSimpleBinary - Implement simple binary operators for integral types...
1437/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1438/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001439///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001440void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1441 unsigned DestReg = getReg(B);
1442 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001443 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1444
Chris Lattner7dee5da2004-03-08 01:58:35 +00001445 // Special case: op Reg, load [mem]
1446 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1447 if (!B.swapOperands())
1448 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1449
1450 unsigned Class = getClassB(B.getType());
1451 if (isa<LoadInst>(Op1) && Class < cFP &&
1452 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1453
1454 static const unsigned OpcodeTab[][3] = {
1455 // Arithmetic operators
1456 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1457 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1458
1459 // Bitwise operators
1460 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1461 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1462 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1463 };
1464
1465 assert(Class < cFP && "General code handles 64-bit integer types!");
1466 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1467
1468 unsigned BaseReg, Scale, IndexReg, Disp;
1469 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1470 Scale, IndexReg, Disp);
1471
1472 unsigned Op0r = getReg(Op0);
1473 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1474 BaseReg, Scale, IndexReg, Disp);
1475 return;
1476 }
1477
Chris Lattner721d2d42004-03-08 01:18:36 +00001478 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001479}
Chris Lattner3e130a22003-01-13 00:32:26 +00001480
Chris Lattnerb2acc512003-10-19 21:09:10 +00001481/// emitSimpleBinaryOperation - Implement simple binary operators for integral
1482/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1483/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00001484///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001485/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1486/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00001487///
1488void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001489 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001490 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001491 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001492 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00001493
1494 // sub 0, X -> neg X
1495 if (OperatorClass == 1 && Class != cLong)
Chris Lattneraf703622004-02-02 18:56:30 +00001496 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001497 if (CI->isNullValue()) {
1498 unsigned op1Reg = getReg(Op1, MBB, IP);
1499 switch (Class) {
1500 default: assert(0 && "Unknown class for this function!");
1501 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001502 BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001503 return;
1504 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001505 BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001506 return;
1507 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001508 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001509 return;
1510 }
1511 }
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001512 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1513 if (CFP->isExactlyValue(-0.0)) {
1514 // -0.0 - X === -X
1515 unsigned op1Reg = getReg(Op1, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001516 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001517 return;
1518 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001519
Chris Lattnerb2acc512003-10-19 21:09:10 +00001520 // Special case: op Reg, <const>
Chris Lattner721d2d42004-03-08 01:18:36 +00001521 if (Class != cLong && isa<ConstantInt>(Op1)) {
1522 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1523 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001524
Chris Lattner721d2d42004-03-08 01:18:36 +00001525 // xor X, -1 -> not X
1526 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1527 static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1528 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1529 return;
1530 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001531
Chris Lattner721d2d42004-03-08 01:18:36 +00001532 // add X, -1 -> dec X
1533 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1534 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1535 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1536 return;
1537 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001538
Chris Lattner721d2d42004-03-08 01:18:36 +00001539 // add X, 1 -> inc X
1540 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1541 static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1542 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1543 return;
1544 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001545
Chris Lattner721d2d42004-03-08 01:18:36 +00001546 static const unsigned OpcodeTab[][3] = {
1547 // Arithmetic operators
1548 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri }, // ADD
1549 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00001550
Chris Lattner721d2d42004-03-08 01:18:36 +00001551 // Bitwise operators
1552 { X86::AND8ri, X86::AND16ri, X86::AND32ri }, // AND
1553 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri }, // OR
1554 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri }, // XOR
1555 };
1556
1557 assert(Class < cFP && "General code handles 64-bit integer types!");
1558 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1559
1560
1561 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1562 BuildMI(*MBB, IP, Opcode, 5, DestReg).addReg(Op0r).addImm(Op1v);
1563 return;
1564 }
1565
1566 // Finally, handle the general case now.
1567 static const unsigned OpcodeTab[][4] = {
1568 // Arithmetic operators
1569 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD }, // ADD
1570 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB }, // SUB
1571
Chris Lattnerb2acc512003-10-19 21:09:10 +00001572 // Bitwise operators
Chris Lattner721d2d42004-03-08 01:18:36 +00001573 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 }, // AND
1574 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 }, // OR
1575 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00001576 };
Chris Lattner721d2d42004-03-08 01:18:36 +00001577
1578 bool isLong = false;
1579 if (Class == cLong) {
1580 isLong = true;
1581 Class = cInt; // Bottom 32 bits are handled just like ints
1582 }
1583
Chris Lattnerb2acc512003-10-19 21:09:10 +00001584 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00001585 assert(Opcode && "Floating point arguments to logical inst?");
1586 unsigned Op0r = getReg(Op0, MBB, IP);
1587 unsigned Op1r = getReg(Op1, MBB, IP);
1588 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1589
1590 if (isLong) { // Handle the upper 32 bits of long values...
1591 static const unsigned TopTab[] = {
1592 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1593 };
1594 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1595 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1596 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001597}
1598
Chris Lattner3e130a22003-01-13 00:32:26 +00001599/// doMultiply - Emit appropriate instructions to multiply together the
1600/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1601/// result should be given as DestTy.
1602///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001603void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00001604 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00001605 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001606 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001607 switch (Class) {
1608 case cFP: // Floating point multiply
Chris Lattneree352852004-02-29 07:22:16 +00001609 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001610 return;
Chris Lattner0f1c4612003-06-21 17:16:58 +00001611 case cInt:
1612 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001613 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00001614 .addReg(op0Reg).addReg(op1Reg);
1615 return;
1616 case cByte:
1617 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001618 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1619 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1620 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00001621 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001622 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001623 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00001624 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001625}
1626
Chris Lattnerb2acc512003-10-19 21:09:10 +00001627// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1628// returns zero when the input is not exactly a power of two.
1629static unsigned ExactLog2(unsigned Val) {
1630 if (Val == 0) return 0;
1631 unsigned Count = 0;
1632 while (Val != 1) {
1633 if (Val & 1) return 0;
1634 Val >>= 1;
1635 ++Count;
1636 }
1637 return Count+1;
1638}
1639
1640void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001641 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001642 unsigned DestReg, const Type *DestTy,
1643 unsigned op0Reg, unsigned ConstRHS) {
1644 unsigned Class = getClass(DestTy);
1645
1646 // If the element size is exactly a power of 2, use a shift to get it.
1647 if (unsigned Shift = ExactLog2(ConstRHS)) {
1648 switch (Class) {
1649 default: assert(0 && "Unknown class for this function!");
1650 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001651 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001652 return;
1653 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001654 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001655 return;
1656 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001657 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001658 return;
1659 }
1660 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00001661
1662 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001663 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00001664 return;
1665 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001666 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00001667 return;
1668 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001669
1670 // Most general case, emit a normal multiply...
Chris Lattner6e173a02004-02-17 06:16:44 +00001671 static const unsigned MOVriTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001672 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +00001673 };
1674
1675 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00001676 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001677
1678 // Emit a MUL to multiply the register holding the index by
1679 // elementSize, putting the result in OffsetReg.
1680 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1681}
1682
Chris Lattnerca9671d2002-11-02 20:28:58 +00001683/// visitMul - Multiplies are not simple binary operators because they must deal
1684/// with the EAX register explicitly.
1685///
1686void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00001687 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00001688 unsigned DestReg = getReg(I);
1689
1690 // Simple scalar multiply?
1691 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001692 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1693 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1694 MachineBasicBlock::iterator MBBI = BB->end();
1695 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1696 } else {
1697 unsigned Op1Reg = getReg(I.getOperand(1));
1698 MachineBasicBlock::iterator MBBI = BB->end();
1699 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1700 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001701 } else {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001702 unsigned Op1Reg = getReg(I.getOperand(1));
1703
Chris Lattner3e130a22003-01-13 00:32:26 +00001704 // Long value. We have to do things the hard way...
1705 // Multiply the two low parts... capturing carry into EDX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001706 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1707 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
Chris Lattner3e130a22003-01-13 00:32:26 +00001708
1709 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001710 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
1711 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
Chris Lattner3e130a22003-01-13 00:32:26 +00001712
1713 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattner034acf02003-06-21 18:15:27 +00001714 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001715 BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001716
1717 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001718 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001719 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001720
1721 MBBI = BB->end();
Chris Lattner034acf02003-06-21 18:15:27 +00001722 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001723 BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001724
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001725 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001726 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001727 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001728}
Chris Lattnerca9671d2002-11-02 20:28:58 +00001729
Chris Lattner06925362002-11-17 21:56:38 +00001730
Chris Lattnerf01729e2002-11-02 20:54:46 +00001731/// visitDivRem - Handle division and remainder instructions... these
1732/// instruction both require the same instructions to be generated, they just
1733/// select the result from a different register. Note that both of these
1734/// instructions work differently for signed and unsigned operands.
1735///
1736void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00001737 unsigned Op0Reg = getReg(I.getOperand(0));
1738 unsigned Op1Reg = getReg(I.getOperand(1));
1739 unsigned ResultReg = getReg(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001740
Chris Lattnercadff442003-10-23 17:21:43 +00001741 MachineBasicBlock::iterator IP = BB->end();
1742 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1743 I.getType(), ResultReg);
1744}
1745
1746void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001747 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +00001748 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1749 const Type *Ty, unsigned ResultReg) {
1750 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00001751 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001752 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00001753 if (isDiv) {
Chris Lattneree352852004-02-29 07:22:16 +00001754 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001755 } else { // Floating point remainder...
Chris Lattner3e130a22003-01-13 00:32:26 +00001756 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001757 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00001758 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00001759 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1760 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00001761 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1762 }
Chris Lattner94af4142002-12-25 05:13:53 +00001763 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001764 case cLong: {
1765 static const char *FnName[] =
1766 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1767
Chris Lattnercadff442003-10-23 17:21:43 +00001768 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00001769 MachineInstr *TheCall =
1770 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1771
1772 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00001773 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1774 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00001775 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1776 return;
1777 }
1778 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00001779 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00001780 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001781 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001782
1783 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001784 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1785 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1786 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001787 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1788
1789 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001790 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
1791 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001792 };
1793
Chris Lattnercadff442003-10-23 17:21:43 +00001794 bool isSigned = Ty->isSigned();
Chris Lattnerf01729e2002-11-02 20:54:46 +00001795 unsigned Reg = Regs[Class];
1796 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001797
1798 // Put the first operand into one of the A registers...
Chris Lattneree352852004-02-29 07:22:16 +00001799 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001800
1801 if (isSigned) {
1802 // Emit a sign extension instruction...
Chris Lattnercadff442003-10-23 17:21:43 +00001803 unsigned ShiftResult = makeAnotherReg(Ty);
Chris Lattneree352852004-02-29 07:22:16 +00001804 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1805 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001806 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00001807 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00001808 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001809 }
1810
Chris Lattner06925362002-11-17 21:56:38 +00001811 // Emit the appropriate divide or remainder instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001812 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001813
Chris Lattnerf01729e2002-11-02 20:54:46 +00001814 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00001815 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00001816
Chris Lattnerf01729e2002-11-02 20:54:46 +00001817 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00001818 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001819}
Chris Lattnere2954c82002-11-02 20:04:26 +00001820
Chris Lattner06925362002-11-17 21:56:38 +00001821
Brian Gaekea1719c92002-10-31 23:03:59 +00001822/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1823/// for constant immediate shift values, and for constant immediate
1824/// shift values equal to 1. Even the general case is sort of special,
1825/// because the shift amount has to be in CL, not just any old register.
1826///
Chris Lattner3e130a22003-01-13 00:32:26 +00001827void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001828 MachineBasicBlock::iterator IP = BB->end ();
1829 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1830 I.getOpcode () == Instruction::Shl, I.getType (),
1831 getReg (I));
1832}
1833
1834/// emitShiftOperation - Common code shared between visitShiftInst and
1835/// constant expression support.
1836void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001837 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001838 Value *Op, Value *ShiftAmount, bool isLeftShift,
1839 const Type *ResultTy, unsigned DestReg) {
1840 unsigned SrcReg = getReg (Op, MBB, IP);
1841 bool isSigned = ResultTy->isSigned ();
1842 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00001843
1844 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001845 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
1846 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
1847 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
1848 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00001849 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001850
Chris Lattner3e130a22003-01-13 00:32:26 +00001851 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001852 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
1853 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
1854 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
1855 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00001856 };
Chris Lattner796df732002-11-02 00:44:25 +00001857
Chris Lattner3e130a22003-01-13 00:32:26 +00001858 // Longs, as usual, are handled specially...
1859 if (Class == cLong) {
1860 // If we have a constant shift, we can generate much more efficient code
1861 // than otherwise...
1862 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001863 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001864 unsigned Amount = CUI->getValue();
1865 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001866 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1867 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00001868 BuildMI(*MBB, IP, Opc[3], 3,
1869 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1870 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001871 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001872 BuildMI(*MBB, IP, Opc[3], 3,
1873 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
1874 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001875 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001876 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001877 Amount -= 32;
1878 if (isLeftShift) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001879 BuildMI(*MBB, IP, X86::SHL32ri, 2,
Chris Lattneree352852004-02-29 07:22:16 +00001880 DestReg + 1).addReg(SrcReg).addImm(Amount);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001881 BuildMI(*MBB, IP, X86::MOV32ri, 1,
Chris Lattneree352852004-02-29 07:22:16 +00001882 DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001883 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001884 unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
Chris Lattneree352852004-02-29 07:22:16 +00001885 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001886 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001887 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001888 }
1889 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00001890 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1891
1892 if (!isLeftShift && isSigned) {
1893 // If this is a SHR of a Long, then we need to do funny sign extension
1894 // stuff. TmpReg gets the value to use as the high-part if we are
1895 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001896 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00001897 } else {
1898 // Other shifts use a fixed zero value if the shift is more than 32
1899 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001900 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00001901 }
1902
1903 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001904 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001905 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001906
1907 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1908 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1909 if (isLeftShift) {
1910 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001911 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00001912 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001913 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001914 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001915
1916 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001917 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00001918
1919 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001920 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001921 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1922 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001923 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001924 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001925 } else {
1926 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001927 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00001928 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00001929 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001930 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00001931 .addReg(SrcReg+1);
1932
1933 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001934 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00001935
1936 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001937 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001938 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1939
1940 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001941 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001942 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1943 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001944 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001945 return;
1946 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001947
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001948 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001949 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1950 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001951
Chris Lattner3e130a22003-01-13 00:32:26 +00001952 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00001953 BuildMI(*MBB, IP, Opc[Class], 2,
1954 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00001955 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001956 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001957 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001958
Chris Lattner3e130a22003-01-13 00:32:26 +00001959 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00001960 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001961 }
1962}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001963
Chris Lattner3e130a22003-01-13 00:32:26 +00001964
Chris Lattner721d2d42004-03-08 01:18:36 +00001965void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
1966 unsigned &IndexReg, unsigned &Disp) {
1967 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
1968 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1969 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1970 BaseReg, Scale, IndexReg, Disp))
1971 return;
1972 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1973 if (CE->getOpcode() == Instruction::GetElementPtr)
1974 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1975 BaseReg, Scale, IndexReg, Disp))
1976 return;
1977 }
1978
1979 // If it's not foldable, reset addr mode.
1980 BaseReg = getReg(Addr);
1981 Scale = 1; IndexReg = 0; Disp = 0;
1982}
1983
1984
Chris Lattner6fc3c522002-11-17 21:11:55 +00001985/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001986/// instruction. The load and store instructions are the only place where we
1987/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001988///
1989void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00001990 // Check to see if this load instruction is going to be folded into a binary
1991 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
1992 // pattern matching instruction selector be nice?
1993 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
1994 Instruction *User = cast<Instruction>(I.use_back());
1995 switch (User->getOpcode()) {
1996 default: User = 0; break;
1997 case Instruction::Add:
1998 case Instruction::Sub:
1999 case Instruction::And:
2000 case Instruction::Or:
2001 case Instruction::Xor:
2002 break;
2003 }
2004
2005 if (User) {
2006 // Okay, we found a user. If the load is the first operand and there is
2007 // no second operand load, reverse the operand ordering. Note that this
2008 // can fail for a subtract (ie, no change will be made).
2009 if (!isa<LoadInst>(User->getOperand(1)))
2010 cast<BinaryOperator>(User)->swapOperands();
2011
2012 // Okay, now that everything is set up, if this load is used by the second
2013 // operand, and if there are no instructions that invalidate the load
2014 // before the binary operator, eliminate the load.
2015 if (User->getOperand(1) == &I &&
2016 isSafeToFoldLoadIntoInstruction(I, *User))
2017 return; // Eliminate the load!
2018 }
2019 }
2020
Chris Lattner94af4142002-12-25 05:13:53 +00002021 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002022 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
Chris Lattner721d2d42004-03-08 01:18:36 +00002023 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
Chris Lattnere8f0d922002-12-24 00:03:11 +00002024
Brian Gaekebfedb912003-07-17 21:30:06 +00002025 unsigned Class = getClassB(I.getType());
Chris Lattner6ac1d712003-10-20 04:48:06 +00002026 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002027 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002028 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002029 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002030 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00002031 return;
2032 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002033
Chris Lattner6ac1d712003-10-20 04:48:06 +00002034 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002035 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00002036 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002037 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002038 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002039 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2040 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00002041}
2042
Chris Lattner6fc3c522002-11-17 21:11:55 +00002043/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2044/// instruction.
2045///
2046void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002047 unsigned BaseReg, Scale, IndexReg, Disp;
2048 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002049
Chris Lattner6c09db22003-10-20 04:11:23 +00002050 const Type *ValTy = I.getOperand(0)->getType();
2051 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002052
Chris Lattner5a830962004-02-25 02:56:58 +00002053 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2054 uint64_t Val = CI->getRawValue();
2055 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002056 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002057 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002058 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002059 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00002060 } else {
2061 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002062 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00002063 };
2064 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00002065 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002066 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00002067 }
2068 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002069 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002070 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattner5a830962004-02-25 02:56:58 +00002071 } else {
2072 if (Class == cLong) {
2073 unsigned ValReg = getReg(I.getOperand(0));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002074 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002075 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002076 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002077 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
Chris Lattner5a830962004-02-25 02:56:58 +00002078 } else {
2079 unsigned ValReg = getReg(I.getOperand(0));
2080 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002081 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
Chris Lattner5a830962004-02-25 02:56:58 +00002082 };
2083 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002084 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002085 addFullAddress(BuildMI(BB, Opcode, 1+4),
2086 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner5a830962004-02-25 02:56:58 +00002087 }
Chris Lattner94af4142002-12-25 05:13:53 +00002088 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002089}
2090
2091
Misha Brukman538607f2004-03-01 23:53:11 +00002092/// visitCastInst - Here we have various kinds of copying with or without sign
2093/// extension going on.
2094///
Chris Lattner3e130a22003-01-13 00:32:26 +00002095void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002096 Value *Op = CI.getOperand(0);
2097 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2098 // of the case are GEP instructions, then the cast does not need to be
2099 // generated explicitly, it will be folded into the GEP.
2100 if (CI.getType() == Type::LongTy &&
2101 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2102 bool AllUsesAreGEPs = true;
2103 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2104 if (!isa<GetElementPtrInst>(*I)) {
2105 AllUsesAreGEPs = false;
2106 break;
2107 }
2108
2109 // No need to codegen this cast if all users are getelementptr instrs...
2110 if (AllUsesAreGEPs) return;
2111 }
2112
Chris Lattner548f61d2003-04-23 17:22:12 +00002113 unsigned DestReg = getReg(CI);
2114 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00002115 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00002116}
2117
Misha Brukman538607f2004-03-01 23:53:11 +00002118/// emitCastOperation - Common code shared between visitCastInst and constant
2119/// expression cast support.
2120///
Chris Lattner548f61d2003-04-23 17:22:12 +00002121void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002122 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00002123 Value *Src, const Type *DestTy,
2124 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00002125 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002126 const Type *SrcTy = Src->getType();
2127 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002128 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00002129
Chris Lattner3e130a22003-01-13 00:32:26 +00002130 // Implement casts to bool by using compare on the operand followed by set if
2131 // not zero on the result.
2132 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00002133 switch (SrcClass) {
2134 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002135 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002136 break;
2137 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002138 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002139 break;
2140 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002141 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002142 break;
2143 case cLong: {
2144 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002145 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00002146 break;
2147 }
2148 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00002149 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002150 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00002151 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00002152 break;
Chris Lattner20772542003-06-01 03:38:24 +00002153 }
2154
2155 // If the zero flag is not set, then the value is true, set the byte to
2156 // true.
Chris Lattneree352852004-02-29 07:22:16 +00002157 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002158 return;
2159 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002160
2161 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002162 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00002163 };
2164
2165 // Implement casts between values of the same type class (as determined by
2166 // getClass) by using a register-to-register move.
2167 if (SrcClass == DestClass) {
2168 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00002169 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002170 } else if (SrcClass == cFP) {
2171 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002172 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00002173 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002174 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002175 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2176 "Unknown cFP member!");
2177 // Truncate from double to float by storing to memory as short, then
2178 // reading it back.
2179 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00002180 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002181 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2182 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002183 }
2184 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002185 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2186 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002187 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00002188 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002189 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00002190 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002191 return;
2192 }
2193
2194 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2195 // or zero extension, depending on whether the source type was signed.
2196 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2197 SrcClass < DestClass) {
2198 bool isLong = DestClass == cLong;
2199 if (isLong) DestClass = cInt;
2200
2201 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002202 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2203 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00002204 };
2205
2206 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattneree352852004-02-29 07:22:16 +00002207 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00002208 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002209
2210 if (isLong) { // Handle upper 32 bits as appropriate...
2211 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002212 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00002213 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002214 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00002215 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002216 return;
2217 }
2218
2219 // Special case long -> int ...
2220 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002221 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002222 return;
2223 }
2224
2225 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2226 // move out of AX or AL.
2227 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2228 && SrcClass > DestClass) {
2229 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00002230 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2231 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00002232 return;
2233 }
2234
2235 // Handle casts from integer to floating point now...
2236 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002237 // Promote the integer to a type supported by FLD. We do this because there
2238 // are no unsigned FLD instructions, so we must promote an unsigned value to
2239 // a larger signed value, then use FLD on the larger value.
2240 //
2241 const Type *PromoteType = 0;
2242 unsigned PromoteOpcode;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002243 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002244 switch (SrcTy->getPrimitiveID()) {
2245 case Type::BoolTyID:
2246 case Type::SByteTyID:
2247 // We don't have the facilities for directly loading byte sized data from
2248 // memory (even signed). Promote it to 16 bits.
2249 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002250 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002251 break;
2252 case Type::UByteTyID:
2253 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002254 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002255 break;
2256 case Type::UShortTyID:
2257 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002258 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002259 break;
2260 case Type::UIntTyID: {
2261 // Make a 64 bit temporary... and zero out the top of it...
2262 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002263 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2264 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002265 SrcTy = Type::LongTy;
2266 SrcClass = cLong;
2267 SrcReg = TmpReg;
2268 break;
2269 }
2270 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002271 // Don't fild into the read destination.
2272 DestReg = makeAnotherReg(Type::DoubleTy);
2273 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002274 default: // No promotion needed...
2275 break;
2276 }
2277
2278 if (PromoteType) {
2279 unsigned TmpReg = makeAnotherReg(PromoteType);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002280 unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
Chris Lattneree352852004-02-29 07:22:16 +00002281 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002282 SrcTy = PromoteType;
2283 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00002284 SrcReg = TmpReg;
2285 }
2286
2287 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002288 int FrameIdx =
2289 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00002290
2291 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002292 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002293 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002294 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002295 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002296 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002297 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00002298 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2299 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002300 }
2301
2302 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002303 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00002304 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002305
2306 // We need special handling for unsigned 64-bit integer sources. If the
2307 // input number has the "sign bit" set, then we loaded it incorrectly as a
2308 // negative 64-bit number. In this case, add an offset value.
2309 if (SrcTy == Type::ULongTy) {
2310 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002311 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002312
Chris Lattnerb6bac512004-02-25 06:13:04 +00002313 // If the sign bit is set, get a pointer to an offset, otherwise get a
2314 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002315 MachineConstantPool *CP = F->getConstantPool();
2316 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002317 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002318 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002319 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002320 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002321 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2322
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002323 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002324 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002325 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002326 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002327
2328 // Load the constant for an add. FIXME: this could make an 'fadd' that
2329 // reads directly from memory, but we don't support these yet.
2330 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002331 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002332
Chris Lattneree352852004-02-29 07:22:16 +00002333 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2334 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002335 }
2336
Chris Lattner3e130a22003-01-13 00:32:26 +00002337 return;
2338 }
2339
2340 // Handle casts from floating point to integer now...
2341 if (SrcClass == cFP) {
2342 // Change the floating point control register to use "round towards zero"
2343 // mode when truncating to an integer value.
2344 //
2345 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002346 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002347
2348 // Load the old value of the high byte of the control word...
2349 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002350 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00002351 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002352
2353 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002354 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002355 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00002356
2357 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002358 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002359
2360 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002361 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002362 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00002363
2364 // We don't have the facilities for directly storing byte sized data to
2365 // memory. Promote it to 16 bits. We also must promote unsigned values to
2366 // larger classes because we only have signed FP stores.
2367 unsigned StoreClass = DestClass;
2368 const Type *StoreTy = DestTy;
2369 if (StoreClass == cByte || DestTy->isUnsigned())
2370 switch (StoreClass) {
2371 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2372 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2373 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00002374 // The following treatment of cLong may not be perfectly right,
2375 // but it survives chains of casts of the form
2376 // double->ulong->double.
2377 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00002378 default: assert(0 && "Unknown store class!");
2379 }
2380
2381 // Spill the integer to memory and reload it from there...
2382 int FrameIdx =
2383 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2384
2385 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002386 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00002387 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2388 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002389
2390 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002391 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2392 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00002393 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00002394 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002395 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00002396 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002397 }
2398
2399 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002400 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002401 return;
2402 }
2403
Brian Gaeked474e9c2002-12-06 10:49:33 +00002404 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00002405 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002406 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00002407}
Brian Gaekea1719c92002-10-31 23:03:59 +00002408
Chris Lattner73815062003-10-18 05:56:40 +00002409/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00002410///
Chris Lattner73815062003-10-18 05:56:40 +00002411void ISel::visitVANextInst(VANextInst &I) {
2412 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00002413 unsigned DestReg = getReg(I);
2414
Chris Lattnereca195e2003-05-08 19:44:13 +00002415 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00002416 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00002417 default:
2418 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00002419 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002420 return;
2421 case Type::PointerTyID:
2422 case Type::UIntTyID:
2423 case Type::IntTyID:
2424 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00002425 break;
2426 case Type::ULongTyID:
2427 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00002428 case Type::DoubleTyID:
2429 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00002430 break;
2431 }
2432
2433 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002434 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00002435}
Chris Lattnereca195e2003-05-08 19:44:13 +00002436
Chris Lattner73815062003-10-18 05:56:40 +00002437void ISel::visitVAArgInst(VAArgInst &I) {
2438 unsigned VAList = getReg(I.getOperand(0));
2439 unsigned DestReg = getReg(I);
2440
2441 switch (I.getType()->getPrimitiveID()) {
2442 default:
2443 std::cerr << I;
2444 assert(0 && "Error: bad type for va_next instruction!");
2445 return;
2446 case Type::PointerTyID:
2447 case Type::UIntTyID:
2448 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002449 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002450 break;
2451 case Type::ULongTyID:
2452 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002453 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2454 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00002455 break;
2456 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002457 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002458 break;
2459 }
Chris Lattnereca195e2003-05-08 19:44:13 +00002460}
2461
Misha Brukman538607f2004-03-01 23:53:11 +00002462/// visitGetElementPtrInst - instruction-select GEP instructions
2463///
Chris Lattner3e130a22003-01-13 00:32:26 +00002464void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00002465 // If this GEP instruction will be folded into all of its users, we don't need
2466 // to explicitly calculate it!
2467 unsigned A, B, C, D;
2468 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2469 // Check all of the users of the instruction to see if they are loads and
2470 // stores.
2471 bool AllWillFold = true;
2472 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2473 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2474 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2475 cast<Instruction>(*UI)->getOperand(0) == &I) {
2476 AllWillFold = false;
2477 break;
2478 }
2479
2480 // If the instruction is foldable, and will be folded into all users, don't
2481 // emit it!
2482 if (AllWillFold) return;
2483 }
2484
Chris Lattner3e130a22003-01-13 00:32:26 +00002485 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00002486 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00002487 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00002488}
2489
Chris Lattner985fe3d2004-02-25 03:45:50 +00002490/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2491/// GEPTypes (the derived types being stepped through at each level). On return
2492/// from this function, if some indexes of the instruction are representable as
2493/// an X86 lea instruction, the machine operands are put into the Ops
2494/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2495/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2496/// addressing mode that only partially consumes the input, the BaseReg input of
2497/// the addressing mode must be left free.
2498///
2499/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2500///
Chris Lattnerb6bac512004-02-25 06:13:04 +00002501void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2502 std::vector<Value*> &GEPOps,
2503 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2504 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2505 const TargetData &TD = TM.getTargetData();
2506
Chris Lattner985fe3d2004-02-25 03:45:50 +00002507 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002508 BaseReg = 0; // No base register
2509 Scale = 1; // Unit scale
2510 IndexReg = 0; // No index register
2511 Disp = 0; // No displacement
2512
Chris Lattner985fe3d2004-02-25 03:45:50 +00002513 // While there are GEP indexes that can be folded into the current address,
2514 // keep processing them.
2515 while (!GEPTypes.empty()) {
2516 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2517 // It's a struct access. CUI is the index into the structure,
2518 // which names the field. This index must have unsigned type.
2519 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2520
2521 // Use the TargetData structure to pick out what the layout of the
2522 // structure is in memory. Since the structure index must be constant, we
2523 // can get its value and use it to find the right byte offset from the
2524 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00002525 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00002526 GEPOps.pop_back(); // Consume a GEP operand
2527 GEPTypes.pop_back();
2528 } else {
2529 // It's an array or pointer access: [ArraySize x ElementType].
2530 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2531 Value *idx = GEPOps.back();
2532
2533 // idx is the index into the array. Unlike with structure
2534 // indices, we may not know its actual value at code-generation
2535 // time.
2536 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2537
2538 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002539 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00002540 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002541 Disp += TypeSize*CSI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00002542 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002543 // If the index reg is already taken, we can't handle this index.
2544 if (IndexReg) return;
2545
2546 // If this is a size that we can handle, then add the index as
2547 switch (TypeSize) {
2548 case 1: case 2: case 4: case 8:
2549 // These are all acceptable scales on X86.
2550 Scale = TypeSize;
2551 break;
2552 default:
2553 // Otherwise, we can't handle this scale
2554 return;
2555 }
2556
2557 if (CastInst *CI = dyn_cast<CastInst>(idx))
2558 if (CI->getOperand(0)->getType() == Type::IntTy ||
2559 CI->getOperand(0)->getType() == Type::UIntTy)
2560 idx = CI->getOperand(0);
2561
2562 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00002563 }
2564
2565 GEPOps.pop_back(); // Consume a GEP operand
2566 GEPTypes.pop_back();
2567 }
2568 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00002569
2570 // GEPTypes is empty, which means we have a single operand left. See if we
2571 // can set it as the base register.
2572 //
2573 // FIXME: When addressing modes are more powerful/correct, we could load
2574 // global addresses directly as 32-bit immediates.
2575 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002576 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002577 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00002578}
2579
2580
Chris Lattnerb6bac512004-02-25 06:13:04 +00002581/// isGEPFoldable - Return true if the specified GEP can be completely
2582/// folded into the addressing mode of a load/store or lea instruction.
2583bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2584 Value *Src, User::op_iterator IdxBegin,
2585 User::op_iterator IdxEnd, unsigned &BaseReg,
2586 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00002587 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2588 Src = CPR->getValue();
2589
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002590 std::vector<Value*> GEPOps;
2591 GEPOps.resize(IdxEnd-IdxBegin+1);
2592 GEPOps[0] = Src;
2593 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2594
2595 std::vector<const Type*> GEPTypes;
2596 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2597 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2598
Chris Lattnerb6bac512004-02-25 06:13:04 +00002599 MachineBasicBlock::iterator IP;
2600 if (MBB) IP = MBB->end();
2601 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2602
2603 // We can fold it away iff the getGEPIndex call eliminated all operands.
2604 return GEPOps.empty();
2605}
2606
2607void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2608 MachineBasicBlock::iterator IP,
2609 Value *Src, User::op_iterator IdxBegin,
2610 User::op_iterator IdxEnd, unsigned TargetReg) {
2611 const TargetData &TD = TM.getTargetData();
2612 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2613 Src = CPR->getValue();
2614
2615 std::vector<Value*> GEPOps;
2616 GEPOps.resize(IdxEnd-IdxBegin+1);
2617 GEPOps[0] = Src;
2618 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2619
2620 std::vector<const Type*> GEPTypes;
2621 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2622 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00002623
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002624 // Keep emitting instructions until we consume the entire GEP instruction.
2625 while (!GEPOps.empty()) {
2626 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00002627 unsigned BaseReg, Scale, IndexReg, Disp;
2628 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002629
Chris Lattner985fe3d2004-02-25 03:45:50 +00002630 if (GEPOps.size() != OldSize) {
2631 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00002632 unsigned NextTarget = 0;
2633 if (!GEPOps.empty()) {
2634 assert(BaseReg == 0 &&
2635 "getGEPIndex should have left the base register open for chaining!");
2636 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00002637 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00002638
2639 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002640 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002641 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002642 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002643 BaseReg, Scale, IndexReg, Disp);
2644 --IP;
2645 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00002646 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002647 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2648 // all operands are consumed but the base pointer. If so, just load it
2649 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00002650 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002651 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00002652 } else {
2653 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002654 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00002655 }
2656 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00002657
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002658 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00002659 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002660 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2661 Value *idx = GEPOps.back();
2662 GEPOps.pop_back(); // Consume a GEP operand
2663 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00002664
Brian Gaeke20244b72002-12-12 15:33:40 +00002665 // idx is the index into the array. Unlike with structure
2666 // indices, we may not know its actual value at code-generation
2667 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00002668 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2669
Chris Lattnerf5854472003-06-21 16:01:24 +00002670 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2671 // operand on X86. Handle this case directly now...
2672 if (CastInst *CI = dyn_cast<CastInst>(idx))
2673 if (CI->getOperand(0)->getType() == Type::IntTy ||
2674 CI->getOperand(0)->getType() == Type::UIntTy)
2675 idx = CI->getOperand(0);
2676
Chris Lattner3e130a22003-01-13 00:32:26 +00002677 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00002678 // must find the size of the pointed-to type (Not coincidentally, the next
2679 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002680 const Type *ElTy = SqTy->getElementType();
2681 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00002682
2683 // If idxReg is a constant, we don't need to perform the multiply!
2684 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002685 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00002686 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002687 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002688 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00002689 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002690 --IP; // Insert the next instruction before this one.
2691 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002692 }
2693 } else if (elementSize == 1) {
2694 // If the element size is 1, we don't have to multiply, just add
2695 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002696 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002697 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002698 --IP; // Insert the next instruction before this one.
2699 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002700 } else {
2701 unsigned idxReg = getReg(idx, MBB, IP);
2702 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002703
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002704 // Make sure we can back the iterator up to point to the first
2705 // instruction emitted.
2706 MachineBasicBlock::iterator BeforeIt = IP;
2707 if (IP == MBB->begin())
2708 BeforeIt = MBB->end();
2709 else
2710 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002711 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2712
Chris Lattner8a307e82002-12-16 19:32:50 +00002713 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002714 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002715 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00002716 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002717
2718 // Step to the first instruction of the multiply.
2719 if (BeforeIt == MBB->end())
2720 IP = MBB->begin();
2721 else
2722 IP = ++BeforeIt;
2723
2724 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002725 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002726 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002727 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002728}
2729
2730
Chris Lattner065faeb2002-12-28 20:24:02 +00002731/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2732/// frame manager, otherwise do it the hard way.
2733///
2734void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00002735 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00002736 const Type *Ty = I.getAllocatedType();
2737 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2738
2739 // If this is a fixed size alloca in the entry block for the function,
2740 // statically stack allocate the space.
2741 //
2742 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2743 if (I.getParent() == I.getParent()->getParent()->begin()) {
2744 TySize *= CUI->getValue(); // Get total allocated size...
2745 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2746
2747 // Create a new stack object using the frame manager...
2748 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002749 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
Chris Lattner065faeb2002-12-28 20:24:02 +00002750 return;
2751 }
2752 }
2753
2754 // Create a register to hold the temporary result of multiplying the type size
2755 // constant by the variable amount.
2756 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2757 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00002758
2759 // TotalSizeReg = mul <numelements>, <TypeSize>
2760 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00002761 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00002762
2763 // AddedSize = add <TotalSizeReg>, 15
2764 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002765 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00002766
2767 // AlignedSize = and <AddedSize>, ~15
2768 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002769 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00002770
Brian Gaekee48ec012002-12-13 06:46:31 +00002771 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002772 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00002773
Brian Gaekee48ec012002-12-13 06:46:31 +00002774 // Put a pointer to the space into the result register, by copying
2775 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002776 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00002777
Misha Brukman48196b32003-05-03 02:18:17 +00002778 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00002779 // object.
2780 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00002781}
Chris Lattner3e130a22003-01-13 00:32:26 +00002782
2783/// visitMallocInst - Malloc instructions are code generated into direct calls
2784/// to the library malloc.
2785///
2786void ISel::visitMallocInst(MallocInst &I) {
2787 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2788 unsigned Arg;
2789
2790 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2791 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2792 } else {
2793 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002794 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00002795 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00002796 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00002797 }
2798
2799 std::vector<ValueRecord> Args;
2800 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2801 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002802 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002803 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2804}
2805
2806
2807/// visitFreeInst - Free instructions are code gen'd to call the free libc
2808/// function.
2809///
2810void ISel::visitFreeInst(FreeInst &I) {
2811 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002812 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00002813 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002814 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002815 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2816}
2817
Chris Lattnerd281de22003-07-26 23:49:58 +00002818/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00002819/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00002820/// generated code sucks but the implementation is nice and simple.
2821///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00002822FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2823 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00002824}