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/Pass.h"
22 #include "llvm/CodeGen/IntrinsicLowering.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");
41 struct ISel : public FunctionPass, InstVisitor<ISel> {
43 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
46 int ReturnAddressIndex; // FrameIndex for the return address
48 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
50 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
53 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
58 bool runOnFunction(Function &Fn) {
59 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
63 F = &MachineFunction::construct(&Fn, TM);
65 // Create all of the machine basic blocks for the function...
66 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
71 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
75 // Copy incoming arguments off of the stack...
76 LoadArgumentsToVirtualRegs(Fn);
78 // Instruction select everything except PHI nodes
81 // Select the PHI nodes
84 // Insert the FP_REG_KILL instructions into blocks that need them.
90 // We always build a machine code representation for the function
94 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
98 /// visitBasicBlock - This method is called when we are visiting a new basic
99 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
104 BB = MBBMap[&LLVM_BB];
107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
111 void LowerUnknownIntrinsicFunctionCalls(Function &F);
113 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
114 /// from the stack into virtual registers.
116 void LoadArgumentsToVirtualRegs(Function &F);
118 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
119 /// because we have to generate our sources into the source basic blocks,
120 /// not the current one.
122 void SelectPHINodes();
124 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
125 /// that need them. This only occurs due to the floating point stackifier
126 /// not being aggressive enough to handle arbitrary global stackification.
128 void InsertFPRegKills();
130 // Visitation methods for various instructions. These methods simply emit
131 // fixed X86 code for each instruction.
134 // Control flow operators
135 void visitReturnInst(ReturnInst &RI);
136 void visitBranchInst(BranchInst &BI);
142 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
143 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
145 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
146 const std::vector<ValueRecord> &Args);
147 void visitCallInst(CallInst &I);
148 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
150 // Arithmetic operators
151 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
152 void visitAdd(BinaryOperator &B);// visitSimpleBinary(B, 0); }
153 void visitSub(BinaryOperator &B);// { visitSimpleBinary(B, 1); }
154 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
155 unsigned DestReg, const Type *DestTy,
156 unsigned Op0Reg, unsigned Op1Reg);
157 void doMultiplyConst(MachineBasicBlock *MBB,
158 MachineBasicBlock::iterator MBBI,
159 unsigned DestReg, const Type *DestTy,
160 unsigned Op0Reg, unsigned Op1Val);
161 void visitMul(BinaryOperator &B);
163 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
164 void visitRem(BinaryOperator &B) { visitDivRem(B); }
165 void visitDivRem(BinaryOperator &B);
168 void visitAnd(BinaryOperator &B);// { visitSimpleBinary(B, 2); }
169 void visitOr (BinaryOperator &B);// { visitSimpleBinary(B, 3); }
170 void visitXor(BinaryOperator &B);// { visitSimpleBinary(B, 4); }
172 // Comparison operators...
173 void visitSetCondInst(SetCondInst &I);
174 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
175 MachineBasicBlock *MBB,
176 MachineBasicBlock::iterator MBBI);
178 // Memory Instructions
179 void visitLoadInst(LoadInst &I);
180 void visitStoreInst(StoreInst &I);
181 void visitGetElementPtrInst(GetElementPtrInst &I);
182 void visitAllocaInst(AllocaInst &I);
183 void visitMallocInst(MallocInst &I);
184 void visitFreeInst(FreeInst &I);
187 void visitShiftInst(ShiftInst &I);
188 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
189 void visitCastInst(CastInst &I);
190 void visitVANextInst(VANextInst &I);
191 void visitVAArgInst(VAArgInst &I);
193 void visitInstruction(Instruction &I) {
194 std::cerr << "Cannot instruction select: " << I;
198 /// promote32 - Make a value 32-bits wide, and put it somewhere.
200 void promote32(unsigned targetReg, const ValueRecord &VR);
202 /// getAddressingMode - Get the addressing mode to use to address the
203 /// specified value. The returned value should be used with addFullAddress.
204 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
205 unsigned &IndexReg, unsigned &Disp);
208 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
210 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
211 std::vector<Value*> &GEPOps,
212 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
213 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
215 /// isGEPFoldable - Return true if the specified GEP can be completely
216 /// folded into the addressing mode of a load/store or lea instruction.
217 bool isGEPFoldable(MachineBasicBlock *MBB,
218 Value *Src, User::op_iterator IdxBegin,
219 User::op_iterator IdxEnd, unsigned &BaseReg,
220 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
222 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
223 /// constant expression GEP support.
225 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
226 Value *Src, User::op_iterator IdxBegin,
227 User::op_iterator IdxEnd, unsigned TargetReg);
229 /// emitCastOperation - Common code shared between visitCastInst and
230 /// constant expression cast support.
232 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
233 Value *Src, const Type *DestTy, unsigned TargetReg);
235 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
236 /// and constant expression support.
238 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
239 MachineBasicBlock::iterator IP,
240 Value *Op0, Value *Op1,
241 unsigned OperatorClass, unsigned TargetReg);
243 void emitDivRemOperation(MachineBasicBlock *BB,
244 MachineBasicBlock::iterator IP,
245 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
246 const Type *Ty, unsigned TargetReg);
248 /// emitSetCCOperation - Common code shared between visitSetCondInst and
249 /// constant expression support.
251 void emitSetCCOperation(MachineBasicBlock *BB,
252 MachineBasicBlock::iterator IP,
253 Value *Op0, Value *Op1, unsigned Opcode,
256 /// emitShiftOperation - Common code shared between visitShiftInst and
257 /// constant expression support.
259 void emitShiftOperation(MachineBasicBlock *MBB,
260 MachineBasicBlock::iterator IP,
261 Value *Op, Value *ShiftAmount, bool isLeftShift,
262 const Type *ResultTy, unsigned DestReg);
265 /// copyConstantToRegister - Output the instructions required to put the
266 /// specified constant into the specified register.
268 void copyConstantToRegister(MachineBasicBlock *MBB,
269 MachineBasicBlock::iterator MBBI,
270 Constant *C, unsigned Reg);
272 /// makeAnotherReg - This method returns the next register number we haven't
275 /// Long values are handled somewhat specially. They are always allocated
276 /// as pairs of 32 bit integer values. The register number returned is the
277 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
278 /// of the long value.
280 unsigned makeAnotherReg(const Type *Ty) {
281 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
282 "Current target doesn't have X86 reg info??");
283 const X86RegisterInfo *MRI =
284 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
285 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
286 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
287 // Create the lower part
288 F->getSSARegMap()->createVirtualRegister(RC);
289 // Create the upper part.
290 return F->getSSARegMap()->createVirtualRegister(RC)-1;
293 // Add the mapping of regnumber => reg class to MachineFunction
294 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
295 return F->getSSARegMap()->createVirtualRegister(RC);
298 /// getReg - This method turns an LLVM value into a register number. This
299 /// is guaranteed to produce the same register number for a particular value
300 /// every time it is queried.
302 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
303 unsigned getReg(Value *V) {
304 // Just append to the end of the current bb.
305 MachineBasicBlock::iterator It = BB->end();
306 return getReg(V, BB, It);
308 unsigned getReg(Value *V, MachineBasicBlock *MBB,
309 MachineBasicBlock::iterator IPt) {
310 unsigned &Reg = RegMap[V];
312 Reg = makeAnotherReg(V->getType());
316 // If this operand is a constant, emit the code to copy the constant into
317 // the register here...
319 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
320 // Move the address of the global into the register
321 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
322 RegMap.erase(V); // Assign a new name to this address if ref'd again
323 } else if (Constant *C = dyn_cast<Constant>(V)) {
324 copyConstantToRegister(MBB, IPt, C, Reg);
325 RegMap.erase(V); // Assign a new name to this constant if ref'd again
333 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
337 cByte, cShort, cInt, cFP, cLong
341 NegOne, PosOne, Cons, Other
346 /// getClass - Turn a primitive type into a "class" number which is based on the
347 /// size of the type, and whether or not it is floating point.
349 static inline TypeClass getClass(const Type *Ty) {
350 switch (Ty->getTypeID()) {
351 case Type::SByteTyID:
352 case Type::UByteTyID: return cByte; // Byte operands are class #0
353 case Type::ShortTyID:
354 case Type::UShortTyID: return cShort; // Short operands are class #1
357 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
359 case Type::FloatTyID:
360 case Type::DoubleTyID: return cFP; // Floating Point is #3
363 case Type::ULongTyID: return cLong; // Longs are class #4
365 assert(0 && "Invalid type to getClass!");
366 return cByte; // not reached
370 // getClassB - Just like getClass, but treat boolean values as bytes.
371 static inline TypeClass getClassB(const Type *Ty) {
372 if (Ty == Type::BoolTy) return cByte;
377 /// copyConstantToRegister - Output the instructions required to put the
378 /// specified constant into the specified register.
380 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
381 MachineBasicBlock::iterator IP,
382 Constant *C, unsigned R) {
383 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
385 switch (CE->getOpcode()) {
386 case Instruction::GetElementPtr:
387 emitGEPOperation(MBB, IP, CE->getOperand(0),
388 CE->op_begin()+1, CE->op_end(), R);
390 case Instruction::Cast:
391 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
394 case Instruction::Xor: ++Class; // FALL THROUGH
395 case Instruction::Or: ++Class; // FALL THROUGH
396 case Instruction::And: ++Class; // FALL THROUGH
397 case Instruction::Sub: ++Class; // FALL THROUGH
398 case Instruction::Add:
399 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
403 case Instruction::Mul: {
404 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
405 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
406 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
409 case Instruction::Div:
410 case Instruction::Rem: {
411 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
412 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
413 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
414 CE->getOpcode() == Instruction::Div,
419 case Instruction::SetNE:
420 case Instruction::SetEQ:
421 case Instruction::SetLT:
422 case Instruction::SetGT:
423 case Instruction::SetLE:
424 case Instruction::SetGE:
425 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
429 case Instruction::Shl:
430 case Instruction::Shr:
431 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
432 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
436 std::cerr << "Offending expr: " << *C << "\n";
437 assert(0 && "Constant expression not yet handled!\n");
441 if (C->getType()->isIntegral()) {
442 unsigned Class = getClassB(C->getType());
444 if (Class == cLong) {
445 // Copy the value into the register pair.
446 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
447 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
448 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
452 assert(Class <= cInt && "Type not handled yet!");
454 static const unsigned IntegralOpcodeTab[] = {
455 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
458 if (C->getType() == Type::BoolTy) {
459 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
461 ConstantInt *CI = cast<ConstantInt>(C);
462 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
464 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
465 if (CFP->isExactlyValue(+0.0))
466 BuildMI(*MBB, IP, X86::FLD0, 0, R);
467 else if (CFP->isExactlyValue(+1.0))
468 BuildMI(*MBB, IP, X86::FLD1, 0, R);
470 // Otherwise we need to spill the constant to memory...
471 MachineConstantPool *CP = F->getConstantPool();
472 unsigned CPI = CP->getConstantPoolIndex(CFP);
473 const Type *Ty = CFP->getType();
475 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
476 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
477 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
480 } else if (isa<ConstantPointerNull>(C)) {
481 // Copy zero (null pointer) to the register.
482 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
483 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
484 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
486 std::cerr << "Offending constant: " << *C << "\n";
487 assert(0 && "Type not handled yet!");
491 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
492 /// the stack into virtual registers.
494 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
495 // Emit instructions to load the arguments... On entry to a function on the
496 // X86, the stack frame looks like this:
498 // [ESP] -- return address
499 // [ESP + 4] -- first argument (leftmost lexically)
500 // [ESP + 8] -- second argument, if first argument is four bytes in size
503 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
504 MachineFrameInfo *MFI = F->getFrameInfo();
506 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
507 unsigned Reg = getReg(*I);
509 int FI; // Frame object index
510 switch (getClassB(I->getType())) {
512 FI = MFI->CreateFixedObject(1, ArgOffset);
513 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
516 FI = MFI->CreateFixedObject(2, ArgOffset);
517 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
520 FI = MFI->CreateFixedObject(4, ArgOffset);
521 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
524 FI = MFI->CreateFixedObject(8, ArgOffset);
525 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
526 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
527 ArgOffset += 4; // longs require 4 additional bytes
531 if (I->getType() == Type::FloatTy) {
532 Opcode = X86::FLD32m;
533 FI = MFI->CreateFixedObject(4, ArgOffset);
535 Opcode = X86::FLD64m;
536 FI = MFI->CreateFixedObject(8, ArgOffset);
537 ArgOffset += 4; // doubles require 4 additional bytes
539 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
542 assert(0 && "Unhandled argument type!");
544 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
547 // If the function takes variable number of arguments, add a frame offset for
548 // the start of the first vararg value... this is used to expand
550 if (Fn.getFunctionType()->isVarArg())
551 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
555 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
556 /// because we have to generate our sources into the source basic blocks, not
559 void ISel::SelectPHINodes() {
560 const TargetInstrInfo &TII = *TM.getInstrInfo();
561 const Function &LF = *F->getFunction(); // The LLVM function...
562 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
563 const BasicBlock *BB = I;
564 MachineBasicBlock &MBB = *MBBMap[I];
566 // Loop over all of the PHI nodes in the LLVM basic block...
567 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
568 for (BasicBlock::const_iterator I = BB->begin();
569 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
571 // Create a new machine instr PHI node, and insert it.
572 unsigned PHIReg = getReg(*PN);
573 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
574 X86::PHI, PN->getNumOperands(), PHIReg);
576 MachineInstr *LongPhiMI = 0;
577 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
578 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
579 X86::PHI, PN->getNumOperands(), PHIReg+1);
581 // PHIValues - Map of blocks to incoming virtual registers. We use this
582 // so that we only initialize one incoming value for a particular block,
583 // even if the block has multiple entries in the PHI node.
585 std::map<MachineBasicBlock*, unsigned> PHIValues;
587 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
588 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
590 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
591 PHIValues.lower_bound(PredMBB);
593 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
594 // We already inserted an initialization of the register for this
595 // predecessor. Recycle it.
596 ValReg = EntryIt->second;
599 // Get the incoming value into a virtual register.
601 Value *Val = PN->getIncomingValue(i);
603 // If this is a constant or GlobalValue, we may have to insert code
604 // into the basic block to compute it into a virtual register.
605 if (isa<Constant>(Val)) {
606 // Because we don't want to clobber any values which might be in
607 // physical registers with the computation of this constant (which
608 // might be arbitrarily complex if it is a constant expression),
609 // just insert the computation at the top of the basic block.
610 MachineBasicBlock::iterator PI = PredMBB->begin();
612 // Skip over any PHI nodes though!
613 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
616 ValReg = getReg(Val, PredMBB, PI);
618 ValReg = getReg(Val);
621 // Remember that we inserted a value for this PHI for this predecessor
622 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
625 PhiMI->addRegOperand(ValReg);
626 PhiMI->addMachineBasicBlockOperand(PredMBB);
628 LongPhiMI->addRegOperand(ValReg+1);
629 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
633 // Now that we emitted all of the incoming values for the PHI node, make
634 // sure to reposition the InsertPoint after the PHI that we just added.
635 // This is needed because we might have inserted a constant into this
636 // block, right after the PHI's which is before the old insert point!
637 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
643 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
644 /// compensation code on critical edges. As such, it requires that we kill all
645 /// FP registers on the exit from any blocks that either ARE critical edges, or
646 /// branch to a block that has incoming critical edges.
648 /// Note that this kill instruction will eventually be eliminated when
649 /// restrictions in the stackifier are relaxed.
651 static bool RequiresFPRegKill(const BasicBlock *BB) {
653 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
654 const BasicBlock *Succ = *SI;
655 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
656 ++PI; // Block have at least one predecessory
657 if (PI != PE) { // If it has exactly one, this isn't crit edge
658 // If this block has more than one predecessor, check all of the
659 // predecessors to see if they have multiple successors. If so, then the
660 // block we are analyzing needs an FPRegKill.
661 for (PI = pred_begin(Succ); PI != PE; ++PI) {
662 const BasicBlock *Pred = *PI;
663 succ_const_iterator SI2 = succ_begin(Pred);
664 ++SI2; // There must be at least one successor of this block.
665 if (SI2 != succ_end(Pred))
666 return true; // Yes, we must insert the kill on this edge.
670 // If we got this far, there is no need to insert the kill instruction.
677 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
678 // need them. This only occurs due to the floating point stackifier not being
679 // aggressive enough to handle arbitrary global stackification.
681 // Currently we insert an FP_REG_KILL instruction into each block that uses or
682 // defines a floating point virtual register.
684 // When the global register allocators (like linear scan) finally update live
685 // variable analysis, we can keep floating point values in registers across
686 // portions of the CFG that do not involve critical edges. This will be a big
687 // win, but we are waiting on the global allocators before we can do this.
689 // With a bit of work, the floating point stackifier pass can be enhanced to
690 // break critical edges as needed (to make a place to put compensation code),
691 // but this will require some infrastructure improvements as well.
693 void ISel::InsertFPRegKills() {
694 SSARegMap &RegMap = *F->getSSARegMap();
696 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
697 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
698 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
699 MachineOperand& MO = I->getOperand(i);
700 if (MO.isRegister() && MO.getReg()) {
701 unsigned Reg = MO.getReg();
702 if (MRegisterInfo::isVirtualRegister(Reg))
703 if (RegMap.getRegClass(Reg)->getSize() == 10)
707 // If we haven't found an FP register use or def in this basic block, check
708 // to see if any of our successors has an FP PHI node, which will cause a
709 // copy to be inserted into this block.
710 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
711 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
712 MachineBasicBlock *SBB = MBBMap[*SI];
713 for (MachineBasicBlock::iterator I = SBB->begin();
714 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
715 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
721 // Okay, this block uses an FP register. If the block has successors (ie,
722 // it's not an unwind/return), insert the FP_REG_KILL instruction.
723 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
724 RequiresFPRegKill(BB->getBasicBlock())) {
725 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
732 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
733 // the conditional branch instruction which is the only user of the cc
734 // instruction. This is the case if the conditional branch is the only user of
735 // the setcc, and if the setcc is in the same basic block as the conditional
736 // branch. We also don't handle long arguments below, so we reject them here as
739 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
740 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
741 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
742 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
743 const Type *Ty = SCI->getOperand(0)->getType();
744 if (Ty != Type::LongTy && Ty != Type::ULongTy)
750 // Return a fixed numbering for setcc instructions which does not depend on the
751 // order of the opcodes.
753 static unsigned getSetCCNumber(unsigned Opcode) {
755 default: assert(0 && "Unknown setcc instruction!");
756 case Instruction::SetEQ: return 0;
757 case Instruction::SetNE: return 1;
758 case Instruction::SetLT: return 2;
759 case Instruction::SetGE: return 3;
760 case Instruction::SetGT: return 4;
761 case Instruction::SetLE: return 5;
765 // LLVM -> X86 signed X86 unsigned
766 // ----- ---------- ------------
767 // seteq -> sete sete
768 // setne -> setne setne
769 // setlt -> setl setb
770 // setge -> setge setae
771 // setgt -> setg seta
772 // setle -> setle setbe
774 // sets // Used by comparison with 0 optimization
776 static const unsigned SetCCOpcodeTab[2][8] = {
777 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
779 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
780 X86::SETSr, X86::SETNSr },
783 // EmitComparison - This function emits a comparison of the two operands,
784 // returning the extended setcc code to use.
785 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
786 MachineBasicBlock *MBB,
787 MachineBasicBlock::iterator IP) {
788 // The arguments are already supposed to be of the same type.
789 const Type *CompTy = Op0->getType();
790 unsigned Class = getClassB(CompTy);
791 unsigned Op0r = getReg(Op0, MBB, IP);
793 // Special case handling of: cmp R, i
794 if (Class == cByte || Class == cShort || Class == cInt)
795 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
796 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
798 // Mask off any upper bits of the constant, if there are any...
799 Op1v &= (1ULL << (8 << Class)) - 1;
801 // If this is a comparison against zero, emit more efficient code. We
802 // can't handle unsigned comparisons against zero unless they are == or
803 // !=. These should have been strength reduced already anyway.
804 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
805 static const unsigned TESTTab[] = {
806 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
808 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
810 if (OpNum == 2) return 6; // Map jl -> js
811 if (OpNum == 3) return 7; // Map jg -> jns
815 static const unsigned CMPTab[] = {
816 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
819 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
823 // Special case handling of comparison against +/- 0.0
824 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
825 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
826 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
827 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
828 BuildMI(*MBB, IP, X86::SAHF, 1);
832 unsigned Op1r = getReg(Op1, MBB, IP);
834 default: assert(0 && "Unknown type class!");
835 // Emit: cmp <var1>, <var2> (do the comparison). We can
836 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
839 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
842 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
845 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
848 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(Op0r).addReg(Op1r);
849 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
850 BuildMI(*MBB, IP, X86::SAHF, 1);
854 if (OpNum < 2) { // seteq, setne
855 unsigned LoTmp = makeAnotherReg(Type::IntTy);
856 unsigned HiTmp = makeAnotherReg(Type::IntTy);
857 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
858 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
859 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
860 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
861 break; // Allow the sete or setne to be generated from flags set by OR
863 // Emit a sequence of code which compares the high and low parts once
864 // each, then uses a conditional move to handle the overflow case. For
865 // example, a setlt for long would generate code like this:
867 // AL = lo(op1) < lo(op2) // Signedness depends on operands
868 // BL = hi(op1) < hi(op2) // Always unsigned comparison
869 // dest = hi(op1) == hi(op2) ? AL : BL;
872 // FIXME: This would be much better if we had hierarchical register
873 // classes! Until then, hardcode registers so that we can deal with their
874 // aliases (because we don't have conditional byte moves).
876 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
877 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
878 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
879 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
880 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
881 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
882 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
884 // NOTE: visitSetCondInst knows that the value is dumped into the BL
885 // register at this point for long values...
893 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
894 /// register, then move it to wherever the result should be.
896 void ISel::visitSetCondInst(SetCondInst &I) {
897 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
899 unsigned DestReg = getReg(I);
900 MachineBasicBlock::iterator MII = BB->end();
901 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
905 /// emitSetCCOperation - Common code shared between visitSetCondInst and
906 /// constant expression support.
908 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
909 MachineBasicBlock::iterator IP,
910 Value *Op0, Value *Op1, unsigned Opcode,
911 unsigned TargetReg) {
912 unsigned OpNum = getSetCCNumber(Opcode);
913 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
915 const Type *CompTy = Op0->getType();
916 unsigned CompClass = getClassB(CompTy);
917 bool isSigned = CompTy->isSigned() && CompClass != cFP;
919 if (CompClass != cLong || OpNum < 2) {
920 // Handle normal comparisons with a setcc instruction...
921 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
923 // Handle long comparisons by copying the value which is already in BL into
924 // the register we want...
925 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
932 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
933 /// operand, in the specified target register.
935 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
936 bool isUnsigned = VR.Ty->isUnsigned();
938 // Make sure we have the register number for this value...
939 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
941 switch (getClassB(VR.Ty)) {
943 // Extend value into target register (8->32)
945 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
947 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
950 // Extend value into target register (16->32)
952 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
954 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
957 // Move value into target register (32->32)
958 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
961 assert(0 && "Unpromotable operand class in promote32");
965 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
966 /// we have the following possibilities:
968 /// ret void: No return value, simply emit a 'ret' instruction
969 /// ret sbyte, ubyte : Extend value into EAX and return
970 /// ret short, ushort: Extend value into EAX and return
971 /// ret int, uint : Move value into EAX and return
972 /// ret pointer : Move value into EAX and return
973 /// ret long, ulong : Move value into EAX/EDX and return
974 /// ret float/double : Top of FP stack
976 void ISel::visitReturnInst(ReturnInst &I) {
977 if (I.getNumOperands() == 0) {
978 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
982 Value *RetVal = I.getOperand(0);
983 unsigned RetReg = getReg(RetVal);
984 switch (getClassB(RetVal->getType())) {
985 case cByte: // integral return values: extend or move into EAX and return
988 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
989 // Declare that EAX is live on exit
990 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
992 case cFP: // Floats & Doubles: Return in ST(0)
993 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
994 // Declare that top-of-stack is live on exit
995 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
998 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
999 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1000 // Declare that EAX & EDX are live on exit
1001 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1005 visitInstruction(I);
1007 // Emit a 'ret' instruction
1008 BuildMI(BB, X86::RET, 0);
1011 // getBlockAfter - Return the basic block which occurs lexically after the
1013 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1014 Function::iterator I = BB; ++I; // Get iterator to next block
1015 return I != BB->getParent()->end() ? &*I : 0;
1018 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1019 /// that since code layout is frozen at this point, that if we are trying to
1020 /// jump to a block that is the immediate successor of the current block, we can
1021 /// just make a fall-through (but we don't currently).
1023 void ISel::visitBranchInst(BranchInst &BI) {
1024 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1026 if (!BI.isConditional()) { // Unconditional branch?
1027 if (BI.getSuccessor(0) != NextBB)
1028 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1032 // See if we can fold the setcc into the branch itself...
1033 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1035 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1036 // computed some other way...
1037 unsigned condReg = getReg(BI.getCondition());
1038 BuildMI(BB, X86::CMP8ri, 2).addReg(condReg).addImm(0);
1039 if (BI.getSuccessor(1) == NextBB) {
1040 if (BI.getSuccessor(0) != NextBB)
1041 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1043 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1045 if (BI.getSuccessor(0) != NextBB)
1046 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1051 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1052 MachineBasicBlock::iterator MII = BB->end();
1053 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1055 const Type *CompTy = SCI->getOperand(0)->getType();
1056 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1059 // LLVM -> X86 signed X86 unsigned
1060 // ----- ---------- ------------
1068 // js // Used by comparison with 0 optimization
1071 static const unsigned OpcodeTab[2][8] = {
1072 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1073 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1074 X86::JS, X86::JNS },
1077 if (BI.getSuccessor(0) != NextBB) {
1078 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1079 if (BI.getSuccessor(1) != NextBB)
1080 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1082 // Change to the inverse condition...
1083 if (BI.getSuccessor(1) != NextBB) {
1085 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1091 /// doCall - This emits an abstract call instruction, setting up the arguments
1092 /// and the return value as appropriate. For the actual function call itself,
1093 /// it inserts the specified CallMI instruction into the stream.
1095 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1096 const std::vector<ValueRecord> &Args) {
1098 // Count how many bytes are to be pushed on the stack...
1099 unsigned NumBytes = 0;
1101 if (!Args.empty()) {
1102 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1103 switch (getClassB(Args[i].Ty)) {
1104 case cByte: case cShort: case cInt:
1105 NumBytes += 4; break;
1107 NumBytes += 8; break;
1109 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1111 default: assert(0 && "Unknown class!");
1114 // Adjust the stack pointer for the new arguments...
1115 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1117 // Arguments go on the stack in reverse order, as specified by the ABI.
1118 unsigned ArgOffset = 0;
1119 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1121 switch (getClassB(Args[i].Ty)) {
1124 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1125 // Zero/Sign extend constant, then stuff into memory.
1126 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1127 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1128 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1129 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1131 // Promote arg to 32 bits wide into a temporary register...
1132 ArgReg = makeAnotherReg(Type::UIntTy);
1133 promote32(ArgReg, Args[i]);
1134 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1135 X86::ESP, ArgOffset).addReg(ArgReg);
1139 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1140 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1141 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1142 X86::ESP, ArgOffset).addImm(Val);
1144 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1145 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1146 X86::ESP, ArgOffset).addReg(ArgReg);
1150 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1151 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1152 X86::ESP, ArgOffset).addReg(ArgReg);
1153 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1154 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1155 ArgOffset += 4; // 8 byte entry, not 4.
1159 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1160 if (Args[i].Ty == Type::FloatTy) {
1161 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1162 X86::ESP, ArgOffset).addReg(ArgReg);
1164 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1165 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1166 X86::ESP, ArgOffset).addReg(ArgReg);
1167 ArgOffset += 4; // 8 byte entry, not 4.
1171 default: assert(0 && "Unknown class!");
1176 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1179 BB->push_back(CallMI);
1181 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1183 // If there is a return value, scavenge the result from the location the call
1186 if (Ret.Ty != Type::VoidTy) {
1187 unsigned DestClass = getClassB(Ret.Ty);
1188 switch (DestClass) {
1192 // Integral results are in %eax, or the appropriate portion
1194 static const unsigned regRegMove[] = {
1195 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1197 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1198 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1201 case cFP: // Floating-point return values live in %ST(0)
1202 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1204 case cLong: // Long values are left in EDX:EAX
1205 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1206 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1208 default: assert(0 && "Unknown class!");
1214 /// visitCallInst - Push args on stack and do a procedure call instruction.
1215 void ISel::visitCallInst(CallInst &CI) {
1216 MachineInstr *TheCall;
1217 if (Function *F = CI.getCalledFunction()) {
1218 // Is it an intrinsic function call?
1219 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1220 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1224 // Emit a CALL instruction with PC-relative displacement.
1225 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1226 } else { // Emit an indirect call...
1227 unsigned Reg = getReg(CI.getCalledValue());
1228 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1231 std::vector<ValueRecord> Args;
1232 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1233 Args.push_back(ValueRecord(CI.getOperand(i)));
1235 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1236 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1240 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1241 /// function, lowering any calls to unknown intrinsic functions into the
1242 /// equivalent LLVM code.
1244 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1245 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1246 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1247 if (CallInst *CI = dyn_cast<CallInst>(I++))
1248 if (Function *F = CI->getCalledFunction())
1249 switch (F->getIntrinsicID()) {
1250 case Intrinsic::not_intrinsic:
1251 case Intrinsic::vastart:
1252 case Intrinsic::vacopy:
1253 case Intrinsic::vaend:
1254 case Intrinsic::returnaddress:
1255 case Intrinsic::frameaddress:
1256 case Intrinsic::memcpy:
1257 case Intrinsic::memset:
1258 // We directly implement these intrinsics
1261 // All other intrinsic calls we must lower.
1262 Instruction *Before = CI->getPrev();
1263 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1264 if (Before) { // Move iterator to instruction after call
1273 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1274 unsigned TmpReg1, TmpReg2;
1276 case Intrinsic::vastart:
1277 // Get the address of the first vararg value...
1278 TmpReg1 = getReg(CI);
1279 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1282 case Intrinsic::vacopy:
1283 TmpReg1 = getReg(CI);
1284 TmpReg2 = getReg(CI.getOperand(1));
1285 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1287 case Intrinsic::vaend: return; // Noop on X86
1289 case Intrinsic::returnaddress:
1290 case Intrinsic::frameaddress:
1291 TmpReg1 = getReg(CI);
1292 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1293 if (ID == Intrinsic::returnaddress) {
1294 // Just load the return address
1295 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1296 ReturnAddressIndex);
1298 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1299 ReturnAddressIndex, -4);
1302 // Values other than zero are not implemented yet.
1303 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1307 case Intrinsic::memcpy: {
1308 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1310 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1311 Align = AlignC->getRawValue();
1312 if (Align == 0) Align = 1;
1315 // Turn the byte code into # iterations
1318 switch (Align & 3) {
1319 case 2: // WORD aligned
1320 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1321 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1323 CountReg = makeAnotherReg(Type::IntTy);
1324 unsigned ByteReg = getReg(CI.getOperand(3));
1325 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1327 Opcode = X86::REP_MOVSW;
1329 case 0: // DWORD aligned
1330 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1331 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1333 CountReg = makeAnotherReg(Type::IntTy);
1334 unsigned ByteReg = getReg(CI.getOperand(3));
1335 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1337 Opcode = X86::REP_MOVSD;
1339 default: // BYTE aligned
1340 CountReg = getReg(CI.getOperand(3));
1341 Opcode = X86::REP_MOVSB;
1345 // No matter what the alignment is, we put the source in ESI, the
1346 // destination in EDI, and the count in ECX.
1347 TmpReg1 = getReg(CI.getOperand(1));
1348 TmpReg2 = getReg(CI.getOperand(2));
1349 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1350 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1351 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1352 BuildMI(BB, Opcode, 0);
1355 case Intrinsic::memset: {
1356 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1358 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1359 Align = AlignC->getRawValue();
1360 if (Align == 0) Align = 1;
1363 // Turn the byte code into # iterations
1366 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1367 unsigned Val = ValC->getRawValue() & 255;
1369 // If the value is a constant, then we can potentially use larger copies.
1370 switch (Align & 3) {
1371 case 2: // WORD aligned
1372 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1373 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1375 CountReg = makeAnotherReg(Type::IntTy);
1376 unsigned ByteReg = getReg(CI.getOperand(3));
1377 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1379 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1380 Opcode = X86::REP_STOSW;
1382 case 0: // DWORD aligned
1383 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1384 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1386 CountReg = makeAnotherReg(Type::IntTy);
1387 unsigned ByteReg = getReg(CI.getOperand(3));
1388 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1390 Val = (Val << 8) | Val;
1391 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1392 Opcode = X86::REP_STOSD;
1394 default: // BYTE aligned
1395 CountReg = getReg(CI.getOperand(3));
1396 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1397 Opcode = X86::REP_STOSB;
1401 // If it's not a constant value we are storing, just fall back. We could
1402 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1403 unsigned ValReg = getReg(CI.getOperand(2));
1404 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1405 CountReg = getReg(CI.getOperand(3));
1406 Opcode = X86::REP_STOSB;
1409 // No matter what the alignment is, we put the source in ESI, the
1410 // destination in EDI, and the count in ECX.
1411 TmpReg1 = getReg(CI.getOperand(1));
1412 //TmpReg2 = getReg(CI.getOperand(2));
1413 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1414 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1415 BuildMI(BB, Opcode, 0);
1419 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1423 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1424 if (LI.getParent() != User.getParent())
1426 BasicBlock::iterator It = &LI;
1427 // Check all of the instructions between the load and the user. We should
1428 // really use alias analysis here, but for now we just do something simple.
1429 for (++It; It != BasicBlock::iterator(&User); ++It) {
1430 switch (It->getOpcode()) {
1431 case Instruction::Store:
1432 case Instruction::Call:
1433 case Instruction::Invoke:
1441 /// visitSimpleBinary - Implement simple binary operators for integral types...
1442 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1445 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1446 unsigned DestReg = getReg(B);
1447 MachineBasicBlock::iterator MI = BB->end();
1448 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1450 // Special case: op Reg, load [mem]
1451 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1452 if (!B.swapOperands())
1453 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1455 unsigned Class = getClassB(B.getType());
1456 if (isa<LoadInst>(Op1) && Class < cFP &&
1457 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1459 static const unsigned OpcodeTab[][3] = {
1460 // Arithmetic operators
1461 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1462 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1464 // Bitwise operators
1465 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1466 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1467 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1470 assert(Class < cFP && "General code handles 64-bit integer types!");
1471 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1473 unsigned BaseReg, Scale, IndexReg, Disp;
1474 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1475 Scale, IndexReg, Disp);
1477 unsigned Op0r = getReg(Op0);
1478 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1479 BaseReg, Scale, IndexReg, Disp);
1483 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1486 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1487 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1490 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1491 /// and constant expression support.
1493 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1494 MachineBasicBlock::iterator IP,
1495 Value *Op0, Value *Op1,
1496 unsigned OperatorClass, unsigned DestReg) {
1497 unsigned Class = getClassB(Op0->getType());
1499 // sub 0, X -> neg X
1500 if (OperatorClass == 1 && Class != cLong)
1501 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1502 if (CI->isNullValue()) {
1503 unsigned op1Reg = getReg(Op1, MBB, IP);
1505 default: assert(0 && "Unknown class for this function!");
1507 BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
1510 BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
1513 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
1517 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1518 if (CFP->isExactlyValue(-0.0)) {
1520 unsigned op1Reg = getReg(Op1, MBB, IP);
1521 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1525 // Special case: op Reg, <const>
1526 if (Class != cLong && isa<ConstantInt>(Op1)) {
1527 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1528 unsigned Op0r = getReg(Op0, MBB, IP);
1530 // xor X, -1 -> not X
1531 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1532 static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1533 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1537 // add X, -1 -> dec X
1538 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1539 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1540 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1544 // add X, 1 -> inc X
1545 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1546 static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1547 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1551 static const unsigned OpcodeTab[][3] = {
1552 // Arithmetic operators
1553 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri }, // ADD
1554 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri }, // SUB
1556 // Bitwise operators
1557 { X86::AND8ri, X86::AND16ri, X86::AND32ri }, // AND
1558 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri }, // OR
1559 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri }, // XOR
1562 assert(Class < cFP && "General code handles 64-bit integer types!");
1563 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1566 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1567 BuildMI(*MBB, IP, Opcode, 5, DestReg).addReg(Op0r).addImm(Op1v);
1571 // Finally, handle the general case now.
1572 static const unsigned OpcodeTab[][4] = {
1573 // Arithmetic operators
1574 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD }, // ADD
1575 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB }, // SUB
1577 // Bitwise operators
1578 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 }, // AND
1579 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 }, // OR
1580 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 }, // XOR
1583 bool isLong = false;
1584 if (Class == cLong) {
1586 Class = cInt; // Bottom 32 bits are handled just like ints
1589 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1590 assert(Opcode && "Floating point arguments to logical inst?");
1591 unsigned Op0r = getReg(Op0, MBB, IP);
1592 unsigned Op1r = getReg(Op1, MBB, IP);
1593 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1595 if (isLong) { // Handle the upper 32 bits of long values...
1596 static const unsigned TopTab[] = {
1597 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1599 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1600 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1604 /// doMultiply - Emit appropriate instructions to multiply together the
1605 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1606 /// result should be given as DestTy.
1608 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1609 unsigned DestReg, const Type *DestTy,
1610 unsigned op0Reg, unsigned op1Reg) {
1611 unsigned Class = getClass(DestTy);
1613 case cFP: // Floating point multiply
1614 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1618 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
1619 .addReg(op0Reg).addReg(op1Reg);
1622 // Must use the MUL instruction, which forces use of AL...
1623 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1624 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1625 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1628 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1632 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1633 // returns zero when the input is not exactly a power of two.
1634 static unsigned ExactLog2(unsigned Val) {
1635 if (Val == 0) return 0;
1638 if (Val & 1) return 0;
1645 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1646 MachineBasicBlock::iterator IP,
1647 unsigned DestReg, const Type *DestTy,
1648 unsigned op0Reg, unsigned ConstRHS) {
1649 unsigned Class = getClass(DestTy);
1651 // If the element size is exactly a power of 2, use a shift to get it.
1652 if (unsigned Shift = ExactLog2(ConstRHS)) {
1654 default: assert(0 && "Unknown class for this function!");
1656 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1659 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1662 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1667 if (Class == cShort) {
1668 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1670 } else if (Class == cInt) {
1671 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1675 // Most general case, emit a normal multiply...
1676 static const unsigned MOVriTab[] = {
1677 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
1680 unsigned TmpReg = makeAnotherReg(DestTy);
1681 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1683 // Emit a MUL to multiply the register holding the index by
1684 // elementSize, putting the result in OffsetReg.
1685 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1688 /// visitMul - Multiplies are not simple binary operators because they must deal
1689 /// with the EAX register explicitly.
1691 void ISel::visitMul(BinaryOperator &I) {
1692 unsigned Op0Reg = getReg(I.getOperand(0));
1693 unsigned DestReg = getReg(I);
1695 // Simple scalar multiply?
1696 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1697 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1698 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1699 MachineBasicBlock::iterator MBBI = BB->end();
1700 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1702 unsigned Op1Reg = getReg(I.getOperand(1));
1703 MachineBasicBlock::iterator MBBI = BB->end();
1704 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1707 unsigned Op1Reg = getReg(I.getOperand(1));
1709 // Long value. We have to do things the hard way...
1710 // Multiply the two low parts... capturing carry into EDX
1711 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1712 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
1714 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1715 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
1716 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1718 MachineBasicBlock::iterator MBBI = BB->end();
1719 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1720 BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1722 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1723 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
1724 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1727 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1728 BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1730 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1731 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1736 /// visitDivRem - Handle division and remainder instructions... these
1737 /// instruction both require the same instructions to be generated, they just
1738 /// select the result from a different register. Note that both of these
1739 /// instructions work differently for signed and unsigned operands.
1741 void ISel::visitDivRem(BinaryOperator &I) {
1742 unsigned Op0Reg = getReg(I.getOperand(0));
1743 unsigned Op1Reg = getReg(I.getOperand(1));
1744 unsigned ResultReg = getReg(I);
1746 MachineBasicBlock::iterator IP = BB->end();
1747 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1748 I.getType(), ResultReg);
1751 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1752 MachineBasicBlock::iterator IP,
1753 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1754 const Type *Ty, unsigned ResultReg) {
1755 unsigned Class = getClass(Ty);
1757 case cFP: // Floating point divide
1759 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1760 } else { // Floating point remainder...
1761 MachineInstr *TheCall =
1762 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1763 std::vector<ValueRecord> Args;
1764 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1765 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1766 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1770 static const char *FnName[] =
1771 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1773 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1774 MachineInstr *TheCall =
1775 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1777 std::vector<ValueRecord> Args;
1778 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1779 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1780 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1783 case cByte: case cShort: case cInt:
1784 break; // Small integrals, handled below...
1785 default: assert(0 && "Unknown class!");
1788 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1789 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1790 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1791 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
1792 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1794 static const unsigned DivOpcode[][4] = {
1795 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
1796 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
1799 bool isSigned = Ty->isSigned();
1800 unsigned Reg = Regs[Class];
1801 unsigned ExtReg = ExtRegs[Class];
1803 // Put the first operand into one of the A registers...
1804 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1807 // Emit a sign extension instruction...
1808 unsigned ShiftResult = makeAnotherReg(Ty);
1809 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1810 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1812 // If unsigned, emit a zeroing instruction... (reg = 0)
1813 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
1816 // Emit the appropriate divide or remainder instruction...
1817 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1819 // Figure out which register we want to pick the result out of...
1820 unsigned DestReg = isDiv ? Reg : ExtReg;
1822 // Put the result into the destination register...
1823 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1827 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1828 /// for constant immediate shift values, and for constant immediate
1829 /// shift values equal to 1. Even the general case is sort of special,
1830 /// because the shift amount has to be in CL, not just any old register.
1832 void ISel::visitShiftInst(ShiftInst &I) {
1833 MachineBasicBlock::iterator IP = BB->end ();
1834 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1835 I.getOpcode () == Instruction::Shl, I.getType (),
1839 /// emitShiftOperation - Common code shared between visitShiftInst and
1840 /// constant expression support.
1841 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1842 MachineBasicBlock::iterator IP,
1843 Value *Op, Value *ShiftAmount, bool isLeftShift,
1844 const Type *ResultTy, unsigned DestReg) {
1845 unsigned SrcReg = getReg (Op, MBB, IP);
1846 bool isSigned = ResultTy->isSigned ();
1847 unsigned Class = getClass (ResultTy);
1849 static const unsigned ConstantOperand[][4] = {
1850 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
1851 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
1852 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
1853 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
1856 static const unsigned NonConstantOperand[][4] = {
1857 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
1858 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
1859 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
1860 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
1863 // Longs, as usual, are handled specially...
1864 if (Class == cLong) {
1865 // If we have a constant shift, we can generate much more efficient code
1866 // than otherwise...
1868 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1869 unsigned Amount = CUI->getValue();
1871 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1873 BuildMI(*MBB, IP, Opc[3], 3,
1874 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1875 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
1877 BuildMI(*MBB, IP, Opc[3], 3,
1878 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
1879 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
1881 } else { // Shifting more than 32 bits
1884 BuildMI(*MBB, IP, X86::SHL32ri, 2,
1885 DestReg + 1).addReg(SrcReg).addImm(Amount);
1886 BuildMI(*MBB, IP, X86::MOV32ri, 1,
1889 unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
1890 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
1891 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1895 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1897 if (!isLeftShift && isSigned) {
1898 // If this is a SHR of a Long, then we need to do funny sign extension
1899 // stuff. TmpReg gets the value to use as the high-part if we are
1900 // shifting more than 32 bits.
1901 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
1903 // Other shifts use a fixed zero value if the shift is more than 32
1905 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
1908 // Initialize CL with the shift amount...
1909 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
1910 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
1912 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1913 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1915 // TmpReg2 = shld inHi, inLo
1916 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
1918 // TmpReg3 = shl inLo, CL
1919 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
1921 // Set the flags to indicate whether the shift was by more than 32 bits.
1922 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1924 // DestHi = (>32) ? TmpReg3 : TmpReg2;
1925 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1926 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1927 // DestLo = (>32) ? TmpReg : TmpReg3;
1928 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1929 DestReg).addReg(TmpReg3).addReg(TmpReg);
1931 // TmpReg2 = shrd inLo, inHi
1932 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
1934 // TmpReg3 = s[ah]r inHi, CL
1935 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
1938 // Set the flags to indicate whether the shift was by more than 32 bits.
1939 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1941 // DestLo = (>32) ? TmpReg3 : TmpReg2;
1942 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1943 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1945 // DestHi = (>32) ? TmpReg : TmpReg3;
1946 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1947 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1953 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1954 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1955 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1957 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1958 BuildMI(*MBB, IP, Opc[Class], 2,
1959 DestReg).addReg(SrcReg).addImm(CUI->getValue());
1960 } else { // The shift amount is non-constant.
1961 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
1962 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
1964 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1965 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
1970 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
1971 unsigned &IndexReg, unsigned &Disp) {
1972 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
1973 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1974 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1975 BaseReg, Scale, IndexReg, Disp))
1977 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1978 if (CE->getOpcode() == Instruction::GetElementPtr)
1979 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1980 BaseReg, Scale, IndexReg, Disp))
1984 // If it's not foldable, reset addr mode.
1985 BaseReg = getReg(Addr);
1986 Scale = 1; IndexReg = 0; Disp = 0;
1990 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1991 /// instruction. The load and store instructions are the only place where we
1992 /// need to worry about the memory layout of the target machine.
1994 void ISel::visitLoadInst(LoadInst &I) {
1995 // Check to see if this load instruction is going to be folded into a binary
1996 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
1997 // pattern matching instruction selector be nice?
1998 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
1999 Instruction *User = cast<Instruction>(I.use_back());
2000 switch (User->getOpcode()) {
2001 default: User = 0; break;
2002 case Instruction::Add:
2003 case Instruction::Sub:
2004 case Instruction::And:
2005 case Instruction::Or:
2006 case Instruction::Xor:
2011 // Okay, we found a user. If the load is the first operand and there is
2012 // no second operand load, reverse the operand ordering. Note that this
2013 // can fail for a subtract (ie, no change will be made).
2014 if (!isa<LoadInst>(User->getOperand(1)))
2015 cast<BinaryOperator>(User)->swapOperands();
2017 // Okay, now that everything is set up, if this load is used by the second
2018 // operand, and if there are no instructions that invalidate the load
2019 // before the binary operator, eliminate the load.
2020 if (User->getOperand(1) == &I &&
2021 isSafeToFoldLoadIntoInstruction(I, *User))
2022 return; // Eliminate the load!
2026 unsigned DestReg = getReg(I);
2027 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2028 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2030 unsigned Class = getClassB(I.getType());
2031 if (Class == cLong) {
2032 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2033 BaseReg, Scale, IndexReg, Disp);
2034 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2035 BaseReg, Scale, IndexReg, Disp+4);
2039 static const unsigned Opcodes[] = {
2040 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2042 unsigned Opcode = Opcodes[Class];
2043 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2044 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2045 BaseReg, Scale, IndexReg, Disp);
2048 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2051 void ISel::visitStoreInst(StoreInst &I) {
2052 unsigned BaseReg, Scale, IndexReg, Disp;
2053 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2055 const Type *ValTy = I.getOperand(0)->getType();
2056 unsigned Class = getClassB(ValTy);
2058 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2059 uint64_t Val = CI->getRawValue();
2060 if (Class == cLong) {
2061 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2062 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2063 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2064 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2066 static const unsigned Opcodes[] = {
2067 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2069 unsigned Opcode = Opcodes[Class];
2070 addFullAddress(BuildMI(BB, Opcode, 5),
2071 BaseReg, Scale, IndexReg, Disp).addImm(Val);
2073 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2074 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2075 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2077 if (Class == cLong) {
2078 unsigned ValReg = getReg(I.getOperand(0));
2079 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2080 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2081 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2082 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2084 unsigned ValReg = getReg(I.getOperand(0));
2085 static const unsigned Opcodes[] = {
2086 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2088 unsigned Opcode = Opcodes[Class];
2089 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2090 addFullAddress(BuildMI(BB, Opcode, 1+4),
2091 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2097 /// visitCastInst - Here we have various kinds of copying with or without sign
2098 /// extension going on.
2100 void ISel::visitCastInst(CastInst &CI) {
2101 Value *Op = CI.getOperand(0);
2102 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2103 // of the case are GEP instructions, then the cast does not need to be
2104 // generated explicitly, it will be folded into the GEP.
2105 if (CI.getType() == Type::LongTy &&
2106 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2107 bool AllUsesAreGEPs = true;
2108 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2109 if (!isa<GetElementPtrInst>(*I)) {
2110 AllUsesAreGEPs = false;
2114 // No need to codegen this cast if all users are getelementptr instrs...
2115 if (AllUsesAreGEPs) return;
2118 unsigned DestReg = getReg(CI);
2119 MachineBasicBlock::iterator MI = BB->end();
2120 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2123 /// emitCastOperation - Common code shared between visitCastInst and constant
2124 /// expression cast support.
2126 void ISel::emitCastOperation(MachineBasicBlock *BB,
2127 MachineBasicBlock::iterator IP,
2128 Value *Src, const Type *DestTy,
2130 unsigned SrcReg = getReg(Src, BB, IP);
2131 const Type *SrcTy = Src->getType();
2132 unsigned SrcClass = getClassB(SrcTy);
2133 unsigned DestClass = getClassB(DestTy);
2135 // Implement casts to bool by using compare on the operand followed by set if
2136 // not zero on the result.
2137 if (DestTy == Type::BoolTy) {
2140 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2143 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2146 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2149 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2150 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2154 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2155 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2156 BuildMI(*BB, IP, X86::SAHF, 1);
2160 // If the zero flag is not set, then the value is true, set the byte to
2162 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2166 static const unsigned RegRegMove[] = {
2167 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2170 // Implement casts between values of the same type class (as determined by
2171 // getClass) by using a register-to-register move.
2172 if (SrcClass == DestClass) {
2173 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2174 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2175 } else if (SrcClass == cFP) {
2176 if (SrcTy == Type::FloatTy) { // double -> float
2177 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2178 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2179 } else { // float -> double
2180 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2181 "Unknown cFP member!");
2182 // Truncate from double to float by storing to memory as short, then
2184 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2185 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2186 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2187 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2189 } else if (SrcClass == cLong) {
2190 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2191 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2193 assert(0 && "Cannot handle this type of cast instruction!");
2199 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2200 // or zero extension, depending on whether the source type was signed.
2201 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2202 SrcClass < DestClass) {
2203 bool isLong = DestClass == cLong;
2204 if (isLong) DestClass = cInt;
2206 static const unsigned Opc[][4] = {
2207 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2208 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
2211 bool isUnsigned = SrcTy->isUnsigned();
2212 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2213 DestReg).addReg(SrcReg);
2215 if (isLong) { // Handle upper 32 bits as appropriate...
2216 if (isUnsigned) // Zero out top bits...
2217 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2218 else // Sign extend bottom half...
2219 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2224 // Special case long -> int ...
2225 if (SrcClass == cLong && DestClass == cInt) {
2226 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2230 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2231 // move out of AX or AL.
2232 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2233 && SrcClass > DestClass) {
2234 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2235 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2236 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2240 // Handle casts from integer to floating point now...
2241 if (DestClass == cFP) {
2242 // Promote the integer to a type supported by FLD. We do this because there
2243 // are no unsigned FLD instructions, so we must promote an unsigned value to
2244 // a larger signed value, then use FLD on the larger value.
2246 const Type *PromoteType = 0;
2247 unsigned PromoteOpcode;
2248 unsigned RealDestReg = DestReg;
2249 switch (SrcTy->getTypeID()) {
2250 case Type::BoolTyID:
2251 case Type::SByteTyID:
2252 // We don't have the facilities for directly loading byte sized data from
2253 // memory (even signed). Promote it to 16 bits.
2254 PromoteType = Type::ShortTy;
2255 PromoteOpcode = X86::MOVSX16rr8;
2257 case Type::UByteTyID:
2258 PromoteType = Type::ShortTy;
2259 PromoteOpcode = X86::MOVZX16rr8;
2261 case Type::UShortTyID:
2262 PromoteType = Type::IntTy;
2263 PromoteOpcode = X86::MOVZX32rr16;
2265 case Type::UIntTyID: {
2266 // Make a 64 bit temporary... and zero out the top of it...
2267 unsigned TmpReg = makeAnotherReg(Type::LongTy);
2268 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2269 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2270 SrcTy = Type::LongTy;
2275 case Type::ULongTyID:
2276 // Don't fild into the read destination.
2277 DestReg = makeAnotherReg(Type::DoubleTy);
2279 default: // No promotion needed...
2284 unsigned TmpReg = makeAnotherReg(PromoteType);
2285 unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
2286 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2287 SrcTy = PromoteType;
2288 SrcClass = getClass(PromoteType);
2292 // Spill the integer to memory and reload it from there...
2294 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2296 if (SrcClass == cLong) {
2297 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2298 FrameIdx).addReg(SrcReg);
2299 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2300 FrameIdx, 4).addReg(SrcReg+1);
2302 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2303 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2304 FrameIdx).addReg(SrcReg);
2307 static const unsigned Op2[] =
2308 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2309 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2311 // We need special handling for unsigned 64-bit integer sources. If the
2312 // input number has the "sign bit" set, then we loaded it incorrectly as a
2313 // negative 64-bit number. In this case, add an offset value.
2314 if (SrcTy == Type::ULongTy) {
2315 // Emit a test instruction to see if the dynamic input value was signed.
2316 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2318 // If the sign bit is set, get a pointer to an offset, otherwise get a
2319 // pointer to a zero.
2320 MachineConstantPool *CP = F->getConstantPool();
2321 unsigned Zero = makeAnotherReg(Type::IntTy);
2322 Constant *Null = Constant::getNullValue(Type::UIntTy);
2323 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
2324 CP->getConstantPoolIndex(Null));
2325 unsigned Offset = makeAnotherReg(Type::IntTy);
2326 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2328 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2329 CP->getConstantPoolIndex(OffsetCst));
2330 unsigned Addr = makeAnotherReg(Type::IntTy);
2331 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2333 // Load the constant for an add. FIXME: this could make an 'fadd' that
2334 // reads directly from memory, but we don't support these yet.
2335 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2336 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2338 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2339 .addReg(ConstReg).addReg(DestReg);
2345 // Handle casts from floating point to integer now...
2346 if (SrcClass == cFP) {
2347 // Change the floating point control register to use "round towards zero"
2348 // mode when truncating to an integer value.
2350 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2351 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2353 // Load the old value of the high byte of the control word...
2354 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2355 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2358 // Set the high part to be round to zero...
2359 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2360 CWFrameIdx, 1).addImm(12);
2362 // Reload the modified control word now...
2363 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2365 // Restore the memory image of control word to original value
2366 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2367 CWFrameIdx, 1).addReg(HighPartOfCW);
2369 // We don't have the facilities for directly storing byte sized data to
2370 // memory. Promote it to 16 bits. We also must promote unsigned values to
2371 // larger classes because we only have signed FP stores.
2372 unsigned StoreClass = DestClass;
2373 const Type *StoreTy = DestTy;
2374 if (StoreClass == cByte || DestTy->isUnsigned())
2375 switch (StoreClass) {
2376 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2377 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2378 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
2379 // The following treatment of cLong may not be perfectly right,
2380 // but it survives chains of casts of the form
2381 // double->ulong->double.
2382 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
2383 default: assert(0 && "Unknown store class!");
2386 // Spill the integer to memory and reload it from there...
2388 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2390 static const unsigned Op1[] =
2391 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2392 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2393 FrameIdx).addReg(SrcReg);
2395 if (DestClass == cLong) {
2396 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2397 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2400 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2401 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2404 // Reload the original control word now...
2405 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2409 // Anything we haven't handled already, we can't (yet) handle at all.
2410 assert(0 && "Unhandled cast instruction!");
2414 /// visitVANextInst - Implement the va_next instruction...
2416 void ISel::visitVANextInst(VANextInst &I) {
2417 unsigned VAList = getReg(I.getOperand(0));
2418 unsigned DestReg = getReg(I);
2421 switch (I.getArgType()->getTypeID()) {
2424 assert(0 && "Error: bad type for va_next instruction!");
2426 case Type::PointerTyID:
2427 case Type::UIntTyID:
2431 case Type::ULongTyID:
2432 case Type::LongTyID:
2433 case Type::DoubleTyID:
2438 // Increment the VAList pointer...
2439 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2442 void ISel::visitVAArgInst(VAArgInst &I) {
2443 unsigned VAList = getReg(I.getOperand(0));
2444 unsigned DestReg = getReg(I);
2446 switch (I.getType()->getTypeID()) {
2449 assert(0 && "Error: bad type for va_next instruction!");
2451 case Type::PointerTyID:
2452 case Type::UIntTyID:
2454 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2456 case Type::ULongTyID:
2457 case Type::LongTyID:
2458 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2459 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2461 case Type::DoubleTyID:
2462 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2467 /// visitGetElementPtrInst - instruction-select GEP instructions
2469 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2470 // If this GEP instruction will be folded into all of its users, we don't need
2471 // to explicitly calculate it!
2472 unsigned A, B, C, D;
2473 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2474 // Check all of the users of the instruction to see if they are loads and
2476 bool AllWillFold = true;
2477 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2478 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2479 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2480 cast<Instruction>(*UI)->getOperand(0) == &I) {
2481 AllWillFold = false;
2485 // If the instruction is foldable, and will be folded into all users, don't
2487 if (AllWillFold) return;
2490 unsigned outputReg = getReg(I);
2491 emitGEPOperation(BB, BB->end(), I.getOperand(0),
2492 I.op_begin()+1, I.op_end(), outputReg);
2495 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2496 /// GEPTypes (the derived types being stepped through at each level). On return
2497 /// from this function, if some indexes of the instruction are representable as
2498 /// an X86 lea instruction, the machine operands are put into the Ops
2499 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2500 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2501 /// addressing mode that only partially consumes the input, the BaseReg input of
2502 /// the addressing mode must be left free.
2504 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2506 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2507 std::vector<Value*> &GEPOps,
2508 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2509 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2510 const TargetData &TD = TM.getTargetData();
2512 // Clear out the state we are working with...
2513 BaseReg = 0; // No base register
2514 Scale = 1; // Unit scale
2515 IndexReg = 0; // No index register
2516 Disp = 0; // No displacement
2518 // While there are GEP indexes that can be folded into the current address,
2519 // keep processing them.
2520 while (!GEPTypes.empty()) {
2521 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2522 // It's a struct access. CUI is the index into the structure,
2523 // which names the field. This index must have unsigned type.
2524 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2526 // Use the TargetData structure to pick out what the layout of the
2527 // structure is in memory. Since the structure index must be constant, we
2528 // can get its value and use it to find the right byte offset from the
2529 // StructLayout class's list of structure member offsets.
2530 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2531 GEPOps.pop_back(); // Consume a GEP operand
2532 GEPTypes.pop_back();
2534 // It's an array or pointer access: [ArraySize x ElementType].
2535 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2536 Value *idx = GEPOps.back();
2538 // idx is the index into the array. Unlike with structure
2539 // indices, we may not know its actual value at code-generation
2541 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2543 // If idx is a constant, fold it into the offset.
2544 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2545 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2546 Disp += TypeSize*CSI->getValue();
2548 // If the index reg is already taken, we can't handle this index.
2549 if (IndexReg) return;
2551 // If this is a size that we can handle, then add the index as
2553 case 1: case 2: case 4: case 8:
2554 // These are all acceptable scales on X86.
2558 // Otherwise, we can't handle this scale
2562 if (CastInst *CI = dyn_cast<CastInst>(idx))
2563 if (CI->getOperand(0)->getType() == Type::IntTy ||
2564 CI->getOperand(0)->getType() == Type::UIntTy)
2565 idx = CI->getOperand(0);
2567 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2570 GEPOps.pop_back(); // Consume a GEP operand
2571 GEPTypes.pop_back();
2575 // GEPTypes is empty, which means we have a single operand left. See if we
2576 // can set it as the base register.
2578 // FIXME: When addressing modes are more powerful/correct, we could load
2579 // global addresses directly as 32-bit immediates.
2580 assert(BaseReg == 0);
2581 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2582 GEPOps.pop_back(); // Consume the last GEP operand
2586 /// isGEPFoldable - Return true if the specified GEP can be completely
2587 /// folded into the addressing mode of a load/store or lea instruction.
2588 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2589 Value *Src, User::op_iterator IdxBegin,
2590 User::op_iterator IdxEnd, unsigned &BaseReg,
2591 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2592 std::vector<Value*> GEPOps;
2593 GEPOps.resize(IdxEnd-IdxBegin+1);
2595 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2597 std::vector<const Type*> GEPTypes;
2598 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2599 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2601 MachineBasicBlock::iterator IP;
2602 if (MBB) IP = MBB->end();
2603 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2605 // We can fold it away iff the getGEPIndex call eliminated all operands.
2606 return GEPOps.empty();
2609 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2610 MachineBasicBlock::iterator IP,
2611 Value *Src, User::op_iterator IdxBegin,
2612 User::op_iterator IdxEnd, unsigned TargetReg) {
2613 const TargetData &TD = TM.getTargetData();
2615 std::vector<Value*> GEPOps;
2616 GEPOps.resize(IdxEnd-IdxBegin+1);
2618 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2620 std::vector<const Type*> GEPTypes;
2621 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2622 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2624 // Keep emitting instructions until we consume the entire GEP instruction.
2625 while (!GEPOps.empty()) {
2626 unsigned OldSize = GEPOps.size();
2627 unsigned BaseReg, Scale, IndexReg, Disp;
2628 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2630 if (GEPOps.size() != OldSize) {
2631 // getGEPIndex consumed some of the input. Build an LEA instruction here.
2632 unsigned NextTarget = 0;
2633 if (!GEPOps.empty()) {
2634 assert(BaseReg == 0 &&
2635 "getGEPIndex should have left the base register open for chaining!");
2636 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2639 if (IndexReg == 0 && Disp == 0)
2640 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2642 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
2643 BaseReg, Scale, IndexReg, Disp);
2645 TargetReg = NextTarget;
2646 } else if (GEPTypes.empty()) {
2647 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2648 // all operands are consumed but the base pointer. If so, just load it
2649 // into the register.
2650 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2651 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
2653 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2654 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2656 break; // we are now done
2659 // It's an array or pointer access: [ArraySize x ElementType].
2660 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2661 Value *idx = GEPOps.back();
2662 GEPOps.pop_back(); // Consume a GEP operand
2663 GEPTypes.pop_back();
2665 // idx is the index into the array. Unlike with structure
2666 // indices, we may not know its actual value at code-generation
2668 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2670 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2671 // operand on X86. Handle this case directly now...
2672 if (CastInst *CI = dyn_cast<CastInst>(idx))
2673 if (CI->getOperand(0)->getType() == Type::IntTy ||
2674 CI->getOperand(0)->getType() == Type::UIntTy)
2675 idx = CI->getOperand(0);
2677 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2678 // must find the size of the pointed-to type (Not coincidentally, the next
2679 // type is the type of the elements in the array).
2680 const Type *ElTy = SqTy->getElementType();
2681 unsigned elementSize = TD.getTypeSize(ElTy);
2683 // If idxReg is a constant, we don't need to perform the multiply!
2684 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2685 if (!CSI->isNullValue()) {
2686 unsigned Offset = elementSize*CSI->getValue();
2687 unsigned Reg = makeAnotherReg(Type::UIntTy);
2688 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
2689 .addReg(Reg).addImm(Offset);
2690 --IP; // Insert the next instruction before this one.
2691 TargetReg = Reg; // Codegen the rest of the GEP into this
2693 } else if (elementSize == 1) {
2694 // If the element size is 1, we don't have to multiply, just add
2695 unsigned idxReg = getReg(idx, MBB, IP);
2696 unsigned Reg = makeAnotherReg(Type::UIntTy);
2697 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
2698 --IP; // Insert the next instruction before this one.
2699 TargetReg = Reg; // Codegen the rest of the GEP into this
2701 unsigned idxReg = getReg(idx, MBB, IP);
2702 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2704 // Make sure we can back the iterator up to point to the first
2705 // instruction emitted.
2706 MachineBasicBlock::iterator BeforeIt = IP;
2707 if (IP == MBB->begin())
2708 BeforeIt = MBB->end();
2711 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2713 // Emit an ADD to add OffsetReg to the basePtr.
2714 unsigned Reg = makeAnotherReg(Type::UIntTy);
2715 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
2716 .addReg(Reg).addReg(OffsetReg);
2718 // Step to the first instruction of the multiply.
2719 if (BeforeIt == MBB->end())
2724 TargetReg = Reg; // Codegen the rest of the GEP into this
2731 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2732 /// frame manager, otherwise do it the hard way.
2734 void ISel::visitAllocaInst(AllocaInst &I) {
2735 // Find the data size of the alloca inst's getAllocatedType.
2736 const Type *Ty = I.getAllocatedType();
2737 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2739 // If this is a fixed size alloca in the entry block for the function,
2740 // statically stack allocate the space.
2742 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2743 if (I.getParent() == I.getParent()->getParent()->begin()) {
2744 TySize *= CUI->getValue(); // Get total allocated size...
2745 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2747 // Create a new stack object using the frame manager...
2748 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2749 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
2754 // Create a register to hold the temporary result of multiplying the type size
2755 // constant by the variable amount.
2756 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2757 unsigned SrcReg1 = getReg(I.getArraySize());
2759 // TotalSizeReg = mul <numelements>, <TypeSize>
2760 MachineBasicBlock::iterator MBBI = BB->end();
2761 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2763 // AddedSize = add <TotalSizeReg>, 15
2764 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2765 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2767 // AlignedSize = and <AddedSize>, ~15
2768 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2769 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2771 // Subtract size from stack pointer, thereby allocating some space.
2772 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2774 // Put a pointer to the space into the result register, by copying
2775 // the stack pointer.
2776 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
2778 // Inform the Frame Information that we have just allocated a variable-sized
2780 F->getFrameInfo()->CreateVariableSizedObject();
2783 /// visitMallocInst - Malloc instructions are code generated into direct calls
2784 /// to the library malloc.
2786 void ISel::visitMallocInst(MallocInst &I) {
2787 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2790 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2791 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2793 Arg = makeAnotherReg(Type::UIntTy);
2794 unsigned Op0Reg = getReg(I.getOperand(0));
2795 MachineBasicBlock::iterator MBBI = BB->end();
2796 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2799 std::vector<ValueRecord> Args;
2800 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2801 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2802 1).addExternalSymbol("malloc", true);
2803 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2807 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2810 void ISel::visitFreeInst(FreeInst &I) {
2811 std::vector<ValueRecord> Args;
2812 Args.push_back(ValueRecord(I.getOperand(0)));
2813 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2814 1).addExternalSymbol("free", true);
2815 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2818 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2819 /// into a machine code representation is a very simple peep-hole fashion. The
2820 /// generated code sucks but the implementation is nice and simple.
2822 FunctionPass *llvm::createX86ReallySimpleInstructionSelector(TargetMachine &TM) {
2823 return new ISel(TM);
2826 #include "X86GenSimpInstrSelector.inc"