blob: 5e6fd2fbd2d9352b543cf127aa7b07002f266f84 [file] [log] [blame]
Misha Brukman91b5ca82004-07-26 18:45:48 +00001//===-- X86ISelSimple.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"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000021#include "llvm/Pass.h"
Chris Lattner30483732004-06-20 07:49:54 +000022#include "llvm/CodeGen/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000023#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"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner986618e2004-02-22 19:47:26 +000034namespace {
35 Statistic<>
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
Chris Lattner427aeb42004-04-11 19:21:59 +000037
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39 /// Representation.
40 ///
41 enum TypeClass {
42 cByte, cShort, cInt, cFP, cLong
43 };
44}
45
46/// getClass - Turn a primitive type into a "class" number which is based on the
47/// size of the type, and whether or not it is floating point.
48///
49static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000050 switch (Ty->getTypeID()) {
Chris Lattner427aeb42004-04-11 19:21:59 +000051 case Type::SByteTyID:
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::ShortTyID:
54 case Type::UShortTyID: return cShort; // Short operands are class #1
55 case Type::IntTyID:
56 case Type::UIntTyID:
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
58
59 case Type::FloatTyID:
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
61
62 case Type::LongTyID:
63 case Type::ULongTyID: return cLong; // Longs are class #4
64 default:
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
67 }
68}
69
70// getClassB - Just like getClass, but treat boolean values as bytes.
71static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
73 return getClass(Ty);
Chris Lattner986618e2004-02-22 19:47:26 +000074}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000075
Chris Lattner72614082002-10-25 22:55:53 +000076namespace {
Misha Brukmaneae1bf12004-09-21 18:21:21 +000077 struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000078 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000079 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000082 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000083
Chris Lattner72614082002-10-25 22:55:53 +000084 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
85
Chris Lattner333b2fa2002-12-13 10:09:43 +000086 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
Chris Lattnercb2fd552004-05-13 07:40:27 +000089 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
92
Misha Brukmaneae1bf12004-09-21 18:21:21 +000093 X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000094
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
97 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000098 bool runOnFunction(Function &Fn) {
Chris Lattner11cf7aa2004-12-17 00:07:46 +000099 // Lazily create a stack slot for the return address if needed.
Chris Lattner8cdbc352004-12-17 00:46:51 +0000100 ReturnAddressIndex = 0;
Chris Lattner11cf7aa2004-12-17 00:07:46 +0000101
Chris Lattner44827152003-12-28 09:47:19 +0000102 // First pass over the function, lower any unknown intrinsic functions
103 // with the IntrinsicLowering class.
104 LowerUnknownIntrinsicFunctionCalls(Fn);
105
Chris Lattner36b36032002-10-29 23:40:58 +0000106 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000107
Chris Lattner065faeb2002-12-28 20:24:02 +0000108 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000109 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
110 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
111
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000112 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000113
Chris Lattnerdbd73722003-05-06 21:32:22 +0000114 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000115 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000116
Chris Lattnerc0354c92004-12-13 17:23:11 +0000117 // If this is main, emit special code.
118 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
119 EmitSpecialCodeForMain();
120
Chris Lattner333b2fa2002-12-13 10:09:43 +0000121 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000122 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000123
124 // Select the PHI nodes
125 SelectPHINodes();
126
Chris Lattner986618e2004-02-22 19:47:26 +0000127 // Insert the FP_REG_KILL instructions into blocks that need them.
128 InsertFPRegKills();
129
Chris Lattner72614082002-10-25 22:55:53 +0000130 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000131 MBBMap.clear();
Chris Lattnercb2fd552004-05-13 07:40:27 +0000132 AllocaMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000133 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000134 // We always build a machine code representation for the function
135 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000136 }
137
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000138 virtual const char *getPassName() const {
139 return "X86 Simple Instruction Selection";
140 }
141
Chris Lattnerc0354c92004-12-13 17:23:11 +0000142 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
143 /// the main function.
144 void EmitSpecialCodeForMain();
145
Chris Lattner72614082002-10-25 22:55:53 +0000146 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000147 /// block. This simply creates a new MachineBasicBlock to emit code into
148 /// and adds it to the current MachineFunction. Subsequent visit* for
149 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000150 ///
151 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000152 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000153 }
154
Chris Lattner44827152003-12-28 09:47:19 +0000155 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
156 /// function, lowering any calls to unknown intrinsic functions into the
157 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000158 ///
Chris Lattner44827152003-12-28 09:47:19 +0000159 void LowerUnknownIntrinsicFunctionCalls(Function &F);
160
Chris Lattner065faeb2002-12-28 20:24:02 +0000161 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
162 /// from the stack into virtual registers.
163 ///
164 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000165
166 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
167 /// because we have to generate our sources into the source basic blocks,
168 /// not the current one.
169 ///
170 void SelectPHINodes();
171
Chris Lattner986618e2004-02-22 19:47:26 +0000172 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
173 /// that need them. This only occurs due to the floating point stackifier
174 /// not being aggressive enough to handle arbitrary global stackification.
175 ///
176 void InsertFPRegKills();
177
Chris Lattner72614082002-10-25 22:55:53 +0000178 // Visitation methods for various instructions. These methods simply emit
179 // fixed X86 code for each instruction.
180 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000181
182 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000183 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000184 void visitBranchInst(BranchInst &BI);
Chris Lattner30483b02004-10-16 18:13:05 +0000185 void visitUnreachableInst(UnreachableInst &UI) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000186
187 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000188 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000189 unsigned Reg;
190 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000191 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
192 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000193 };
194 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000195 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000196 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000197 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000198
199 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000200 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000201 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
202 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerca9671d2002-11-02 20:28:58 +0000203 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000204
Chris Lattnerf01729e2002-11-02 20:54:46 +0000205 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
206 void visitRem(BinaryOperator &B) { visitDivRem(B); }
207 void visitDivRem(BinaryOperator &B);
208
Chris Lattnere2954c82002-11-02 20:04:26 +0000209 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000210 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
211 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
212 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000213
Chris Lattner6d40c192003-01-16 16:43:00 +0000214 // Comparison operators...
215 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000216 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
217 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000218 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000219 void visitSelectInst(SelectInst &SI);
220
Chris Lattnerb2acc512003-10-19 21:09:10 +0000221
Chris Lattner6fc3c522002-11-17 21:11:55 +0000222 // Memory Instructions
223 void visitLoadInst(LoadInst &I);
224 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000225 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000226 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000227 void visitMallocInst(MallocInst &I);
228 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000229
Chris Lattnere2954c82002-11-02 20:04:26 +0000230 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000231 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000232 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000233 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000234 void visitVANextInst(VANextInst &I);
235 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000236
237 void visitInstruction(Instruction &I) {
238 std::cerr << "Cannot instruction select: " << I;
239 abort();
240 }
241
Brian Gaeke95780cc2002-12-13 07:56:18 +0000242 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000243 ///
244 void promote32(unsigned targetReg, const ValueRecord &VR);
245
Chris Lattner721d2d42004-03-08 01:18:36 +0000246 /// getAddressingMode - Get the addressing mode to use to address the
247 /// specified value. The returned value should be used with addFullAddress.
Reid Spencerfc989e12004-08-30 00:13:26 +0000248 void getAddressingMode(Value *Addr, X86AddressMode &AM);
Chris Lattner721d2d42004-03-08 01:18:36 +0000249
250
251 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
252 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000253 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
254 std::vector<Value*> &GEPOps,
Reid Spencerfc989e12004-08-30 00:13:26 +0000255 std::vector<const Type*> &GEPTypes,
256 X86AddressMode &AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +0000257
258 /// isGEPFoldable - Return true if the specified GEP can be completely
259 /// folded into the addressing mode of a load/store or lea instruction.
260 bool isGEPFoldable(MachineBasicBlock *MBB,
261 Value *Src, User::op_iterator IdxBegin,
Reid Spencerfc989e12004-08-30 00:13:26 +0000262 User::op_iterator IdxEnd, X86AddressMode &AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +0000263
Chris Lattner3e130a22003-01-13 00:32:26 +0000264 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
265 /// constant expression GEP support.
266 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000267 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000268 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000269 User::op_iterator IdxEnd, unsigned TargetReg);
270
Chris Lattner548f61d2003-04-23 17:22:12 +0000271 /// emitCastOperation - Common code shared between visitCastInst and
272 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000273 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000274 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000275 Value *Src, const Type *DestTy, unsigned TargetReg);
276
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000277 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
278 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000279 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000280 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000281 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000282 Value *Op0, Value *Op1,
283 unsigned OperatorClass, unsigned TargetReg);
284
Chris Lattner6621ed92004-04-11 21:23:56 +0000285 /// emitBinaryFPOperation - This method handles emission of floating point
286 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
287 void emitBinaryFPOperation(MachineBasicBlock *BB,
288 MachineBasicBlock::iterator IP,
289 Value *Op0, Value *Op1,
290 unsigned OperatorClass, unsigned TargetReg);
291
Chris Lattner462fa822004-04-11 20:56:28 +0000292 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
293 Value *Op0, Value *Op1, unsigned TargetReg);
294
295 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
296 unsigned DestReg, const Type *DestTy,
297 unsigned Op0Reg, unsigned Op1Reg);
298 void doMultiplyConst(MachineBasicBlock *MBB,
299 MachineBasicBlock::iterator MBBI,
300 unsigned DestReg, const Type *DestTy,
301 unsigned Op0Reg, unsigned Op1Val);
302
Chris Lattnercadff442003-10-23 17:21:43 +0000303 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000304 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +0000305 Value *Op0, Value *Op1, bool isDiv,
306 unsigned TargetReg);
Chris Lattnercadff442003-10-23 17:21:43 +0000307
Chris Lattner58c41fe2003-08-24 19:19:47 +0000308 /// emitSetCCOperation - Common code shared between visitSetCondInst and
309 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000310 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000311 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000312 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000313 Value *Op0, Value *Op1, unsigned Opcode,
314 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000315
316 /// emitShiftOperation - Common code shared between visitShiftInst and
317 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000318 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000319 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000320 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000321 Value *Op, Value *ShiftAmount, bool isLeftShift,
322 const Type *ResultTy, unsigned DestReg);
Chris Lattnerce7cafa2004-11-13 20:48:57 +0000323
324 // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
325 // constant.
326 void doSHLDConst(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator MBBI,
328 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
329 unsigned Op1Val);
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000330
Chris Lattner12d96a02004-03-30 21:22:00 +0000331 /// emitSelectOperation - Common code shared between visitSelectInst and the
332 /// constant expression support.
333 void emitSelectOperation(MachineBasicBlock *MBB,
334 MachineBasicBlock::iterator IP,
335 Value *Cond, Value *TrueVal, Value *FalseVal,
336 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000337
Chris Lattnerc5291f52002-10-27 21:16:59 +0000338 /// copyConstantToRegister - Output the instructions required to put the
339 /// specified constant into the specified register.
340 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000341 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000342 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000343 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000344
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000345 void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
346 unsigned LHS, unsigned RHS);
347
Chris Lattner3e130a22003-01-13 00:32:26 +0000348 /// makeAnotherReg - This method returns the next register number we haven't
349 /// yet used.
350 ///
351 /// Long values are handled somewhat specially. They are always allocated
352 /// as pairs of 32 bit integer values. The register number returned is the
353 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
354 /// of the long value.
355 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000356 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000357 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
358 "Current target doesn't have X86 reg info??");
359 const X86RegisterInfo *MRI =
360 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000361 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000362 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
363 // Create the lower part
364 F->getSSARegMap()->createVirtualRegister(RC);
365 // Create the upper part.
366 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000367 }
368
Chris Lattnerc0812d82002-12-13 06:56:29 +0000369 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000370 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000371 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000372 }
373
Chris Lattnercb2fd552004-05-13 07:40:27 +0000374 /// getReg - This method turns an LLVM value into a register number.
Chris Lattner72614082002-10-25 22:55:53 +0000375 ///
376 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000377 unsigned getReg(Value *V) {
378 // Just append to the end of the current bb.
379 MachineBasicBlock::iterator It = BB->end();
380 return getReg(V, BB, It);
381 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000382 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnercb2fd552004-05-13 07:40:27 +0000383 MachineBasicBlock::iterator IPt);
Chris Lattner427aeb42004-04-11 19:21:59 +0000384
Chris Lattnercb2fd552004-05-13 07:40:27 +0000385 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
386 /// that is to be statically allocated with the initial stack frame
387 /// adjustment.
388 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
Chris Lattner72614082002-10-25 22:55:53 +0000389 };
390}
391
Chris Lattnercb2fd552004-05-13 07:40:27 +0000392/// dyn_castFixedAlloca - If the specified value is a fixed size alloca
393/// instruction in the entry block, return it. Otherwise, return a null
394/// pointer.
395static AllocaInst *dyn_castFixedAlloca(Value *V) {
396 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
397 BasicBlock *BB = AI->getParent();
398 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
399 return AI;
400 }
401 return 0;
402}
403
404/// getReg - This method turns an LLVM value into a register number.
405///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000406unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
407 MachineBasicBlock::iterator IPt) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000408 // If this operand is a constant, emit the code to copy the constant into
409 // the register here...
Chris Lattnercb2fd552004-05-13 07:40:27 +0000410 if (Constant *C = dyn_cast<Constant>(V)) {
411 unsigned Reg = makeAnotherReg(V->getType());
412 copyConstantToRegister(MBB, IPt, C, Reg);
413 return Reg;
Chris Lattnercb2fd552004-05-13 07:40:27 +0000414 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chris Lattner8b486a12004-06-29 00:14:38 +0000415 // Do not emit noop casts at all, unless it's a double -> float cast.
416 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
417 (CI->getType() != Type::FloatTy ||
418 CI->getOperand(0)->getType() != Type::DoubleTy))
Chris Lattnercb2fd552004-05-13 07:40:27 +0000419 return getReg(CI->getOperand(0), MBB, IPt);
420 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
421 // If the alloca address couldn't be folded into the instruction addressing,
422 // emit an explicit LEA as appropriate.
423 unsigned Reg = makeAnotherReg(V->getType());
424 unsigned FI = getFixedSizedAllocaFI(AI);
425 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
426 return Reg;
427 }
428
429 unsigned &Reg = RegMap[V];
430 if (Reg == 0) {
431 Reg = makeAnotherReg(V->getType());
432 RegMap[V] = Reg;
433 }
434
435 return Reg;
436}
437
438/// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
439/// that is to be statically allocated with the initial stack frame
440/// adjustment.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000441unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000442 // Already computed this?
443 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
444 if (I != AllocaMap.end() && I->first == AI) return I->second;
445
446 const Type *Ty = AI->getAllocatedType();
447 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
448 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
449 TySize *= CUI->getValue(); // Get total allocated size...
450 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
451
452 // Create a new stack object using the frame manager...
453 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
454 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
455 return FrameIdx;
456}
457
458
Chris Lattnerc5291f52002-10-27 21:16:59 +0000459/// copyConstantToRegister - Output the instructions required to put the
460/// specified constant into the specified register.
461///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000462void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
463 MachineBasicBlock::iterator IP,
464 Constant *C, unsigned R) {
Chris Lattner30483b02004-10-16 18:13:05 +0000465 if (isa<UndefValue>(C)) {
466 switch (getClassB(C->getType())) {
467 case cFP:
468 // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
469 BuildMI(*MBB, IP, X86::FLD0, 0, R);
470 return;
471 case cLong:
472 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
473 // FALL THROUGH
474 default:
475 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
476 return;
477 }
478 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000479 unsigned Class = 0;
480 switch (CE->getOpcode()) {
481 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000482 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000483 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000484 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000485 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000486 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000487 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000488
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000489 case Instruction::Xor: ++Class; // FALL THROUGH
490 case Instruction::Or: ++Class; // FALL THROUGH
491 case Instruction::And: ++Class; // FALL THROUGH
492 case Instruction::Sub: ++Class; // FALL THROUGH
493 case Instruction::Add:
494 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
495 Class, R);
496 return;
497
Chris Lattner462fa822004-04-11 20:56:28 +0000498 case Instruction::Mul:
499 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
Chris Lattnercadff442003-10-23 17:21:43 +0000500 return;
Chris Lattner462fa822004-04-11 20:56:28 +0000501
Chris Lattnercadff442003-10-23 17:21:43 +0000502 case Instruction::Div:
Chris Lattner462fa822004-04-11 20:56:28 +0000503 case Instruction::Rem:
504 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
505 CE->getOpcode() == Instruction::Div, R);
Chris Lattnercadff442003-10-23 17:21:43 +0000506 return;
Chris Lattnercadff442003-10-23 17:21:43 +0000507
Chris Lattner58c41fe2003-08-24 19:19:47 +0000508 case Instruction::SetNE:
509 case Instruction::SetEQ:
510 case Instruction::SetLT:
511 case Instruction::SetGT:
512 case Instruction::SetLE:
513 case Instruction::SetGE:
514 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
515 CE->getOpcode(), R);
516 return;
517
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000518 case Instruction::Shl:
519 case Instruction::Shr:
520 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000521 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
522 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000523
Chris Lattner12d96a02004-03-30 21:22:00 +0000524 case Instruction::Select:
525 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
526 CE->getOperand(2), R);
527 return;
528
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000529 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000530 std::cerr << "Offending expr: " << *C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000531 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000532 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000533 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000534
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000535 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000536 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000537
538 if (Class == cLong) {
539 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000540 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000541 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
542 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000543 return;
544 }
545
Chris Lattner94af4142002-12-25 05:13:53 +0000546 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000547
548 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000549 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000550 };
551
Chris Lattner6b993cc2002-12-15 08:02:15 +0000552 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000553 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000554 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000555 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000556 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000557 }
Chris Lattner94af4142002-12-25 05:13:53 +0000558 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000559 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000560 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000561 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000562 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner5384b382005-01-05 16:30:14 +0000563 else { // FIXME: PI, other native values
564 // FIXME: Could handle -1.0 with FLD1/FCHS
565 // FIXME: 2*PI -> LDPI + FADD
566
567 // Otherwise we need to spill the constant to memory.
Chris Lattner3e130a22003-01-13 00:32:26 +0000568 MachineConstantPool *CP = F->getConstantPool();
Chris Lattner5384b382005-01-05 16:30:14 +0000569
Chris Lattner6c09db22003-10-20 04:11:23 +0000570 const Type *Ty = CFP->getType();
571
Chris Lattner5384b382005-01-05 16:30:14 +0000572 // If a FP immediate is precise when represented as a float, we put it
573 // into the constant pool as a float, even if it's is statically typed as
574 // a double.
575 if (Ty == Type::DoubleTy)
576 if (CFP->isExactlyValue((float)CFP->getValue())) {
577 Ty = Type::FloatTy;
578 CFP = cast<ConstantFP>(ConstantExpr::getCast(CFP, Ty));
579 }
580
581 unsigned CPI = CP->getConstantPoolIndex(CFP);
582
Chris Lattner6c09db22003-10-20 04:11:23 +0000583 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000584 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000585 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000586 }
587
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000588 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000589 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000590 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Reid Spencer8863f182004-07-18 00:38:32 +0000591 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
592 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000593 } else {
Chris Lattner76e2df22004-07-15 02:14:30 +0000594 std::cerr << "Offending constant: " << *C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000595 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000596 }
597}
598
Chris Lattner065faeb2002-12-28 20:24:02 +0000599/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
600/// the stack into virtual registers.
601///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000602void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000603 // Emit instructions to load the arguments... On entry to a function on the
604 // X86, the stack frame looks like this:
605 //
606 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000607 // [ESP + 4] -- first argument (leftmost lexically)
608 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000609 // ...
610 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000611 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000612 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000613
614 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000615 bool ArgLive = !I->use_empty();
616 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000617 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000618
Chris Lattner065faeb2002-12-28 20:24:02 +0000619 switch (getClassB(I->getType())) {
620 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000621 if (ArgLive) {
622 FI = MFI->CreateFixedObject(1, ArgOffset);
623 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
624 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000625 break;
626 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000627 if (ArgLive) {
628 FI = MFI->CreateFixedObject(2, ArgOffset);
629 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
630 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000631 break;
632 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000633 if (ArgLive) {
634 FI = MFI->CreateFixedObject(4, ArgOffset);
635 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
636 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000637 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000638 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000639 if (ArgLive) {
640 FI = MFI->CreateFixedObject(8, ArgOffset);
641 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
642 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
643 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000644 ArgOffset += 4; // longs require 4 additional bytes
645 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000646 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000647 if (ArgLive) {
648 unsigned Opcode;
649 if (I->getType() == Type::FloatTy) {
650 Opcode = X86::FLD32m;
651 FI = MFI->CreateFixedObject(4, ArgOffset);
652 } else {
653 Opcode = X86::FLD64m;
654 FI = MFI->CreateFixedObject(8, ArgOffset);
655 }
656 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000657 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000658 if (I->getType() == Type::DoubleTy)
659 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000660 break;
661 default:
662 assert(0 && "Unhandled argument type!");
663 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000664 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000665 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000666
667 // If the function takes variable number of arguments, add a frame offset for
668 // the start of the first vararg value... this is used to expand
669 // llvm.va_start.
670 if (Fn.getFunctionType()->isVarArg())
671 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000672}
673
Chris Lattnerc0354c92004-12-13 17:23:11 +0000674/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
675/// the main function.
676void X86ISel::EmitSpecialCodeForMain() {
677 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
678 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
679 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
680
681 // Set the high part to be 64-bit precision.
682 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
683 CWFrameIdx, 1).addImm(2);
684
685 // Reload the modified control word now.
686 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
687}
Chris Lattner065faeb2002-12-28 20:24:02 +0000688
Chris Lattner333b2fa2002-12-13 10:09:43 +0000689/// SelectPHINodes - Insert machine code to generate phis. This is tricky
690/// because we have to generate our sources into the source basic blocks, not
691/// the current one.
692///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000693void X86ISel::SelectPHINodes() {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000694 const TargetInstrInfo &TII = *TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000695 const Function &LF = *F->getFunction(); // The LLVM function...
696 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
697 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000698 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000699
700 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000701 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000702 for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
703 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
Chris Lattner3e130a22003-01-13 00:32:26 +0000704
Chris Lattner333b2fa2002-12-13 10:09:43 +0000705 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000706 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000707 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
708 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000709
710 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000711 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
712 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
713 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000714
Chris Lattnera6e73f12003-05-12 14:22:21 +0000715 // PHIValues - Map of blocks to incoming virtual registers. We use this
716 // so that we only initialize one incoming value for a particular block,
717 // even if the block has multiple entries in the PHI node.
718 //
719 std::map<MachineBasicBlock*, unsigned> PHIValues;
720
Chris Lattner333b2fa2002-12-13 10:09:43 +0000721 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
722 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000723 unsigned ValReg;
724 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
725 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000726
Chris Lattnera6e73f12003-05-12 14:22:21 +0000727 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
728 // We already inserted an initialization of the register for this
729 // predecessor. Recycle it.
730 ValReg = EntryIt->second;
731
732 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000733 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000734 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000735 Value *Val = PN->getIncomingValue(i);
736
737 // If this is a constant or GlobalValue, we may have to insert code
738 // into the basic block to compute it into a virtual register.
Reid Spencer8863f182004-07-18 00:38:32 +0000739 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000740 // Simple constants get emitted at the end of the basic block,
741 // before any terminator instructions. We "know" that the code to
742 // move a constant into a register will never clobber any flags.
743 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
Chris Lattnera81fc682003-10-19 00:26:11 +0000744 } else {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000745 // Because we don't want to clobber any values which might be in
746 // physical registers with the computation of this constant (which
747 // might be arbitrarily complex if it is a constant expression),
748 // just insert the computation at the top of the basic block.
749 MachineBasicBlock::iterator PI = PredMBB->begin();
750
751 // Skip over any PHI nodes though!
752 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
753 ++PI;
754
755 ValReg = getReg(Val, PredMBB, PI);
Chris Lattnera81fc682003-10-19 00:26:11 +0000756 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000757
758 // Remember that we inserted a value for this PHI for this predecessor
759 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
760 }
761
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000762 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000763 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000764 if (LongPhiMI) {
765 LongPhiMI->addRegOperand(ValReg+1);
766 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
767 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000768 }
Chris Lattner168aa902004-02-29 07:10:16 +0000769
770 // Now that we emitted all of the incoming values for the PHI node, make
771 // sure to reposition the InsertPoint after the PHI that we just added.
772 // This is needed because we might have inserted a constant into this
773 // block, right after the PHI's which is before the old insert point!
774 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
775 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000776 }
777 }
778}
779
Chris Lattner986618e2004-02-22 19:47:26 +0000780/// RequiresFPRegKill - The floating point stackifier pass cannot insert
781/// compensation code on critical edges. As such, it requires that we kill all
782/// FP registers on the exit from any blocks that either ARE critical edges, or
783/// branch to a block that has incoming critical edges.
784///
785/// Note that this kill instruction will eventually be eliminated when
786/// restrictions in the stackifier are relaxed.
787///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000788static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000789#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000790 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000791 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
792 const BasicBlock *Succ = *SI;
793 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
794 ++PI; // Block have at least one predecessory
795 if (PI != PE) { // If it has exactly one, this isn't crit edge
796 // If this block has more than one predecessor, check all of the
797 // predecessors to see if they have multiple successors. If so, then the
798 // block we are analyzing needs an FPRegKill.
799 for (PI = pred_begin(Succ); PI != PE; ++PI) {
800 const BasicBlock *Pred = *PI;
801 succ_const_iterator SI2 = succ_begin(Pred);
802 ++SI2; // There must be at least one successor of this block.
803 if (SI2 != succ_end(Pred))
804 return true; // Yes, we must insert the kill on this edge.
805 }
806 }
807 }
808 // If we got this far, there is no need to insert the kill instruction.
809 return false;
810#else
811 return true;
812#endif
813}
814
815// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
816// need them. This only occurs due to the floating point stackifier not being
817// aggressive enough to handle arbitrary global stackification.
818//
819// Currently we insert an FP_REG_KILL instruction into each block that uses or
820// defines a floating point virtual register.
821//
822// When the global register allocators (like linear scan) finally update live
823// variable analysis, we can keep floating point values in registers across
824// portions of the CFG that do not involve critical edges. This will be a big
825// win, but we are waiting on the global allocators before we can do this.
826//
827// With a bit of work, the floating point stackifier pass can be enhanced to
828// break critical edges as needed (to make a place to put compensation code),
829// but this will require some infrastructure improvements as well.
830//
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000831void X86ISel::InsertFPRegKills() {
Chris Lattner986618e2004-02-22 19:47:26 +0000832 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000833
834 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000835 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000836 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
837 MachineOperand& MO = I->getOperand(i);
838 if (MO.isRegister() && MO.getReg()) {
839 unsigned Reg = MO.getReg();
Chris Lattner223d4c42004-12-03 05:13:15 +0000840 if (MRegisterInfo::isVirtualRegister(Reg)) {
841 unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
842 if (RegSize == 10 || RegSize == 8)
Chris Lattner65cf42d2004-02-23 07:29:45 +0000843 goto UsesFPReg;
Chris Lattner223d4c42004-12-03 05:13:15 +0000844 }
Chris Lattner986618e2004-02-22 19:47:26 +0000845 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000846 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000847 // If we haven't found an FP register use or def in this basic block, check
848 // to see if any of our successors has an FP PHI node, which will cause a
849 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000850 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
851 SE = BB->succ_end(); SI != SE; ++SI) {
852 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000853 for (MachineBasicBlock::iterator I = SBB->begin();
854 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
Chris Lattner39869242004-12-02 17:57:21 +0000855 const TargetRegisterClass *RC =
856 RegMap.getRegClass(I->getOperand(0).getReg());
857 if (RC->getSize() == 10 || RC->getSize() == 8)
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000858 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000859 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000860 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000861 continue;
862 UsesFPReg:
863 // Okay, this block uses an FP register. If the block has successors (ie,
864 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Chris Lattner5384b382005-01-05 16:30:14 +0000865 if (BB->succ_size() && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000866 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000867 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000868 }
869 }
870}
871
872
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000873void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
Reid Spencerfc989e12004-08-30 00:13:26 +0000874 AM.BaseType = X86AddressMode::RegBase;
875 AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000876 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
877 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000878 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000879 return;
880 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
881 if (CE->getOpcode() == Instruction::GetElementPtr)
882 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000883 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000884 return;
Reid Spencerfc989e12004-08-30 00:13:26 +0000885 } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
886 AM.BaseType = X86AddressMode::FrameIndexBase;
887 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
888 return;
Chris Lattner358a9022004-10-15 05:05:29 +0000889 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
890 AM.GV = GV;
891 return;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000892 }
893
894 // If it's not foldable, reset addr mode.
Reid Spencerfc989e12004-08-30 00:13:26 +0000895 AM.BaseType = X86AddressMode::RegBase;
896 AM.Base.Reg = getReg(Addr);
897 AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000898}
899
Chris Lattner307ecba2004-03-30 22:39:09 +0000900// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
901// it into the conditional branch or select instruction which is the only user
902// of the cc instruction. This is the case if the conditional branch is the
Chris Lattnera6f9fe62004-06-18 00:29:22 +0000903// only user of the setcc. We also don't handle long arguments below, so we
904// reject them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000905//
Chris Lattner307ecba2004-03-30 22:39:09 +0000906static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000907 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000908 if (SCI->hasOneUse()) {
909 Instruction *User = cast<Instruction>(SCI->use_back());
Tanya Lattner9855b842004-12-01 18:27:03 +0000910 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
911 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
912 SCI->getOpcode() == Instruction::SetEQ ||
913 SCI->getOpcode() == Instruction::SetNE) &&
914 (isa<BranchInst>(User) || User->getOperand(0) == V))
Chris Lattner6d40c192003-01-16 16:43:00 +0000915 return SCI;
916 }
917 return 0;
918}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000919
Chris Lattner6d40c192003-01-16 16:43:00 +0000920// Return a fixed numbering for setcc instructions which does not depend on the
921// order of the opcodes.
922//
923static unsigned getSetCCNumber(unsigned Opcode) {
924 switch(Opcode) {
925 default: assert(0 && "Unknown setcc instruction!");
926 case Instruction::SetEQ: return 0;
927 case Instruction::SetNE: return 1;
928 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000929 case Instruction::SetGE: return 3;
930 case Instruction::SetGT: return 4;
931 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000932 }
933}
Chris Lattner06925362002-11-17 21:56:38 +0000934
Chris Lattner6d40c192003-01-16 16:43:00 +0000935// LLVM -> X86 signed X86 unsigned
936// ----- ---------- ------------
937// seteq -> sete sete
938// setne -> setne setne
939// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000940// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000941// setgt -> setg seta
942// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000943// ----
944// sets // Used by comparison with 0 optimization
945// setns
946static const unsigned SetCCOpcodeTab[2][8] = {
947 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
948 0, 0 },
949 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
950 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000951};
952
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000953/// emitUCOMr - In the future when we support processors before the P6, this
954/// wraps the logic for emitting an FUCOMr vs FUCOMIr.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000955void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
956 unsigned LHS, unsigned RHS) {
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000957 if (0) { // for processors prior to the P6
958 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
959 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
960 BuildMI(*MBB, IP, X86::SAHF, 1);
961 } else {
962 BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
963 }
964}
965
Chris Lattnerb2acc512003-10-19 21:09:10 +0000966// EmitComparison - This function emits a comparison of the two operands,
967// returning the extended setcc code to use.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000968unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
969 MachineBasicBlock *MBB,
970 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000971 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000972 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000973 unsigned Class = getClassB(CompTy);
Chris Lattner333864d2003-06-05 19:30:30 +0000974
975 // Special case handling of: cmp R, i
Chris Lattner260195d2004-05-07 19:55:55 +0000976 if (isa<ConstantPointerNull>(Op1)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +0000977 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner260195d2004-05-07 19:55:55 +0000978 if (OpNum < 2) // seteq/setne -> test
979 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
980 else
981 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
982 return OpNum;
983
984 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere80e6372004-04-06 16:02:27 +0000985 if (Class == cByte || Class == cShort || Class == cInt) {
986 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000987
Chris Lattner333864d2003-06-05 19:30:30 +0000988 // Mask off any upper bits of the constant, if there are any...
989 Op1v &= (1ULL << (8 << Class)) - 1;
990
Chris Lattnerb2acc512003-10-19 21:09:10 +0000991 // If this is a comparison against zero, emit more efficient code. We
992 // can't handle unsigned comparisons against zero unless they are == or
993 // !=. These should have been strength reduced already anyway.
994 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +0000995
996 // If this is a comparison against zero and the LHS is an and of a
997 // register with a constant, use the test to do the and.
998 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
999 if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
1000 isa<ConstantInt>(Op0I->getOperand(1))) {
1001 static const unsigned TESTTab[] = {
1002 X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
1003 };
1004
1005 // Emit test X, i
1006 unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
1007 unsigned Imm =
1008 cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
1009 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
1010
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001011 if (OpNum == 2) return 6; // Map jl -> js
1012 if (OpNum == 3) return 7; // Map jg -> jns
1013 return OpNum;
1014 }
1015
1016 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001017 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001018 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +00001019 };
Chris Lattneree352852004-02-29 07:22:16 +00001020 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001021
1022 if (OpNum == 2) return 6; // Map jl -> js
1023 if (OpNum == 3) return 7; // Map jg -> jns
1024 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +00001025 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001026
1027 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001028 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +00001029 };
1030
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001031 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001032 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001033 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001034 } else {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001035 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnere80e6372004-04-06 16:02:27 +00001036 assert(Class == cLong && "Unknown integer class!");
1037 unsigned LowCst = CI->getRawValue();
1038 unsigned HiCst = CI->getRawValue() >> 32;
1039 if (OpNum < 2) { // seteq, setne
1040 unsigned LoTmp = Op0r;
1041 if (LowCst != 0) {
1042 LoTmp = makeAnotherReg(Type::IntTy);
1043 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1044 }
1045 unsigned HiTmp = Op0r+1;
1046 if (HiCst != 0) {
1047 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +00001048 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +00001049 }
1050 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1051 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1052 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +00001053 } else {
Tanya Lattner9855b842004-12-01 18:27:03 +00001054 // Emit a sequence of code which compares the high and low parts once
1055 // each, then uses a conditional move to handle the overflow case. For
1056 // example, a setlt for long would generate code like this:
1057 //
1058 // AL = lo(op1) < lo(op2) // Always unsigned comparison
1059 // BL = hi(op1) < hi(op2) // Signedness depends on operands
1060 // dest = hi(op1) == hi(op2) ? BL : AL;
1061 //
1062
1063 // FIXME: This would be much better if we had hierarchical register
1064 // classes! Until then, hardcode registers so that we can deal with
1065 // their aliases (because we don't have conditional byte moves).
1066 //
1067 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1068 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1069 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1070 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1071 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1072 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1073 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1074 .addReg(X86::AX);
1075 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1076 // register at this point for long values...
Chris Lattner48c937e2004-04-06 17:34:50 +00001077 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001078 }
Chris Lattner333864d2003-06-05 19:30:30 +00001079 }
Chris Lattnere80e6372004-04-06 16:02:27 +00001080 }
Chris Lattner333864d2003-06-05 19:30:30 +00001081
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001082 unsigned Op0r = getReg(Op0, MBB, IP);
1083
Chris Lattner9f08a922004-02-03 18:54:04 +00001084 // Special case handling of comparison against +/- 0.0
1085 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1086 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +00001087 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001088 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00001089 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +00001090 return OpNum;
1091 }
1092
Chris Lattner58c41fe2003-08-24 19:19:47 +00001093 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001094 switch (Class) {
1095 default: assert(0 && "Unknown type class!");
1096 // Emit: cmp <var1>, <var2> (do the comparison). We can
1097 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1098 // 32-bit.
1099 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001100 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001101 break;
1102 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001103 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001104 break;
1105 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001106 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001107 break;
1108 case cFP:
Chris Lattner01cdb1b2004-06-11 05:33:49 +00001109 emitUCOMr(MBB, IP, Op0r, Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001110 break;
1111
1112 case cLong:
1113 if (OpNum < 2) { // seteq, setne
1114 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1115 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1116 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001117 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1118 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1119 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001120 break; // Allow the sete or setne to be generated from flags set by OR
1121 } else {
1122 // Emit a sequence of code which compares the high and low parts once
1123 // each, then uses a conditional move to handle the overflow case. For
1124 // example, a setlt for long would generate code like this:
1125 //
1126 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1127 // BL = hi(op1) < hi(op2) // Always unsigned comparison
Chris Lattner9984fd02004-05-09 23:16:33 +00001128 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner3e130a22003-01-13 00:32:26 +00001129 //
1130
Chris Lattner6d40c192003-01-16 16:43:00 +00001131 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +00001132 // classes! Until then, hardcode registers so that we can deal with their
1133 // aliases (because we don't have conditional byte moves).
1134 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001135 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +00001136 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001137 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +00001138 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1139 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1140 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001141 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +00001142 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +00001143 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1144 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +00001145 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +00001146 }
1147 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001148 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +00001149}
Chris Lattner3e130a22003-01-13 00:32:26 +00001150
Chris Lattner6d40c192003-01-16 16:43:00 +00001151/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1152/// register, then move it to wherever the result should be.
1153///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001154void X86ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +00001155 if (canFoldSetCCIntoBranchOrSelect(&I))
1156 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +00001157
Chris Lattner6d40c192003-01-16 16:43:00 +00001158 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001159 MachineBasicBlock::iterator MII = BB->end();
1160 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1161 DestReg);
1162}
Chris Lattner6d40c192003-01-16 16:43:00 +00001163
Chris Lattner58c41fe2003-08-24 19:19:47 +00001164/// emitSetCCOperation - Common code shared between visitSetCondInst and
1165/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +00001166///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001167void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1168 MachineBasicBlock::iterator IP,
1169 Value *Op0, Value *Op1, unsigned Opcode,
1170 unsigned TargetReg) {
Chris Lattner58c41fe2003-08-24 19:19:47 +00001171 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001172 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001173
Chris Lattnerb2acc512003-10-19 21:09:10 +00001174 const Type *CompTy = Op0->getType();
1175 unsigned CompClass = getClassB(CompTy);
1176 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1177
Tanya Lattner9855b842004-12-01 18:27:03 +00001178 if (CompClass != cLong || OpNum < 2) {
1179 // Handle normal comparisons with a setcc instruction...
1180 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1181 } else {
1182 // Handle long comparisons by copying the value which is already in BL into
1183 // the register we want...
1184 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1185 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001186}
Chris Lattner51b49a92002-11-02 19:45:49 +00001187
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001188void X86ISel::visitSelectInst(SelectInst &SI) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001189 unsigned DestReg = getReg(SI);
1190 MachineBasicBlock::iterator MII = BB->end();
1191 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1192 SI.getFalseValue(), DestReg);
1193}
1194
1195/// emitSelect - Common code shared between visitSelectInst and the constant
1196/// expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001197void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1198 MachineBasicBlock::iterator IP,
1199 Value *Cond, Value *TrueVal, Value *FalseVal,
1200 unsigned DestReg) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001201 unsigned SelectClass = getClassB(TrueVal->getType());
1202
1203 // We don't support 8-bit conditional moves. If we have incoming constants,
1204 // transform them into 16-bit constants to avoid having a run-time conversion.
1205 if (SelectClass == cByte) {
1206 if (Constant *T = dyn_cast<Constant>(TrueVal))
1207 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1208 if (Constant *F = dyn_cast<Constant>(FalseVal))
1209 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1210 }
1211
Chris Lattner82c5a992004-04-13 21:56:09 +00001212 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1213 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1214 if (TrueReg == FalseReg) {
1215 static const unsigned Opcode[] = {
1216 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1217 };
1218 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1219 if (SelectClass == cLong)
1220 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1221 return;
1222 }
1223
Chris Lattner307ecba2004-03-30 22:39:09 +00001224 unsigned Opcode;
1225 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1226 // We successfully folded the setcc into the select instruction.
1227
1228 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1229 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1230 IP);
1231
1232 const Type *CompTy = SCI->getOperand(0)->getType();
1233 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1234
1235 // LLVM -> X86 signed X86 unsigned
1236 // ----- ---------- ------------
1237 // seteq -> cmovNE cmovNE
1238 // setne -> cmovE cmovE
1239 // setlt -> cmovGE cmovAE
1240 // setge -> cmovL cmovB
1241 // setgt -> cmovLE cmovBE
1242 // setle -> cmovG cmovA
1243 // ----
1244 // cmovNS // Used by comparison with 0 optimization
1245 // cmovS
1246
1247 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001248 default: assert(0 && "Unknown value class!");
1249 case cFP: {
1250 // Annoyingly, we don't have a full set of floating point conditional
1251 // moves. :(
1252 static const unsigned OpcodeTab[2][8] = {
1253 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1254 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1255 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1256 };
1257 Opcode = OpcodeTab[isSigned][OpNum];
1258
1259 // If opcode == 0, we hit a case that we don't support. Output a setcc
1260 // and compare the result against zero.
1261 if (Opcode == 0) {
1262 unsigned CompClass = getClassB(CompTy);
1263 unsigned CondReg;
1264 if (CompClass != cLong || OpNum < 2) {
1265 CondReg = makeAnotherReg(Type::BoolTy);
1266 // Handle normal comparisons with a setcc instruction...
1267 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1268 } else {
1269 // Long comparisons end up in the BL register.
1270 CondReg = X86::BL;
1271 }
1272
Chris Lattner68626c22004-03-31 22:22:36 +00001273 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001274 Opcode = X86::FCMOVE;
1275 }
1276 break;
1277 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001278 case cByte:
1279 case cShort: {
1280 static const unsigned OpcodeTab[2][8] = {
1281 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1282 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1283 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1284 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1285 };
1286 Opcode = OpcodeTab[isSigned][OpNum];
1287 break;
1288 }
1289 case cInt:
1290 case cLong: {
1291 static const unsigned OpcodeTab[2][8] = {
1292 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1293 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1294 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1295 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1296 };
1297 Opcode = OpcodeTab[isSigned][OpNum];
1298 break;
1299 }
1300 }
1301 } else {
1302 // Get the value being branched on, and use it to set the condition codes.
1303 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001304 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001305 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001306 default: assert(0 && "Unknown value class!");
1307 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001308 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001309 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001310 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001311 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001312 }
1313 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001314
Chris Lattner12d96a02004-03-30 21:22:00 +00001315 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001316
Chris Lattner12d96a02004-03-30 21:22:00 +00001317
1318 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1319 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1320 // cmove, then truncate the result.
1321 if (SelectClass == cByte) {
1322 DestReg = makeAnotherReg(Type::ShortTy);
1323 if (getClassB(TrueVal->getType()) == cByte) {
1324 // Promote the true value, by storing it into AL, and reading from AX.
1325 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1326 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1327 TrueReg = makeAnotherReg(Type::ShortTy);
1328 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1329 }
1330 if (getClassB(FalseVal->getType()) == cByte) {
1331 // Promote the true value, by storing it into CL, and reading from CX.
1332 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1333 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1334 FalseReg = makeAnotherReg(Type::ShortTy);
1335 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1336 }
1337 }
1338
1339 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1340
1341 switch (SelectClass) {
1342 case cByte:
1343 // We did the computation with 16-bit registers. Truncate back to our
1344 // result by copying into AX then copying out AL.
1345 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1346 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1347 break;
1348 case cLong:
1349 // Move the upper half of the value as well.
1350 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1351 break;
1352 }
1353}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001354
1355
1356
Brian Gaekec2505982002-11-30 11:57:28 +00001357/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1358/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001359///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001360void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
Chris Lattner9984fd02004-05-09 23:16:33 +00001361 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001362
Chris Lattner29bf0622004-04-06 01:21:00 +00001363 Value *Val = VR.Val;
1364 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001365 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001366 if (Constant *C = dyn_cast<Constant>(Val)) {
1367 Val = ConstantExpr::getCast(C, Type::IntTy);
1368 Ty = Type::IntTy;
1369 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001370
Chris Lattner502e36c2004-04-06 01:25:33 +00001371 // If this is a simple constant, just emit a MOVri directly to avoid the
1372 // copy.
1373 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1374 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
Chris Lattner2b10b082004-05-12 16:35:04 +00001375 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
Chris Lattner502e36c2004-04-06 01:25:33 +00001376 return;
1377 }
1378 }
1379
Chris Lattner29bf0622004-04-06 01:21:00 +00001380 // Make sure we have the register number for this value...
1381 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1382
1383 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001384 case cByte:
1385 // Extend value into target register (8->32)
1386 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001387 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001388 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001389 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001390 break;
1391 case cShort:
1392 // Extend value into target register (16->32)
1393 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001394 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001395 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001396 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001397 break;
1398 case cInt:
1399 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001400 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001401 break;
1402 default:
1403 assert(0 && "Unpromotable operand class in promote32");
1404 }
Brian Gaekec2505982002-11-30 11:57:28 +00001405}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001406
Chris Lattner72614082002-10-25 22:55:53 +00001407/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1408/// we have the following possibilities:
1409///
1410/// ret void: No return value, simply emit a 'ret' instruction
1411/// ret sbyte, ubyte : Extend value into EAX and return
1412/// ret short, ushort: Extend value into EAX and return
1413/// ret int, uint : Move value into EAX and return
1414/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001415/// ret long, ulong : Move value into EAX/EDX and return
1416/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001417///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001418void X86ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001419 if (I.getNumOperands() == 0) {
1420 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1421 return;
1422 }
1423
1424 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001425 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001426 case cByte: // integral return values: extend or move into EAX and return
1427 case cShort:
1428 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001429 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001430 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001431 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001432 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001433 case cFP: { // Floats & Doubles: Return in ST(0)
1434 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001435 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001436 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001437 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001438 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001439 }
1440 case cLong: {
1441 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001442 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1443 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001444 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001445 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1446 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001447 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001448 }
Chris Lattner94af4142002-12-25 05:13:53 +00001449 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001450 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001451 }
Chris Lattner43189d12002-11-17 20:07:45 +00001452 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001453 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001454}
1455
Chris Lattner55f6fab2003-01-16 18:07:23 +00001456// getBlockAfter - Return the basic block which occurs lexically after the
1457// specified one.
1458static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1459 Function::iterator I = BB; ++I; // Get iterator to next block
1460 return I != BB->getParent()->end() ? &*I : 0;
1461}
1462
Chris Lattner51b49a92002-11-02 19:45:49 +00001463/// visitBranchInst - Handle conditional and unconditional branches here. Note
1464/// that since code layout is frozen at this point, that if we are trying to
1465/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001466/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001467///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001468void X86ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001469 // Update machine-CFG edges
1470 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1471 if (BI.isConditional())
1472 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1473
Chris Lattner55f6fab2003-01-16 18:07:23 +00001474 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1475
1476 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001477 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001478 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner6d40c192003-01-16 16:43:00 +00001479 return;
1480 }
1481
1482 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001483 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001484 if (SCI == 0) {
1485 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1486 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001487 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001488 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001489 if (BI.getSuccessor(1) == NextBB) {
1490 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001491 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001492 } else {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001493 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001494
1495 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001496 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001497 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001498 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001499 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001500
1501 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001502 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001503 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001504
1505 const Type *CompTy = SCI->getOperand(0)->getType();
1506 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001507
Chris Lattnerb2acc512003-10-19 21:09:10 +00001508
Chris Lattner6d40c192003-01-16 16:43:00 +00001509 // LLVM -> X86 signed X86 unsigned
1510 // ----- ---------- ------------
1511 // seteq -> je je
1512 // setne -> jne jne
1513 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001514 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001515 // setgt -> jg ja
1516 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001517 // ----
1518 // js // Used by comparison with 0 optimization
1519 // jns
1520
1521 static const unsigned OpcodeTab[2][8] = {
1522 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1523 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1524 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001525 };
1526
Chris Lattner55f6fab2003-01-16 18:07:23 +00001527 if (BI.getSuccessor(0) != NextBB) {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001528 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1529 .addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001530 if (BI.getSuccessor(1) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001531 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001532 } else {
1533 // Change to the inverse condition...
1534 if (BI.getSuccessor(1) != NextBB) {
1535 OpNum ^= 1;
Brian Gaeke9f088e42004-05-14 06:54:56 +00001536 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1537 .addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001538 }
1539 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001540}
1541
Chris Lattner3e130a22003-01-13 00:32:26 +00001542
1543/// doCall - This emits an abstract call instruction, setting up the arguments
1544/// and the return value as appropriate. For the actual function call itself,
1545/// it inserts the specified CallMI instruction into the stream.
1546///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001547void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1548 const std::vector<ValueRecord> &Args) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001549 // Count how many bytes are to be pushed on the stack...
1550 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001551
Chris Lattner3e130a22003-01-13 00:32:26 +00001552 if (!Args.empty()) {
1553 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1554 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001555 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001556 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001557 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001558 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001559 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001560 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1561 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001562 default: assert(0 && "Unknown class!");
1563 }
1564
1565 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001566 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001567
1568 // Arguments go on the stack in reverse order, as specified by the ABI.
1569 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001570 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001571 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001572 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001573 case cByte:
Chris Lattner2b10b082004-05-12 16:35:04 +00001574 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1575 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1576 .addImm(Args[i].Val == ConstantBool::True);
1577 break;
1578 }
1579 // FALL THROUGH
Chris Lattner21585222004-03-01 02:42:43 +00001580 case cShort:
1581 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1582 // Zero/Sign extend constant, then stuff into memory.
1583 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1584 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1585 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1586 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1587 } else {
1588 // Promote arg to 32 bits wide into a temporary register...
1589 ArgReg = makeAnotherReg(Type::UIntTy);
1590 promote32(ArgReg, Args[i]);
1591 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1592 X86::ESP, ArgOffset).addReg(ArgReg);
1593 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001594 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001595 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001596 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1597 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1598 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1599 X86::ESP, ArgOffset).addImm(Val);
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00001600 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1601 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1602 X86::ESP, ArgOffset).addImm(0);
Chris Lattner21585222004-03-01 02:42:43 +00001603 } else {
1604 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1605 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1606 X86::ESP, ArgOffset).addReg(ArgReg);
1607 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001608 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001609 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001610 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1611 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1612 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1613 X86::ESP, ArgOffset).addImm(Val & ~0U);
1614 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1615 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1616 } else {
1617 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1618 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1619 X86::ESP, ArgOffset).addReg(ArgReg);
1620 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1621 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1622 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001623 ArgOffset += 4; // 8 byte entry, not 4.
1624 break;
1625
Chris Lattner065faeb2002-12-28 20:24:02 +00001626 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001627 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001628 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001629 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001630 X86::ESP, ArgOffset).addReg(ArgReg);
1631 } else {
1632 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001633 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001634 X86::ESP, ArgOffset).addReg(ArgReg);
1635 ArgOffset += 4; // 8 byte entry, not 4.
1636 }
1637 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001638
Chris Lattner3e130a22003-01-13 00:32:26 +00001639 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001640 }
1641 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001642 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001643 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001644 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001645 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001646
Chris Lattner3e130a22003-01-13 00:32:26 +00001647 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001648
Chris Lattneree352852004-02-29 07:22:16 +00001649 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001650
1651 // If there is a return value, scavenge the result from the location the call
1652 // leaves it in...
1653 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001654 if (Ret.Ty != Type::VoidTy) {
1655 unsigned DestClass = getClassB(Ret.Ty);
1656 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001657 case cByte:
1658 case cShort:
1659 case cInt: {
1660 // Integral results are in %eax, or the appropriate portion
1661 // thereof.
1662 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001663 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001664 };
1665 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001666 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001667 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001668 }
Chris Lattner94af4142002-12-25 05:13:53 +00001669 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001670 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001671 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001672 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001673 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1674 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001675 break;
1676 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001677 }
Chris Lattnera3243642002-12-04 23:45:28 +00001678 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001679}
Chris Lattner2df035b2002-11-02 19:27:56 +00001680
Chris Lattner3e130a22003-01-13 00:32:26 +00001681
1682/// visitCallInst - Push args on stack and do a procedure call instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001683void X86ISel::visitCallInst(CallInst &CI) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001684 MachineInstr *TheCall;
1685 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001686 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001687 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001688 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1689 return;
1690 }
1691
Chris Lattner3e130a22003-01-13 00:32:26 +00001692 // Emit a CALL instruction with PC-relative displacement.
1693 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1694 } else { // Emit an indirect call...
1695 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001696 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001697 }
1698
1699 std::vector<ValueRecord> Args;
1700 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001701 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001702
1703 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1704 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001705}
Chris Lattner3e130a22003-01-13 00:32:26 +00001706
Chris Lattner44827152003-12-28 09:47:19 +00001707/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1708/// function, lowering any calls to unknown intrinsic functions into the
1709/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001710///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001711void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
Chris Lattner44827152003-12-28 09:47:19 +00001712 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1713 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1714 if (CallInst *CI = dyn_cast<CallInst>(I++))
1715 if (Function *F = CI->getCalledFunction())
1716 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001717 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001718 case Intrinsic::vastart:
1719 case Intrinsic::vacopy:
1720 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001721 case Intrinsic::returnaddress:
1722 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001723 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001724 case Intrinsic::memset:
Chris Lattnerdc572442004-06-15 21:36:44 +00001725 case Intrinsic::isunordered:
John Criswell4ffff9e2004-04-08 20:31:47 +00001726 case Intrinsic::readport:
1727 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001728 // We directly implement these intrinsics
1729 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001730 case Intrinsic::readio: {
1731 // On X86, memory operations are in-order. Lower this intrinsic
1732 // into a volatile load.
1733 Instruction *Before = CI->getPrev();
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001734 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1735 CI->replaceAllUsesWith(LI);
1736 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001737 break;
1738 }
1739 case Intrinsic::writeio: {
1740 // On X86, memory operations are in-order. Lower this intrinsic
1741 // into a volatile store.
1742 Instruction *Before = CI->getPrev();
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001743 StoreInst *LI = new StoreInst(CI->getOperand(1),
1744 CI->getOperand(2), true, CI);
1745 CI->replaceAllUsesWith(LI);
1746 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001747 break;
1748 }
Chris Lattner44827152003-12-28 09:47:19 +00001749 default:
1750 // All other intrinsic calls we must lower.
1751 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001752 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001753 if (Before) { // Move iterator to instruction after call
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001754 I = Before; ++I;
Chris Lattner44827152003-12-28 09:47:19 +00001755 } else {
1756 I = BB->begin();
1757 }
1758 }
Chris Lattner44827152003-12-28 09:47:19 +00001759}
1760
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001761void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001762 unsigned TmpReg1, TmpReg2;
1763 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001764 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001765 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001766 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001767 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001768 return;
1769
Chris Lattner5634b9f2004-03-13 00:24:52 +00001770 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001771 TmpReg1 = getReg(CI);
1772 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001773 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001774 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001775 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001776
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001777 case Intrinsic::returnaddress:
1778 case Intrinsic::frameaddress:
1779 TmpReg1 = getReg(CI);
1780 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
Chris Lattner8cdbc352004-12-17 00:46:51 +00001781 if (ReturnAddressIndex == 0) {
Chris Lattner11cf7aa2004-12-17 00:07:46 +00001782 // Set up a frame object for the return address.
1783 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
1784 }
1785
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001786 if (ID == Intrinsic::returnaddress) {
1787 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001788 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001789 ReturnAddressIndex);
1790 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001791 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001792 ReturnAddressIndex, -4);
1793 }
1794 } else {
1795 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001796 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001797 }
1798 return;
1799
Chris Lattnerdc572442004-06-15 21:36:44 +00001800 case Intrinsic::isunordered:
1801 TmpReg1 = getReg(CI.getOperand(1));
1802 TmpReg2 = getReg(CI.getOperand(2));
1803 emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1804 TmpReg2 = getReg(CI);
1805 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1806 return;
1807
Chris Lattner915e5e52004-02-12 17:53:22 +00001808 case Intrinsic::memcpy: {
1809 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1810 unsigned Align = 1;
1811 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1812 Align = AlignC->getRawValue();
1813 if (Align == 0) Align = 1;
1814 }
1815
1816 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001817 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001818 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001819 switch (Align & 3) {
1820 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001821 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1822 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1823 } else {
1824 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001825 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001826 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001827 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001828 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001829 break;
1830 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001831 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1832 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1833 } else {
1834 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001835 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001836 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001837 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001838 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001839 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001840 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001841 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001842 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001843 break;
1844 }
1845
1846 // No matter what the alignment is, we put the source in ESI, the
1847 // destination in EDI, and the count in ECX.
1848 TmpReg1 = getReg(CI.getOperand(1));
1849 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001850 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1851 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1852 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001853 BuildMI(BB, Opcode, 0);
1854 return;
1855 }
1856 case Intrinsic::memset: {
1857 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1858 unsigned Align = 1;
1859 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1860 Align = AlignC->getRawValue();
1861 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001862 }
1863
Chris Lattner2a0f2242004-02-14 04:46:05 +00001864 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001865 unsigned CountReg;
1866 unsigned Opcode;
1867 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1868 unsigned Val = ValC->getRawValue() & 255;
1869
1870 // If the value is a constant, then we can potentially use larger copies.
1871 switch (Align & 3) {
1872 case 2: // WORD aligned
1873 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001874 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001875 } else {
1876 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001877 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001878 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001879 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001880 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001881 Opcode = X86::REP_STOSW;
1882 break;
1883 case 0: // DWORD aligned
1884 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001885 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001886 } else {
1887 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001888 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001889 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001890 }
1891 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001892 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001893 Opcode = X86::REP_STOSD;
1894 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001895 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001896 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001897 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001898 Opcode = X86::REP_STOSB;
1899 break;
1900 }
1901 } else {
1902 // If it's not a constant value we are storing, just fall back. We could
1903 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1904 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001905 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001906 CountReg = getReg(CI.getOperand(3));
1907 Opcode = X86::REP_STOSB;
1908 }
1909
1910 // No matter what the alignment is, we put the source in ESI, the
1911 // destination in EDI, and the count in ECX.
1912 TmpReg1 = getReg(CI.getOperand(1));
1913 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001914 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1915 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001916 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001917 return;
1918 }
1919
Chris Lattner87e18de2004-04-13 17:20:37 +00001920 case Intrinsic::readport: {
1921 // First, determine that the size of the operand falls within the acceptable
1922 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001923 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001924 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001925 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001926 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001927 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001928
John Criswell4ffff9e2004-04-08 20:31:47 +00001929 // Now, move the I/O port address into the DX register and use the IN
1930 // instruction to get the input data.
1931 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001932 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1933 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001934
Chris Lattner87e18de2004-04-13 17:20:37 +00001935 // If the port is a single-byte constant, use the immediate form.
1936 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1937 if ((C->getRawValue() & 255) == C->getRawValue()) {
1938 switch (Class) {
1939 case cByte:
1940 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1941 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1942 return;
1943 case cShort:
1944 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1945 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1946 return;
1947 case cInt:
1948 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1949 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1950 return;
1951 }
1952 }
1953
1954 unsigned Reg = getReg(CI.getOperand(1));
1955 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1956 switch (Class) {
1957 case cByte:
1958 BuildMI(BB, X86::IN8rr, 0);
1959 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1960 break;
1961 case cShort:
1962 BuildMI(BB, X86::IN16rr, 0);
1963 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1964 break;
1965 case cInt:
1966 BuildMI(BB, X86::IN32rr, 0);
1967 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1968 break;
1969 default:
1970 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00001971 exit (1);
1972 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001973 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00001974 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001975
Chris Lattner87e18de2004-04-13 17:20:37 +00001976 case Intrinsic::writeport: {
1977 // First, determine that the size of the operand falls within the
1978 // acceptable range for this architecture.
1979 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1980 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1981 exit(1);
1982 }
1983
1984 unsigned Class = getClassB(CI.getOperand(1)->getType());
1985 unsigned ValReg = getReg(CI.getOperand(1));
1986 switch (Class) {
1987 case cByte:
1988 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1989 break;
1990 case cShort:
1991 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1992 break;
1993 case cInt:
1994 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1995 break;
1996 default:
1997 std::cerr << "llvm.writeport: invalid data type for X86 target";
1998 exit(1);
1999 }
2000
2001
2002 // If the port is a single-byte constant, use the immediate form.
2003 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
2004 if ((C->getRawValue() & 255) == C->getRawValue()) {
2005 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
2006 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
2007 return;
2008 }
2009
2010 // Otherwise, move the I/O port address into the DX register and the value
2011 // to write into the AL/AX/EAX register.
2012 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
2013 unsigned Reg = getReg(CI.getOperand(2));
2014 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
2015 BuildMI(BB, Opc[Class], 0);
2016 return;
2017 }
2018
Chris Lattner44827152003-12-28 09:47:19 +00002019 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002020 }
2021}
2022
Chris Lattner7dee5da2004-03-08 01:58:35 +00002023static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
2024 if (LI.getParent() != User.getParent())
2025 return false;
2026 BasicBlock::iterator It = &LI;
2027 // Check all of the instructions between the load and the user. We should
2028 // really use alias analysis here, but for now we just do something simple.
2029 for (++It; It != BasicBlock::iterator(&User); ++It) {
2030 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00002031 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00002032 case Instruction::Store:
2033 case Instruction::Call:
2034 case Instruction::Invoke:
2035 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00002036 case Instruction::Load:
2037 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
2038 return false;
2039 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002040 }
2041 }
2042 return true;
2043}
2044
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002045/// visitSimpleBinary - Implement simple binary operators for integral types...
2046/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2047/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00002048///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002049void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002050 unsigned DestReg = getReg(B);
2051 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00002052 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002053 unsigned Class = getClassB(B.getType());
Chris Lattner721d2d42004-03-08 01:18:36 +00002054
Chris Lattnerde95c9e2004-10-17 06:10:40 +00002055 // If this is AND X, C, and it is only used by a setcc instruction, it will
2056 // be folded. There is no need to emit this instruction.
2057 if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2058 if (Class == cByte || Class == cShort || Class == cInt) {
2059 Instruction *Use = cast<Instruction>(B.use_back());
2060 if (isa<SetCondInst>(Use) &&
2061 Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2062 switch (getSetCCNumber(Use->getOpcode())) {
2063 case 0:
2064 case 1:
2065 return;
2066 default:
2067 if (B.getType()->isSigned()) return;
2068 }
2069 }
2070 }
2071
Chris Lattner7dee5da2004-03-08 01:58:35 +00002072 // Special case: op Reg, load [mem]
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002073 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattnerccd97962004-06-17 22:15:25 +00002074 Op0->hasOneUse() &&
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002075 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
Chris Lattner7dee5da2004-03-08 01:58:35 +00002076 if (!B.swapOperands())
2077 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2078
Chris Lattnerccd97962004-06-17 22:15:25 +00002079 if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00002080 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2081
Chris Lattner95157f72004-04-11 22:05:45 +00002082 unsigned Opcode;
2083 if (Class != cFP) {
2084 static const unsigned OpcodeTab[][3] = {
2085 // Arithmetic operators
2086 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
2087 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
2088
2089 // Bitwise operators
2090 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
2091 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
2092 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
2093 };
2094 Opcode = OpcodeTab[OperatorClass][Class];
2095 } else {
2096 static const unsigned OpcodeTab[][2] = {
2097 { X86::FADD32m, X86::FADD64m }, // ADD
2098 { X86::FSUB32m, X86::FSUB64m }, // SUB
2099 };
2100 const Type *Ty = Op0->getType();
2101 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2102 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2103 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002104
Chris Lattner7dee5da2004-03-08 01:58:35 +00002105 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002106 if (AllocaInst *AI =
2107 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2108 unsigned FI = getFixedSizedAllocaFI(AI);
2109 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2110
2111 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002112 X86AddressMode AM;
2113 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002114
Reid Spencerfc989e12004-08-30 00:13:26 +00002115 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002116 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002117 return;
2118 }
2119
Chris Lattner95157f72004-04-11 22:05:45 +00002120 // If this is a floating point subtract, check to see if we can fold the first
2121 // operand in.
2122 if (Class == cFP && OperatorClass == 1 &&
2123 isa<LoadInst>(Op0) &&
2124 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2125 const Type *Ty = Op0->getType();
2126 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2127 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2128
Chris Lattner95157f72004-04-11 22:05:45 +00002129 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002130 if (AllocaInst *AI =
2131 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2132 unsigned FI = getFixedSizedAllocaFI(AI);
2133 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2134 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002135 X86AddressMode AM;
2136 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002137
Reid Spencerfc989e12004-08-30 00:13:26 +00002138 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002139 }
Chris Lattner95157f72004-04-11 22:05:45 +00002140 return;
2141 }
2142
Chris Lattner721d2d42004-03-08 01:18:36 +00002143 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002144}
Chris Lattner3e130a22003-01-13 00:32:26 +00002145
Chris Lattner6621ed92004-04-11 21:23:56 +00002146
2147/// emitBinaryFPOperation - This method handles emission of floating point
2148/// Add (0), Sub (1), Mul (2), and Div (3) operations.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002149void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2150 MachineBasicBlock::iterator IP,
2151 Value *Op0, Value *Op1,
2152 unsigned OperatorClass, unsigned DestReg) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002153 // Special case: op Reg, <const fp>
2154 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2155 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2156 // Create a constant pool entry for this constant.
2157 MachineConstantPool *CP = F->getConstantPool();
2158 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2159 const Type *Ty = Op1->getType();
2160
2161 static const unsigned OpcodeTab[][4] = {
2162 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2163 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2164 };
2165
2166 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2167 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2168 unsigned Op0r = getReg(Op0, BB, IP);
2169 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2170 DestReg).addReg(Op0r), CPI);
2171 return;
2172 }
2173
Chris Lattner13c07fe2004-04-12 00:12:04 +00002174 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00002175 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2176 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2177 // -0.0 - X === -X
2178 unsigned op1Reg = getReg(Op1, BB, IP);
2179 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2180 return;
2181 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00002182 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00002183
2184 // Create a constant pool entry for this constant.
2185 MachineConstantPool *CP = F->getConstantPool();
2186 unsigned CPI = CP->getConstantPoolIndex(CFP);
2187 const Type *Ty = CFP->getType();
2188
2189 static const unsigned OpcodeTab[][4] = {
2190 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2191 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2192 };
2193
2194 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2195 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2196 unsigned Op1r = getReg(Op1, BB, IP);
2197 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2198 DestReg).addReg(Op1r), CPI);
2199 return;
2200 }
2201
2202 // General case.
2203 static const unsigned OpcodeTab[4] = {
2204 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2205 };
2206
2207 unsigned Opcode = OpcodeTab[OperatorClass];
2208 unsigned Op0r = getReg(Op0, BB, IP);
2209 unsigned Op1r = getReg(Op1, BB, IP);
2210 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2211}
2212
Chris Lattnerb2acc512003-10-19 21:09:10 +00002213/// emitSimpleBinaryOperation - Implement simple binary operators for integral
2214/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2215/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00002216///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002217/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2218/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002219///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002220void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2221 MachineBasicBlock::iterator IP,
2222 Value *Op0, Value *Op1,
2223 unsigned OperatorClass,
2224 unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002225 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002226
Chris Lattner6621ed92004-04-11 21:23:56 +00002227 if (Class == cFP) {
2228 assert(OperatorClass < 2 && "No logical ops for FP!");
2229 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2230 return;
2231 }
2232
Chris Lattner48b0c972004-04-11 20:26:20 +00002233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
Chris Lattner667ea022004-06-18 00:50:37 +00002234 if (OperatorClass == 1) {
Chris Lattner48b0c972004-04-11 20:26:20 +00002235 static unsigned const NEGTab[] = {
2236 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2237 };
Chris Lattner667ea022004-06-18 00:50:37 +00002238
2239 // sub 0, X -> neg X
2240 if (CI->isNullValue()) {
2241 unsigned op1Reg = getReg(Op1, MBB, IP);
2242 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
Chris Lattner48b0c972004-04-11 20:26:20 +00002243
Chris Lattner667ea022004-06-18 00:50:37 +00002244 if (Class == cLong) {
2245 // We just emitted: Dl = neg Sl
2246 // Now emit : T = addc Sh, 0
2247 // : Dh = neg T
2248 unsigned T = makeAnotherReg(Type::IntTy);
2249 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2250 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2251 }
2252 return;
2253 } else if (Op1->hasOneUse() && Class != cLong) {
2254 // sub C, X -> tmp = neg X; DestReg = add tmp, C. This is better
2255 // than copying C into a temporary register, because of register
2256 // pressure (tmp and destreg can share a register.
2257 static unsigned const ADDRITab[] = {
2258 X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2259 };
2260 unsigned op1Reg = getReg(Op1, MBB, IP);
2261 unsigned Tmp = makeAnotherReg(Op0->getType());
2262 BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
Chris Lattner30483732004-06-20 07:49:54 +00002263 BuildMI(*MBB, IP, ADDRITab[Class], 2,
2264 DestReg).addReg(Tmp).addImm(CI->getRawValue());
Chris Lattner667ea022004-06-18 00:50:37 +00002265 return;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002266 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002267 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002268
Chris Lattner48b0c972004-04-11 20:26:20 +00002269 // Special case: op Reg, <const int>
2270 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002271 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002272
Chris Lattner721d2d42004-03-08 01:18:36 +00002273 // xor X, -1 -> not X
2274 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002275 static unsigned const NOTTab[] = {
2276 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2277 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002278 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002279 if (Class == cLong) // Invert the top part too
2280 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002281 return;
2282 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002283
Chris Lattner721d2d42004-03-08 01:18:36 +00002284 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002285 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2286 // Note that we can't use dec for 64-bit decrements, because it does not
2287 // set the carry flag!
2288 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002289 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2290 return;
2291 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002292
Chris Lattner721d2d42004-03-08 01:18:36 +00002293 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002294 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2295 // Note that we can't use inc for 64-bit increments, because it does not
2296 // set the carry flag!
2297 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002298 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002299 return;
2300 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002301
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002302 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002303 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002304 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2305 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002306
Chris Lattner721d2d42004-03-08 01:18:36 +00002307 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002308 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2309 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2310 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002311 };
2312
Chris Lattner721d2d42004-03-08 01:18:36 +00002313 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002314 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002315
Chris Lattner33f7fa32004-04-06 03:15:53 +00002316 if (Class != cLong) {
2317 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2318 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002319 }
2320
2321 // If this is a long value and the high or low bits have a special
2322 // property, emit some special cases.
2323 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2324
2325 // If the constant is zero in the low 32-bits, just copy the low part
2326 // across and apply the normal 32-bit operation to the high parts. There
2327 // will be no carry or borrow into the top.
2328 if (Op1l == 0) {
2329 if (OperatorClass != 2) // All but and...
2330 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2331 else
2332 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2333 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2334 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002335 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002336 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002337
2338 // If this is a logical operation and the top 32-bits are zero, just
2339 // operate on the lower 32.
2340 if (Op1h == 0 && OperatorClass > 1) {
2341 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2342 .addReg(Op0r).addImm(Op1l);
2343 if (OperatorClass != 2) // All but and
2344 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2345 else
2346 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2347 return;
2348 }
2349
2350 // TODO: We could handle lots of other special cases here, such as AND'ing
2351 // with 0xFFFFFFFF00000000 -> noop, etc.
2352
2353 // Otherwise, code generate the full operation with a constant.
2354 static const unsigned TopTab[] = {
2355 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2356 };
2357
2358 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2359 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2360 .addReg(Op0r+1).addImm(Op1h);
2361 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002362 }
2363
2364 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002365 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002366 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002367 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2368 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002369
Chris Lattnerb2acc512003-10-19 21:09:10 +00002370 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002371 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2372 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2373 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002374 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002375
Chris Lattnerb2acc512003-10-19 21:09:10 +00002376 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002377 unsigned Op0r = getReg(Op0, MBB, IP);
2378 unsigned Op1r = getReg(Op1, MBB, IP);
2379 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2380
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002381 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002382 static const unsigned TopTab[] = {
2383 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2384 };
2385 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2386 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2387 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002388}
2389
Chris Lattner3e130a22003-01-13 00:32:26 +00002390/// doMultiply - Emit appropriate instructions to multiply together the
2391/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2392/// result should be given as DestTy.
2393///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002394void X86ISel::doMultiply(MachineBasicBlock *MBB,
2395 MachineBasicBlock::iterator MBBI,
2396 unsigned DestReg, const Type *DestTy,
2397 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002398 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002399 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002400 case cInt:
2401 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002402 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002403 .addReg(op0Reg).addReg(op1Reg);
2404 return;
2405 case cByte:
2406 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002407 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2408 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2409 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002410 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002411 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002412 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002413 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002414}
2415
Chris Lattnerb2acc512003-10-19 21:09:10 +00002416// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2417// returns zero when the input is not exactly a power of two.
2418static unsigned ExactLog2(unsigned Val) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002419 if (Val == 0 || (Val & (Val-1))) return 0;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002420 unsigned Count = 0;
2421 while (Val != 1) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002422 Val >>= 1;
2423 ++Count;
2424 }
2425 return Count+1;
2426}
2427
Chris Lattner462fa822004-04-11 20:56:28 +00002428
2429/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2430/// 16, or 32-bit integer multiply by a constant.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002431void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2432 MachineBasicBlock::iterator IP,
2433 unsigned DestReg, const Type *DestTy,
2434 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002435 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2436 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002437 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
Chris Lattner596b97f2004-07-19 23:47:21 +00002438 static const unsigned NEGrTab[] = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
Chris Lattner6ab06d52004-04-06 04:55:43 +00002439
Chris Lattnerb2acc512003-10-19 21:09:10 +00002440 unsigned Class = getClass(DestTy);
Chris Lattner596b97f2004-07-19 23:47:21 +00002441 unsigned TmpReg;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002442
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002443 // Handle special cases here.
2444 switch (ConstRHS) {
Chris Lattner596b97f2004-07-19 23:47:21 +00002445 case -2:
2446 TmpReg = makeAnotherReg(DestTy);
2447 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2448 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2449 return;
2450 case -1:
2451 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2452 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002453 case 0:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002454 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2455 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002456 case 1:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002457 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2458 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002459 case 2:
2460 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2461 return;
2462 case 3:
2463 case 5:
2464 case 9:
2465 if (Class == cInt) {
Reid Spencerfc989e12004-08-30 00:13:26 +00002466 X86AddressMode AM;
2467 AM.BaseType = X86AddressMode::RegBase;
2468 AM.Base.Reg = op0Reg;
2469 AM.Scale = ConstRHS-1;
2470 AM.IndexReg = op0Reg;
2471 AM.Disp = 0;
2472 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002473 return;
2474 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002475 case -3:
2476 case -5:
2477 case -9:
2478 if (Class == cInt) {
2479 TmpReg = makeAnotherReg(DestTy);
Reid Spencerfc989e12004-08-30 00:13:26 +00002480 X86AddressMode AM;
2481 AM.BaseType = X86AddressMode::RegBase;
2482 AM.Base.Reg = op0Reg;
2483 AM.Scale = -ConstRHS-1;
2484 AM.IndexReg = op0Reg;
2485 AM.Disp = 0;
2486 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
Chris Lattner596b97f2004-07-19 23:47:21 +00002487 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2488 return;
2489 }
Chris Lattner6ab06d52004-04-06 04:55:43 +00002490 }
2491
Chris Lattnerb2acc512003-10-19 21:09:10 +00002492 // If the element size is exactly a power of 2, use a shift to get it.
2493 if (unsigned Shift = ExactLog2(ConstRHS)) {
2494 switch (Class) {
2495 default: assert(0 && "Unknown class for this function!");
2496 case cByte:
Chris Lattner596b97f2004-07-19 23:47:21 +00002497 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002498 return;
2499 case cShort:
Chris Lattner596b97f2004-07-19 23:47:21 +00002500 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002501 return;
2502 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002503 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002504 return;
2505 }
2506 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002507
2508 // If the element size is a negative power of 2, use a shift/neg to get it.
2509 if (unsigned Shift = ExactLog2(-ConstRHS)) {
2510 TmpReg = makeAnotherReg(DestTy);
2511 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2512 switch (Class) {
2513 default: assert(0 && "Unknown class for this function!");
2514 case cByte:
2515 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2516 return;
2517 case cShort:
2518 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2519 return;
2520 case cInt:
2521 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2522 return;
2523 }
2524 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002525
2526 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002527 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002528 return;
2529 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002530 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002531 return;
2532 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002533
2534 // Most general case, emit a normal multiply...
Chris Lattner596b97f2004-07-19 23:47:21 +00002535 TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002536 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002537
2538 // Emit a MUL to multiply the register holding the index by
2539 // elementSize, putting the result in OffsetReg.
2540 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2541}
2542
Chris Lattnerca9671d2002-11-02 20:28:58 +00002543/// visitMul - Multiplies are not simple binary operators because they must deal
2544/// with the EAX register explicitly.
2545///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002546void X86ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002547 unsigned ResultReg = getReg(I);
2548
Chris Lattner95157f72004-04-11 22:05:45 +00002549 Value *Op0 = I.getOperand(0);
2550 Value *Op1 = I.getOperand(1);
2551
2552 // Fold loads into floating point multiplies.
2553 if (getClass(Op0->getType()) == cFP) {
2554 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2555 if (!I.swapOperands())
2556 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2557 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2558 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2559 const Type *Ty = Op0->getType();
2560 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2561 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2562
Chris Lattner95157f72004-04-11 22:05:45 +00002563 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002564 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2565 unsigned FI = getFixedSizedAllocaFI(AI);
2566 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2567 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002568 X86AddressMode AM;
2569 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002570
Reid Spencerfc989e12004-08-30 00:13:26 +00002571 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002572 }
Chris Lattner95157f72004-04-11 22:05:45 +00002573 return;
2574 }
2575 }
2576
Chris Lattner462fa822004-04-11 20:56:28 +00002577 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002578 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002579}
2580
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002581void X86ISel::emitMultiply(MachineBasicBlock *MBB,
2582 MachineBasicBlock::iterator IP,
2583 Value *Op0, Value *Op1, unsigned DestReg) {
Chris Lattner462fa822004-04-11 20:56:28 +00002584 MachineBasicBlock &BB = *MBB;
2585 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002586
2587 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002588 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002589 switch (Class) {
2590 case cByte:
2591 case cShort:
2592 case cInt:
2593 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002594 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2595 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002596 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002597 unsigned Op1Reg = getReg(Op1, &BB, IP);
2598 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002599 }
Chris Lattner462fa822004-04-11 20:56:28 +00002600 return;
2601 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002602 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2603 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002604 case cLong:
2605 break;
2606 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002607
Chris Lattner462fa822004-04-11 20:56:28 +00002608 // Long value. We have to do things the hard way...
2609 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2610 unsigned CLow = CI->getRawValue();
2611 unsigned CHi = CI->getRawValue() >> 32;
2612
2613 if (CLow == 0) {
2614 // If the low part of the constant is all zeros, things are simple.
2615 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2616 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2617 return;
2618 }
2619
2620 // Multiply the two low parts... capturing carry into EDX
2621 unsigned OverflowReg = 0;
2622 if (CLow == 1) {
2623 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002624 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002625 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2626 OverflowReg = makeAnotherReg(Type::UIntTy);
2627 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2628 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2629 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002630
Chris Lattner462fa822004-04-11 20:56:28 +00002631 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2632 BuildMI(BB, IP, X86::MOV32rr, 1,
2633 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2634 }
2635
2636 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2637 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2638
2639 unsigned AHBLplusOverflowReg;
2640 if (OverflowReg) {
2641 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2642 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002643 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002644 } else {
2645 AHBLplusOverflowReg = AHBLReg;
2646 }
2647
2648 if (CHi == 0) {
2649 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2650 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002651 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002652 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002653
Chris Lattner462fa822004-04-11 20:56:28 +00002654 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002655 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2656 }
Chris Lattner462fa822004-04-11 20:56:28 +00002657 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002658 }
Chris Lattner462fa822004-04-11 20:56:28 +00002659
2660 // General 64x64 multiply
2661
2662 unsigned Op1Reg = getReg(Op1, &BB, IP);
2663 // Multiply the two low parts... capturing carry into EDX
2664 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2665 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2666
2667 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2668 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2669 BuildMI(BB, IP, X86::MOV32rr, 1,
2670 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2671
2672 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2673 BuildMI(BB, IP, X86::IMUL32rr, 2,
2674 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2675
2676 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2677 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2678 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2679
2680 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2681 BuildMI(BB, IP, X86::IMUL32rr, 2,
2682 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2683
2684 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2685 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002686}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002687
Chris Lattner06925362002-11-17 21:56:38 +00002688
Chris Lattnerf01729e2002-11-02 20:54:46 +00002689/// visitDivRem - Handle division and remainder instructions... these
2690/// instruction both require the same instructions to be generated, they just
2691/// select the result from a different register. Note that both of these
2692/// instructions work differently for signed and unsigned operands.
2693///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002694void X86ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002695 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2697
2698 // Fold loads into floating point divides.
2699 if (getClass(Op0->getType()) == cFP) {
2700 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2701 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2702 const Type *Ty = Op0->getType();
2703 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2704 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2705
Chris Lattner95157f72004-04-11 22:05:45 +00002706 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002707 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2708 unsigned FI = getFixedSizedAllocaFI(AI);
2709 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2710 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002711 X86AddressMode AM;
2712 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002713
Reid Spencerfc989e12004-08-30 00:13:26 +00002714 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002715 }
Chris Lattner95157f72004-04-11 22:05:45 +00002716 return;
2717 }
2718
2719 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2720 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2721 const Type *Ty = Op0->getType();
2722 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2723 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2724
Chris Lattner95157f72004-04-11 22:05:45 +00002725 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002726 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2727 unsigned FI = getFixedSizedAllocaFI(AI);
2728 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2729 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002730 X86AddressMode AM;
2731 getAddressingMode(LI->getOperand(0), AM);
2732 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002733 }
Chris Lattner95157f72004-04-11 22:05:45 +00002734 return;
2735 }
2736 }
2737
Chris Lattner94af4142002-12-25 05:13:53 +00002738
Chris Lattnercadff442003-10-23 17:21:43 +00002739 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002740 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002741 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002742}
2743
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002744void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2745 MachineBasicBlock::iterator IP,
2746 Value *Op0, Value *Op1, bool isDiv,
2747 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002748 const Type *Ty = Op0->getType();
2749 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002750 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002751 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002752 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002753 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2754 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002755 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002756 unsigned Op0Reg = getReg(Op0, BB, IP);
2757 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002758 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002759 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002760 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002761 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2762 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002763 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2764 }
Chris Lattner94af4142002-12-25 05:13:53 +00002765 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002766 case cLong: {
2767 static const char *FnName[] =
2768 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002769 unsigned Op0Reg = getReg(Op0, BB, IP);
2770 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002771 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002772 MachineInstr *TheCall =
2773 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2774
2775 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002776 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2777 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002778 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2779 return;
2780 }
2781 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002782 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002783 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002784 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002785
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002786 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
Chris Lattner2483f672004-10-06 05:01:07 +00002787 static const unsigned NEGOpcode[]={ X86::NEG8r, X86::NEG16r, X86::NEG32r };
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002788 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2789 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2790 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2791
2792 // Special case signed division by power of 2.
Chris Lattner2483f672004-10-06 05:01:07 +00002793 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2794 if (isDiv) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002795 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2796 int V = CI->getValue();
2797
2798 if (V == 1) { // X /s 1 => X
2799 unsigned Op0Reg = getReg(Op0, BB, IP);
2800 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2801 return;
2802 }
2803
2804 if (V == -1) { // X /s -1 => -X
2805 unsigned Op0Reg = getReg(Op0, BB, IP);
2806 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2807 return;
2808 }
2809
Chris Lattner610f1e22004-10-06 04:02:39 +00002810 if (V == 2 || V == -2) { // X /s 2
2811 static const unsigned CMPOpcode[] = {
2812 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2813 };
2814 static const unsigned SBBOpcode[] = {
2815 X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2816 };
2817 unsigned Op0Reg = getReg(Op0, BB, IP);
2818 unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2819 BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2820
2821 unsigned TmpReg = makeAnotherReg(Op0->getType());
2822 BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2823
2824 unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2825 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2826 if (V == -2) {
2827 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2828 }
2829 return;
2830 }
2831
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002832 bool isNeg = false;
2833 if (V < 0) { // Not a positive power of 2?
2834 V = -V;
2835 isNeg = true; // Maybe it's a negative power of 2.
2836 }
2837 if (unsigned Log = ExactLog2(V)) {
2838 --Log;
2839 unsigned Op0Reg = getReg(Op0, BB, IP);
2840 unsigned TmpReg = makeAnotherReg(Op0->getType());
Chris Lattner3ffdff62004-10-06 04:19:43 +00002841 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2842 .addReg(Op0Reg).addImm(Log-1);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002843 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2844 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2845 .addReg(TmpReg).addImm(32-Log);
2846 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2847 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2848 .addReg(Op0Reg).addReg(TmpReg2);
2849
2850 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2851 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
Chris Lattner3ffdff62004-10-06 04:19:43 +00002852 .addReg(TmpReg3).addImm(Log);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002853 if (isNeg)
2854 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2855 return;
2856 }
Chris Lattner2483f672004-10-06 05:01:07 +00002857 } else { // X % C
2858 assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2859 int V = CI->getValue();
2860
2861 if (V == 2 || V == -2) { // X % 2, X % -2
Chris Lattner2483f672004-10-06 05:01:07 +00002862 static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2863 static const unsigned BaseReg[] = { X86::AL , X86::AX , X86::EAX };
2864 static const unsigned SExtReg[] = { X86::AH , X86::DX , X86::EDX };
2865 static const unsigned ANDOpcode[] = {
2866 X86::AND8ri, X86::AND16ri, X86::AND32ri
2867 };
2868 static const unsigned XOROpcode[] = {
2869 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2870 };
2871 static const unsigned SUBOpcode[] = {
2872 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2873 };
2874
2875 // Sign extend result into reg of -1 or 0.
2876 unsigned Op0Reg = getReg(Op0, BB, IP);
2877 BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2878 BuildMI(*BB, IP, SExtOpcode[Class], 0);
2879 unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2880 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2881
2882 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2883 BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2884
2885 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2886 BuildMI(*BB, IP, XOROpcode[Class], 2,
2887 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2888 BuildMI(*BB, IP, SUBOpcode[Class], 2,
2889 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2890 return;
2891 }
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002892 }
2893
2894 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002895 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002896 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
Chris Lattner5384b382005-01-05 16:30:14 +00002897 static const unsigned SExOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002898
2899 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002900 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2901 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002902 };
2903
Chris Lattnerf01729e2002-11-02 20:54:46 +00002904 unsigned Reg = Regs[Class];
2905 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002906
2907 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002908 unsigned Op0Reg = getReg(Op0, BB, IP);
2909 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002910 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002911
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002912 if (Ty->isSigned()) {
Chris Lattner5384b382005-01-05 16:30:14 +00002913 // Emit a sign extension instruction.
2914 BuildMI(*BB, IP, SExOpcode[Class], 0);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002915
2916 // Emit the appropriate divide or remainder instruction...
2917 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002918 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002919 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002920 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002921
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002922 // Emit the appropriate divide or remainder instruction...
2923 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2924 }
Chris Lattner06925362002-11-17 21:56:38 +00002925
Chris Lattnerf01729e2002-11-02 20:54:46 +00002926 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002927 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002928
Chris Lattnerf01729e2002-11-02 20:54:46 +00002929 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002930 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002931}
Chris Lattnere2954c82002-11-02 20:04:26 +00002932
Chris Lattner06925362002-11-17 21:56:38 +00002933
Brian Gaekea1719c92002-10-31 23:03:59 +00002934/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2935/// for constant immediate shift values, and for constant immediate
2936/// shift values equal to 1. Even the general case is sort of special,
2937/// because the shift amount has to be in CL, not just any old register.
2938///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002939void X86ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002940 MachineBasicBlock::iterator IP = BB->end ();
2941 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2942 I.getOpcode () == Instruction::Shl, I.getType (),
2943 getReg (I));
2944}
2945
Chris Lattnerce7cafa2004-11-13 20:48:57 +00002946/// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2947/// constant.
2948void X86ISel::doSHLDConst(MachineBasicBlock *MBB,
2949 MachineBasicBlock::iterator IP,
2950 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2951 unsigned Amt) {
2952 // SHLD is a very inefficient operation on every processor, try to do
2953 // somethign simpler for common values of 'Amt'.
2954 if (Amt == 0) {
2955 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2956 } else if (Amt == 1) {
2957 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2958 BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
2959 BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2960 } else if (Amt == 2 || Amt == 3) {
2961 // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
2962 // shift/lea pair. NOTE: This should not be done on the P6 family!
2963 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2964 BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
2965 X86AddressMode AM;
2966 AM.BaseType = X86AddressMode::RegBase;
2967 AM.Base.Reg = Tmp;
2968 AM.Scale = 1 << Amt;
2969 AM.IndexReg = Op0Reg;
2970 AM.Disp = 0;
2971 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
2972 } else {
2973 // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
2974 // than it is to emit a real SHLD.
2975
2976 BuildMI(*MBB, IP, X86::SHLD32rri8, 3,
2977 DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
2978 }
2979}
2980
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002981/// emitShiftOperation - Common code shared between visitShiftInst and
2982/// constant expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002983void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
2984 MachineBasicBlock::iterator IP,
2985 Value *Op, Value *ShiftAmount,
2986 bool isLeftShift, const Type *ResultTy,
2987 unsigned DestReg) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002988 unsigned SrcReg = getReg (Op, MBB, IP);
2989 bool isSigned = ResultTy->isSigned ();
2990 unsigned Class = getClass (ResultTy);
Chris Lattnerde95c9e2004-10-17 06:10:40 +00002991
Chris Lattnerce7cafa2004-11-13 20:48:57 +00002992 static const unsigned ConstantOperand[][3] = {
2993 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri }, // SHR
2994 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri }, // SAR
2995 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SHL
2996 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002997 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002998
Chris Lattnerce7cafa2004-11-13 20:48:57 +00002999 static const unsigned NonConstantOperand[][3] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003000 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
3001 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
3002 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
3003 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00003004 };
Chris Lattner796df732002-11-02 00:44:25 +00003005
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003006 // Longs, as usual, are handled specially.
Chris Lattner3e130a22003-01-13 00:32:26 +00003007 if (Class == cLong) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003008 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003009 unsigned Amount = CUI->getValue();
Chris Lattner62f5a942004-11-13 20:04:38 +00003010 if (Amount == 1 && isLeftShift) { // X << 1 == X+X
Chris Lattner44205ca2004-11-13 20:03:48 +00003011 BuildMI(*MBB, IP, X86::ADD32rr, 2,
3012 DestReg).addReg(SrcReg).addReg(SrcReg);
3013 BuildMI(*MBB, IP, X86::ADC32rr, 2,
3014 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
3015 } else if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003016 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3017 if (isLeftShift) {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003018 doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003019 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003020 } else {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003021 BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
3022 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003023 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003024 }
Chris Lattner36c625d2004-11-15 23:16:34 +00003025 } else if (Amount == 32) {
3026 if (isLeftShift) {
3027 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
3028 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3029 } else {
Chris Lattner39a83dc2004-11-16 18:40:52 +00003030 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
Chris Lattner36c625d2004-11-15 23:16:34 +00003031 if (!isSigned) {
3032 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3033 } else {
3034 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3035 DestReg+1).addReg(SrcReg).addImm(31);
3036 }
3037 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003038 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003039 Amount -= 32;
3040 if (isLeftShift) {
Chris Lattner36c625d2004-11-15 23:16:34 +00003041 BuildMI(*MBB, IP, X86::SHL32ri, 2,
3042 DestReg + 1).addReg(SrcReg).addImm(Amount);
Chris Lattner722070e2004-04-06 03:42:38 +00003043 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003044 } else {
Chris Lattner36c625d2004-11-15 23:16:34 +00003045 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3046 DestReg).addReg(SrcReg+1).addImm(Amount);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003047 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003048 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003049 }
3050 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00003051 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Chris Lattner9171ef52003-06-01 01:56:54 +00003052 if (!isLeftShift && isSigned) {
3053 // If this is a SHR of a Long, then we need to do funny sign extension
3054 // stuff. TmpReg gets the value to use as the high-part if we are
3055 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003056 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00003057 } else {
3058 // Other shifts use a fixed zero value if the shift is more than 32
3059 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003060 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00003061 }
3062
3063 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003064 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003065 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003066
3067 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3068 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3069 if (isLeftShift) {
3070 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003071 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00003072 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003073 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003074 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003075
3076 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003077 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003078
3079 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003080 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003081 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3082 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003083 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003084 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003085 } else {
3086 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003087 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00003088 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00003089 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003090 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00003091 .addReg(SrcReg+1);
3092
3093 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003094 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003095
3096 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003097 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003098 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3099
3100 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003101 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003102 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3103 }
Brian Gaekea1719c92002-10-31 23:03:59 +00003104 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003105 return;
3106 }
Chris Lattnere9913f22002-11-02 01:41:55 +00003107
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003108 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003109 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3110 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003111
Chris Lattner44205ca2004-11-13 20:03:48 +00003112 if (CUI->getValue() == 1 && isLeftShift) { // X << 1 -> X+X
3113 static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3114 BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3115 } else {
3116 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3117 BuildMI(*MBB, IP, Opc[Class], 2,
3118 DestReg).addReg(SrcReg).addImm(CUI->getValue());
3119 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003120 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003121 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003122 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003123
Chris Lattner3e130a22003-01-13 00:32:26 +00003124 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00003125 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003126 }
3127}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003128
Chris Lattner3e130a22003-01-13 00:32:26 +00003129
Chris Lattner6fc3c522002-11-17 21:11:55 +00003130/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00003131/// instruction. The load and store instructions are the only place where we
3132/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00003133///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003134void X86ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003135 // Check to see if this load instruction is going to be folded into a binary
3136 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
3137 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00003138 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003139 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003140 Instruction *User = cast<Instruction>(I.use_back());
3141 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003142 case Instruction::Cast:
3143 // If this is a cast from a signed-integer type to a floating point type,
3144 // fold the cast here.
John Criswell6b5bd582004-06-09 15:18:51 +00003145 if (getClassB(User->getType()) == cFP &&
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003146 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3147 I.getType() == Type::LongTy)) {
3148 unsigned DestReg = getReg(User);
3149 static const unsigned Opcode[] = {
3150 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3151 };
Chris Lattner9f1b5312004-05-13 15:12:43 +00003152
3153 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3154 unsigned FI = getFixedSizedAllocaFI(AI);
3155 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3156 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003157 X86AddressMode AM;
3158 getAddressingMode(I.getOperand(0), AM);
3159 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003160 }
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003161 return;
3162 } else {
3163 User = 0;
3164 }
3165 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00003166
Chris Lattner7dee5da2004-03-08 01:58:35 +00003167 case Instruction::Add:
3168 case Instruction::Sub:
3169 case Instruction::And:
3170 case Instruction::Or:
3171 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003172 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003173 break;
Chris Lattner95157f72004-04-11 22:05:45 +00003174 case Instruction::Mul:
3175 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00003176 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003177 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00003178 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003179 }
3180
3181 if (User) {
3182 // Okay, we found a user. If the load is the first operand and there is
3183 // no second operand load, reverse the operand ordering. Note that this
3184 // can fail for a subtract (ie, no change will be made).
Chris Lattner3dbb5042004-07-21 21:28:26 +00003185 bool Swapped = false;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003186 if (!isa<LoadInst>(User->getOperand(1)))
Chris Lattner3dbb5042004-07-21 21:28:26 +00003187 Swapped = !cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003188
3189 // Okay, now that everything is set up, if this load is used by the second
3190 // operand, and if there are no instructions that invalidate the load
3191 // before the binary operator, eliminate the load.
3192 if (User->getOperand(1) == &I &&
3193 isSafeToFoldLoadIntoInstruction(I, *User))
3194 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00003195
3196 // If this is a floating point sub or div, we won't be able to swap the
3197 // operands, but we will still be able to eliminate the load.
3198 if (Class == cFP && User->getOperand(0) == &I &&
3199 !isa<LoadInst>(User->getOperand(1)) &&
3200 (User->getOpcode() == Instruction::Sub ||
3201 User->getOpcode() == Instruction::Div) &&
3202 isSafeToFoldLoadIntoInstruction(I, *User))
3203 return; // Eliminate the load!
Chris Lattner3dbb5042004-07-21 21:28:26 +00003204
3205 // If we swapped the operands to the instruction, but couldn't fold the
3206 // load anyway, swap them back. We don't want to break add X, int
3207 // folding.
3208 if (Swapped) cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003209 }
3210 }
3211
Chris Lattner6ac1d712003-10-20 04:48:06 +00003212 static const unsigned Opcodes[] = {
Chris Lattner9f1b5312004-05-13 15:12:43 +00003213 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
Chris Lattner3e130a22003-01-13 00:32:26 +00003214 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00003215 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003216 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003217
3218 unsigned DestReg = getReg(I);
3219
3220 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3221 unsigned FI = getFixedSizedAllocaFI(AI);
3222 if (Class == cLong) {
3223 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3224 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3225 } else {
3226 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3227 }
3228 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003229 X86AddressMode AM;
3230 getAddressingMode(I.getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003231
3232 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003233 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3234 AM.Disp += 4;
3235 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003236 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003237 addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003238 }
3239 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003240}
3241
Chris Lattner6fc3c522002-11-17 21:11:55 +00003242/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3243/// instruction.
3244///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003245void X86ISel::visitStoreInst(StoreInst &I) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003246 X86AddressMode AM;
3247 getAddressingMode(I.getOperand(1), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003248
Chris Lattner6c09db22003-10-20 04:11:23 +00003249 const Type *ValTy = I.getOperand(0)->getType();
3250 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00003251
Chris Lattner5a830962004-02-25 02:56:58 +00003252 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3253 uint64_t Val = CI->getRawValue();
3254 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003255 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3256 AM.Disp += 4;
3257 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00003258 } else {
3259 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003260 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00003261 };
3262 unsigned Opcode = Opcodes[Class];
Reid Spencerfc989e12004-08-30 00:13:26 +00003263 addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00003264 }
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003265 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
Chris Lattner358a9022004-10-15 05:05:29 +00003266 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
Chris Lattner5a830962004-02-25 02:56:58 +00003267 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003268 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
Chris Lattnere7a31c92004-05-07 21:18:15 +00003269 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3270 // Store constant FP values with integer instructions to avoid having to
3271 // load the constants from the constant pool then do a store.
3272 if (CFP->getType() == Type::FloatTy) {
3273 union {
3274 unsigned I;
3275 float F;
3276 } V;
3277 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003278 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
Chris Lattner5a830962004-02-25 02:56:58 +00003279 } else {
Chris Lattnere7a31c92004-05-07 21:18:15 +00003280 union {
3281 uint64_t I;
3282 double F;
3283 } V;
3284 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003285 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3286 AM.Disp += 4;
3287 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
Chris Lattnere7a31c92004-05-07 21:18:15 +00003288 unsigned(V.I >> 32));
Chris Lattner5a830962004-02-25 02:56:58 +00003289 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00003290
3291 } else if (Class == cLong) {
3292 unsigned ValReg = getReg(I.getOperand(0));
Reid Spencerfc989e12004-08-30 00:13:26 +00003293 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3294 AM.Disp += 4;
3295 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
Chris Lattnere7a31c92004-05-07 21:18:15 +00003296 } else {
Chris Lattner358a9022004-10-15 05:05:29 +00003297 // FIXME: stop emitting these two instructions:
3298 // movl $global,%eax
3299 // movl %eax,(%ebx)
3300 // when one instruction will suffice. That includes when the global
3301 // has an offset applied to it.
Chris Lattnere7a31c92004-05-07 21:18:15 +00003302 unsigned ValReg = getReg(I.getOperand(0));
3303 static const unsigned Opcodes[] = {
3304 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3305 };
3306 unsigned Opcode = Opcodes[Class];
3307 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003308
Reid Spencerfc989e12004-08-30 00:13:26 +00003309 addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003310 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00003311}
3312
3313
Misha Brukman538607f2004-03-01 23:53:11 +00003314/// visitCastInst - Here we have various kinds of copying with or without sign
3315/// extension going on.
3316///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003317void X86ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003318 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00003319
Chris Lattner99382862004-04-12 00:23:04 +00003320 unsigned SrcClass = getClassB(Op->getType());
3321 unsigned DestClass = getClassB(CI.getType());
3322 // Noop casts are not emitted: getReg will return the source operand as the
3323 // register to use for any uses of the noop cast.
Chris Lattner8b486a12004-06-29 00:14:38 +00003324 if (DestClass == SrcClass) {
3325 // The only detail in this plan is that casts from double -> float are
3326 // truncating operations that we have to codegen through memory (despite
3327 // the fact that the source/dest registers are the same class).
3328 if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3329 return;
3330 }
Chris Lattner427aeb42004-04-11 19:21:59 +00003331
Chris Lattnerf5854472003-06-21 16:01:24 +00003332 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3333 // of the case are GEP instructions, then the cast does not need to be
3334 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00003335 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003336 bool AllUsesAreGEPs = true;
3337 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3338 if (!isa<GetElementPtrInst>(*I)) {
3339 AllUsesAreGEPs = false;
3340 break;
3341 }
3342
3343 // No need to codegen this cast if all users are getelementptr instrs...
3344 if (AllUsesAreGEPs) return;
3345 }
3346
Chris Lattner99382862004-04-12 00:23:04 +00003347 // If this cast converts a load from a short,int, or long integer to a FP
3348 // value, we will have folded this cast away.
3349 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3350 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3351 Op->getType() == Type::LongTy))
3352 return;
3353
3354
Chris Lattner548f61d2003-04-23 17:22:12 +00003355 unsigned DestReg = getReg(CI);
3356 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00003357 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00003358}
3359
Misha Brukman538607f2004-03-01 23:53:11 +00003360/// emitCastOperation - Common code shared between visitCastInst and constant
3361/// expression cast support.
3362///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003363void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3364 MachineBasicBlock::iterator IP,
3365 Value *Src, const Type *DestTy,
3366 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003367 const Type *SrcTy = Src->getType();
3368 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00003369 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003370 unsigned SrcReg = getReg(Src, BB, IP);
3371
Chris Lattner3e130a22003-01-13 00:32:26 +00003372 // Implement casts to bool by using compare on the operand followed by set if
3373 // not zero on the result.
3374 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00003375 switch (SrcClass) {
3376 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003377 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003378 break;
3379 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003380 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003381 break;
3382 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003383 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003384 break;
3385 case cLong: {
3386 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003387 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00003388 break;
3389 }
3390 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00003391 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003392 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00003393 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00003394 break;
Chris Lattner20772542003-06-01 03:38:24 +00003395 }
3396
3397 // If the zero flag is not set, then the value is true, set the byte to
3398 // true.
Chris Lattneree352852004-02-29 07:22:16 +00003399 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003400 return;
3401 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003402
3403 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003404 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00003405 };
3406
3407 // Implement casts between values of the same type class (as determined by
3408 // getClass) by using a register-to-register move.
3409 if (SrcClass == DestClass) {
3410 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00003411 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003412 } else if (SrcClass == cFP) {
3413 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003414 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00003415 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003416 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003417 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3418 "Unknown cFP member!");
3419 // Truncate from double to float by storing to memory as short, then
3420 // reading it back.
3421 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00003422 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner5384b382005-01-05 16:30:14 +00003423 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5),
3424 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003425 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003426 }
3427 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003428 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3429 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003430 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00003431 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003432 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00003433 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003434 return;
3435 }
3436
3437 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3438 // or zero extension, depending on whether the source type was signed.
3439 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3440 SrcClass < DestClass) {
3441 bool isLong = DestClass == cLong;
3442 if (isLong) DestClass = cInt;
3443
3444 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003445 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3446 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00003447 };
3448
Chris Lattner96e3b422004-05-09 22:28:45 +00003449 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
Chris Lattneree352852004-02-29 07:22:16 +00003450 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00003451 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003452
3453 if (isLong) { // Handle upper 32 bits as appropriate...
3454 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003455 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00003456 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003457 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00003458 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003459 return;
3460 }
3461
3462 // Special case long -> int ...
3463 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003464 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003465 return;
3466 }
3467
3468 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3469 // move out of AX or AL.
3470 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3471 && SrcClass > DestClass) {
3472 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00003473 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3474 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00003475 return;
3476 }
3477
3478 // Handle casts from integer to floating point now...
3479 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003480 // Promote the integer to a type supported by FLD. We do this because there
3481 // are no unsigned FLD instructions, so we must promote an unsigned value to
3482 // a larger signed value, then use FLD on the larger value.
3483 //
3484 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00003485 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003486 unsigned RealDestReg = DestReg;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003487 switch (SrcTy->getTypeID()) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003488 case Type::BoolTyID:
3489 case Type::SByteTyID:
3490 // We don't have the facilities for directly loading byte sized data from
3491 // memory (even signed). Promote it to 16 bits.
3492 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003493 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003494 break;
3495 case Type::UByteTyID:
3496 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003497 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003498 break;
3499 case Type::UShortTyID:
3500 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003501 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003502 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003503 case Type::ULongTyID:
Chris Lattner56a31c62004-10-17 08:01:28 +00003504 case Type::UIntTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003505 // Don't fild into the read destination.
3506 DestReg = makeAnotherReg(Type::DoubleTy);
3507 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003508 default: // No promotion needed...
3509 break;
3510 }
3511
3512 if (PromoteType) {
3513 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003514 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003515 SrcTy = PromoteType;
3516 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003517 SrcReg = TmpReg;
3518 }
3519
3520 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003521 int FrameIdx =
3522 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003523
3524 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003525 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003526 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003527 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003528 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003529 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003530 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003531 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3532 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003533 }
3534
3535 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003536 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003537 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003538
Chris Lattner56a31c62004-10-17 08:01:28 +00003539 if (SrcTy == Type::UIntTy) {
3540 // If this is a cast from uint -> double, we need to be careful about if
3541 // the "sign" bit is set. If so, we don't want to make a negative number,
3542 // we want to make a positive number. Emit code to add an offset if the
3543 // sign bit is set.
3544
3545 // Compute whether the sign bit is set by shifting the reg right 31 bits.
3546 unsigned IsNeg = makeAnotherReg(Type::IntTy);
3547 BuildMI(BB, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
3548
3549 // Create a CP value that has the offset in one word and 0 in the other.
3550 static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3551 0x4f80000000000000ULL);
3552 unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
3553 BuildMI(BB, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
3554 .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3555
3556 } else if (SrcTy == Type::ULongTy) {
3557 // We need special handling for unsigned 64-bit integer sources. If the
3558 // input number has the "sign bit" set, then we loaded it incorrectly as a
3559 // negative 64-bit number. In this case, add an offset value.
3560
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003561 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003562 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003563
Chris Lattnerb6bac512004-02-25 06:13:04 +00003564 // If the sign bit is set, get a pointer to an offset, otherwise get a
3565 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003566 MachineConstantPool *CP = F->getConstantPool();
3567 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003568 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003569 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003570 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003571 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003572 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3573
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003574 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003575 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003576 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003577 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003578
3579 // Load the constant for an add. FIXME: this could make an 'fadd' that
3580 // reads directly from memory, but we don't support these yet.
3581 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003582 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003583
Chris Lattneree352852004-02-29 07:22:16 +00003584 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3585 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003586 }
3587
Chris Lattner3e130a22003-01-13 00:32:26 +00003588 return;
3589 }
3590
3591 // Handle casts from floating point to integer now...
3592 if (SrcClass == cFP) {
3593 // Change the floating point control register to use "round towards zero"
3594 // mode when truncating to an integer value.
3595 //
3596 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003597 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003598
3599 // Load the old value of the high byte of the control word...
3600 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003601 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003602 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003603
3604 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003605 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003606 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003607
3608 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003609 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003610
3611 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003612 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003613 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003614
3615 // We don't have the facilities for directly storing byte sized data to
3616 // memory. Promote it to 16 bits. We also must promote unsigned values to
3617 // larger classes because we only have signed FP stores.
3618 unsigned StoreClass = DestClass;
3619 const Type *StoreTy = DestTy;
3620 if (StoreClass == cByte || DestTy->isUnsigned())
3621 switch (StoreClass) {
3622 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3623 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3624 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003625 // The following treatment of cLong may not be perfectly right,
3626 // but it survives chains of casts of the form
3627 // double->ulong->double.
3628 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003629 default: assert(0 && "Unknown store class!");
3630 }
3631
3632 // Spill the integer to memory and reload it from there...
3633 int FrameIdx =
3634 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3635
3636 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003637 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003638 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3639 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003640
3641 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003642 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3643 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003644 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003645 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003646 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003647 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003648 }
3649
3650 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003651 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003652 return;
3653 }
3654
Brian Gaeked474e9c2002-12-06 10:49:33 +00003655 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003656 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003657 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003658}
Brian Gaekea1719c92002-10-31 23:03:59 +00003659
Chris Lattner73815062003-10-18 05:56:40 +00003660/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003661///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003662void X86ISel::visitVANextInst(VANextInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003663 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003664 unsigned DestReg = getReg(I);
3665
Chris Lattnereca195e2003-05-08 19:44:13 +00003666 unsigned Size;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003667 switch (I.getArgType()->getTypeID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003668 default:
3669 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003670 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003671 return;
3672 case Type::PointerTyID:
3673 case Type::UIntTyID:
3674 case Type::IntTyID:
3675 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003676 break;
3677 case Type::ULongTyID:
3678 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003679 case Type::DoubleTyID:
3680 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003681 break;
3682 }
3683
3684 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003685 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003686}
Chris Lattnereca195e2003-05-08 19:44:13 +00003687
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003688void X86ISel::visitVAArgInst(VAArgInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003689 unsigned VAList = getReg(I.getOperand(0));
3690 unsigned DestReg = getReg(I);
3691
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003692 switch (I.getType()->getTypeID()) {
Chris Lattner73815062003-10-18 05:56:40 +00003693 default:
3694 std::cerr << I;
3695 assert(0 && "Error: bad type for va_next instruction!");
3696 return;
3697 case Type::PointerTyID:
3698 case Type::UIntTyID:
3699 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003700 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003701 break;
3702 case Type::ULongTyID:
3703 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003704 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3705 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003706 break;
3707 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003708 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003709 break;
3710 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003711}
3712
Misha Brukman538607f2004-03-01 23:53:11 +00003713/// visitGetElementPtrInst - instruction-select GEP instructions
3714///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003715void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003716 // If this GEP instruction will be folded into all of its users, we don't need
3717 // to explicitly calculate it!
Reid Spencerfc989e12004-08-30 00:13:26 +00003718 X86AddressMode AM;
3719 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003720 // Check all of the users of the instruction to see if they are loads and
3721 // stores.
3722 bool AllWillFold = true;
3723 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3724 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3725 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3726 cast<Instruction>(*UI)->getOperand(0) == &I) {
3727 AllWillFold = false;
3728 break;
3729 }
3730
3731 // If the instruction is foldable, and will be folded into all users, don't
3732 // emit it!
3733 if (AllWillFold) return;
3734 }
3735
Chris Lattner3e130a22003-01-13 00:32:26 +00003736 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003737 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003738 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003739}
3740
Chris Lattner985fe3d2004-02-25 03:45:50 +00003741/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3742/// GEPTypes (the derived types being stepped through at each level). On return
3743/// from this function, if some indexes of the instruction are representable as
3744/// an X86 lea instruction, the machine operands are put into the Ops
3745/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3746/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3747/// addressing mode that only partially consumes the input, the BaseReg input of
3748/// the addressing mode must be left free.
3749///
3750/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3751///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003752void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
3753 MachineBasicBlock::iterator IP,
3754 std::vector<Value*> &GEPOps,
3755 std::vector<const Type*> &GEPTypes,
3756 X86AddressMode &AM) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003757 const TargetData &TD = TM.getTargetData();
3758
Chris Lattner985fe3d2004-02-25 03:45:50 +00003759 // Clear out the state we are working with...
Reid Spencerfc989e12004-08-30 00:13:26 +00003760 AM.BaseType = X86AddressMode::RegBase;
3761 AM.Base.Reg = 0; // No base register
3762 AM.Scale = 1; // Unit scale
3763 AM.IndexReg = 0; // No index register
3764 AM.Disp = 0; // No displacement
Chris Lattnerb6bac512004-02-25 06:13:04 +00003765
Chris Lattner985fe3d2004-02-25 03:45:50 +00003766 // While there are GEP indexes that can be folded into the current address,
3767 // keep processing them.
3768 while (!GEPTypes.empty()) {
3769 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3770 // It's a struct access. CUI is the index into the structure,
3771 // which names the field. This index must have unsigned type.
3772 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3773
3774 // Use the TargetData structure to pick out what the layout of the
3775 // structure is in memory. Since the structure index must be constant, we
3776 // can get its value and use it to find the right byte offset from the
3777 // StructLayout class's list of structure member offsets.
Reid Spencerfc989e12004-08-30 00:13:26 +00003778 AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003779 GEPOps.pop_back(); // Consume a GEP operand
3780 GEPTypes.pop_back();
3781 } else {
3782 // It's an array or pointer access: [ArraySize x ElementType].
3783 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3784 Value *idx = GEPOps.back();
3785
3786 // idx is the index into the array. Unlike with structure
3787 // indices, we may not know its actual value at code-generation
3788 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003789
3790 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003791 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003792 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003793 AM.Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003794 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003795 AM.Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003796 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003797 // If the index reg is already taken, we can't handle this index.
Reid Spencerfc989e12004-08-30 00:13:26 +00003798 if (AM.IndexReg) return;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003799
3800 // If this is a size that we can handle, then add the index as
3801 switch (TypeSize) {
3802 case 1: case 2: case 4: case 8:
3803 // These are all acceptable scales on X86.
Reid Spencerfc989e12004-08-30 00:13:26 +00003804 AM.Scale = TypeSize;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003805 break;
3806 default:
3807 // Otherwise, we can't handle this scale
3808 return;
3809 }
3810
3811 if (CastInst *CI = dyn_cast<CastInst>(idx))
3812 if (CI->getOperand(0)->getType() == Type::IntTy ||
3813 CI->getOperand(0)->getType() == Type::UIntTy)
3814 idx = CI->getOperand(0);
3815
Reid Spencerfc989e12004-08-30 00:13:26 +00003816 AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003817 }
3818
3819 GEPOps.pop_back(); // Consume a GEP operand
3820 GEPTypes.pop_back();
3821 }
3822 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003823
Chris Lattnerdf040972004-05-23 21:23:12 +00003824 // GEPTypes is empty, which means we have a single operand left. Set it as
3825 // the base register.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003826 //
Reid Spencerfc989e12004-08-30 00:13:26 +00003827 assert(AM.Base.Reg == 0);
Chris Lattnerdf040972004-05-23 21:23:12 +00003828
Reid Spencerfc989e12004-08-30 00:13:26 +00003829 if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3830 AM.BaseType = X86AddressMode::FrameIndexBase;
3831 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
Chris Lattnerdf040972004-05-23 21:23:12 +00003832 GEPOps.pop_back();
3833 return;
Reid Spencerfc989e12004-08-30 00:13:26 +00003834 }
3835
Chris Lattner358a9022004-10-15 05:05:29 +00003836 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3837 AM.GV = GV;
3838 GEPOps.pop_back();
3839 return;
Chris Lattnerdf040972004-05-23 21:23:12 +00003840 }
Chris Lattnerdf040972004-05-23 21:23:12 +00003841
Reid Spencerfc989e12004-08-30 00:13:26 +00003842 AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003843 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003844}
3845
3846
Chris Lattnerb6bac512004-02-25 06:13:04 +00003847/// isGEPFoldable - Return true if the specified GEP can be completely
3848/// folded into the addressing mode of a load/store or lea instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003849bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3850 Value *Src, User::op_iterator IdxBegin,
3851 User::op_iterator IdxEnd, X86AddressMode &AM) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003852
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003853 std::vector<Value*> GEPOps;
3854 GEPOps.resize(IdxEnd-IdxBegin+1);
3855 GEPOps[0] = Src;
3856 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3857
Chris Lattnerdf040972004-05-23 21:23:12 +00003858 std::vector<const Type*>
3859 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3860 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003861
Chris Lattnerb6bac512004-02-25 06:13:04 +00003862 MachineBasicBlock::iterator IP;
3863 if (MBB) IP = MBB->end();
Reid Spencerfc989e12004-08-30 00:13:26 +00003864 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003865
3866 // We can fold it away iff the getGEPIndex call eliminated all operands.
3867 return GEPOps.empty();
3868}
3869
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003870void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3871 MachineBasicBlock::iterator IP,
3872 Value *Src, User::op_iterator IdxBegin,
3873 User::op_iterator IdxEnd, unsigned TargetReg) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003874 const TargetData &TD = TM.getTargetData();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003875
Chris Lattnerd2995df2004-07-15 00:58:53 +00003876 // If this is a getelementptr null, with all constant integer indices, just
3877 // replace it with TargetReg = 42.
3878 if (isa<ConstantPointerNull>(Src)) {
3879 User::op_iterator I = IdxBegin;
3880 for (; I != IdxEnd; ++I)
3881 if (!isa<ConstantInt>(*I))
3882 break;
3883 if (I == IdxEnd) { // All constant indices
3884 unsigned Offset = TD.getIndexedOffset(Src->getType(),
3885 std::vector<Value*>(IdxBegin, IdxEnd));
3886 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3887 return;
3888 }
3889 }
3890
Chris Lattnerb6bac512004-02-25 06:13:04 +00003891 std::vector<Value*> GEPOps;
3892 GEPOps.resize(IdxEnd-IdxBegin+1);
3893 GEPOps[0] = Src;
3894 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3895
3896 std::vector<const Type*> GEPTypes;
3897 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3898 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003899
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003900 // Keep emitting instructions until we consume the entire GEP instruction.
3901 while (!GEPOps.empty()) {
3902 unsigned OldSize = GEPOps.size();
Reid Spencerfc989e12004-08-30 00:13:26 +00003903 X86AddressMode AM;
3904 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003905
Chris Lattner985fe3d2004-02-25 03:45:50 +00003906 if (GEPOps.size() != OldSize) {
3907 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003908 unsigned NextTarget = 0;
3909 if (!GEPOps.empty()) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003910 assert(AM.Base.Reg == 0 &&
Chris Lattnerb6bac512004-02-25 06:13:04 +00003911 "getGEPIndex should have left the base register open for chaining!");
Reid Spencerfc989e12004-08-30 00:13:26 +00003912 NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003913 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003914
Reid Spencerfc989e12004-08-30 00:13:26 +00003915 if (AM.BaseType == X86AddressMode::RegBase &&
Chris Lattner358a9022004-10-15 05:05:29 +00003916 AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
Reid Spencerfc989e12004-08-30 00:13:26 +00003917 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
Chris Lattner358a9022004-10-15 05:05:29 +00003918 else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3919 AM.IndexReg == 0 && AM.Disp == 0)
3920 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003921 else
Reid Spencerfc989e12004-08-30 00:13:26 +00003922 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003923 --IP;
3924 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003925 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003926 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3927 // all operands are consumed but the base pointer. If so, just load it
3928 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003929 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003930 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003931 } else {
3932 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003933 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003934 }
3935 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003936
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003937 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003938 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003939 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3940 Value *idx = GEPOps.back();
3941 GEPOps.pop_back(); // Consume a GEP operand
3942 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003943
Chris Lattner28977af2004-04-05 01:30:19 +00003944 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003945 // operand on X86. Handle this case directly now...
3946 if (CastInst *CI = dyn_cast<CastInst>(idx))
3947 if (CI->getOperand(0)->getType() == Type::IntTy ||
3948 CI->getOperand(0)->getType() == Type::UIntTy)
3949 idx = CI->getOperand(0);
3950
Chris Lattner3e130a22003-01-13 00:32:26 +00003951 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003952 // must find the size of the pointed-to type (Not coincidentally, the next
3953 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003954 const Type *ElTy = SqTy->getElementType();
3955 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003956
3957 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003958 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003959 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003960 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003961 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003962 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003963 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003964 --IP; // Insert the next instruction before this one.
3965 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003966 }
3967 } else if (elementSize == 1) {
3968 // If the element size is 1, we don't have to multiply, just add
3969 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003970 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003971 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003972 --IP; // Insert the next instruction before this one.
3973 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003974 } else {
3975 unsigned idxReg = getReg(idx, MBB, IP);
3976 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003977
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003978 // Make sure we can back the iterator up to point to the first
3979 // instruction emitted.
3980 MachineBasicBlock::iterator BeforeIt = IP;
3981 if (IP == MBB->begin())
3982 BeforeIt = MBB->end();
3983 else
3984 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003985 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3986
Chris Lattner8a307e82002-12-16 19:32:50 +00003987 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003988 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003989 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003990 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003991
3992 // Step to the first instruction of the multiply.
3993 if (BeforeIt == MBB->end())
3994 IP = MBB->begin();
3995 else
3996 IP = ++BeforeIt;
3997
3998 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003999 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004000 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004001 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004002}
4003
Chris Lattner065faeb2002-12-28 20:24:02 +00004004/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
4005/// frame manager, otherwise do it the hard way.
4006///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004007void X86ISel::visitAllocaInst(AllocaInst &I) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00004008 // If this is a fixed size alloca in the entry block for the function, we
4009 // statically stack allocate the space, so we don't need to do anything here.
4010 //
Chris Lattnercb2fd552004-05-13 07:40:27 +00004011 if (dyn_castFixedAlloca(&I)) return;
Chris Lattner9f1b5312004-05-13 15:12:43 +00004012
Brian Gaekee48ec012002-12-13 06:46:31 +00004013 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00004014 const Type *Ty = I.getAllocatedType();
4015 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
4016
Chris Lattner065faeb2002-12-28 20:24:02 +00004017 // Create a register to hold the temporary result of multiplying the type size
4018 // constant by the variable amount.
4019 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
4020 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00004021
4022 // TotalSizeReg = mul <numelements>, <TypeSize>
4023 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004024 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004025
4026 // AddedSize = add <TotalSizeReg>, 15
4027 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004028 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004029
4030 // AlignedSize = and <AddedSize>, ~15
4031 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004032 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004033
Brian Gaekee48ec012002-12-13 06:46:31 +00004034 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004035 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004036
Brian Gaekee48ec012002-12-13 06:46:31 +00004037 // Put a pointer to the space into the result register, by copying
4038 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004039 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00004040
Misha Brukman48196b32003-05-03 02:18:17 +00004041 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00004042 // object.
4043 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00004044}
Chris Lattner3e130a22003-01-13 00:32:26 +00004045
4046/// visitMallocInst - Malloc instructions are code generated into direct calls
4047/// to the library malloc.
4048///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004049void X86ISel::visitMallocInst(MallocInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004050 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4051 unsigned Arg;
4052
4053 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4054 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4055 } else {
4056 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00004057 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00004058 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004059 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00004060 }
4061
4062 std::vector<ValueRecord> Args;
4063 Args.push_back(ValueRecord(Arg, Type::UIntTy));
4064 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004065 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004066 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4067}
4068
4069
4070/// visitFreeInst - Free instructions are code gen'd to call the free libc
4071/// function.
4072///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004073void X86ISel::visitFreeInst(FreeInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004074 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00004075 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00004076 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004077 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004078 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4079}
4080
Chris Lattnerd281de22003-07-26 23:49:58 +00004081/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00004082/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00004083/// generated code sucks but the implementation is nice and simple.
4084///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00004085FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004086 return new X86ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00004087}