blob: e35867df009df3ffabdbc1104bfe5e6d438cd0a7 [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2//
3// This file defines a simple peephole instruction selector for the x86 platform
4//
5//===----------------------------------------------------------------------===//
6
7#include "X86.h"
Chris Lattner055c9652002-10-29 21:05:24 +00008#include "X86InstrInfo.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +00009#include "X86InstrBuilder.h"
Chris Lattner72614082002-10-25 22:55:53 +000010#include "llvm/Function.h"
11#include "llvm/iTerminators.h"
Brian Gaeke1749d632002-11-07 17:59:21 +000012#include "llvm/iOperators.h"
Brian Gaekea1719c92002-10-31 23:03:59 +000013#include "llvm/iOther.h"
Chris Lattner51b49a92002-11-02 19:45:49 +000014#include "llvm/iPHINode.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "llvm/iMemory.h"
Chris Lattner72614082002-10-25 22:55:53 +000016#include "llvm/Type.h"
Brian Gaeke20244b72002-12-12 15:33:40 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerc5291f52002-10-27 21:16:59 +000018#include "llvm/Constants.h"
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000019#include "llvm/Pass.h"
Chris Lattner341a9372002-10-29 17:43:55 +000020#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000023#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000024#include "llvm/Target/MRegisterInfo.h"
25#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000026
Chris Lattner06925362002-11-17 21:56:38 +000027using namespace MOTy; // Get Use, Def, UseAndDef
28
Chris Lattner333b2fa2002-12-13 10:09:43 +000029
30/// BMI - A special BuildMI variant that takes an iterator to insert the
31/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000032/// this is the version for when you have a destination register in mind.
33inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattner333b2fa2002-12-13 10:09:43 +000034 MachineBasicBlock::iterator &I,
35 MachineOpCode Opcode,
36 unsigned NumOperands,
37 unsigned DestReg) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000038 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattner333b2fa2002-12-13 10:09:43 +000039 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Brian Gaeke71794c02002-12-13 11:22:48 +000040 I = ++MBB->insert(I, MI);
Chris Lattner333b2fa2002-12-13 10:09:43 +000041 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
42}
43
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000044/// BMI - A special BuildMI variant that takes an iterator to insert the
45/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000046inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000047 MachineBasicBlock::iterator &I,
48 MachineOpCode Opcode,
49 unsigned NumOperands) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000050 assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000051 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Brian Gaeke71794c02002-12-13 11:22:48 +000052 I = ++MBB->insert(I, MI);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000053 return MachineInstrBuilder(MI);
54}
55
Chris Lattner333b2fa2002-12-13 10:09:43 +000056
Chris Lattner72614082002-10-25 22:55:53 +000057namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000058 struct ISel : public FunctionPass, InstVisitor<ISel> {
59 TargetMachine &TM;
Chris Lattner341a9372002-10-29 17:43:55 +000060 MachineFunction *F; // The function we are compiling into
61 MachineBasicBlock *BB; // The current MBB we are compiling
Chris Lattner72614082002-10-25 22:55:53 +000062
63 unsigned CurReg;
64 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
65
Chris Lattner333b2fa2002-12-13 10:09:43 +000066 // MBBMap - Mapping between LLVM BB -> Machine BB
67 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
68
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000069 ISel(TargetMachine &tm)
70 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
Chris Lattner72614082002-10-25 22:55:53 +000071
72 /// runOnFunction - Top level implementation of instruction selection for
73 /// the entire function.
74 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000075 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000076 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000077
78 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
79 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
80
81 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000082 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000083
84 // Select the PHI nodes
85 SelectPHINodes();
86
Chris Lattner72614082002-10-25 22:55:53 +000087 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000088 MBBMap.clear();
Chris Lattner94e8ee22002-11-21 17:26:58 +000089 CurReg = MRegisterInfo::FirstVirtualRegister;
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000090 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000091 return false; // We never modify the LLVM itself.
92 }
93
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000094 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
96 }
97
Chris Lattner72614082002-10-25 22:55:53 +000098 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000099 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000102 ///
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000105 }
106
Chris Lattner333b2fa2002-12-13 10:09:43 +0000107
108 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
109 /// because we have to generate our sources into the source basic blocks,
110 /// not the current one.
111 ///
112 void SelectPHINodes();
113
Chris Lattner72614082002-10-25 22:55:53 +0000114 // Visitation methods for various instructions. These methods simply emit
115 // fixed X86 code for each instruction.
116 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000117
118 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000119 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000120 void visitBranchInst(BranchInst &BI);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000121 void visitCallInst(CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000122
123 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000124 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000125 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
126 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattner8a307e82002-12-16 19:32:50 +0000127 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
128 unsigned destReg, const Type *resultType,
129 unsigned op0Reg, unsigned op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000130 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000131
Chris Lattnerf01729e2002-11-02 20:54:46 +0000132 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
133 void visitRem(BinaryOperator &B) { visitDivRem(B); }
134 void visitDivRem(BinaryOperator &B);
135
Chris Lattnere2954c82002-11-02 20:04:26 +0000136 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000137 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
138 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
139 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000140
141 // Binary comparison operators
Chris Lattner05093a52002-11-21 15:52:38 +0000142 void visitSetCCInst(SetCondInst &I, unsigned OpNum);
143 void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
144 void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
145 void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
146 void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
147 void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
148 void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
Chris Lattner6fc3c522002-11-17 21:11:55 +0000149
150 // Memory Instructions
151 void visitLoadInst(LoadInst &I);
152 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000153 void visitGetElementPtrInst(GetElementPtrInst &I);
154 void visitMallocInst(MallocInst &I);
Brian Gaekee48ec012002-12-13 06:46:31 +0000155 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000156 void visitAllocaInst(AllocaInst &I);
157
Chris Lattnere2954c82002-11-02 20:04:26 +0000158 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000159 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000160 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000161 void visitCastInst(CastInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000162
163 void visitInstruction(Instruction &I) {
164 std::cerr << "Cannot instruction select: " << I;
165 abort();
166 }
167
Brian Gaeke95780cc2002-12-13 07:56:18 +0000168 /// promote32 - Make a value 32-bits wide, and put it somewhere.
169 void promote32 (const unsigned targetReg, Value *v);
170
171 // emitGEPOperation - Common code shared between visitGetElementPtrInst and
Chris Lattnerc0812d82002-12-13 06:56:29 +0000172 // constant expression GEP support.
173 //
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000174 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000175 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000176 User::op_iterator IdxEnd, unsigned TargetReg);
177
Chris Lattnerc5291f52002-10-27 21:16:59 +0000178 /// copyConstantToRegister - Output the instructions required to put the
179 /// specified constant into the specified register.
180 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000181 void copyConstantToRegister(MachineBasicBlock *MBB,
182 MachineBasicBlock::iterator &MBBI,
183 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000184
Brian Gaeke20244b72002-12-12 15:33:40 +0000185 /// makeAnotherReg - This method returns the next register number
186 /// we haven't yet used.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000187 unsigned makeAnotherReg(const Type *Ty) {
188 // Add the mapping of regnumber => reg class to MachineFunction
189 F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
190 return CurReg++;
Brian Gaeke20244b72002-12-12 15:33:40 +0000191 }
192
Chris Lattner72614082002-10-25 22:55:53 +0000193 /// getReg - This method turns an LLVM value into a register number. This
194 /// is guaranteed to produce the same register number for a particular value
195 /// every time it is queried.
196 ///
197 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000198 unsigned getReg(Value *V) {
199 // Just append to the end of the current bb.
200 MachineBasicBlock::iterator It = BB->end();
201 return getReg(V, BB, It);
202 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000203 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000204 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000205 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000206 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000207 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000208 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000209 }
Chris Lattner72614082002-10-25 22:55:53 +0000210
Chris Lattner6f8fd252002-10-27 21:23:43 +0000211 // If this operand is a constant, emit the code to copy the constant into
212 // the register here...
213 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000214 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000215 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000216 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
217 // Move the address of the global into the register
Brian Gaeke71794c02002-12-13 11:22:48 +0000218 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
Chris Lattnerd6c4cfa2002-12-04 17:15:34 +0000219 } else if (Argument *A = dyn_cast<Argument>(V)) {
Brian Gaeke95780cc2002-12-13 07:56:18 +0000220 // Find the position of the argument in the argument list.
221 const Function *f = F->getFunction ();
Brian Gaekeed6902c2002-12-13 09:28:50 +0000222 // The function's arguments look like this:
223 // [EBP] -- copy of old EBP
224 // [EBP + 4] -- return address
225 // [EBP + 8] -- first argument (leftmost lexically)
226 // So we want to start with counter = 2.
Chris Lattner333b2fa2002-12-13 10:09:43 +0000227 int counter = 2, argPos = -1;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000228 for (Function::const_aiterator ai = f->abegin (), ae = f->aend ();
229 ai != ae; ++ai) {
Brian Gaeke95780cc2002-12-13 07:56:18 +0000230 if (&(*ai) == A) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000231 argPos = counter;
Brian Gaekeed6902c2002-12-13 09:28:50 +0000232 break; // Only need to find it once. ;-)
Brian Gaeke95780cc2002-12-13 07:56:18 +0000233 }
Brian Gaekeed6902c2002-12-13 09:28:50 +0000234 ++counter;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000235 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000236 assert (argPos != -1
Brian Gaeke95780cc2002-12-13 07:56:18 +0000237 && "Argument not found in current function's argument list");
Chris Lattner333b2fa2002-12-13 10:09:43 +0000238 // Load it out of the stack frame at EBP + 4*argPos.
Brian Gaeke71794c02002-12-13 11:22:48 +0000239 addRegOffset(BMI(MBB, IPt, X86::MOVmr32, 4, Reg), X86::EBP, 4*argPos);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000240 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000241
Chris Lattner72614082002-10-25 22:55:53 +0000242 return Reg;
243 }
Chris Lattner72614082002-10-25 22:55:53 +0000244 };
245}
246
Chris Lattner43189d12002-11-17 20:07:45 +0000247/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
248/// Representation.
249///
250enum TypeClass {
251 cByte, cShort, cInt, cLong, cFloat, cDouble
252};
253
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000254/// getClass - Turn a primitive type into a "class" number which is based on the
255/// size of the type, and whether or not it is floating point.
256///
Chris Lattner43189d12002-11-17 20:07:45 +0000257static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000258 switch (Ty->getPrimitiveID()) {
259 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000260 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000261 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000262 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000263 case Type::IntTyID:
264 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000265 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000266
267 case Type::LongTyID:
Chris Lattnerc0812d82002-12-13 06:56:29 +0000268 case Type::ULongTyID: //return cLong; // Longs are class #3
269 return cInt; // FIXME: LONGS ARE TREATED AS INTS!
270
Chris Lattner43189d12002-11-17 20:07:45 +0000271 case Type::FloatTyID: return cFloat; // Float is class #4
272 case Type::DoubleTyID: return cDouble; // Doubles are class #5
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000273 default:
274 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000275 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000276 }
277}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000278
Chris Lattner6b993cc2002-12-15 08:02:15 +0000279// getClassB - Just like getClass, but treat boolean values as bytes.
280static inline TypeClass getClassB(const Type *Ty) {
281 if (Ty == Type::BoolTy) return cByte;
282 return getClass(Ty);
283}
284
Chris Lattner06925362002-11-17 21:56:38 +0000285
Chris Lattnerc5291f52002-10-27 21:16:59 +0000286/// copyConstantToRegister - Output the instructions required to put the
287/// specified constant into the specified register.
288///
Chris Lattner8a307e82002-12-16 19:32:50 +0000289void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
290 MachineBasicBlock::iterator &IP,
291 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000292 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
293 if (CE->getOpcode() == Instruction::GetElementPtr) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000294 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000295 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000296 return;
297 }
298
Brian Gaeke20244b72002-12-12 15:33:40 +0000299 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerc0812d82002-12-13 06:56:29 +0000300 assert (0 && "Constant expressions not yet handled!\n");
Brian Gaeke20244b72002-12-12 15:33:40 +0000301 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000302
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000303 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000304 unsigned Class = getClassB(C->getType());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000305 assert(Class != 3 && "Type not handled yet!");
306
307 static const unsigned IntegralOpcodeTab[] = {
308 X86::MOVir8, X86::MOVir16, X86::MOVir32
309 };
310
Chris Lattner6b993cc2002-12-15 08:02:15 +0000311 if (C->getType() == Type::BoolTy) {
312 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
313 } else if (C->getType()->isSigned()) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000314 ConstantSInt *CSI = cast<ConstantSInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000315 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000316 } else {
317 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000318 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000319 }
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000320 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000321 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000322 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000323 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000324 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000325 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000326 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000327 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000328 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000329 }
330}
331
Chris Lattner333b2fa2002-12-13 10:09:43 +0000332/// SelectPHINodes - Insert machine code to generate phis. This is tricky
333/// because we have to generate our sources into the source basic blocks, not
334/// the current one.
335///
336void ISel::SelectPHINodes() {
337 const Function &LF = *F->getFunction(); // The LLVM function...
338 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
339 const BasicBlock *BB = I;
340 MachineBasicBlock *MBB = MBBMap[I];
341
342 // Loop over all of the PHI nodes in the LLVM basic block...
343 unsigned NumPHIs = 0;
344 for (BasicBlock::const_iterator I = BB->begin();
345 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
346 // Create a new machine instr PHI node, and insert it.
347 MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
348 MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
349
350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
351 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
352
353 // Get the incoming value into a virtual register. If it is not already
354 // available in a virtual register, insert the computation code into
355 // PredMBB
Chris Lattner92053632002-12-13 11:52:34 +0000356 //
357
358 MachineBasicBlock::iterator PI = PredMBB->begin();
359 while ((*PI)->getOpcode() == X86::PHI) ++PI;
360
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000361 MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
Chris Lattner6b993cc2002-12-15 08:02:15 +0000362 MI->addMachineBasicBlockOperand(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000363 }
364 }
365 }
366}
367
368
Chris Lattner06925362002-11-17 21:56:38 +0000369
Brian Gaeke1749d632002-11-07 17:59:21 +0000370/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
371/// register, then move it to wherever the result should be.
372/// We handle FP setcc instructions by pushing them, doing a
373/// compare-and-pop-twice, and then copying the concodes to the main
374/// processor's concodes (I didn't make this up, it's in the Intel manual)
375///
Chris Lattner05093a52002-11-21 15:52:38 +0000376void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000377 // The arguments are already supposed to be of the same type.
Chris Lattner05093a52002-11-21 15:52:38 +0000378 const Type *CompTy = I.getOperand(0)->getType();
379 unsigned reg1 = getReg(I.getOperand(0));
380 unsigned reg2 = getReg(I.getOperand(1));
381
382 unsigned Class = getClass(CompTy);
383 switch (Class) {
384 // Emit: cmp <var1>, <var2> (do the comparison). We can
385 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
386 // 32-bit.
387 case cByte:
388 BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
389 break;
390 case cShort:
391 BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
392 break;
393 case cInt:
394 BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
395 break;
396
397 // Push the variables on the stack with fldl opcodes.
398 // FIXME: assuming var1, var2 are in memory, if not, spill to
399 // stack first
400 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000401 BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
402 BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000403 break;
404 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000405 BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
406 BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000407 break;
408 case cLong:
409 default:
410 visitInstruction(I);
411 }
412
413 if (CompTy->isFloatingPoint()) {
414 // (Non-trapping) compare and pop twice.
415 BuildMI (BB, X86::FUCOMPP, 0);
416 // Move fp status word (concodes) to ax.
417 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
418 // Load real concodes from ax.
419 BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
420 }
421
Brian Gaeke1749d632002-11-07 17:59:21 +0000422 // Emit setOp instruction (extract concode; clobbers ax),
423 // using the following mapping:
424 // LLVM -> X86 signed X86 unsigned
425 // ----- ----- -----
426 // seteq -> sete sete
427 // setne -> setne setne
428 // setlt -> setl setb
429 // setgt -> setg seta
430 // setle -> setle setbe
431 // setge -> setge setae
Chris Lattner05093a52002-11-21 15:52:38 +0000432
433 static const unsigned OpcodeTab[2][6] = {
Chris Lattner4b4e9dd2002-11-21 16:19:42 +0000434 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
435 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
Chris Lattner05093a52002-11-21 15:52:38 +0000436 };
437
438 BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
439
Brian Gaeke1749d632002-11-07 17:59:21 +0000440 // Put it in the result using a move.
Chris Lattner05093a52002-11-21 15:52:38 +0000441 BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
Brian Gaeke1749d632002-11-07 17:59:21 +0000442}
Chris Lattner51b49a92002-11-02 19:45:49 +0000443
Brian Gaekec2505982002-11-30 11:57:28 +0000444/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
445/// operand, in the specified target register.
446void
Chris Lattnerc0812d82002-12-13 06:56:29 +0000447ISel::promote32 (unsigned targetReg, Value *v)
Brian Gaekec2505982002-11-30 11:57:28 +0000448{
449 unsigned vReg = getReg (v);
450 unsigned Class = getClass (v->getType ());
451 bool isUnsigned = v->getType ()->isUnsigned ();
452 assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
453 && "Unpromotable operand class in promote32");
454 switch (Class)
455 {
456 case cByte:
457 // Extend value into target register (8->32)
458 if (isUnsigned)
459 BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
460 else
461 BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
462 break;
463 case cShort:
464 // Extend value into target register (16->32)
465 if (isUnsigned)
466 BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
467 else
468 BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
469 break;
470 case cInt:
471 // Move value into target register (32->32)
472 BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
473 break;
474 }
475}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000476
Chris Lattner72614082002-10-25 22:55:53 +0000477/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
478/// we have the following possibilities:
479///
480/// ret void: No return value, simply emit a 'ret' instruction
481/// ret sbyte, ubyte : Extend value into EAX and return
482/// ret short, ushort: Extend value into EAX and return
483/// ret int, uint : Move value into EAX and return
484/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000485/// ret long, ulong : Move value into EAX/EDX and return
486/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000487///
Brian Gaekec2505982002-11-30 11:57:28 +0000488void
489ISel::visitReturnInst (ReturnInst &I)
490{
491 if (I.getNumOperands () == 0)
492 {
493 // Emit a 'ret' instruction
494 BuildMI (BB, X86::RET, 0);
495 return;
496 }
497 Value *rv = I.getOperand (0);
498 unsigned Class = getClass (rv->getType ());
499 switch (Class)
500 {
501 // integral return values: extend or move into EAX and return.
502 case cByte:
503 case cShort:
504 case cInt:
505 promote32 (X86::EAX, rv);
506 break;
507 // ret float/double: top of FP stack
508 // FLD <val>
509 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000510 BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000511 break;
512 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000513 BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000514 break;
515 case cLong:
516 // ret long: use EAX(least significant 32 bits)/EDX (most
517 // significant 32)...uh, I think so Brain, but how do i call
518 // up the two parts of the value from inside this mouse
519 // cage? *zort*
520 default:
521 visitInstruction (I);
522 }
Chris Lattner43189d12002-11-17 20:07:45 +0000523 // Emit a 'ret' instruction
Brian Gaekec2505982002-11-30 11:57:28 +0000524 BuildMI (BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000525}
526
Chris Lattner51b49a92002-11-02 19:45:49 +0000527/// visitBranchInst - Handle conditional and unconditional branches here. Note
528/// that since code layout is frozen at this point, that if we are trying to
529/// jump to a block that is the immediate successor of the current block, we can
530/// just make a fall-through. (but we don't currently).
531///
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000532void
533ISel::visitBranchInst (BranchInst & BI)
534{
535 if (BI.isConditional ())
536 {
537 BasicBlock *ifTrue = BI.getSuccessor (0);
538 BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious
Chris Lattner2df035b2002-11-02 19:27:56 +0000539
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000540 // simplest thing I can think of: compare condition with zero,
541 // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
542 // ifTrue
543 unsigned int condReg = getReg (BI.getCondition ());
Chris Lattner97ad9e12002-11-21 01:59:50 +0000544 BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000545 BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
546 BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
547 }
548 else // unconditional branch
549 {
550 BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
551 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000552}
553
Brian Gaeke18a20212002-11-29 12:01:58 +0000554/// visitCallInst - Push args on stack and do a procedure call instruction.
555void
556ISel::visitCallInst (CallInst & CI)
557{
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000558 // keep a counter of how many bytes we pushed on the stack
559 unsigned bytesPushed = 0;
560
Brian Gaeke18a20212002-11-29 12:01:58 +0000561 // Push the arguments on the stack in reverse order, as specified by
562 // the ABI.
Chris Lattnerd852c152002-12-03 20:30:12 +0000563 for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
Brian Gaeke18a20212002-11-29 12:01:58 +0000564 {
565 Value *v = CI.getOperand (i);
Brian Gaeke18a20212002-11-29 12:01:58 +0000566 switch (getClass (v->getType ()))
567 {
Brian Gaekec2505982002-11-30 11:57:28 +0000568 case cByte:
569 case cShort:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000570 // Promote V to 32 bits wide, and move the result into EAX,
571 // then push EAX.
Brian Gaekec2505982002-11-30 11:57:28 +0000572 promote32 (X86::EAX, v);
573 BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000574 bytesPushed += 4;
Brian Gaekec2505982002-11-30 11:57:28 +0000575 break;
Brian Gaeke18a20212002-11-29 12:01:58 +0000576 case cInt:
Chris Lattner33ced562002-12-04 06:56:56 +0000577 case cFloat: {
578 unsigned Reg = getReg(v);
579 BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000580 bytesPushed += 4;
Brian Gaeke18a20212002-11-29 12:01:58 +0000581 break;
Chris Lattner33ced562002-12-04 06:56:56 +0000582 }
Brian Gaeke18a20212002-11-29 12:01:58 +0000583 default:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000584 // FIXME: long/ulong/double args not handled.
Brian Gaeke18a20212002-11-29 12:01:58 +0000585 visitInstruction (CI);
586 break;
587 }
588 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +0000589
590 if (Function *F = CI.getCalledFunction()) {
591 // Emit a CALL instruction with PC-relative displacement.
592 BuildMI(BB, X86::CALLpcrel32, 1).addPCDisp(F);
593 } else {
594 unsigned Reg = getReg(CI.getCalledValue());
595 BuildMI(BB, X86::CALLr32, 1).addReg(Reg);
596 }
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000597
598 // Adjust the stack by `bytesPushed' amount if non-zero
599 if (bytesPushed > 0)
600 BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
Chris Lattnera3243642002-12-04 23:45:28 +0000601
602 // If there is a return value, scavenge the result from the location the call
603 // leaves it in...
604 //
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000605 if (CI.getType() != Type::VoidTy) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000606 unsigned resultTypeClass = getClass (CI.getType ());
607 switch (resultTypeClass) {
608 case cByte:
609 case cShort:
610 case cInt: {
611 // Integral results are in %eax, or the appropriate portion
612 // thereof.
613 static const unsigned regRegMove[] = {
614 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
615 };
616 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
617 BuildMI (BB, regRegMove[resultTypeClass], 1,
618 getReg (CI)).addReg (AReg[resultTypeClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000619 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000620 }
621 case cFloat:
622 // Floating-point return values live in %st(0) (i.e., the top of
623 // the FP stack.) The general way to approach this is to do a
624 // FSTP to save the top of the FP stack on the real stack, then
625 // do a MOV to load the top of the real stack into the target
626 // register.
627 visitInstruction (CI); // FIXME: add the right args for the calls below
628 // BuildMI (BB, X86::FSTPm32, 0);
629 // BuildMI (BB, X86::MOVmr32, 0);
630 break;
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000631 default:
632 std::cerr << "Cannot get return value for call of type '"
633 << *CI.getType() << "'\n";
634 visitInstruction(CI);
635 }
Chris Lattnera3243642002-12-04 23:45:28 +0000636 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000637}
Chris Lattner2df035b2002-11-02 19:27:56 +0000638
Chris Lattner68aad932002-11-02 20:13:22 +0000639/// visitSimpleBinary - Implement simple binary operators for integral types...
640/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
641/// 4 for Xor.
642///
643void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
644 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
Chris Lattnere2954c82002-11-02 20:04:26 +0000645 visitInstruction(B);
646
647 unsigned Class = getClass(B.getType());
648 if (Class > 2) // FIXME: Handle longs
649 visitInstruction(B);
650
651 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000652 // Arithmetic operators
653 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
654 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
655
656 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000657 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
658 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
659 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
660 };
661
662 unsigned Opcode = OpcodeTab[OperatorClass][Class];
663 unsigned Op0r = getReg(B.getOperand(0));
664 unsigned Op1r = getReg(B.getOperand(1));
665 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
666}
667
Brian Gaeke20244b72002-12-12 15:33:40 +0000668/// doMultiply - Emit appropriate instructions to multiply together
669/// the registers op0Reg and op1Reg, and put the result in destReg.
670/// The type of the result should be given as resultType.
Chris Lattner8a307e82002-12-16 19:32:50 +0000671void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
672 unsigned destReg, const Type *resultType,
673 unsigned op0Reg, unsigned op1Reg) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000674 unsigned Class = getClass (resultType);
675
676 // FIXME:
677 assert (Class <= 2 && "Someday, we will learn how to multiply"
678 "longs and floating-point numbers. This is not that day.");
679
680 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
681 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
682 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
683 unsigned Reg = Regs[Class];
684
685 // Emit a MOV to put the first operand into the appropriately-sized
686 // subreg of EAX.
Brian Gaeke71794c02002-12-13 11:22:48 +0000687 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000688
689 // Emit the appropriate multiply instruction.
Brian Gaeke71794c02002-12-13 11:22:48 +0000690 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000691
692 // Emit another MOV to put the result into the destination register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000693 BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000694}
695
Chris Lattnerca9671d2002-11-02 20:28:58 +0000696/// visitMul - Multiplies are not simple binary operators because they must deal
697/// with the EAX register explicitly.
698///
699void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +0000700 unsigned DestReg = getReg(I);
701 unsigned Op0Reg = getReg(I.getOperand(0));
702 unsigned Op1Reg = getReg(I.getOperand(1));
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000703 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattner8a307e82002-12-16 19:32:50 +0000704 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000705}
Chris Lattnerca9671d2002-11-02 20:28:58 +0000706
Chris Lattner06925362002-11-17 21:56:38 +0000707
Chris Lattnerf01729e2002-11-02 20:54:46 +0000708/// visitDivRem - Handle division and remainder instructions... these
709/// instruction both require the same instructions to be generated, they just
710/// select the result from a different register. Note that both of these
711/// instructions work differently for signed and unsigned operands.
712///
713void ISel::visitDivRem(BinaryOperator &I) {
714 unsigned Class = getClass(I.getType());
715 if (Class > 2) // FIXME: Handle longs
716 visitInstruction(I);
717
718 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
719 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +0000720 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +0000721 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
722 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
723
724 static const unsigned DivOpcode[][4] = {
725 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
726 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
727 };
728
729 bool isSigned = I.getType()->isSigned();
730 unsigned Reg = Regs[Class];
731 unsigned ExtReg = ExtRegs[Class];
Chris Lattner6fc3c522002-11-17 21:11:55 +0000732 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000733 unsigned Op1Reg = getReg(I.getOperand(1));
734
735 // Put the first operand into one of the A registers...
736 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
737
738 if (isSigned) {
739 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +0000740 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000741 } else {
742 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
743 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
744 }
745
Chris Lattner06925362002-11-17 21:56:38 +0000746 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +0000747 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +0000748
Chris Lattnerf01729e2002-11-02 20:54:46 +0000749 // Figure out which register we want to pick the result out of...
750 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
751
Chris Lattnerf01729e2002-11-02 20:54:46 +0000752 // Put the result into the destination register...
753 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000754}
Chris Lattnere2954c82002-11-02 20:04:26 +0000755
Chris Lattner06925362002-11-17 21:56:38 +0000756
Brian Gaekea1719c92002-10-31 23:03:59 +0000757/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
758/// for constant immediate shift values, and for constant immediate
759/// shift values equal to 1. Even the general case is sort of special,
760/// because the shift amount has to be in CL, not just any old register.
761///
Chris Lattnerf01729e2002-11-02 20:54:46 +0000762void ISel::visitShiftInst (ShiftInst &I) {
763 unsigned Op0r = getReg (I.getOperand(0));
764 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +0000765 bool isLeftShift = I.getOpcode() == Instruction::Shl;
766 bool isOperandSigned = I.getType()->isUnsigned();
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000767 unsigned OperandClass = getClass(I.getType());
768
769 if (OperandClass > 2)
770 visitInstruction(I); // Can't handle longs yet!
Chris Lattner796df732002-11-02 00:44:25 +0000771
Brian Gaekea1719c92002-10-31 23:03:59 +0000772 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
773 {
Chris Lattner796df732002-11-02 00:44:25 +0000774 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
775 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
776 unsigned char shAmt = CUI->getValue();
777
Chris Lattnere9913f22002-11-02 01:41:55 +0000778 static const unsigned ConstantOperand[][4] = {
779 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
780 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
781 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
782 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000783 };
784
Chris Lattnere9913f22002-11-02 01:41:55 +0000785 const unsigned *OpTab = // Figure out the operand table to use
786 ConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000787
Brian Gaekea1719c92002-10-31 23:03:59 +0000788 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000789 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
Brian Gaekea1719c92002-10-31 23:03:59 +0000790 }
791 else
792 {
793 // The shift amount is non-constant.
794 //
795 // In fact, you can only shift with a variable shift amount if
796 // that amount is already in the CL register, so we have to put it
797 // there first.
798 //
Chris Lattnere9913f22002-11-02 01:41:55 +0000799
Brian Gaekea1719c92002-10-31 23:03:59 +0000800 // Emit: move cl, shiftAmount (put the shift amount in CL.)
Chris Lattnerca9671d2002-11-02 20:28:58 +0000801 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000802
803 // This is a shift right (SHR).
Chris Lattnere9913f22002-11-02 01:41:55 +0000804 static const unsigned NonConstantOperand[][4] = {
805 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
806 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
807 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
808 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000809 };
810
Chris Lattnere9913f22002-11-02 01:41:55 +0000811 const unsigned *OpTab = // Figure out the operand table to use
812 NonConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000813
Chris Lattner3a9a6932002-11-21 22:49:20 +0000814 BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
Brian Gaekea1719c92002-10-31 23:03:59 +0000815 }
816}
817
Chris Lattner06925362002-11-17 21:56:38 +0000818
Chris Lattner6fc3c522002-11-17 21:11:55 +0000819/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
820/// instruction.
821///
822void ISel::visitLoadInst(LoadInst &I) {
823 unsigned Class = getClass(I.getType());
824 if (Class > 2) // FIXME: Handle longs and others...
825 visitInstruction(I);
826
827 static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
828
829 unsigned AddressReg = getReg(I.getOperand(0));
830 addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
831}
832
Chris Lattner06925362002-11-17 21:56:38 +0000833
Chris Lattner6fc3c522002-11-17 21:11:55 +0000834/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
835/// instruction.
836///
837void ISel::visitStoreInst(StoreInst &I) {
838 unsigned Class = getClass(I.getOperand(0)->getType());
839 if (Class > 2) // FIXME: Handle longs and others...
840 visitInstruction(I);
841
842 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
843
844 unsigned ValReg = getReg(I.getOperand(0));
845 unsigned AddressReg = getReg(I.getOperand(1));
846 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
847}
848
849
Brian Gaekec11232a2002-11-26 10:43:30 +0000850/// visitCastInst - Here we have various kinds of copying with or without
851/// sign extension going on.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000852void
853ISel::visitCastInst (CastInst &CI)
854{
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000855 const Type *targetType = CI.getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000856 Value *operand = CI.getOperand (0);
857 unsigned int operandReg = getReg (operand);
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000858 const Type *sourceType = operand->getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000859 unsigned int destReg = getReg (CI);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000860 //
861 // Currently we handle:
862 //
863 // 1) cast * to bool
864 //
865 // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
866 // cast {short, ushort} to {ushort, short}
867 // cast {int, uint, ptr} to {int, uint, ptr}
868 //
869 // 3) cast {sbyte, ubyte} to {ushort, short}
870 // cast {sbyte, ubyte} to {int, uint, ptr}
871 // cast {short, ushort} to {int, uint, ptr}
872 //
873 // 4) cast {int, uint, ptr} to {short, ushort}
874 // cast {int, uint, ptr} to {sbyte, ubyte}
875 // cast {short, ushort} to {sbyte, ubyte}
Chris Lattner7d255892002-12-13 11:31:59 +0000876
Brian Gaeked474e9c2002-12-06 10:49:33 +0000877 // 1) Implement casts to bool by using compare on the operand followed
878 // by set if not zero on the result.
879 if (targetType == Type::BoolTy)
880 {
881 BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
882 BuildMI (BB, X86::SETNEr, 1, destReg);
883 return;
884 }
Chris Lattner7d255892002-12-13 11:31:59 +0000885
Brian Gaeked474e9c2002-12-06 10:49:33 +0000886 // 2) Implement casts between values of the same type class (as determined
887 // by getClass) by using a register-to-register move.
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000888 unsigned srcClass = getClassB (sourceType);
Chris Lattner7d255892002-12-13 11:31:59 +0000889 unsigned targClass = getClass (targetType);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000890 static const unsigned regRegMove[] = {
891 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
892 };
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000893 if ((srcClass < cLong) && (targClass < cLong) && (srcClass == targClass))
Brian Gaeked474e9c2002-12-06 10:49:33 +0000894 {
895 BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
896 return;
897 }
898 // 3) Handle cast of SMALLER int to LARGER int using a move with sign
899 // extension or zero extension, depending on whether the source type
900 // was signed.
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000901 if ((srcClass < cLong) && (targClass < cLong) && (srcClass < targClass))
Brian Gaeked474e9c2002-12-06 10:49:33 +0000902 {
903 static const unsigned ops[] = {
904 X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
905 X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
906 };
907 unsigned srcSigned = sourceType->isSigned ();
908 BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
909 destReg).addReg (operandReg);
910 return;
911 }
912 // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
913 // followed by a move out of AX or AL.
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000914 if ((srcClass < cLong) && (targClass < cLong) && (srcClass > targClass))
Brian Gaeked474e9c2002-12-06 10:49:33 +0000915 {
916 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
917 BuildMI (BB, regRegMove[srcClass], 1,
918 AReg[srcClass]).addReg (operandReg);
919 BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
920 return;
921 }
922 // Anything we haven't handled already, we can't (yet) handle at all.
Brian Gaeke20244b72002-12-12 15:33:40 +0000923 //
924 // FP to integral casts can be handled with FISTP to store onto the
925 // stack while converting to integer, followed by a MOV to load from
926 // the stack into the result register. Integral to FP casts can be
927 // handled with MOV to store onto the stack, followed by a FILD to
928 // load from the stack while converting to FP. For the moment, I
929 // can't quite get straight in my head how to borrow myself some
930 // stack space and write on it. Otherwise, this would be trivial.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000931 visitInstruction (CI);
932}
Brian Gaekea1719c92002-10-31 23:03:59 +0000933
Chris Lattner8a307e82002-12-16 19:32:50 +0000934// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
935// returns zero when the input is not exactly a power of two.
936static unsigned ExactLog2(unsigned Val) {
937 if (Val == 0) return 0;
938 unsigned Count = 0;
939 while (Val != 1) {
940 if (Val & 1) return 0;
941 Val >>= 1;
942 ++Count;
943 }
944 return Count+1;
945}
946
Brian Gaeke20244b72002-12-12 15:33:40 +0000947/// visitGetElementPtrInst - I don't know, most programs don't have
948/// getelementptr instructions, right? That means we can put off
949/// implementing this, right? Right. This method emits machine
950/// instructions to perform type-safe pointer arithmetic. I am
951/// guessing this could be cleaned up somewhat to use fewer temporary
952/// registers.
953void
954ISel::visitGetElementPtrInst (GetElementPtrInst &I)
955{
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000956 unsigned outputReg = getReg (I);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000957 MachineBasicBlock::iterator MI = BB->end();
958 emitGEPOperation(BB, MI, I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000959 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000960}
961
Brian Gaeke71794c02002-12-13 11:22:48 +0000962void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000963 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000964 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000965 User::op_iterator IdxEnd, unsigned TargetReg) {
966 const TargetData &TD = TM.getTargetData();
967 const Type *Ty = Src->getType();
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000968 unsigned basePtrReg = getReg(Src, MBB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000969
Brian Gaeke20244b72002-12-12 15:33:40 +0000970 // GEPs have zero or more indices; we must perform a struct access
971 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000972 for (GetElementPtrInst::op_iterator oi = IdxBegin,
973 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000974 Value *idx = *oi;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000975 unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000976 if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
977 // It's a struct access. idx is the index into the structure,
978 // which names the field. This index must have ubyte type.
979 const ConstantUInt *CUI = cast <ConstantUInt> (idx);
980 assert (CUI->getType () == Type::UByteTy
981 && "Funny-looking structure index in GEP");
982 // Use the TargetData structure to pick out what the layout of
983 // the structure is in memory. Since the structure index must
984 // be constant, we can get its value and use it to find the
985 // right byte offset from the StructLayout class's list of
986 // structure member offsets.
987 unsigned idxValue = CUI->getValue ();
988 unsigned memberOffset =
989 TD.getStructLayout (StTy)->MemberOffsets[idxValue];
990 // Emit an ADD to add memberOffset to the basePtr.
Brian Gaeke71794c02002-12-13 11:22:48 +0000991 BMI(MBB, IP, X86::ADDri32, 2,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000992 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
Brian Gaeke20244b72002-12-12 15:33:40 +0000993 // The next type is the member of the structure selected by the
994 // index.
995 Ty = StTy->getElementTypes ()[idxValue];
Chris Lattner8a307e82002-12-16 19:32:50 +0000996 } else if (const SequentialType *SqTy = cast <SequentialType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000997 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner8a307e82002-12-16 19:32:50 +0000998
Brian Gaeke20244b72002-12-12 15:33:40 +0000999 // idx is the index into the array. Unlike with structure
1000 // indices, we may not know its actual value at code-generation
1001 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00001002 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1003
1004 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1005 // must find the size of the pointed-to type (Not coincidentally, the next
1006 // type is the type of the elements in the array).
1007 Ty = SqTy->getElementType();
1008 unsigned elementSize = TD.getTypeSize(Ty);
1009
1010 // If idxReg is a constant, we don't need to perform the multiply!
1011 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1012 if (CSI->isNullValue()) {
1013 BMI(MBB, IP, X86::MOVrr32, 1, nextBasePtrReg).addReg(basePtrReg);
1014 } else {
1015 unsigned Offset = elementSize*CSI->getValue();
1016
1017 BMI(MBB, IP, X86::ADDri32, 2,
1018 nextBasePtrReg).addReg(basePtrReg).addZImm(Offset);
1019 }
1020 } else if (elementSize == 1) {
1021 // If the element size is 1, we don't have to multiply, just add
1022 unsigned idxReg = getReg(idx, MBB, IP);
1023 BMI(MBB, IP, X86::ADDrr32, 2,
1024 nextBasePtrReg).addReg(basePtrReg).addReg(idxReg);
1025 } else {
1026 unsigned idxReg = getReg(idx, MBB, IP);
1027 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1028 if (unsigned Shift = ExactLog2(elementSize)) {
1029 // If the element size is exactly a power of 2, use a shift to get it.
1030
1031 BMI(MBB, IP, X86::SHLir32, 2,
1032 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1033 } else {
1034 // Most general case, emit a multiply...
1035 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1036 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1037
1038 // Emit a MUL to multiply the register holding the index by
1039 // elementSize, putting the result in OffsetReg.
1040 doMultiply(MBB, IP, OffsetReg, Type::LongTy, idxReg, elementSizeReg);
1041 }
1042 // Emit an ADD to add OffsetReg to the basePtr.
1043 BMI(MBB, IP, X86::ADDrr32, 2,
1044 nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1045 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001046 }
1047 // Now that we are here, further indices refer to subtypes of this
1048 // one, so we don't need to worry about basePtrReg itself, anymore.
1049 basePtrReg = nextBasePtrReg;
1050 }
1051 // After we have processed all the indices, the result is left in
1052 // basePtrReg. Move it to the register where we were expected to
1053 // put the answer. A 32-bit move should do it, because we are in
1054 // ILP32 land.
Brian Gaeke71794c02002-12-13 11:22:48 +00001055 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001056}
1057
1058
1059/// visitMallocInst - I know that personally, whenever I want to remember
1060/// something, I have to clear off some space in my brain.
1061void
1062ISel::visitMallocInst (MallocInst &I)
1063{
Brian Gaekee48ec012002-12-13 06:46:31 +00001064 // We assume that by this point, malloc instructions have been
1065 // lowered to calls, and dlsym will magically find malloc for us.
1066 // So we do not want to see malloc instructions here.
1067 visitInstruction (I);
1068}
1069
1070
1071/// visitFreeInst - same story as MallocInst
1072void
1073ISel::visitFreeInst (FreeInst &I)
1074{
1075 // We assume that by this point, free instructions have been
1076 // lowered to calls, and dlsym will magically find free for us.
1077 // So we do not want to see free instructions here.
Brian Gaeke20244b72002-12-12 15:33:40 +00001078 visitInstruction (I);
1079}
1080
1081
1082/// visitAllocaInst - I want some stack space. Come on, man, I said I
1083/// want some freakin' stack space.
1084void
1085ISel::visitAllocaInst (AllocaInst &I)
1086{
Brian Gaekee48ec012002-12-13 06:46:31 +00001087 // Find the data size of the alloca inst's getAllocatedType.
1088 const Type *allocatedType = I.getAllocatedType ();
1089 const TargetData &TD = TM.DataLayout;
1090 unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1091 // Keep stack 32-bit aligned.
1092 unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1093 if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1094 // Subtract size from stack pointer, thereby allocating some space.
Chris Lattner4863fe12002-12-16 22:29:06 +00001095 BuildMI(BB, X86::SUBri32, 2,
1096 X86::ESP).addReg(X86::ESP).addZImm(allocatedTypeWords * 4);
Brian Gaekee48ec012002-12-13 06:46:31 +00001097 // Put a pointer to the space into the result register, by copying
1098 // the stack pointer.
1099 BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
Brian Gaeke20244b72002-12-12 15:33:40 +00001100}
1101
1102
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001103/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1104/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001105/// generated code sucks but the implementation is nice and simple.
1106///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001107Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1108 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001109}