blob: cad8e0d912f1bb1b898769dcf5d9b088a6c24f57 [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) {
38 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Brian Gaeke71794c02002-12-13 11:22:48 +000039 I = ++MBB->insert(I, MI);
Chris Lattner333b2fa2002-12-13 10:09:43 +000040 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
41}
42
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000043/// BMI - A special BuildMI variant that takes an iterator to insert the
44/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000045inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000046 MachineBasicBlock::iterator &I,
47 MachineOpCode Opcode,
48 unsigned NumOperands) {
49 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Brian Gaeke71794c02002-12-13 11:22:48 +000050 I = ++MBB->insert(I, MI);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000051 return MachineInstrBuilder(MI);
52}
53
Chris Lattner333b2fa2002-12-13 10:09:43 +000054
Chris Lattner72614082002-10-25 22:55:53 +000055namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000056 struct ISel : public FunctionPass, InstVisitor<ISel> {
57 TargetMachine &TM;
Chris Lattner341a9372002-10-29 17:43:55 +000058 MachineFunction *F; // The function we are compiling into
59 MachineBasicBlock *BB; // The current MBB we are compiling
Chris Lattner72614082002-10-25 22:55:53 +000060
61 unsigned CurReg;
62 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
63
Chris Lattner333b2fa2002-12-13 10:09:43 +000064 // MBBMap - Mapping between LLVM BB -> Machine BB
65 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
66
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000067 ISel(TargetMachine &tm)
68 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
Chris Lattner72614082002-10-25 22:55:53 +000069
70 /// runOnFunction - Top level implementation of instruction selection for
71 /// the entire function.
72 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000073 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000074 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000075
76 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
77 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
78
79 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000080 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000081
82 // Select the PHI nodes
83 SelectPHINodes();
84
Chris Lattner72614082002-10-25 22:55:53 +000085 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000086 MBBMap.clear();
Chris Lattner94e8ee22002-11-21 17:26:58 +000087 CurReg = MRegisterInfo::FirstVirtualRegister;
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000088 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000089 return false; // We never modify the LLVM itself.
90 }
91
92 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000093 /// block. This simply creates a new MachineBasicBlock to emit code into
94 /// and adds it to the current MachineFunction. Subsequent visit* for
95 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +000096 ///
97 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +000098 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +000099 }
100
Chris Lattner333b2fa2002-12-13 10:09:43 +0000101
102 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
103 /// because we have to generate our sources into the source basic blocks,
104 /// not the current one.
105 ///
106 void SelectPHINodes();
107
Chris Lattner72614082002-10-25 22:55:53 +0000108 // Visitation methods for various instructions. These methods simply emit
109 // fixed X86 code for each instruction.
110 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000111
112 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000113 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000114 void visitBranchInst(BranchInst &BI);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000115 void visitCallInst(CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000116
117 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000118 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000119 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
120 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Brian Gaeke20244b72002-12-12 15:33:40 +0000121 void doMultiply(unsigned destReg, const Type *resultType,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000122 unsigned op0Reg, unsigned op1Reg,
123 MachineBasicBlock *MBB,
124 MachineBasicBlock::iterator &MBBI);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000125 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000126
Chris Lattnerf01729e2002-11-02 20:54:46 +0000127 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
128 void visitRem(BinaryOperator &B) { visitDivRem(B); }
129 void visitDivRem(BinaryOperator &B);
130
Chris Lattnere2954c82002-11-02 20:04:26 +0000131 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000132 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
133 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
134 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000135
136 // Binary comparison operators
Chris Lattner05093a52002-11-21 15:52:38 +0000137 void visitSetCCInst(SetCondInst &I, unsigned OpNum);
138 void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
139 void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
140 void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
141 void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
142 void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
143 void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
Chris Lattner6fc3c522002-11-17 21:11:55 +0000144
145 // Memory Instructions
146 void visitLoadInst(LoadInst &I);
147 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000148 void visitGetElementPtrInst(GetElementPtrInst &I);
149 void visitMallocInst(MallocInst &I);
Brian Gaekee48ec012002-12-13 06:46:31 +0000150 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000151 void visitAllocaInst(AllocaInst &I);
152
Chris Lattnere2954c82002-11-02 20:04:26 +0000153 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000154 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000155 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000156 void visitCastInst(CastInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000157
158 void visitInstruction(Instruction &I) {
159 std::cerr << "Cannot instruction select: " << I;
160 abort();
161 }
162
Brian Gaeke95780cc2002-12-13 07:56:18 +0000163 /// promote32 - Make a value 32-bits wide, and put it somewhere.
164 void promote32 (const unsigned targetReg, Value *v);
165
166 // emitGEPOperation - Common code shared between visitGetElementPtrInst and
Chris Lattnerc0812d82002-12-13 06:56:29 +0000167 // constant expression GEP support.
168 //
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000169 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000170 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000171 User::op_iterator IdxEnd, unsigned TargetReg);
172
Chris Lattnerc5291f52002-10-27 21:16:59 +0000173 /// copyConstantToRegister - Output the instructions required to put the
174 /// specified constant into the specified register.
175 ///
Chris Lattner333b2fa2002-12-13 10:09:43 +0000176 void copyConstantToRegister(Constant *C, unsigned Reg,
177 MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000178 MachineBasicBlock::iterator &MBBI);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000179
Brian Gaeke20244b72002-12-12 15:33:40 +0000180 /// makeAnotherReg - This method returns the next register number
181 /// we haven't yet used.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000182 unsigned makeAnotherReg(const Type *Ty) {
183 // Add the mapping of regnumber => reg class to MachineFunction
184 F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
185 return CurReg++;
Brian Gaeke20244b72002-12-12 15:33:40 +0000186 }
187
Chris Lattner72614082002-10-25 22:55:53 +0000188 /// getReg - This method turns an LLVM value into a register number. This
189 /// is guaranteed to produce the same register number for a particular value
190 /// every time it is queried.
191 ///
192 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000193 unsigned getReg(Value *V) {
194 // Just append to the end of the current bb.
195 MachineBasicBlock::iterator It = BB->end();
196 return getReg(V, BB, It);
197 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000198 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000199 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000200 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000201 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000202 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000203 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000204 }
Chris Lattner72614082002-10-25 22:55:53 +0000205
Chris Lattner6f8fd252002-10-27 21:23:43 +0000206 // If this operand is a constant, emit the code to copy the constant into
207 // the register here...
208 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000209 if (Constant *C = dyn_cast<Constant>(V)) {
Brian Gaeke992447f2002-12-13 11:39:18 +0000210 copyConstantToRegister(C, Reg, MBB, IPt);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000211 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
212 // Move the address of the global into the register
Brian Gaeke71794c02002-12-13 11:22:48 +0000213 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
Chris Lattnerd6c4cfa2002-12-04 17:15:34 +0000214 } else if (Argument *A = dyn_cast<Argument>(V)) {
Brian Gaeke95780cc2002-12-13 07:56:18 +0000215 // Find the position of the argument in the argument list.
216 const Function *f = F->getFunction ();
Brian Gaekeed6902c2002-12-13 09:28:50 +0000217 // The function's arguments look like this:
218 // [EBP] -- copy of old EBP
219 // [EBP + 4] -- return address
220 // [EBP + 8] -- first argument (leftmost lexically)
221 // So we want to start with counter = 2.
Chris Lattner333b2fa2002-12-13 10:09:43 +0000222 int counter = 2, argPos = -1;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000223 for (Function::const_aiterator ai = f->abegin (), ae = f->aend ();
224 ai != ae; ++ai) {
Brian Gaeke95780cc2002-12-13 07:56:18 +0000225 if (&(*ai) == A) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000226 argPos = counter;
Brian Gaekeed6902c2002-12-13 09:28:50 +0000227 break; // Only need to find it once. ;-)
Brian Gaeke95780cc2002-12-13 07:56:18 +0000228 }
Brian Gaekeed6902c2002-12-13 09:28:50 +0000229 ++counter;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000230 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000231 assert (argPos != -1
Brian Gaeke95780cc2002-12-13 07:56:18 +0000232 && "Argument not found in current function's argument list");
Chris Lattner333b2fa2002-12-13 10:09:43 +0000233 // Load it out of the stack frame at EBP + 4*argPos.
Brian Gaeke71794c02002-12-13 11:22:48 +0000234 addRegOffset(BMI(MBB, IPt, X86::MOVmr32, 4, Reg), X86::EBP, 4*argPos);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000235 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000236
Chris Lattner72614082002-10-25 22:55:53 +0000237 return Reg;
238 }
Chris Lattner72614082002-10-25 22:55:53 +0000239 };
240}
241
Chris Lattner43189d12002-11-17 20:07:45 +0000242/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
243/// Representation.
244///
245enum TypeClass {
246 cByte, cShort, cInt, cLong, cFloat, cDouble
247};
248
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000249/// getClass - Turn a primitive type into a "class" number which is based on the
250/// size of the type, and whether or not it is floating point.
251///
Chris Lattner43189d12002-11-17 20:07:45 +0000252static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000253 switch (Ty->getPrimitiveID()) {
254 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000255 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000256 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000257 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000258 case Type::IntTyID:
259 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000260 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000261
262 case Type::LongTyID:
Chris Lattnerc0812d82002-12-13 06:56:29 +0000263 case Type::ULongTyID: //return cLong; // Longs are class #3
264 return cInt; // FIXME: LONGS ARE TREATED AS INTS!
265
Chris Lattner43189d12002-11-17 20:07:45 +0000266 case Type::FloatTyID: return cFloat; // Float is class #4
267 case Type::DoubleTyID: return cDouble; // Doubles are class #5
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000268 default:
269 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000270 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000271 }
272}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000273
Chris Lattner06925362002-11-17 21:56:38 +0000274
Chris Lattnerc5291f52002-10-27 21:16:59 +0000275/// copyConstantToRegister - Output the instructions required to put the
276/// specified constant into the specified register.
277///
Chris Lattner333b2fa2002-12-13 10:09:43 +0000278void ISel::copyConstantToRegister(Constant *C, unsigned R,
Brian Gaeke71794c02002-12-13 11:22:48 +0000279 MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000280 MachineBasicBlock::iterator &IP) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
282 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000283 emitGEPOperation(BB, IP, CE->getOperand(0),
284 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000285 return;
286 }
287
Brian Gaeke20244b72002-12-12 15:33:40 +0000288 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerc0812d82002-12-13 06:56:29 +0000289 assert (0 && "Constant expressions not yet handled!\n");
Brian Gaeke20244b72002-12-12 15:33:40 +0000290 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000291
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000292 if (C->getType()->isIntegral()) {
293 unsigned Class = getClass(C->getType());
294 assert(Class != 3 && "Type not handled yet!");
295
296 static const unsigned IntegralOpcodeTab[] = {
297 X86::MOVir8, X86::MOVir16, X86::MOVir32
298 };
299
300 if (C->getType()->isSigned()) {
301 ConstantSInt *CSI = cast<ConstantSInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000302 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000303 } else {
304 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000305 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000306 }
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000307 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000308 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000309 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000310 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000311 unsigned SrcReg = getReg(CPR->getValue(), BB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000312 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000313 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000314 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000315 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000316 }
317}
318
Chris Lattner333b2fa2002-12-13 10:09:43 +0000319/// SelectPHINodes - Insert machine code to generate phis. This is tricky
320/// because we have to generate our sources into the source basic blocks, not
321/// the current one.
322///
323void ISel::SelectPHINodes() {
324 const Function &LF = *F->getFunction(); // The LLVM function...
325 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
326 const BasicBlock *BB = I;
327 MachineBasicBlock *MBB = MBBMap[I];
328
329 // Loop over all of the PHI nodes in the LLVM basic block...
330 unsigned NumPHIs = 0;
331 for (BasicBlock::const_iterator I = BB->begin();
332 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
333 // Create a new machine instr PHI node, and insert it.
334 MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
335 MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
336
337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
338 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
339
340 // Get the incoming value into a virtual register. If it is not already
341 // available in a virtual register, insert the computation code into
342 // PredMBB
Chris Lattner92053632002-12-13 11:52:34 +0000343 //
344
345 MachineBasicBlock::iterator PI = PredMBB->begin();
346 while ((*PI)->getOpcode() == X86::PHI) ++PI;
347
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000348 MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
Chris Lattner333b2fa2002-12-13 10:09:43 +0000349
350 // FIXME: Pass in the MachineBasicBlocks instead of the basic blocks...
351 MI->addPCDispOperand(PN->getIncomingBlock(i)); // PredMBB
352 }
353 }
354 }
355}
356
357
Chris Lattner06925362002-11-17 21:56:38 +0000358
Brian Gaeke1749d632002-11-07 17:59:21 +0000359/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
360/// register, then move it to wherever the result should be.
361/// We handle FP setcc instructions by pushing them, doing a
362/// compare-and-pop-twice, and then copying the concodes to the main
363/// processor's concodes (I didn't make this up, it's in the Intel manual)
364///
Chris Lattner05093a52002-11-21 15:52:38 +0000365void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000366 // The arguments are already supposed to be of the same type.
Chris Lattner05093a52002-11-21 15:52:38 +0000367 const Type *CompTy = I.getOperand(0)->getType();
368 unsigned reg1 = getReg(I.getOperand(0));
369 unsigned reg2 = getReg(I.getOperand(1));
370
371 unsigned Class = getClass(CompTy);
372 switch (Class) {
373 // Emit: cmp <var1>, <var2> (do the comparison). We can
374 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
375 // 32-bit.
376 case cByte:
377 BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
378 break;
379 case cShort:
380 BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
381 break;
382 case cInt:
383 BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
384 break;
385
386 // Push the variables on the stack with fldl opcodes.
387 // FIXME: assuming var1, var2 are in memory, if not, spill to
388 // stack first
389 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000390 BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
391 BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000392 break;
393 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000394 BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
395 BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000396 break;
397 case cLong:
398 default:
399 visitInstruction(I);
400 }
401
402 if (CompTy->isFloatingPoint()) {
403 // (Non-trapping) compare and pop twice.
404 BuildMI (BB, X86::FUCOMPP, 0);
405 // Move fp status word (concodes) to ax.
406 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
407 // Load real concodes from ax.
408 BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
409 }
410
Brian Gaeke1749d632002-11-07 17:59:21 +0000411 // Emit setOp instruction (extract concode; clobbers ax),
412 // using the following mapping:
413 // LLVM -> X86 signed X86 unsigned
414 // ----- ----- -----
415 // seteq -> sete sete
416 // setne -> setne setne
417 // setlt -> setl setb
418 // setgt -> setg seta
419 // setle -> setle setbe
420 // setge -> setge setae
Chris Lattner05093a52002-11-21 15:52:38 +0000421
422 static const unsigned OpcodeTab[2][6] = {
Chris Lattner4b4e9dd2002-11-21 16:19:42 +0000423 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
424 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
Chris Lattner05093a52002-11-21 15:52:38 +0000425 };
426
427 BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
428
Brian Gaeke1749d632002-11-07 17:59:21 +0000429 // Put it in the result using a move.
Chris Lattner05093a52002-11-21 15:52:38 +0000430 BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
Brian Gaeke1749d632002-11-07 17:59:21 +0000431}
Chris Lattner51b49a92002-11-02 19:45:49 +0000432
Brian Gaekec2505982002-11-30 11:57:28 +0000433/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
434/// operand, in the specified target register.
435void
Chris Lattnerc0812d82002-12-13 06:56:29 +0000436ISel::promote32 (unsigned targetReg, Value *v)
Brian Gaekec2505982002-11-30 11:57:28 +0000437{
438 unsigned vReg = getReg (v);
439 unsigned Class = getClass (v->getType ());
440 bool isUnsigned = v->getType ()->isUnsigned ();
441 assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
442 && "Unpromotable operand class in promote32");
443 switch (Class)
444 {
445 case cByte:
446 // Extend value into target register (8->32)
447 if (isUnsigned)
448 BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
449 else
450 BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
451 break;
452 case cShort:
453 // Extend value into target register (16->32)
454 if (isUnsigned)
455 BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
456 else
457 BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
458 break;
459 case cInt:
460 // Move value into target register (32->32)
461 BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
462 break;
463 }
464}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000465
Chris Lattner72614082002-10-25 22:55:53 +0000466/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
467/// we have the following possibilities:
468///
469/// ret void: No return value, simply emit a 'ret' instruction
470/// ret sbyte, ubyte : Extend value into EAX and return
471/// ret short, ushort: Extend value into EAX and return
472/// ret int, uint : Move value into EAX and return
473/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000474/// ret long, ulong : Move value into EAX/EDX and return
475/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000476///
Brian Gaekec2505982002-11-30 11:57:28 +0000477void
478ISel::visitReturnInst (ReturnInst &I)
479{
480 if (I.getNumOperands () == 0)
481 {
482 // Emit a 'ret' instruction
483 BuildMI (BB, X86::RET, 0);
484 return;
485 }
486 Value *rv = I.getOperand (0);
487 unsigned Class = getClass (rv->getType ());
488 switch (Class)
489 {
490 // integral return values: extend or move into EAX and return.
491 case cByte:
492 case cShort:
493 case cInt:
494 promote32 (X86::EAX, rv);
495 break;
496 // ret float/double: top of FP stack
497 // FLD <val>
498 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000499 BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000500 break;
501 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000502 BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000503 break;
504 case cLong:
505 // ret long: use EAX(least significant 32 bits)/EDX (most
506 // significant 32)...uh, I think so Brain, but how do i call
507 // up the two parts of the value from inside this mouse
508 // cage? *zort*
509 default:
510 visitInstruction (I);
511 }
Chris Lattner43189d12002-11-17 20:07:45 +0000512 // Emit a 'ret' instruction
Brian Gaekec2505982002-11-30 11:57:28 +0000513 BuildMI (BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000514}
515
Chris Lattner51b49a92002-11-02 19:45:49 +0000516/// visitBranchInst - Handle conditional and unconditional branches here. Note
517/// that since code layout is frozen at this point, that if we are trying to
518/// jump to a block that is the immediate successor of the current block, we can
519/// just make a fall-through. (but we don't currently).
520///
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000521void
522ISel::visitBranchInst (BranchInst & BI)
523{
524 if (BI.isConditional ())
525 {
526 BasicBlock *ifTrue = BI.getSuccessor (0);
527 BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious
Chris Lattner2df035b2002-11-02 19:27:56 +0000528
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000529 // simplest thing I can think of: compare condition with zero,
530 // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
531 // ifTrue
532 unsigned int condReg = getReg (BI.getCondition ());
Chris Lattner97ad9e12002-11-21 01:59:50 +0000533 BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000534 BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
535 BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
536 }
537 else // unconditional branch
538 {
539 BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
540 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000541}
542
Brian Gaeke18a20212002-11-29 12:01:58 +0000543/// visitCallInst - Push args on stack and do a procedure call instruction.
544void
545ISel::visitCallInst (CallInst & CI)
546{
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000547 // keep a counter of how many bytes we pushed on the stack
548 unsigned bytesPushed = 0;
549
Brian Gaeke18a20212002-11-29 12:01:58 +0000550 // Push the arguments on the stack in reverse order, as specified by
551 // the ABI.
Chris Lattnerd852c152002-12-03 20:30:12 +0000552 for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
Brian Gaeke18a20212002-11-29 12:01:58 +0000553 {
554 Value *v = CI.getOperand (i);
Brian Gaeke18a20212002-11-29 12:01:58 +0000555 switch (getClass (v->getType ()))
556 {
Brian Gaekec2505982002-11-30 11:57:28 +0000557 case cByte:
558 case cShort:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000559 // Promote V to 32 bits wide, and move the result into EAX,
560 // then push EAX.
Brian Gaekec2505982002-11-30 11:57:28 +0000561 promote32 (X86::EAX, v);
562 BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000563 bytesPushed += 4;
Brian Gaekec2505982002-11-30 11:57:28 +0000564 break;
Brian Gaeke18a20212002-11-29 12:01:58 +0000565 case cInt:
Chris Lattner33ced562002-12-04 06:56:56 +0000566 case cFloat: {
567 unsigned Reg = getReg(v);
568 BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000569 bytesPushed += 4;
Brian Gaeke18a20212002-11-29 12:01:58 +0000570 break;
Chris Lattner33ced562002-12-04 06:56:56 +0000571 }
Brian Gaeke18a20212002-11-29 12:01:58 +0000572 default:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000573 // FIXME: long/ulong/double args not handled.
Brian Gaeke18a20212002-11-29 12:01:58 +0000574 visitInstruction (CI);
575 break;
576 }
577 }
578 // Emit a CALL instruction with PC-relative displacement.
579 BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000580
581 // Adjust the stack by `bytesPushed' amount if non-zero
582 if (bytesPushed > 0)
583 BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
Chris Lattnera3243642002-12-04 23:45:28 +0000584
585 // If there is a return value, scavenge the result from the location the call
586 // leaves it in...
587 //
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000588 if (CI.getType() != Type::VoidTy) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000589 unsigned resultTypeClass = getClass (CI.getType ());
590 switch (resultTypeClass) {
591 case cByte:
592 case cShort:
593 case cInt: {
594 // Integral results are in %eax, or the appropriate portion
595 // thereof.
596 static const unsigned regRegMove[] = {
597 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
598 };
599 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
600 BuildMI (BB, regRegMove[resultTypeClass], 1,
601 getReg (CI)).addReg (AReg[resultTypeClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000602 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000603 }
604 case cFloat:
605 // Floating-point return values live in %st(0) (i.e., the top of
606 // the FP stack.) The general way to approach this is to do a
607 // FSTP to save the top of the FP stack on the real stack, then
608 // do a MOV to load the top of the real stack into the target
609 // register.
610 visitInstruction (CI); // FIXME: add the right args for the calls below
611 // BuildMI (BB, X86::FSTPm32, 0);
612 // BuildMI (BB, X86::MOVmr32, 0);
613 break;
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000614 default:
615 std::cerr << "Cannot get return value for call of type '"
616 << *CI.getType() << "'\n";
617 visitInstruction(CI);
618 }
Chris Lattnera3243642002-12-04 23:45:28 +0000619 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000620}
Chris Lattner2df035b2002-11-02 19:27:56 +0000621
Chris Lattner68aad932002-11-02 20:13:22 +0000622/// visitSimpleBinary - Implement simple binary operators for integral types...
623/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
624/// 4 for Xor.
625///
626void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
627 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
Chris Lattnere2954c82002-11-02 20:04:26 +0000628 visitInstruction(B);
629
630 unsigned Class = getClass(B.getType());
631 if (Class > 2) // FIXME: Handle longs
632 visitInstruction(B);
633
634 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000635 // Arithmetic operators
636 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
637 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
638
639 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000640 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
641 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
642 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
643 };
644
645 unsigned Opcode = OpcodeTab[OperatorClass][Class];
646 unsigned Op0r = getReg(B.getOperand(0));
647 unsigned Op1r = getReg(B.getOperand(1));
648 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
649}
650
Brian Gaeke20244b72002-12-12 15:33:40 +0000651/// doMultiply - Emit appropriate instructions to multiply together
652/// the registers op0Reg and op1Reg, and put the result in destReg.
653/// The type of the result should be given as resultType.
654void
655ISel::doMultiply(unsigned destReg, const Type *resultType,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000656 unsigned op0Reg, unsigned op1Reg,
657 MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI)
Brian Gaeke20244b72002-12-12 15:33:40 +0000658{
659 unsigned Class = getClass (resultType);
660
661 // FIXME:
662 assert (Class <= 2 && "Someday, we will learn how to multiply"
663 "longs and floating-point numbers. This is not that day.");
664
665 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
666 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
667 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
668 unsigned Reg = Regs[Class];
669
670 // Emit a MOV to put the first operand into the appropriately-sized
671 // subreg of EAX.
Brian Gaeke71794c02002-12-13 11:22:48 +0000672 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000673
674 // Emit the appropriate multiply instruction.
Brian Gaeke71794c02002-12-13 11:22:48 +0000675 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000676
677 // Emit another MOV to put the result into the destination register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000678 BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000679}
680
Chris Lattnerca9671d2002-11-02 20:28:58 +0000681/// visitMul - Multiplies are not simple binary operators because they must deal
682/// with the EAX register explicitly.
683///
684void ISel::visitMul(BinaryOperator &I) {
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000685 MachineBasicBlock::iterator MBBI = BB->end();
Brian Gaeke20244b72002-12-12 15:33:40 +0000686 doMultiply (getReg (I), I.getType (),
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000687 getReg (I.getOperand (0)), getReg (I.getOperand (1)),
688 BB, MBBI);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000689}
Chris Lattnerca9671d2002-11-02 20:28:58 +0000690
Chris Lattner06925362002-11-17 21:56:38 +0000691
Chris Lattnerf01729e2002-11-02 20:54:46 +0000692/// visitDivRem - Handle division and remainder instructions... these
693/// instruction both require the same instructions to be generated, they just
694/// select the result from a different register. Note that both of these
695/// instructions work differently for signed and unsigned operands.
696///
697void ISel::visitDivRem(BinaryOperator &I) {
698 unsigned Class = getClass(I.getType());
699 if (Class > 2) // FIXME: Handle longs
700 visitInstruction(I);
701
702 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
703 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +0000704 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +0000705 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
706 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
707
708 static const unsigned DivOpcode[][4] = {
709 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
710 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
711 };
712
713 bool isSigned = I.getType()->isSigned();
714 unsigned Reg = Regs[Class];
715 unsigned ExtReg = ExtRegs[Class];
Chris Lattner6fc3c522002-11-17 21:11:55 +0000716 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000717 unsigned Op1Reg = getReg(I.getOperand(1));
718
719 // Put the first operand into one of the A registers...
720 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
721
722 if (isSigned) {
723 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +0000724 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000725 } else {
726 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
727 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
728 }
729
Chris Lattner06925362002-11-17 21:56:38 +0000730 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +0000731 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +0000732
Chris Lattnerf01729e2002-11-02 20:54:46 +0000733 // Figure out which register we want to pick the result out of...
734 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
735
Chris Lattnerf01729e2002-11-02 20:54:46 +0000736 // Put the result into the destination register...
737 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000738}
Chris Lattnere2954c82002-11-02 20:04:26 +0000739
Chris Lattner06925362002-11-17 21:56:38 +0000740
Brian Gaekea1719c92002-10-31 23:03:59 +0000741/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
742/// for constant immediate shift values, and for constant immediate
743/// shift values equal to 1. Even the general case is sort of special,
744/// because the shift amount has to be in CL, not just any old register.
745///
Chris Lattnerf01729e2002-11-02 20:54:46 +0000746void ISel::visitShiftInst (ShiftInst &I) {
747 unsigned Op0r = getReg (I.getOperand(0));
748 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +0000749 bool isLeftShift = I.getOpcode() == Instruction::Shl;
750 bool isOperandSigned = I.getType()->isUnsigned();
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000751 unsigned OperandClass = getClass(I.getType());
752
753 if (OperandClass > 2)
754 visitInstruction(I); // Can't handle longs yet!
Chris Lattner796df732002-11-02 00:44:25 +0000755
Brian Gaekea1719c92002-10-31 23:03:59 +0000756 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
757 {
Chris Lattner796df732002-11-02 00:44:25 +0000758 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
759 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
760 unsigned char shAmt = CUI->getValue();
761
Chris Lattnere9913f22002-11-02 01:41:55 +0000762 static const unsigned ConstantOperand[][4] = {
763 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
764 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
765 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
766 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000767 };
768
Chris Lattnere9913f22002-11-02 01:41:55 +0000769 const unsigned *OpTab = // Figure out the operand table to use
770 ConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000771
Brian Gaekea1719c92002-10-31 23:03:59 +0000772 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000773 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
Brian Gaekea1719c92002-10-31 23:03:59 +0000774 }
775 else
776 {
777 // The shift amount is non-constant.
778 //
779 // In fact, you can only shift with a variable shift amount if
780 // that amount is already in the CL register, so we have to put it
781 // there first.
782 //
Chris Lattnere9913f22002-11-02 01:41:55 +0000783
Brian Gaekea1719c92002-10-31 23:03:59 +0000784 // Emit: move cl, shiftAmount (put the shift amount in CL.)
Chris Lattnerca9671d2002-11-02 20:28:58 +0000785 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000786
787 // This is a shift right (SHR).
Chris Lattnere9913f22002-11-02 01:41:55 +0000788 static const unsigned NonConstantOperand[][4] = {
789 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
790 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
791 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
792 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000793 };
794
Chris Lattnere9913f22002-11-02 01:41:55 +0000795 const unsigned *OpTab = // Figure out the operand table to use
796 NonConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000797
Chris Lattner3a9a6932002-11-21 22:49:20 +0000798 BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
Brian Gaekea1719c92002-10-31 23:03:59 +0000799 }
800}
801
Chris Lattner06925362002-11-17 21:56:38 +0000802
Chris Lattner6fc3c522002-11-17 21:11:55 +0000803/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
804/// instruction.
805///
806void ISel::visitLoadInst(LoadInst &I) {
807 unsigned Class = getClass(I.getType());
808 if (Class > 2) // FIXME: Handle longs and others...
809 visitInstruction(I);
810
811 static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
812
813 unsigned AddressReg = getReg(I.getOperand(0));
814 addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
815}
816
Chris Lattner06925362002-11-17 21:56:38 +0000817
Chris Lattner6fc3c522002-11-17 21:11:55 +0000818/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
819/// instruction.
820///
821void ISel::visitStoreInst(StoreInst &I) {
822 unsigned Class = getClass(I.getOperand(0)->getType());
823 if (Class > 2) // FIXME: Handle longs and others...
824 visitInstruction(I);
825
826 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
827
828 unsigned ValReg = getReg(I.getOperand(0));
829 unsigned AddressReg = getReg(I.getOperand(1));
830 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
831}
832
833
Brian Gaekec11232a2002-11-26 10:43:30 +0000834/// visitCastInst - Here we have various kinds of copying with or without
835/// sign extension going on.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000836void
837ISel::visitCastInst (CastInst &CI)
838{
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000839 const Type *targetType = CI.getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000840 Value *operand = CI.getOperand (0);
841 unsigned int operandReg = getReg (operand);
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000842 const Type *sourceType = operand->getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000843 unsigned int destReg = getReg (CI);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000844 //
845 // Currently we handle:
846 //
847 // 1) cast * to bool
848 //
849 // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
850 // cast {short, ushort} to {ushort, short}
851 // cast {int, uint, ptr} to {int, uint, ptr}
852 //
853 // 3) cast {sbyte, ubyte} to {ushort, short}
854 // cast {sbyte, ubyte} to {int, uint, ptr}
855 // cast {short, ushort} to {int, uint, ptr}
856 //
857 // 4) cast {int, uint, ptr} to {short, ushort}
858 // cast {int, uint, ptr} to {sbyte, ubyte}
859 // cast {short, ushort} to {sbyte, ubyte}
Chris Lattner7d255892002-12-13 11:31:59 +0000860
Brian Gaeked474e9c2002-12-06 10:49:33 +0000861 // 1) Implement casts to bool by using compare on the operand followed
862 // by set if not zero on the result.
863 if (targetType == Type::BoolTy)
864 {
865 BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
866 BuildMI (BB, X86::SETNEr, 1, destReg);
867 return;
868 }
Chris Lattner7d255892002-12-13 11:31:59 +0000869
Brian Gaeked474e9c2002-12-06 10:49:33 +0000870 // 2) Implement casts between values of the same type class (as determined
871 // by getClass) by using a register-to-register move.
Chris Lattner7d255892002-12-13 11:31:59 +0000872 unsigned srcClass = sourceType == Type::BoolTy ? cByte : getClass(sourceType);
873 unsigned targClass = getClass (targetType);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000874 static const unsigned regRegMove[] = {
875 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
876 };
877 if ((srcClass < 3) && (targClass < 3) && (srcClass == targClass))
878 {
879 BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
880 return;
881 }
882 // 3) Handle cast of SMALLER int to LARGER int using a move with sign
883 // extension or zero extension, depending on whether the source type
884 // was signed.
885 if ((srcClass < 3) && (targClass < 3) && (srcClass < targClass))
886 {
887 static const unsigned ops[] = {
888 X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
889 X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
890 };
891 unsigned srcSigned = sourceType->isSigned ();
892 BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
893 destReg).addReg (operandReg);
894 return;
895 }
896 // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
897 // followed by a move out of AX or AL.
898 if ((srcClass < 3) && (targClass < 3) && (srcClass > targClass))
899 {
900 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
901 BuildMI (BB, regRegMove[srcClass], 1,
902 AReg[srcClass]).addReg (operandReg);
903 BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
904 return;
905 }
906 // Anything we haven't handled already, we can't (yet) handle at all.
Brian Gaeke20244b72002-12-12 15:33:40 +0000907 //
908 // FP to integral casts can be handled with FISTP to store onto the
909 // stack while converting to integer, followed by a MOV to load from
910 // the stack into the result register. Integral to FP casts can be
911 // handled with MOV to store onto the stack, followed by a FILD to
912 // load from the stack while converting to FP. For the moment, I
913 // can't quite get straight in my head how to borrow myself some
914 // stack space and write on it. Otherwise, this would be trivial.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000915 visitInstruction (CI);
916}
Brian Gaekea1719c92002-10-31 23:03:59 +0000917
Brian Gaeke20244b72002-12-12 15:33:40 +0000918/// visitGetElementPtrInst - I don't know, most programs don't have
919/// getelementptr instructions, right? That means we can put off
920/// implementing this, right? Right. This method emits machine
921/// instructions to perform type-safe pointer arithmetic. I am
922/// guessing this could be cleaned up somewhat to use fewer temporary
923/// registers.
924void
925ISel::visitGetElementPtrInst (GetElementPtrInst &I)
926{
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000927 MachineBasicBlock::iterator MI = BB->end();
928 emitGEPOperation(BB, MI, I.getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000929 I.op_begin()+1, I.op_end(), getReg(I));
Chris Lattnerc0812d82002-12-13 06:56:29 +0000930}
931
Brian Gaeke71794c02002-12-13 11:22:48 +0000932void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000933 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000934 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000935 User::op_iterator IdxEnd, unsigned TargetReg) {
936 const TargetData &TD = TM.getTargetData();
937 const Type *Ty = Src->getType();
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000938 unsigned basePtrReg = getReg(Src, BB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000939
Brian Gaeke20244b72002-12-12 15:33:40 +0000940 // GEPs have zero or more indices; we must perform a struct access
941 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000942 for (GetElementPtrInst::op_iterator oi = IdxBegin,
943 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000944 Value *idx = *oi;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000945 unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000946 if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
947 // It's a struct access. idx is the index into the structure,
948 // which names the field. This index must have ubyte type.
949 const ConstantUInt *CUI = cast <ConstantUInt> (idx);
950 assert (CUI->getType () == Type::UByteTy
951 && "Funny-looking structure index in GEP");
952 // Use the TargetData structure to pick out what the layout of
953 // the structure is in memory. Since the structure index must
954 // be constant, we can get its value and use it to find the
955 // right byte offset from the StructLayout class's list of
956 // structure member offsets.
957 unsigned idxValue = CUI->getValue ();
958 unsigned memberOffset =
959 TD.getStructLayout (StTy)->MemberOffsets[idxValue];
960 // Emit an ADD to add memberOffset to the basePtr.
Brian Gaeke71794c02002-12-13 11:22:48 +0000961 BMI(MBB, IP, X86::ADDri32, 2,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000962 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
Brian Gaeke20244b72002-12-12 15:33:40 +0000963 // The next type is the member of the structure selected by the
964 // index.
965 Ty = StTy->getElementTypes ()[idxValue];
966 } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
967 // It's an array or pointer access: [ArraySize x ElementType].
Brian Gaeke20244b72002-12-12 15:33:40 +0000968 const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
969 // idx is the index into the array. Unlike with structure
970 // indices, we may not know its actual value at code-generation
971 // time.
972 assert (idx->getType () == typeOfSequentialTypeIndex
973 && "Funny-looking array index in GEP");
974 // We want to add basePtrReg to (idxReg * sizeof
975 // ElementType). First, we must find the size of the pointed-to
976 // type. (Not coincidentally, the next type is the type of the
977 // elements in the array.)
978 Ty = SqTy->getElementType ();
979 unsigned elementSize = TD.getTypeSize (Ty);
Brian Gaeke71794c02002-12-13 11:22:48 +0000980 unsigned elementSizeReg = makeAnotherReg(typeOfSequentialTypeIndex);
981 copyConstantToRegister(ConstantSInt::get(typeOfSequentialTypeIndex,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000982 elementSize), elementSizeReg,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000983 BB, IP);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000984
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000985 unsigned idxReg = getReg(idx, BB, IP);
Brian Gaeke20244b72002-12-12 15:33:40 +0000986 // Emit a MUL to multiply the register holding the index by
987 // elementSize, putting the result in memberOffsetReg.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000988 unsigned memberOffsetReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000989 doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000990 elementSizeReg, idxReg, BB, IP);
Brian Gaeke20244b72002-12-12 15:33:40 +0000991 // Emit an ADD to add memberOffsetReg to the basePtr.
Brian Gaeke71794c02002-12-13 11:22:48 +0000992 BMI(MBB, IP, X86::ADDrr32, 2,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000993 nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000994 }
995 // Now that we are here, further indices refer to subtypes of this
996 // one, so we don't need to worry about basePtrReg itself, anymore.
997 basePtrReg = nextBasePtrReg;
998 }
999 // After we have processed all the indices, the result is left in
1000 // basePtrReg. Move it to the register where we were expected to
1001 // put the answer. A 32-bit move should do it, because we are in
1002 // ILP32 land.
Brian Gaeke71794c02002-12-13 11:22:48 +00001003 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001004}
1005
1006
1007/// visitMallocInst - I know that personally, whenever I want to remember
1008/// something, I have to clear off some space in my brain.
1009void
1010ISel::visitMallocInst (MallocInst &I)
1011{
Brian Gaekee48ec012002-12-13 06:46:31 +00001012 // We assume that by this point, malloc instructions have been
1013 // lowered to calls, and dlsym will magically find malloc for us.
1014 // So we do not want to see malloc instructions here.
1015 visitInstruction (I);
1016}
1017
1018
1019/// visitFreeInst - same story as MallocInst
1020void
1021ISel::visitFreeInst (FreeInst &I)
1022{
1023 // We assume that by this point, free instructions have been
1024 // lowered to calls, and dlsym will magically find free for us.
1025 // So we do not want to see free instructions here.
Brian Gaeke20244b72002-12-12 15:33:40 +00001026 visitInstruction (I);
1027}
1028
1029
1030/// visitAllocaInst - I want some stack space. Come on, man, I said I
1031/// want some freakin' stack space.
1032void
1033ISel::visitAllocaInst (AllocaInst &I)
1034{
Brian Gaekee48ec012002-12-13 06:46:31 +00001035 // Find the data size of the alloca inst's getAllocatedType.
1036 const Type *allocatedType = I.getAllocatedType ();
1037 const TargetData &TD = TM.DataLayout;
1038 unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1039 // Keep stack 32-bit aligned.
1040 unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1041 if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1042 // Subtract size from stack pointer, thereby allocating some space.
1043 BuildMI (BB, X86::SUBri32, 1, X86::ESP).addZImm (allocatedTypeWords * 4);
1044 // Put a pointer to the space into the result register, by copying
1045 // the stack pointer.
1046 BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
Brian Gaeke20244b72002-12-12 15:33:40 +00001047}
1048
1049
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001050/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1051/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001052/// generated code sucks but the implementation is nice and simple.
1053///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001054Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1055 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001056}