1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a simple peephole instruction selector for the x86 target
12 //===----------------------------------------------------------------------===//
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicLowering.h"
22 #include "llvm/Pass.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
39 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
43 cByte, cShort, cInt, cFP, cLong
47 /// getClass - Turn a primitive type into a "class" number which is based on the
48 /// size of the type, and whether or not it is floating point.
50 static inline TypeClass getClass(const Type *Ty) {
51 switch (Ty->getPrimitiveID()) {
53 case Type::UByteTyID: return cByte; // Byte operands are class #0
55 case Type::UShortTyID: return cShort; // Short operands are class #1
58 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
61 case Type::DoubleTyID: return cFP; // Floating Point is #3
64 case Type::ULongTyID: return cLong; // Longs are class #4
66 assert(0 && "Invalid type to getClass!");
67 return cByte; // not reached
71 // getClassB - Just like getClass, but treat boolean values as bytes.
72 static inline TypeClass getClassB(const Type *Ty) {
73 if (Ty == Type::BoolTy) return cByte;
78 struct ISel : public FunctionPass, InstVisitor<ISel> {
80 MachineFunction *F; // The function we are compiling into
81 MachineBasicBlock *BB; // The current MBB we are compiling
82 int VarArgsFrameIndex; // FrameIndex for start of varargs area
83 int ReturnAddressIndex; // FrameIndex for the return address
85 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
87 // MBBMap - Mapping between LLVM BB -> Machine BB
88 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
90 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
92 /// runOnFunction - Top level implementation of instruction selection for
93 /// the entire function.
95 bool runOnFunction(Function &Fn) {
96 // First pass over the function, lower any unknown intrinsic functions
97 // with the IntrinsicLowering class.
98 LowerUnknownIntrinsicFunctionCalls(Fn);
100 F = &MachineFunction::construct(&Fn, TM);
102 // Create all of the machine basic blocks for the function...
103 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
104 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
108 // Set up a frame object for the return address. This is used by the
109 // llvm.returnaddress & llvm.frameaddress intrinisics.
110 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
112 // Copy incoming arguments off of the stack...
113 LoadArgumentsToVirtualRegs(Fn);
115 // Instruction select everything except PHI nodes
118 // Select the PHI nodes
121 // Insert the FP_REG_KILL instructions into blocks that need them.
127 // We always build a machine code representation for the function
131 virtual const char *getPassName() const {
132 return "X86 Simple Instruction Selection";
135 /// visitBasicBlock - This method is called when we are visiting a new basic
136 /// block. This simply creates a new MachineBasicBlock to emit code into
137 /// and adds it to the current MachineFunction. Subsequent visit* for
138 /// instructions will be invoked for all instructions in the basic block.
140 void visitBasicBlock(BasicBlock &LLVM_BB) {
141 BB = MBBMap[&LLVM_BB];
144 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
145 /// function, lowering any calls to unknown intrinsic functions into the
146 /// equivalent LLVM code.
148 void LowerUnknownIntrinsicFunctionCalls(Function &F);
150 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
151 /// from the stack into virtual registers.
153 void LoadArgumentsToVirtualRegs(Function &F);
155 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
156 /// because we have to generate our sources into the source basic blocks,
157 /// not the current one.
159 void SelectPHINodes();
161 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
162 /// that need them. This only occurs due to the floating point stackifier
163 /// not being aggressive enough to handle arbitrary global stackification.
165 void InsertFPRegKills();
167 // Visitation methods for various instructions. These methods simply emit
168 // fixed X86 code for each instruction.
171 // Control flow operators
172 void visitReturnInst(ReturnInst &RI);
173 void visitBranchInst(BranchInst &BI);
179 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
180 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
182 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
183 const std::vector<ValueRecord> &Args);
184 void visitCallInst(CallInst &I);
185 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
187 // Arithmetic operators
188 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
189 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
190 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
191 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
192 unsigned DestReg, const Type *DestTy,
193 unsigned Op0Reg, unsigned Op1Reg);
194 void doMultiplyConst(MachineBasicBlock *MBB,
195 MachineBasicBlock::iterator MBBI,
196 unsigned DestReg, const Type *DestTy,
197 unsigned Op0Reg, unsigned Op1Val);
198 void visitMul(BinaryOperator &B);
200 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
201 void visitRem(BinaryOperator &B) { visitDivRem(B); }
202 void visitDivRem(BinaryOperator &B);
205 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
206 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
207 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
209 // Comparison operators...
210 void visitSetCondInst(SetCondInst &I);
211 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
212 MachineBasicBlock *MBB,
213 MachineBasicBlock::iterator MBBI);
214 void visitSelectInst(SelectInst &SI);
217 // Memory Instructions
218 void visitLoadInst(LoadInst &I);
219 void visitStoreInst(StoreInst &I);
220 void visitGetElementPtrInst(GetElementPtrInst &I);
221 void visitAllocaInst(AllocaInst &I);
222 void visitMallocInst(MallocInst &I);
223 void visitFreeInst(FreeInst &I);
226 void visitShiftInst(ShiftInst &I);
227 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
228 void visitCastInst(CastInst &I);
229 void visitVANextInst(VANextInst &I);
230 void visitVAArgInst(VAArgInst &I);
232 void visitInstruction(Instruction &I) {
233 std::cerr << "Cannot instruction select: " << I;
237 /// promote32 - Make a value 32-bits wide, and put it somewhere.
239 void promote32(unsigned targetReg, const ValueRecord &VR);
241 /// getAddressingMode - Get the addressing mode to use to address the
242 /// specified value. The returned value should be used with addFullAddress.
243 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
244 unsigned &IndexReg, unsigned &Disp);
247 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
249 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
250 std::vector<Value*> &GEPOps,
251 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
252 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
254 /// isGEPFoldable - Return true if the specified GEP can be completely
255 /// folded into the addressing mode of a load/store or lea instruction.
256 bool isGEPFoldable(MachineBasicBlock *MBB,
257 Value *Src, User::op_iterator IdxBegin,
258 User::op_iterator IdxEnd, unsigned &BaseReg,
259 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
261 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
262 /// constant expression GEP support.
264 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
265 Value *Src, User::op_iterator IdxBegin,
266 User::op_iterator IdxEnd, unsigned TargetReg);
268 /// emitCastOperation - Common code shared between visitCastInst and
269 /// constant expression cast support.
271 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
272 Value *Src, const Type *DestTy, unsigned TargetReg);
274 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
275 /// and constant expression support.
277 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
278 MachineBasicBlock::iterator IP,
279 Value *Op0, Value *Op1,
280 unsigned OperatorClass, unsigned TargetReg);
282 void emitDivRemOperation(MachineBasicBlock *BB,
283 MachineBasicBlock::iterator IP,
284 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
285 const Type *Ty, unsigned TargetReg);
287 /// emitSetCCOperation - Common code shared between visitSetCondInst and
288 /// constant expression support.
290 void emitSetCCOperation(MachineBasicBlock *BB,
291 MachineBasicBlock::iterator IP,
292 Value *Op0, Value *Op1, unsigned Opcode,
295 /// emitShiftOperation - Common code shared between visitShiftInst and
296 /// constant expression support.
298 void emitShiftOperation(MachineBasicBlock *MBB,
299 MachineBasicBlock::iterator IP,
300 Value *Op, Value *ShiftAmount, bool isLeftShift,
301 const Type *ResultTy, unsigned DestReg);
303 /// emitSelectOperation - Common code shared between visitSelectInst and the
304 /// constant expression support.
305 void emitSelectOperation(MachineBasicBlock *MBB,
306 MachineBasicBlock::iterator IP,
307 Value *Cond, Value *TrueVal, Value *FalseVal,
310 /// copyConstantToRegister - Output the instructions required to put the
311 /// specified constant into the specified register.
313 void copyConstantToRegister(MachineBasicBlock *MBB,
314 MachineBasicBlock::iterator MBBI,
315 Constant *C, unsigned Reg);
317 /// makeAnotherReg - This method returns the next register number we haven't
320 /// Long values are handled somewhat specially. They are always allocated
321 /// as pairs of 32 bit integer values. The register number returned is the
322 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
323 /// of the long value.
325 unsigned makeAnotherReg(const Type *Ty) {
326 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
327 "Current target doesn't have X86 reg info??");
328 const X86RegisterInfo *MRI =
329 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
330 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
331 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
332 // Create the lower part
333 F->getSSARegMap()->createVirtualRegister(RC);
334 // Create the upper part.
335 return F->getSSARegMap()->createVirtualRegister(RC)-1;
338 // Add the mapping of regnumber => reg class to MachineFunction
339 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
340 return F->getSSARegMap()->createVirtualRegister(RC);
343 /// getReg - This method turns an LLVM value into a register number. This
344 /// is guaranteed to produce the same register number for a particular value
345 /// every time it is queried.
347 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
348 unsigned getReg(Value *V) {
349 // Just append to the end of the current bb.
350 MachineBasicBlock::iterator It = BB->end();
351 return getReg(V, BB, It);
353 unsigned getReg(Value *V, MachineBasicBlock *MBB,
354 MachineBasicBlock::iterator IPt) {
355 // If this operand is a constant, emit the code to copy the constant into
356 // the register here...
358 if (Constant *C = dyn_cast<Constant>(V)) {
359 unsigned Reg = makeAnotherReg(V->getType());
360 copyConstantToRegister(MBB, IPt, C, Reg);
362 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
363 unsigned Reg = makeAnotherReg(V->getType());
364 // Move the address of the global into the register
365 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
367 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
368 // Do not emit noop casts at all.
369 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
370 return getReg(CI->getOperand(0), MBB, IPt);
373 unsigned &Reg = RegMap[V];
375 Reg = makeAnotherReg(V->getType());
384 /// copyConstantToRegister - Output the instructions required to put the
385 /// specified constant into the specified register.
387 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
388 MachineBasicBlock::iterator IP,
389 Constant *C, unsigned R) {
390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
392 switch (CE->getOpcode()) {
393 case Instruction::GetElementPtr:
394 emitGEPOperation(MBB, IP, CE->getOperand(0),
395 CE->op_begin()+1, CE->op_end(), R);
397 case Instruction::Cast:
398 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
401 case Instruction::Xor: ++Class; // FALL THROUGH
402 case Instruction::Or: ++Class; // FALL THROUGH
403 case Instruction::And: ++Class; // FALL THROUGH
404 case Instruction::Sub: ++Class; // FALL THROUGH
405 case Instruction::Add:
406 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
410 case Instruction::Mul: {
411 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
412 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
413 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
416 case Instruction::Div:
417 case Instruction::Rem: {
418 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
419 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
420 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
421 CE->getOpcode() == Instruction::Div,
426 case Instruction::SetNE:
427 case Instruction::SetEQ:
428 case Instruction::SetLT:
429 case Instruction::SetGT:
430 case Instruction::SetLE:
431 case Instruction::SetGE:
432 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
436 case Instruction::Shl:
437 case Instruction::Shr:
438 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
439 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
442 case Instruction::Select:
443 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
444 CE->getOperand(2), R);
448 std::cerr << "Offending expr: " << C << "\n";
449 assert(0 && "Constant expression not yet handled!\n");
453 if (C->getType()->isIntegral()) {
454 unsigned Class = getClassB(C->getType());
456 if (Class == cLong) {
457 // Copy the value into the register pair.
458 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
459 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
460 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
464 assert(Class <= cInt && "Type not handled yet!");
466 static const unsigned IntegralOpcodeTab[] = {
467 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
470 if (C->getType() == Type::BoolTy) {
471 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
473 ConstantInt *CI = cast<ConstantInt>(C);
474 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
476 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
477 if (CFP->isExactlyValue(+0.0))
478 BuildMI(*MBB, IP, X86::FLD0, 0, R);
479 else if (CFP->isExactlyValue(+1.0))
480 BuildMI(*MBB, IP, X86::FLD1, 0, R);
482 // Otherwise we need to spill the constant to memory...
483 MachineConstantPool *CP = F->getConstantPool();
484 unsigned CPI = CP->getConstantPoolIndex(CFP);
485 const Type *Ty = CFP->getType();
487 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
488 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
489 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
492 } else if (isa<ConstantPointerNull>(C)) {
493 // Copy zero (null pointer) to the register.
494 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
495 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
496 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
498 std::cerr << "Offending constant: " << C << "\n";
499 assert(0 && "Type not handled yet!");
503 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
504 /// the stack into virtual registers.
506 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
507 // Emit instructions to load the arguments... On entry to a function on the
508 // X86, the stack frame looks like this:
510 // [ESP] -- return address
511 // [ESP + 4] -- first argument (leftmost lexically)
512 // [ESP + 8] -- second argument, if first argument is four bytes in size
515 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
516 MachineFrameInfo *MFI = F->getFrameInfo();
518 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
519 bool ArgLive = !I->use_empty();
520 unsigned Reg = ArgLive ? getReg(*I) : 0;
521 int FI; // Frame object index
523 switch (getClassB(I->getType())) {
526 FI = MFI->CreateFixedObject(1, ArgOffset);
527 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
532 FI = MFI->CreateFixedObject(2, ArgOffset);
533 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
538 FI = MFI->CreateFixedObject(4, ArgOffset);
539 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
544 FI = MFI->CreateFixedObject(8, ArgOffset);
545 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
546 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
548 ArgOffset += 4; // longs require 4 additional bytes
553 if (I->getType() == Type::FloatTy) {
554 Opcode = X86::FLD32m;
555 FI = MFI->CreateFixedObject(4, ArgOffset);
557 Opcode = X86::FLD64m;
558 FI = MFI->CreateFixedObject(8, ArgOffset);
560 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
562 if (I->getType() == Type::DoubleTy)
563 ArgOffset += 4; // doubles require 4 additional bytes
566 assert(0 && "Unhandled argument type!");
568 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
571 // If the function takes variable number of arguments, add a frame offset for
572 // the start of the first vararg value... this is used to expand
574 if (Fn.getFunctionType()->isVarArg())
575 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
579 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
580 /// because we have to generate our sources into the source basic blocks, not
583 void ISel::SelectPHINodes() {
584 const TargetInstrInfo &TII = TM.getInstrInfo();
585 const Function &LF = *F->getFunction(); // The LLVM function...
586 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
587 const BasicBlock *BB = I;
588 MachineBasicBlock &MBB = *MBBMap[I];
590 // Loop over all of the PHI nodes in the LLVM basic block...
591 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
592 for (BasicBlock::const_iterator I = BB->begin();
593 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
595 // Create a new machine instr PHI node, and insert it.
596 unsigned PHIReg = getReg(*PN);
597 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
598 X86::PHI, PN->getNumOperands(), PHIReg);
600 MachineInstr *LongPhiMI = 0;
601 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
602 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
603 X86::PHI, PN->getNumOperands(), PHIReg+1);
605 // PHIValues - Map of blocks to incoming virtual registers. We use this
606 // so that we only initialize one incoming value for a particular block,
607 // even if the block has multiple entries in the PHI node.
609 std::map<MachineBasicBlock*, unsigned> PHIValues;
611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
612 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
614 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
615 PHIValues.lower_bound(PredMBB);
617 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
618 // We already inserted an initialization of the register for this
619 // predecessor. Recycle it.
620 ValReg = EntryIt->second;
623 // Get the incoming value into a virtual register.
625 Value *Val = PN->getIncomingValue(i);
627 // If this is a constant or GlobalValue, we may have to insert code
628 // into the basic block to compute it into a virtual register.
629 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
630 if (isa<ConstantExpr>(Val)) {
631 // Because we don't want to clobber any values which might be in
632 // physical registers with the computation of this constant (which
633 // might be arbitrarily complex if it is a constant expression),
634 // just insert the computation at the top of the basic block.
635 MachineBasicBlock::iterator PI = PredMBB->begin();
637 // Skip over any PHI nodes though!
638 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
641 ValReg = getReg(Val, PredMBB, PI);
643 // Simple constants get emitted at the end of the basic block,
644 // before any terminator instructions. We "know" that the code to
645 // move a constant into a register will never clobber any flags.
646 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
649 ValReg = getReg(Val);
652 // Remember that we inserted a value for this PHI for this predecessor
653 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
656 PhiMI->addRegOperand(ValReg);
657 PhiMI->addMachineBasicBlockOperand(PredMBB);
659 LongPhiMI->addRegOperand(ValReg+1);
660 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
664 // Now that we emitted all of the incoming values for the PHI node, make
665 // sure to reposition the InsertPoint after the PHI that we just added.
666 // This is needed because we might have inserted a constant into this
667 // block, right after the PHI's which is before the old insert point!
668 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
674 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
675 /// compensation code on critical edges. As such, it requires that we kill all
676 /// FP registers on the exit from any blocks that either ARE critical edges, or
677 /// branch to a block that has incoming critical edges.
679 /// Note that this kill instruction will eventually be eliminated when
680 /// restrictions in the stackifier are relaxed.
682 static bool RequiresFPRegKill(const BasicBlock *BB) {
684 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
685 const BasicBlock *Succ = *SI;
686 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
687 ++PI; // Block have at least one predecessory
688 if (PI != PE) { // If it has exactly one, this isn't crit edge
689 // If this block has more than one predecessor, check all of the
690 // predecessors to see if they have multiple successors. If so, then the
691 // block we are analyzing needs an FPRegKill.
692 for (PI = pred_begin(Succ); PI != PE; ++PI) {
693 const BasicBlock *Pred = *PI;
694 succ_const_iterator SI2 = succ_begin(Pred);
695 ++SI2; // There must be at least one successor of this block.
696 if (SI2 != succ_end(Pred))
697 return true; // Yes, we must insert the kill on this edge.
701 // If we got this far, there is no need to insert the kill instruction.
708 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
709 // need them. This only occurs due to the floating point stackifier not being
710 // aggressive enough to handle arbitrary global stackification.
712 // Currently we insert an FP_REG_KILL instruction into each block that uses or
713 // defines a floating point virtual register.
715 // When the global register allocators (like linear scan) finally update live
716 // variable analysis, we can keep floating point values in registers across
717 // portions of the CFG that do not involve critical edges. This will be a big
718 // win, but we are waiting on the global allocators before we can do this.
720 // With a bit of work, the floating point stackifier pass can be enhanced to
721 // break critical edges as needed (to make a place to put compensation code),
722 // but this will require some infrastructure improvements as well.
724 void ISel::InsertFPRegKills() {
725 SSARegMap &RegMap = *F->getSSARegMap();
727 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
728 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
729 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
730 MachineOperand& MO = I->getOperand(i);
731 if (MO.isRegister() && MO.getReg()) {
732 unsigned Reg = MO.getReg();
733 if (MRegisterInfo::isVirtualRegister(Reg))
734 if (RegMap.getRegClass(Reg)->getSize() == 10)
738 // If we haven't found an FP register use or def in this basic block, check
739 // to see if any of our successors has an FP PHI node, which will cause a
740 // copy to be inserted into this block.
741 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
742 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
743 MachineBasicBlock *SBB = MBBMap[*SI];
744 for (MachineBasicBlock::iterator I = SBB->begin();
745 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
746 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
752 // Okay, this block uses an FP register. If the block has successors (ie,
753 // it's not an unwind/return), insert the FP_REG_KILL instruction.
754 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
755 RequiresFPRegKill(BB->getBasicBlock())) {
756 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
763 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
764 // it into the conditional branch or select instruction which is the only user
765 // of the cc instruction. This is the case if the conditional branch is the
766 // only user of the setcc, and if the setcc is in the same basic block as the
767 // conditional branch. We also don't handle long arguments below, so we reject
768 // them here as well.
770 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
771 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
772 if (SCI->hasOneUse()) {
773 Instruction *User = cast<Instruction>(SCI->use_back());
774 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
775 SCI->getParent() == User->getParent() &&
776 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
777 SCI->getOpcode() == Instruction::SetEQ ||
778 SCI->getOpcode() == Instruction::SetNE))
784 // Return a fixed numbering for setcc instructions which does not depend on the
785 // order of the opcodes.
787 static unsigned getSetCCNumber(unsigned Opcode) {
789 default: assert(0 && "Unknown setcc instruction!");
790 case Instruction::SetEQ: return 0;
791 case Instruction::SetNE: return 1;
792 case Instruction::SetLT: return 2;
793 case Instruction::SetGE: return 3;
794 case Instruction::SetGT: return 4;
795 case Instruction::SetLE: return 5;
799 // LLVM -> X86 signed X86 unsigned
800 // ----- ---------- ------------
801 // seteq -> sete sete
802 // setne -> setne setne
803 // setlt -> setl setb
804 // setge -> setge setae
805 // setgt -> setg seta
806 // setle -> setle setbe
808 // sets // Used by comparison with 0 optimization
810 static const unsigned SetCCOpcodeTab[2][8] = {
811 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
813 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
814 X86::SETSr, X86::SETNSr },
817 // EmitComparison - This function emits a comparison of the two operands,
818 // returning the extended setcc code to use.
819 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
820 MachineBasicBlock *MBB,
821 MachineBasicBlock::iterator IP) {
822 // The arguments are already supposed to be of the same type.
823 const Type *CompTy = Op0->getType();
824 unsigned Class = getClassB(CompTy);
825 unsigned Op0r = getReg(Op0, MBB, IP);
827 // Special case handling of: cmp R, i
828 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
829 if (Class == cByte || Class == cShort || Class == cInt) {
830 unsigned Op1v = CI->getRawValue();
832 // Mask off any upper bits of the constant, if there are any...
833 Op1v &= (1ULL << (8 << Class)) - 1;
835 // If this is a comparison against zero, emit more efficient code. We
836 // can't handle unsigned comparisons against zero unless they are == or
837 // !=. These should have been strength reduced already anyway.
838 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
839 static const unsigned TESTTab[] = {
840 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
842 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
844 if (OpNum == 2) return 6; // Map jl -> js
845 if (OpNum == 3) return 7; // Map jg -> jns
849 static const unsigned CMPTab[] = {
850 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
853 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
856 assert(Class == cLong && "Unknown integer class!");
857 unsigned LowCst = CI->getRawValue();
858 unsigned HiCst = CI->getRawValue() >> 32;
859 if (OpNum < 2) { // seteq, setne
860 unsigned LoTmp = Op0r;
862 LoTmp = makeAnotherReg(Type::IntTy);
863 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
865 unsigned HiTmp = Op0r+1;
867 HiTmp = makeAnotherReg(Type::IntTy);
868 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
870 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
871 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
874 // Emit a sequence of code which compares the high and low parts once
875 // each, then uses a conditional move to handle the overflow case. For
876 // example, a setlt for long would generate code like this:
878 // AL = lo(op1) < lo(op2) // Signedness depends on operands
879 // BL = hi(op1) < hi(op2) // Always unsigned comparison
880 // dest = hi(op1) == hi(op2) ? AL : BL;
883 // FIXME: This would be much better if we had hierarchical register
884 // classes! Until then, hardcode registers so that we can deal with
885 // their aliases (because we don't have conditional byte moves).
887 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
888 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
889 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
890 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
891 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
892 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
893 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
895 // NOTE: visitSetCondInst knows that the value is dumped into the BL
896 // register at this point for long values...
902 // Special case handling of comparison against +/- 0.0
903 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
904 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
905 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
906 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
907 BuildMI(*MBB, IP, X86::SAHF, 1);
911 unsigned Op1r = getReg(Op1, MBB, IP);
913 default: assert(0 && "Unknown type class!");
914 // Emit: cmp <var1>, <var2> (do the comparison). We can
915 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
918 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
921 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
924 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
927 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
928 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
929 BuildMI(*MBB, IP, X86::SAHF, 1);
933 if (OpNum < 2) { // seteq, setne
934 unsigned LoTmp = makeAnotherReg(Type::IntTy);
935 unsigned HiTmp = makeAnotherReg(Type::IntTy);
936 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
937 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
938 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
939 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
940 break; // Allow the sete or setne to be generated from flags set by OR
942 // Emit a sequence of code which compares the high and low parts once
943 // each, then uses a conditional move to handle the overflow case. For
944 // example, a setlt for long would generate code like this:
946 // AL = lo(op1) < lo(op2) // Signedness depends on operands
947 // BL = hi(op1) < hi(op2) // Always unsigned comparison
948 // dest = hi(op1) == hi(op2) ? AL : BL;
951 // FIXME: This would be much better if we had hierarchical register
952 // classes! Until then, hardcode registers so that we can deal with their
953 // aliases (because we don't have conditional byte moves).
955 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
956 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
957 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
958 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
959 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
960 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
961 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
963 // NOTE: visitSetCondInst knows that the value is dumped into the BL
964 // register at this point for long values...
971 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
972 /// register, then move it to wherever the result should be.
974 void ISel::visitSetCondInst(SetCondInst &I) {
975 if (canFoldSetCCIntoBranchOrSelect(&I))
976 return; // Fold this into a branch or select.
978 unsigned DestReg = getReg(I);
979 MachineBasicBlock::iterator MII = BB->end();
980 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
984 /// emitSetCCOperation - Common code shared between visitSetCondInst and
985 /// constant expression support.
987 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
988 MachineBasicBlock::iterator IP,
989 Value *Op0, Value *Op1, unsigned Opcode,
990 unsigned TargetReg) {
991 unsigned OpNum = getSetCCNumber(Opcode);
992 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
994 const Type *CompTy = Op0->getType();
995 unsigned CompClass = getClassB(CompTy);
996 bool isSigned = CompTy->isSigned() && CompClass != cFP;
998 if (CompClass != cLong || OpNum < 2) {
999 // Handle normal comparisons with a setcc instruction...
1000 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1002 // Handle long comparisons by copying the value which is already in BL into
1003 // the register we want...
1004 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1008 void ISel::visitSelectInst(SelectInst &SI) {
1009 unsigned DestReg = getReg(SI);
1010 MachineBasicBlock::iterator MII = BB->end();
1011 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1012 SI.getFalseValue(), DestReg);
1015 /// emitSelect - Common code shared between visitSelectInst and the constant
1016 /// expression support.
1017 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1018 MachineBasicBlock::iterator IP,
1019 Value *Cond, Value *TrueVal, Value *FalseVal,
1021 unsigned SelectClass = getClassB(TrueVal->getType());
1023 // We don't support 8-bit conditional moves. If we have incoming constants,
1024 // transform them into 16-bit constants to avoid having a run-time conversion.
1025 if (SelectClass == cByte) {
1026 if (Constant *T = dyn_cast<Constant>(TrueVal))
1027 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1028 if (Constant *F = dyn_cast<Constant>(FalseVal))
1029 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1034 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1035 // We successfully folded the setcc into the select instruction.
1037 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1038 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1041 const Type *CompTy = SCI->getOperand(0)->getType();
1042 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1044 // LLVM -> X86 signed X86 unsigned
1045 // ----- ---------- ------------
1046 // seteq -> cmovNE cmovNE
1047 // setne -> cmovE cmovE
1048 // setlt -> cmovGE cmovAE
1049 // setge -> cmovL cmovB
1050 // setgt -> cmovLE cmovBE
1051 // setle -> cmovG cmovA
1053 // cmovNS // Used by comparison with 0 optimization
1056 switch (SelectClass) {
1057 default: assert(0 && "Unknown value class!");
1059 // Annoyingly, we don't have a full set of floating point conditional
1061 static const unsigned OpcodeTab[2][8] = {
1062 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1063 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1064 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1066 Opcode = OpcodeTab[isSigned][OpNum];
1068 // If opcode == 0, we hit a case that we don't support. Output a setcc
1069 // and compare the result against zero.
1071 unsigned CompClass = getClassB(CompTy);
1073 if (CompClass != cLong || OpNum < 2) {
1074 CondReg = makeAnotherReg(Type::BoolTy);
1075 // Handle normal comparisons with a setcc instruction...
1076 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1078 // Long comparisons end up in the BL register.
1082 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1083 Opcode = X86::FCMOVE;
1089 static const unsigned OpcodeTab[2][8] = {
1090 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1091 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1092 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1093 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1095 Opcode = OpcodeTab[isSigned][OpNum];
1100 static const unsigned OpcodeTab[2][8] = {
1101 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1102 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1103 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1104 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1106 Opcode = OpcodeTab[isSigned][OpNum];
1111 // Get the value being branched on, and use it to set the condition codes.
1112 unsigned CondReg = getReg(Cond, MBB, IP);
1113 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1114 switch (SelectClass) {
1115 default: assert(0 && "Unknown value class!");
1116 case cFP: Opcode = X86::FCMOVE; break;
1118 case cShort: Opcode = X86::CMOVE16rr; break;
1120 case cLong: Opcode = X86::CMOVE32rr; break;
1124 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1125 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1126 unsigned RealDestReg = DestReg;
1129 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1130 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1131 // cmove, then truncate the result.
1132 if (SelectClass == cByte) {
1133 DestReg = makeAnotherReg(Type::ShortTy);
1134 if (getClassB(TrueVal->getType()) == cByte) {
1135 // Promote the true value, by storing it into AL, and reading from AX.
1136 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1137 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1138 TrueReg = makeAnotherReg(Type::ShortTy);
1139 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1141 if (getClassB(FalseVal->getType()) == cByte) {
1142 // Promote the true value, by storing it into CL, and reading from CX.
1143 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1144 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1145 FalseReg = makeAnotherReg(Type::ShortTy);
1146 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1150 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1152 switch (SelectClass) {
1154 // We did the computation with 16-bit registers. Truncate back to our
1155 // result by copying into AX then copying out AL.
1156 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1157 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1160 // Move the upper half of the value as well.
1161 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1168 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1169 /// operand, in the specified target register.
1171 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1172 bool isUnsigned = VR.Ty->isUnsigned();
1174 Value *Val = VR.Val;
1175 const Type *Ty = VR.Ty;
1177 if (Constant *C = dyn_cast<Constant>(Val)) {
1178 Val = ConstantExpr::getCast(C, Type::IntTy);
1182 // If this is a simple constant, just emit a MOVri directly to avoid the
1184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1185 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1186 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1191 // Make sure we have the register number for this value...
1192 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1194 switch (getClassB(Ty)) {
1196 // Extend value into target register (8->32)
1198 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1200 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1203 // Extend value into target register (16->32)
1205 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1207 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1210 // Move value into target register (32->32)
1211 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1214 assert(0 && "Unpromotable operand class in promote32");
1218 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1219 /// we have the following possibilities:
1221 /// ret void: No return value, simply emit a 'ret' instruction
1222 /// ret sbyte, ubyte : Extend value into EAX and return
1223 /// ret short, ushort: Extend value into EAX and return
1224 /// ret int, uint : Move value into EAX and return
1225 /// ret pointer : Move value into EAX and return
1226 /// ret long, ulong : Move value into EAX/EDX and return
1227 /// ret float/double : Top of FP stack
1229 void ISel::visitReturnInst(ReturnInst &I) {
1230 if (I.getNumOperands() == 0) {
1231 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1235 Value *RetVal = I.getOperand(0);
1236 switch (getClassB(RetVal->getType())) {
1237 case cByte: // integral return values: extend or move into EAX and return
1240 promote32(X86::EAX, ValueRecord(RetVal));
1241 // Declare that EAX is live on exit
1242 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1244 case cFP: { // Floats & Doubles: Return in ST(0)
1245 unsigned RetReg = getReg(RetVal);
1246 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1247 // Declare that top-of-stack is live on exit
1248 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1252 unsigned RetReg = getReg(RetVal);
1253 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1254 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1255 // Declare that EAX & EDX are live on exit
1256 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1261 visitInstruction(I);
1263 // Emit a 'ret' instruction
1264 BuildMI(BB, X86::RET, 0);
1267 // getBlockAfter - Return the basic block which occurs lexically after the
1269 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1270 Function::iterator I = BB; ++I; // Get iterator to next block
1271 return I != BB->getParent()->end() ? &*I : 0;
1274 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1275 /// that since code layout is frozen at this point, that if we are trying to
1276 /// jump to a block that is the immediate successor of the current block, we can
1277 /// just make a fall-through (but we don't currently).
1279 void ISel::visitBranchInst(BranchInst &BI) {
1280 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1282 if (!BI.isConditional()) { // Unconditional branch?
1283 if (BI.getSuccessor(0) != NextBB)
1284 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1288 // See if we can fold the setcc into the branch itself...
1289 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1291 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1292 // computed some other way...
1293 unsigned condReg = getReg(BI.getCondition());
1294 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1295 if (BI.getSuccessor(1) == NextBB) {
1296 if (BI.getSuccessor(0) != NextBB)
1297 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1299 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1301 if (BI.getSuccessor(0) != NextBB)
1302 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1307 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1308 MachineBasicBlock::iterator MII = BB->end();
1309 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1311 const Type *CompTy = SCI->getOperand(0)->getType();
1312 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1315 // LLVM -> X86 signed X86 unsigned
1316 // ----- ---------- ------------
1324 // js // Used by comparison with 0 optimization
1327 static const unsigned OpcodeTab[2][8] = {
1328 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1329 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1330 X86::JS, X86::JNS },
1333 if (BI.getSuccessor(0) != NextBB) {
1334 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1335 if (BI.getSuccessor(1) != NextBB)
1336 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1338 // Change to the inverse condition...
1339 if (BI.getSuccessor(1) != NextBB) {
1341 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1347 /// doCall - This emits an abstract call instruction, setting up the arguments
1348 /// and the return value as appropriate. For the actual function call itself,
1349 /// it inserts the specified CallMI instruction into the stream.
1351 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1352 const std::vector<ValueRecord> &Args) {
1354 // Count how many bytes are to be pushed on the stack...
1355 unsigned NumBytes = 0;
1357 if (!Args.empty()) {
1358 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1359 switch (getClassB(Args[i].Ty)) {
1360 case cByte: case cShort: case cInt:
1361 NumBytes += 4; break;
1363 NumBytes += 8; break;
1365 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1367 default: assert(0 && "Unknown class!");
1370 // Adjust the stack pointer for the new arguments...
1371 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1373 // Arguments go on the stack in reverse order, as specified by the ABI.
1374 unsigned ArgOffset = 0;
1375 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1377 switch (getClassB(Args[i].Ty)) {
1380 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1381 // Zero/Sign extend constant, then stuff into memory.
1382 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1383 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1384 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1385 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1387 // Promote arg to 32 bits wide into a temporary register...
1388 ArgReg = makeAnotherReg(Type::UIntTy);
1389 promote32(ArgReg, Args[i]);
1390 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1391 X86::ESP, ArgOffset).addReg(ArgReg);
1395 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1396 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1397 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1398 X86::ESP, ArgOffset).addImm(Val);
1400 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1401 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1402 X86::ESP, ArgOffset).addReg(ArgReg);
1406 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1407 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1408 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1409 X86::ESP, ArgOffset).addImm(Val & ~0U);
1410 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1411 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1413 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1414 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1415 X86::ESP, ArgOffset).addReg(ArgReg);
1416 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1417 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1419 ArgOffset += 4; // 8 byte entry, not 4.
1423 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1424 if (Args[i].Ty == Type::FloatTy) {
1425 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1426 X86::ESP, ArgOffset).addReg(ArgReg);
1428 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1429 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1430 X86::ESP, ArgOffset).addReg(ArgReg);
1431 ArgOffset += 4; // 8 byte entry, not 4.
1435 default: assert(0 && "Unknown class!");
1440 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1443 BB->push_back(CallMI);
1445 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1447 // If there is a return value, scavenge the result from the location the call
1450 if (Ret.Ty != Type::VoidTy) {
1451 unsigned DestClass = getClassB(Ret.Ty);
1452 switch (DestClass) {
1456 // Integral results are in %eax, or the appropriate portion
1458 static const unsigned regRegMove[] = {
1459 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1461 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1462 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1465 case cFP: // Floating-point return values live in %ST(0)
1466 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1468 case cLong: // Long values are left in EDX:EAX
1469 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1470 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1472 default: assert(0 && "Unknown class!");
1478 /// visitCallInst - Push args on stack and do a procedure call instruction.
1479 void ISel::visitCallInst(CallInst &CI) {
1480 MachineInstr *TheCall;
1481 if (Function *F = CI.getCalledFunction()) {
1482 // Is it an intrinsic function call?
1483 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1484 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1488 // Emit a CALL instruction with PC-relative displacement.
1489 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1490 } else { // Emit an indirect call...
1491 unsigned Reg = getReg(CI.getCalledValue());
1492 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1495 std::vector<ValueRecord> Args;
1496 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1497 Args.push_back(ValueRecord(CI.getOperand(i)));
1499 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1500 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1504 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1505 /// function, lowering any calls to unknown intrinsic functions into the
1506 /// equivalent LLVM code.
1508 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1509 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1510 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1511 if (CallInst *CI = dyn_cast<CallInst>(I++))
1512 if (Function *F = CI->getCalledFunction())
1513 switch (F->getIntrinsicID()) {
1514 case Intrinsic::not_intrinsic:
1515 case Intrinsic::vastart:
1516 case Intrinsic::vacopy:
1517 case Intrinsic::vaend:
1518 case Intrinsic::returnaddress:
1519 case Intrinsic::frameaddress:
1520 case Intrinsic::memcpy:
1521 case Intrinsic::memset:
1522 case Intrinsic::readport:
1523 case Intrinsic::writeport:
1524 // We directly implement these intrinsics
1527 // All other intrinsic calls we must lower.
1528 Instruction *Before = CI->getPrev();
1529 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1530 if (Before) { // Move iterator to instruction after call
1539 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1540 unsigned TmpReg1, TmpReg2;
1542 case Intrinsic::vastart:
1543 // Get the address of the first vararg value...
1544 TmpReg1 = getReg(CI);
1545 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1548 case Intrinsic::vacopy:
1549 TmpReg1 = getReg(CI);
1550 TmpReg2 = getReg(CI.getOperand(1));
1551 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1553 case Intrinsic::vaend: return; // Noop on X86
1555 case Intrinsic::returnaddress:
1556 case Intrinsic::frameaddress:
1557 TmpReg1 = getReg(CI);
1558 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1559 if (ID == Intrinsic::returnaddress) {
1560 // Just load the return address
1561 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1562 ReturnAddressIndex);
1564 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1565 ReturnAddressIndex, -4);
1568 // Values other than zero are not implemented yet.
1569 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1573 case Intrinsic::memcpy: {
1574 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1576 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1577 Align = AlignC->getRawValue();
1578 if (Align == 0) Align = 1;
1581 // Turn the byte code into # iterations
1584 switch (Align & 3) {
1585 case 2: // WORD aligned
1586 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1587 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1589 CountReg = makeAnotherReg(Type::IntTy);
1590 unsigned ByteReg = getReg(CI.getOperand(3));
1591 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1593 Opcode = X86::REP_MOVSW;
1595 case 0: // DWORD aligned
1596 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1597 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1599 CountReg = makeAnotherReg(Type::IntTy);
1600 unsigned ByteReg = getReg(CI.getOperand(3));
1601 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1603 Opcode = X86::REP_MOVSD;
1605 default: // BYTE aligned
1606 CountReg = getReg(CI.getOperand(3));
1607 Opcode = X86::REP_MOVSB;
1611 // No matter what the alignment is, we put the source in ESI, the
1612 // destination in EDI, and the count in ECX.
1613 TmpReg1 = getReg(CI.getOperand(1));
1614 TmpReg2 = getReg(CI.getOperand(2));
1615 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1616 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1617 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1618 BuildMI(BB, Opcode, 0);
1621 case Intrinsic::memset: {
1622 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1624 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1625 Align = AlignC->getRawValue();
1626 if (Align == 0) Align = 1;
1629 // Turn the byte code into # iterations
1632 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1633 unsigned Val = ValC->getRawValue() & 255;
1635 // If the value is a constant, then we can potentially use larger copies.
1636 switch (Align & 3) {
1637 case 2: // WORD aligned
1638 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1639 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1641 CountReg = makeAnotherReg(Type::IntTy);
1642 unsigned ByteReg = getReg(CI.getOperand(3));
1643 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1645 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1646 Opcode = X86::REP_STOSW;
1648 case 0: // DWORD aligned
1649 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1650 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1652 CountReg = makeAnotherReg(Type::IntTy);
1653 unsigned ByteReg = getReg(CI.getOperand(3));
1654 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1656 Val = (Val << 8) | Val;
1657 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1658 Opcode = X86::REP_STOSD;
1660 default: // BYTE aligned
1661 CountReg = getReg(CI.getOperand(3));
1662 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1663 Opcode = X86::REP_STOSB;
1667 // If it's not a constant value we are storing, just fall back. We could
1668 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1669 unsigned ValReg = getReg(CI.getOperand(2));
1670 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1671 CountReg = getReg(CI.getOperand(3));
1672 Opcode = X86::REP_STOSB;
1675 // No matter what the alignment is, we put the source in ESI, the
1676 // destination in EDI, and the count in ECX.
1677 TmpReg1 = getReg(CI.getOperand(1));
1678 //TmpReg2 = getReg(CI.getOperand(2));
1679 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1680 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1681 BuildMI(BB, Opcode, 0);
1685 case Intrinsic::readport:
1687 // First, determine that the size of the operand falls within the
1688 // acceptable range for this architecture.
1690 if ((CI.getOperand(1)->getType()->getPrimitiveSize()) != 2) {
1691 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1696 // Now, move the I/O port address into the DX register and use the IN
1697 // instruction to get the input data.
1699 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(1)));
1700 switch (CI.getCalledFunction()->getReturnType()->getPrimitiveSize()) {
1702 BuildMI(BB, X86::IN8, 0);
1705 BuildMI(BB, X86::IN16, 0);
1708 BuildMI(BB, X86::IN32, 0);
1711 std::cerr << "Cannot do input on this data type";
1716 case Intrinsic::writeport:
1718 // First, determine that the size of the operand falls within the
1719 // acceptable range for this architecture.
1722 if ((CI.getOperand(2)->getType()->getPrimitiveSize()) != 2) {
1723 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1728 // Now, move the I/O port address into the DX register and the value to
1729 // write into the AL/AX/EAX register.
1731 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(2)));
1732 switch (CI.getOperand(1)->getType()->getPrimitiveSize()) {
1734 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(getReg(CI.getOperand(1)));
1735 BuildMI(BB, X86::OUT8, 0);
1738 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(getReg(CI.getOperand(1)));
1739 BuildMI(BB, X86::OUT16, 0);
1742 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(getReg(CI.getOperand(1)));
1743 BuildMI(BB, X86::OUT32, 0);
1746 std::cerr << "Cannot do output on this data type";
1751 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1755 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1756 if (LI.getParent() != User.getParent())
1758 BasicBlock::iterator It = &LI;
1759 // Check all of the instructions between the load and the user. We should
1760 // really use alias analysis here, but for now we just do something simple.
1761 for (++It; It != BasicBlock::iterator(&User); ++It) {
1762 switch (It->getOpcode()) {
1763 case Instruction::Free:
1764 case Instruction::Store:
1765 case Instruction::Call:
1766 case Instruction::Invoke:
1774 /// visitSimpleBinary - Implement simple binary operators for integral types...
1775 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1778 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1779 unsigned DestReg = getReg(B);
1780 MachineBasicBlock::iterator MI = BB->end();
1781 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1783 // Special case: op Reg, load [mem]
1784 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1785 if (!B.swapOperands())
1786 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1788 unsigned Class = getClassB(B.getType());
1789 if (isa<LoadInst>(Op1) && Class < cFP &&
1790 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1792 static const unsigned OpcodeTab[][3] = {
1793 // Arithmetic operators
1794 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1795 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1797 // Bitwise operators
1798 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1799 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1800 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1803 assert(Class < cFP && "General code handles 64-bit integer types!");
1804 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1806 unsigned BaseReg, Scale, IndexReg, Disp;
1807 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1808 Scale, IndexReg, Disp);
1810 unsigned Op0r = getReg(Op0);
1811 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1812 BaseReg, Scale, IndexReg, Disp);
1816 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1819 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1820 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1823 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1824 /// and constant expression support.
1826 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1827 MachineBasicBlock::iterator IP,
1828 Value *Op0, Value *Op1,
1829 unsigned OperatorClass, unsigned DestReg) {
1830 unsigned Class = getClassB(Op0->getType());
1832 // sub 0, X -> neg X
1833 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1834 if (OperatorClass == 1 && CI->isNullValue()) {
1835 unsigned op1Reg = getReg(Op1, MBB, IP);
1836 static unsigned const NEGTab[] = {
1837 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
1839 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
1841 if (Class == cLong) {
1842 // We just emitted: Dl = neg Sl
1843 // Now emit : T = addc Sh, 0
1845 unsigned T = makeAnotherReg(Type::IntTy);
1846 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
1847 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
1852 // Special case: op Reg, <const int>
1853 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1854 unsigned Op0r = getReg(Op0, MBB, IP);
1856 // xor X, -1 -> not X
1857 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1858 static unsigned const NOTTab[] = {
1859 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
1861 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1862 if (Class == cLong) // Invert the top part too
1863 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
1867 // add X, -1 -> dec X
1868 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
1869 // Note that we can't use dec for 64-bit decrements, because it does not
1870 // set the carry flag!
1871 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1872 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1876 // add X, 1 -> inc X
1877 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
1878 // Note that we can't use inc for 64-bit increments, because it does not
1879 // set the carry flag!
1880 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1881 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
1885 static const unsigned OpcodeTab[][5] = {
1886 // Arithmetic operators
1887 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
1888 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
1890 // Bitwise operators
1891 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
1892 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
1893 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
1896 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1897 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
1899 if (Class != cLong) {
1900 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
1903 // If this is a long value and the high or low bits have a special
1904 // property, emit some special cases.
1905 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1907 // If the constant is zero in the low 32-bits, just copy the low part
1908 // across and apply the normal 32-bit operation to the high parts. There
1909 // will be no carry or borrow into the top.
1911 if (OperatorClass != 2) // All but and...
1912 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
1914 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
1915 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
1916 .addReg(Op0r+1).addImm(Op1h);
1920 // If this is a logical operation and the top 32-bits are zero, just
1921 // operate on the lower 32.
1922 if (Op1h == 0 && OperatorClass > 1) {
1923 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
1924 .addReg(Op0r).addImm(Op1l);
1925 if (OperatorClass != 2) // All but and
1926 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
1928 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1932 // TODO: We could handle lots of other special cases here, such as AND'ing
1933 // with 0xFFFFFFFF00000000 -> noop, etc.
1935 // Otherwise, code generate the full operation with a constant.
1936 static const unsigned TopTab[] = {
1937 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
1940 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
1941 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
1942 .addReg(Op0r+1).addImm(Op1h);
1947 // Special case: op Reg, <const fp>
1948 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
1949 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
1950 assert(OperatorClass < 2 && "FP operations only support add/sub!");
1952 // Create a constant pool entry for this constant.
1953 MachineConstantPool *CP = F->getConstantPool();
1954 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1955 const Type *Ty = Op1->getType();
1957 static const unsigned OpcodeTab[][2] = {
1958 { X86::FADD32m, X86::FSUB32m }, // Float
1959 { X86::FADD64m, X86::FSUB64m }, // Double
1962 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1963 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1964 unsigned Op0r = getReg(Op0, MBB, IP);
1965 addConstantPoolReference(BuildMI(*MBB, IP, Opcode, 5,
1966 DestReg).addReg(Op0r), CPI);
1970 // Special case: R1 = sub <const fp>, R2
1971 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1972 if (OperatorClass == 1) { // sub only
1973 if (CFP->isExactlyValue(-0.0)) {
1975 unsigned op1Reg = getReg(Op1, MBB, IP);
1976 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1978 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
1979 // R1 = sub CST, R2 --> R1 = subr R2, CST
1981 // Create a constant pool entry for this constant.
1982 MachineConstantPool *CP = F->getConstantPool();
1983 unsigned CPI = CP->getConstantPoolIndex(CFP);
1984 const Type *Ty = CFP->getType();
1986 static const unsigned OpcodeTab[2] = { X86::FSUBR32m, X86::FSUBR64m };
1988 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
1989 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy];
1990 unsigned Op1r = getReg(Op1, MBB, IP);
1991 addConstantPoolReference(BuildMI(*MBB, IP, Opcode, 5,
1992 DestReg).addReg(Op1r), CPI);
1997 // Finally, handle the general case now.
1998 static const unsigned OpcodeTab[][5] = {
1999 // Arithmetic operators
2000 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD, X86::ADD32rr },// ADD
2001 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB, X86::SUB32rr },// SUB
2003 // Bitwise operators
2004 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2005 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2006 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
2009 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2010 assert(Opcode && "Floating point arguments to logical inst?");
2011 unsigned Op0r = getReg(Op0, MBB, IP);
2012 unsigned Op1r = getReg(Op1, MBB, IP);
2013 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2015 if (Class == cLong) { // Handle the upper 32 bits of long values...
2016 static const unsigned TopTab[] = {
2017 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2019 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2020 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2024 /// doMultiply - Emit appropriate instructions to multiply together the
2025 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2026 /// result should be given as DestTy.
2028 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
2029 unsigned DestReg, const Type *DestTy,
2030 unsigned op0Reg, unsigned op1Reg) {
2031 unsigned Class = getClass(DestTy);
2033 case cFP: // Floating point multiply
2034 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
2038 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2039 .addReg(op0Reg).addReg(op1Reg);
2042 // Must use the MUL instruction, which forces use of AL...
2043 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2044 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2045 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2048 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2052 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2053 // returns zero when the input is not exactly a power of two.
2054 static unsigned ExactLog2(unsigned Val) {
2055 if (Val == 0) return 0;
2058 if (Val & 1) return 0;
2065 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
2066 MachineBasicBlock::iterator IP,
2067 unsigned DestReg, const Type *DestTy,
2068 unsigned op0Reg, unsigned ConstRHS) {
2069 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2070 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2072 unsigned Class = getClass(DestTy);
2074 if (ConstRHS == 0) {
2075 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2077 } else if (ConstRHS == 1) {
2078 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2082 // If the element size is exactly a power of 2, use a shift to get it.
2083 if (unsigned Shift = ExactLog2(ConstRHS)) {
2085 default: assert(0 && "Unknown class for this function!");
2087 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2090 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2093 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2098 if (Class == cShort) {
2099 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2101 } else if (Class == cInt) {
2102 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2106 // Most general case, emit a normal multiply...
2107 unsigned TmpReg = makeAnotherReg(DestTy);
2108 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2110 // Emit a MUL to multiply the register holding the index by
2111 // elementSize, putting the result in OffsetReg.
2112 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2115 /// visitMul - Multiplies are not simple binary operators because they must deal
2116 /// with the EAX register explicitly.
2118 void ISel::visitMul(BinaryOperator &I) {
2119 unsigned Op0Reg = getReg(I.getOperand(0));
2120 unsigned DestReg = getReg(I);
2122 // Simple scalar multiply?
2123 if (getClass(I.getType()) != cLong) {
2124 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2125 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
2126 MachineBasicBlock::iterator MBBI = BB->end();
2127 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
2129 unsigned Op1Reg = getReg(I.getOperand(1));
2130 MachineBasicBlock::iterator MBBI = BB->end();
2131 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
2134 // Long value. We have to do things the hard way...
2135 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2136 unsigned CLow = CI->getRawValue();
2137 unsigned CHi = CI->getRawValue() >> 32;
2140 // If the low part of the constant is all zeros, things are simple.
2141 BuildMI(BB, X86::MOV32ri, 1, DestReg).addImm(0);
2142 doMultiplyConst(BB, BB->end(), DestReg+1, Type::UIntTy, Op0Reg, CHi);
2146 // Multiply the two low parts... capturing carry into EDX
2147 unsigned OverflowReg = 0;
2149 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2151 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2152 OverflowReg = makeAnotherReg(Type::UIntTy);
2153 BuildMI(BB, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2154 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2155 BuildMI(BB, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
2157 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2158 BuildMI(BB, X86::MOV32rr, 1,OverflowReg).addReg(X86::EDX);// AL*BL >> 32
2161 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2162 doMultiplyConst(BB, BB->end(), AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2164 unsigned AHBLplusOverflowReg;
2166 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2167 BuildMI(BB, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2168 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2170 AHBLplusOverflowReg = AHBLReg;
2174 BuildMI(BB, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2176 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2177 doMultiplyConst(BB, BB->end(), ALBHReg, Type::UIntTy, Op0Reg, CHi);
2179 BuildMI(BB, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2180 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2183 unsigned Op1Reg = getReg(I.getOperand(1));
2184 // Multiply the two low parts... capturing carry into EDX
2185 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2186 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2188 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2189 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2190 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2192 MachineBasicBlock::iterator MBBI = BB->end();
2193 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2194 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2195 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2197 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2198 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2199 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2202 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2203 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2204 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2206 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2207 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2213 /// visitDivRem - Handle division and remainder instructions... these
2214 /// instruction both require the same instructions to be generated, they just
2215 /// select the result from a different register. Note that both of these
2216 /// instructions work differently for signed and unsigned operands.
2218 void ISel::visitDivRem(BinaryOperator &I) {
2219 unsigned Op0Reg = getReg(I.getOperand(0));
2220 unsigned Op1Reg = getReg(I.getOperand(1));
2221 unsigned ResultReg = getReg(I);
2223 MachineBasicBlock::iterator IP = BB->end();
2224 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
2225 I.getType(), ResultReg);
2228 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2229 MachineBasicBlock::iterator IP,
2230 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
2231 const Type *Ty, unsigned ResultReg) {
2232 unsigned Class = getClass(Ty);
2234 case cFP: // Floating point divide
2236 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2237 } else { // Floating point remainder...
2238 MachineInstr *TheCall =
2239 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2240 std::vector<ValueRecord> Args;
2241 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2242 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2243 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2247 static const char *FnName[] =
2248 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2250 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2251 MachineInstr *TheCall =
2252 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2254 std::vector<ValueRecord> Args;
2255 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2256 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2257 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2260 case cByte: case cShort: case cInt:
2261 break; // Small integrals, handled below...
2262 default: assert(0 && "Unknown class!");
2265 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
2266 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2267 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2268 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2269 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2271 static const unsigned DivOpcode[][4] = {
2272 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2273 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
2276 bool isSigned = Ty->isSigned();
2277 unsigned Reg = Regs[Class];
2278 unsigned ExtReg = ExtRegs[Class];
2280 // Put the first operand into one of the A registers...
2281 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2284 // Emit a sign extension instruction...
2285 unsigned ShiftResult = makeAnotherReg(Ty);
2286 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2287 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2289 // If unsigned, emit a zeroing instruction... (reg = 0)
2290 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2293 // Emit the appropriate divide or remainder instruction...
2294 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
2296 // Figure out which register we want to pick the result out of...
2297 unsigned DestReg = isDiv ? Reg : ExtReg;
2299 // Put the result into the destination register...
2300 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2304 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2305 /// for constant immediate shift values, and for constant immediate
2306 /// shift values equal to 1. Even the general case is sort of special,
2307 /// because the shift amount has to be in CL, not just any old register.
2309 void ISel::visitShiftInst(ShiftInst &I) {
2310 MachineBasicBlock::iterator IP = BB->end ();
2311 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2312 I.getOpcode () == Instruction::Shl, I.getType (),
2316 /// emitShiftOperation - Common code shared between visitShiftInst and
2317 /// constant expression support.
2318 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2319 MachineBasicBlock::iterator IP,
2320 Value *Op, Value *ShiftAmount, bool isLeftShift,
2321 const Type *ResultTy, unsigned DestReg) {
2322 unsigned SrcReg = getReg (Op, MBB, IP);
2323 bool isSigned = ResultTy->isSigned ();
2324 unsigned Class = getClass (ResultTy);
2326 static const unsigned ConstantOperand[][4] = {
2327 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2328 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2329 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2330 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
2333 static const unsigned NonConstantOperand[][4] = {
2334 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2335 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2336 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2337 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
2340 // Longs, as usual, are handled specially...
2341 if (Class == cLong) {
2342 // If we have a constant shift, we can generate much more efficient code
2343 // than otherwise...
2345 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2346 unsigned Amount = CUI->getValue();
2348 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2350 BuildMI(*MBB, IP, Opc[3], 3,
2351 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2352 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2354 BuildMI(*MBB, IP, Opc[3], 3,
2355 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2356 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2358 } else { // Shifting more than 32 bits
2362 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2363 DestReg + 1).addReg(SrcReg).addImm(Amount);
2365 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2367 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2370 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2371 DestReg).addReg(SrcReg+1).addImm(Amount);
2373 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2375 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2379 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2381 if (!isLeftShift && isSigned) {
2382 // If this is a SHR of a Long, then we need to do funny sign extension
2383 // stuff. TmpReg gets the value to use as the high-part if we are
2384 // shifting more than 32 bits.
2385 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
2387 // Other shifts use a fixed zero value if the shift is more than 32
2389 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2392 // Initialize CL with the shift amount...
2393 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2394 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2396 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2397 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2399 // TmpReg2 = shld inHi, inLo
2400 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2402 // TmpReg3 = shl inLo, CL
2403 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2405 // Set the flags to indicate whether the shift was by more than 32 bits.
2406 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2408 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2409 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2410 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2411 // DestLo = (>32) ? TmpReg : TmpReg3;
2412 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2413 DestReg).addReg(TmpReg3).addReg(TmpReg);
2415 // TmpReg2 = shrd inLo, inHi
2416 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2418 // TmpReg3 = s[ah]r inHi, CL
2419 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2422 // Set the flags to indicate whether the shift was by more than 32 bits.
2423 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2425 // DestLo = (>32) ? TmpReg3 : TmpReg2;
2426 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2427 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2429 // DestHi = (>32) ? TmpReg : TmpReg3;
2430 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2431 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2437 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2438 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2439 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2441 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2442 BuildMI(*MBB, IP, Opc[Class], 2,
2443 DestReg).addReg(SrcReg).addImm(CUI->getValue());
2444 } else { // The shift amount is non-constant.
2445 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2446 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2448 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2449 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2454 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2455 unsigned &IndexReg, unsigned &Disp) {
2456 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2457 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2458 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2459 BaseReg, Scale, IndexReg, Disp))
2461 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2462 if (CE->getOpcode() == Instruction::GetElementPtr)
2463 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2464 BaseReg, Scale, IndexReg, Disp))
2468 // If it's not foldable, reset addr mode.
2469 BaseReg = getReg(Addr);
2470 Scale = 1; IndexReg = 0; Disp = 0;
2474 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2475 /// instruction. The load and store instructions are the only place where we
2476 /// need to worry about the memory layout of the target machine.
2478 void ISel::visitLoadInst(LoadInst &I) {
2479 // Check to see if this load instruction is going to be folded into a binary
2480 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2481 // pattern matching instruction selector be nice?
2482 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2483 Instruction *User = cast<Instruction>(I.use_back());
2484 switch (User->getOpcode()) {
2485 default: User = 0; break;
2486 case Instruction::Add:
2487 case Instruction::Sub:
2488 case Instruction::And:
2489 case Instruction::Or:
2490 case Instruction::Xor:
2495 // Okay, we found a user. If the load is the first operand and there is
2496 // no second operand load, reverse the operand ordering. Note that this
2497 // can fail for a subtract (ie, no change will be made).
2498 if (!isa<LoadInst>(User->getOperand(1)))
2499 cast<BinaryOperator>(User)->swapOperands();
2501 // Okay, now that everything is set up, if this load is used by the second
2502 // operand, and if there are no instructions that invalidate the load
2503 // before the binary operator, eliminate the load.
2504 if (User->getOperand(1) == &I &&
2505 isSafeToFoldLoadIntoInstruction(I, *User))
2506 return; // Eliminate the load!
2510 unsigned DestReg = getReg(I);
2511 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2512 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2514 unsigned Class = getClassB(I.getType());
2515 if (Class == cLong) {
2516 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2517 BaseReg, Scale, IndexReg, Disp);
2518 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2519 BaseReg, Scale, IndexReg, Disp+4);
2523 static const unsigned Opcodes[] = {
2524 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2526 unsigned Opcode = Opcodes[Class];
2527 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2528 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2529 BaseReg, Scale, IndexReg, Disp);
2532 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2535 void ISel::visitStoreInst(StoreInst &I) {
2536 unsigned BaseReg, Scale, IndexReg, Disp;
2537 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2539 const Type *ValTy = I.getOperand(0)->getType();
2540 unsigned Class = getClassB(ValTy);
2542 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2543 uint64_t Val = CI->getRawValue();
2544 if (Class == cLong) {
2545 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2546 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2547 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2548 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2550 static const unsigned Opcodes[] = {
2551 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2553 unsigned Opcode = Opcodes[Class];
2554 addFullAddress(BuildMI(BB, Opcode, 5),
2555 BaseReg, Scale, IndexReg, Disp).addImm(Val);
2557 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2558 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2559 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2561 if (Class == cLong) {
2562 unsigned ValReg = getReg(I.getOperand(0));
2563 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2564 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2565 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2566 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2568 unsigned ValReg = getReg(I.getOperand(0));
2569 static const unsigned Opcodes[] = {
2570 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2572 unsigned Opcode = Opcodes[Class];
2573 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2574 addFullAddress(BuildMI(BB, Opcode, 1+4),
2575 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2581 /// visitCastInst - Here we have various kinds of copying with or without sign
2582 /// extension going on.
2584 void ISel::visitCastInst(CastInst &CI) {
2585 Value *Op = CI.getOperand(0);
2587 // Noop casts are not even emitted.
2588 if (getClassB(CI.getType()) == getClassB(Op->getType()))
2591 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2592 // of the case are GEP instructions, then the cast does not need to be
2593 // generated explicitly, it will be folded into the GEP.
2594 if (CI.getType() == Type::LongTy &&
2595 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2596 bool AllUsesAreGEPs = true;
2597 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2598 if (!isa<GetElementPtrInst>(*I)) {
2599 AllUsesAreGEPs = false;
2603 // No need to codegen this cast if all users are getelementptr instrs...
2604 if (AllUsesAreGEPs) return;
2607 unsigned DestReg = getReg(CI);
2608 MachineBasicBlock::iterator MI = BB->end();
2609 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2612 /// emitCastOperation - Common code shared between visitCastInst and constant
2613 /// expression cast support.
2615 void ISel::emitCastOperation(MachineBasicBlock *BB,
2616 MachineBasicBlock::iterator IP,
2617 Value *Src, const Type *DestTy,
2619 unsigned SrcReg = getReg(Src, BB, IP);
2620 const Type *SrcTy = Src->getType();
2621 unsigned SrcClass = getClassB(SrcTy);
2622 unsigned DestClass = getClassB(DestTy);
2624 // Implement casts to bool by using compare on the operand followed by set if
2625 // not zero on the result.
2626 if (DestTy == Type::BoolTy) {
2629 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2632 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2635 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2638 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2639 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2643 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2644 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2645 BuildMI(*BB, IP, X86::SAHF, 1);
2649 // If the zero flag is not set, then the value is true, set the byte to
2651 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2655 static const unsigned RegRegMove[] = {
2656 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2659 // Implement casts between values of the same type class (as determined by
2660 // getClass) by using a register-to-register move.
2661 if (SrcClass == DestClass) {
2662 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2663 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2664 } else if (SrcClass == cFP) {
2665 if (SrcTy == Type::FloatTy) { // double -> float
2666 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2667 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2668 } else { // float -> double
2669 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2670 "Unknown cFP member!");
2671 // Truncate from double to float by storing to memory as short, then
2673 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2674 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2675 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2676 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2678 } else if (SrcClass == cLong) {
2679 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2680 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2682 assert(0 && "Cannot handle this type of cast instruction!");
2688 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2689 // or zero extension, depending on whether the source type was signed.
2690 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2691 SrcClass < DestClass) {
2692 bool isLong = DestClass == cLong;
2693 if (isLong) DestClass = cInt;
2695 static const unsigned Opc[][4] = {
2696 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2697 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
2700 bool isUnsigned = SrcTy->isUnsigned();
2701 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2702 DestReg).addReg(SrcReg);
2704 if (isLong) { // Handle upper 32 bits as appropriate...
2705 if (isUnsigned) // Zero out top bits...
2706 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2707 else // Sign extend bottom half...
2708 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2713 // Special case long -> int ...
2714 if (SrcClass == cLong && DestClass == cInt) {
2715 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2719 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2720 // move out of AX or AL.
2721 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2722 && SrcClass > DestClass) {
2723 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2724 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2725 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2729 // Handle casts from integer to floating point now...
2730 if (DestClass == cFP) {
2731 // Promote the integer to a type supported by FLD. We do this because there
2732 // are no unsigned FLD instructions, so we must promote an unsigned value to
2733 // a larger signed value, then use FLD on the larger value.
2735 const Type *PromoteType = 0;
2736 unsigned PromoteOpcode = 0;
2737 unsigned RealDestReg = DestReg;
2738 switch (SrcTy->getPrimitiveID()) {
2739 case Type::BoolTyID:
2740 case Type::SByteTyID:
2741 // We don't have the facilities for directly loading byte sized data from
2742 // memory (even signed). Promote it to 16 bits.
2743 PromoteType = Type::ShortTy;
2744 PromoteOpcode = X86::MOVSX16rr8;
2746 case Type::UByteTyID:
2747 PromoteType = Type::ShortTy;
2748 PromoteOpcode = X86::MOVZX16rr8;
2750 case Type::UShortTyID:
2751 PromoteType = Type::IntTy;
2752 PromoteOpcode = X86::MOVZX32rr16;
2754 case Type::UIntTyID: {
2755 // Make a 64 bit temporary... and zero out the top of it...
2756 unsigned TmpReg = makeAnotherReg(Type::LongTy);
2757 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2758 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2759 SrcTy = Type::LongTy;
2764 case Type::ULongTyID:
2765 // Don't fild into the read destination.
2766 DestReg = makeAnotherReg(Type::DoubleTy);
2768 default: // No promotion needed...
2773 unsigned TmpReg = makeAnotherReg(PromoteType);
2774 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
2775 SrcTy = PromoteType;
2776 SrcClass = getClass(PromoteType);
2780 // Spill the integer to memory and reload it from there...
2782 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2784 if (SrcClass == cLong) {
2785 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2786 FrameIdx).addReg(SrcReg);
2787 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2788 FrameIdx, 4).addReg(SrcReg+1);
2790 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2791 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2792 FrameIdx).addReg(SrcReg);
2795 static const unsigned Op2[] =
2796 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2797 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2799 // We need special handling for unsigned 64-bit integer sources. If the
2800 // input number has the "sign bit" set, then we loaded it incorrectly as a
2801 // negative 64-bit number. In this case, add an offset value.
2802 if (SrcTy == Type::ULongTy) {
2803 // Emit a test instruction to see if the dynamic input value was signed.
2804 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2806 // If the sign bit is set, get a pointer to an offset, otherwise get a
2807 // pointer to a zero.
2808 MachineConstantPool *CP = F->getConstantPool();
2809 unsigned Zero = makeAnotherReg(Type::IntTy);
2810 Constant *Null = Constant::getNullValue(Type::UIntTy);
2811 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
2812 CP->getConstantPoolIndex(Null));
2813 unsigned Offset = makeAnotherReg(Type::IntTy);
2814 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2816 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2817 CP->getConstantPoolIndex(OffsetCst));
2818 unsigned Addr = makeAnotherReg(Type::IntTy);
2819 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2821 // Load the constant for an add. FIXME: this could make an 'fadd' that
2822 // reads directly from memory, but we don't support these yet.
2823 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2824 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2826 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2827 .addReg(ConstReg).addReg(DestReg);
2833 // Handle casts from floating point to integer now...
2834 if (SrcClass == cFP) {
2835 // Change the floating point control register to use "round towards zero"
2836 // mode when truncating to an integer value.
2838 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2839 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2841 // Load the old value of the high byte of the control word...
2842 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2843 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2846 // Set the high part to be round to zero...
2847 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2848 CWFrameIdx, 1).addImm(12);
2850 // Reload the modified control word now...
2851 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2853 // Restore the memory image of control word to original value
2854 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2855 CWFrameIdx, 1).addReg(HighPartOfCW);
2857 // We don't have the facilities for directly storing byte sized data to
2858 // memory. Promote it to 16 bits. We also must promote unsigned values to
2859 // larger classes because we only have signed FP stores.
2860 unsigned StoreClass = DestClass;
2861 const Type *StoreTy = DestTy;
2862 if (StoreClass == cByte || DestTy->isUnsigned())
2863 switch (StoreClass) {
2864 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2865 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2866 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
2867 // The following treatment of cLong may not be perfectly right,
2868 // but it survives chains of casts of the form
2869 // double->ulong->double.
2870 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
2871 default: assert(0 && "Unknown store class!");
2874 // Spill the integer to memory and reload it from there...
2876 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2878 static const unsigned Op1[] =
2879 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2880 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2881 FrameIdx).addReg(SrcReg);
2883 if (DestClass == cLong) {
2884 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2885 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2888 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2889 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2892 // Reload the original control word now...
2893 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2897 // Anything we haven't handled already, we can't (yet) handle at all.
2898 assert(0 && "Unhandled cast instruction!");
2902 /// visitVANextInst - Implement the va_next instruction...
2904 void ISel::visitVANextInst(VANextInst &I) {
2905 unsigned VAList = getReg(I.getOperand(0));
2906 unsigned DestReg = getReg(I);
2909 switch (I.getArgType()->getPrimitiveID()) {
2912 assert(0 && "Error: bad type for va_next instruction!");
2914 case Type::PointerTyID:
2915 case Type::UIntTyID:
2919 case Type::ULongTyID:
2920 case Type::LongTyID:
2921 case Type::DoubleTyID:
2926 // Increment the VAList pointer...
2927 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2930 void ISel::visitVAArgInst(VAArgInst &I) {
2931 unsigned VAList = getReg(I.getOperand(0));
2932 unsigned DestReg = getReg(I);
2934 switch (I.getType()->getPrimitiveID()) {
2937 assert(0 && "Error: bad type for va_next instruction!");
2939 case Type::PointerTyID:
2940 case Type::UIntTyID:
2942 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2944 case Type::ULongTyID:
2945 case Type::LongTyID:
2946 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2947 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2949 case Type::DoubleTyID:
2950 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2955 /// visitGetElementPtrInst - instruction-select GEP instructions
2957 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2958 // If this GEP instruction will be folded into all of its users, we don't need
2959 // to explicitly calculate it!
2960 unsigned A, B, C, D;
2961 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2962 // Check all of the users of the instruction to see if they are loads and
2964 bool AllWillFold = true;
2965 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2966 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2967 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2968 cast<Instruction>(*UI)->getOperand(0) == &I) {
2969 AllWillFold = false;
2973 // If the instruction is foldable, and will be folded into all users, don't
2975 if (AllWillFold) return;
2978 unsigned outputReg = getReg(I);
2979 emitGEPOperation(BB, BB->end(), I.getOperand(0),
2980 I.op_begin()+1, I.op_end(), outputReg);
2983 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2984 /// GEPTypes (the derived types being stepped through at each level). On return
2985 /// from this function, if some indexes of the instruction are representable as
2986 /// an X86 lea instruction, the machine operands are put into the Ops
2987 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2988 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2989 /// addressing mode that only partially consumes the input, the BaseReg input of
2990 /// the addressing mode must be left free.
2992 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2994 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2995 std::vector<Value*> &GEPOps,
2996 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2997 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2998 const TargetData &TD = TM.getTargetData();
3000 // Clear out the state we are working with...
3001 BaseReg = 0; // No base register
3002 Scale = 1; // Unit scale
3003 IndexReg = 0; // No index register
3004 Disp = 0; // No displacement
3006 // While there are GEP indexes that can be folded into the current address,
3007 // keep processing them.
3008 while (!GEPTypes.empty()) {
3009 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3010 // It's a struct access. CUI is the index into the structure,
3011 // which names the field. This index must have unsigned type.
3012 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3014 // Use the TargetData structure to pick out what the layout of the
3015 // structure is in memory. Since the structure index must be constant, we
3016 // can get its value and use it to find the right byte offset from the
3017 // StructLayout class's list of structure member offsets.
3018 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3019 GEPOps.pop_back(); // Consume a GEP operand
3020 GEPTypes.pop_back();
3022 // It's an array or pointer access: [ArraySize x ElementType].
3023 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3024 Value *idx = GEPOps.back();
3026 // idx is the index into the array. Unlike with structure
3027 // indices, we may not know its actual value at code-generation
3030 // If idx is a constant, fold it into the offset.
3031 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3032 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3033 Disp += TypeSize*CSI->getValue();
3034 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3035 Disp += TypeSize*CUI->getValue();
3037 // If the index reg is already taken, we can't handle this index.
3038 if (IndexReg) return;
3040 // If this is a size that we can handle, then add the index as
3042 case 1: case 2: case 4: case 8:
3043 // These are all acceptable scales on X86.
3047 // Otherwise, we can't handle this scale
3051 if (CastInst *CI = dyn_cast<CastInst>(idx))
3052 if (CI->getOperand(0)->getType() == Type::IntTy ||
3053 CI->getOperand(0)->getType() == Type::UIntTy)
3054 idx = CI->getOperand(0);
3056 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3059 GEPOps.pop_back(); // Consume a GEP operand
3060 GEPTypes.pop_back();
3064 // GEPTypes is empty, which means we have a single operand left. See if we
3065 // can set it as the base register.
3067 // FIXME: When addressing modes are more powerful/correct, we could load
3068 // global addresses directly as 32-bit immediates.
3069 assert(BaseReg == 0);
3070 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3071 GEPOps.pop_back(); // Consume the last GEP operand
3075 /// isGEPFoldable - Return true if the specified GEP can be completely
3076 /// folded into the addressing mode of a load/store or lea instruction.
3077 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3078 Value *Src, User::op_iterator IdxBegin,
3079 User::op_iterator IdxEnd, unsigned &BaseReg,
3080 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3081 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3082 Src = CPR->getValue();
3084 std::vector<Value*> GEPOps;
3085 GEPOps.resize(IdxEnd-IdxBegin+1);
3087 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3089 std::vector<const Type*> GEPTypes;
3090 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3091 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3093 MachineBasicBlock::iterator IP;
3094 if (MBB) IP = MBB->end();
3095 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3097 // We can fold it away iff the getGEPIndex call eliminated all operands.
3098 return GEPOps.empty();
3101 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3102 MachineBasicBlock::iterator IP,
3103 Value *Src, User::op_iterator IdxBegin,
3104 User::op_iterator IdxEnd, unsigned TargetReg) {
3105 const TargetData &TD = TM.getTargetData();
3106 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3107 Src = CPR->getValue();
3109 std::vector<Value*> GEPOps;
3110 GEPOps.resize(IdxEnd-IdxBegin+1);
3112 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3114 std::vector<const Type*> GEPTypes;
3115 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3116 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3118 // Keep emitting instructions until we consume the entire GEP instruction.
3119 while (!GEPOps.empty()) {
3120 unsigned OldSize = GEPOps.size();
3121 unsigned BaseReg, Scale, IndexReg, Disp;
3122 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3124 if (GEPOps.size() != OldSize) {
3125 // getGEPIndex consumed some of the input. Build an LEA instruction here.
3126 unsigned NextTarget = 0;
3127 if (!GEPOps.empty()) {
3128 assert(BaseReg == 0 &&
3129 "getGEPIndex should have left the base register open for chaining!");
3130 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
3133 if (IndexReg == 0 && Disp == 0)
3134 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3136 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
3137 BaseReg, Scale, IndexReg, Disp);
3139 TargetReg = NextTarget;
3140 } else if (GEPTypes.empty()) {
3141 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3142 // all operands are consumed but the base pointer. If so, just load it
3143 // into the register.
3144 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3145 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3147 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3148 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3150 break; // we are now done
3153 // It's an array or pointer access: [ArraySize x ElementType].
3154 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3155 Value *idx = GEPOps.back();
3156 GEPOps.pop_back(); // Consume a GEP operand
3157 GEPTypes.pop_back();
3159 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3160 // operand on X86. Handle this case directly now...
3161 if (CastInst *CI = dyn_cast<CastInst>(idx))
3162 if (CI->getOperand(0)->getType() == Type::IntTy ||
3163 CI->getOperand(0)->getType() == Type::UIntTy)
3164 idx = CI->getOperand(0);
3166 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3167 // must find the size of the pointed-to type (Not coincidentally, the next
3168 // type is the type of the elements in the array).
3169 const Type *ElTy = SqTy->getElementType();
3170 unsigned elementSize = TD.getTypeSize(ElTy);
3172 // If idxReg is a constant, we don't need to perform the multiply!
3173 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3174 if (!CSI->isNullValue()) {
3175 unsigned Offset = elementSize*CSI->getRawValue();
3176 unsigned Reg = makeAnotherReg(Type::UIntTy);
3177 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3178 .addReg(Reg).addImm(Offset);
3179 --IP; // Insert the next instruction before this one.
3180 TargetReg = Reg; // Codegen the rest of the GEP into this
3182 } else if (elementSize == 1) {
3183 // If the element size is 1, we don't have to multiply, just add
3184 unsigned idxReg = getReg(idx, MBB, IP);
3185 unsigned Reg = makeAnotherReg(Type::UIntTy);
3186 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3187 --IP; // Insert the next instruction before this one.
3188 TargetReg = Reg; // Codegen the rest of the GEP into this
3190 unsigned idxReg = getReg(idx, MBB, IP);
3191 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3193 // Make sure we can back the iterator up to point to the first
3194 // instruction emitted.
3195 MachineBasicBlock::iterator BeforeIt = IP;
3196 if (IP == MBB->begin())
3197 BeforeIt = MBB->end();
3200 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3202 // Emit an ADD to add OffsetReg to the basePtr.
3203 unsigned Reg = makeAnotherReg(Type::UIntTy);
3204 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3205 .addReg(Reg).addReg(OffsetReg);
3207 // Step to the first instruction of the multiply.
3208 if (BeforeIt == MBB->end())
3213 TargetReg = Reg; // Codegen the rest of the GEP into this
3220 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3221 /// frame manager, otherwise do it the hard way.
3223 void ISel::visitAllocaInst(AllocaInst &I) {
3224 // Find the data size of the alloca inst's getAllocatedType.
3225 const Type *Ty = I.getAllocatedType();
3226 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3228 // If this is a fixed size alloca in the entry block for the function,
3229 // statically stack allocate the space.
3231 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
3232 if (I.getParent() == I.getParent()->getParent()->begin()) {
3233 TySize *= CUI->getValue(); // Get total allocated size...
3234 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
3236 // Create a new stack object using the frame manager...
3237 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
3238 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
3243 // Create a register to hold the temporary result of multiplying the type size
3244 // constant by the variable amount.
3245 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3246 unsigned SrcReg1 = getReg(I.getArraySize());
3248 // TotalSizeReg = mul <numelements>, <TypeSize>
3249 MachineBasicBlock::iterator MBBI = BB->end();
3250 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
3252 // AddedSize = add <TotalSizeReg>, 15
3253 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3254 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
3256 // AlignedSize = and <AddedSize>, ~15
3257 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3258 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
3260 // Subtract size from stack pointer, thereby allocating some space.
3261 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
3263 // Put a pointer to the space into the result register, by copying
3264 // the stack pointer.
3265 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
3267 // Inform the Frame Information that we have just allocated a variable-sized
3269 F->getFrameInfo()->CreateVariableSizedObject();
3272 /// visitMallocInst - Malloc instructions are code generated into direct calls
3273 /// to the library malloc.
3275 void ISel::visitMallocInst(MallocInst &I) {
3276 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3279 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3280 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3282 Arg = makeAnotherReg(Type::UIntTy);
3283 unsigned Op0Reg = getReg(I.getOperand(0));
3284 MachineBasicBlock::iterator MBBI = BB->end();
3285 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
3288 std::vector<ValueRecord> Args;
3289 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3290 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3291 1).addExternalSymbol("malloc", true);
3292 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3296 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3299 void ISel::visitFreeInst(FreeInst &I) {
3300 std::vector<ValueRecord> Args;
3301 Args.push_back(ValueRecord(I.getOperand(0)));
3302 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3303 1).addExternalSymbol("free", true);
3304 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3307 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
3308 /// into a machine code representation is a very simple peep-hole fashion. The
3309 /// generated code sucks but the implementation is nice and simple.
3311 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3312 return new ISel(TM);