1 //===-- X86ISelSimple.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/ADT/Statistic.h"
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
42 cByte, cShort, cInt, cFP, cLong
46 /// getClass - Turn a primitive type into a "class" number which is based on the
47 /// size of the type, and whether or not it is floating point.
49 static inline TypeClass getClass(const Type *Ty) {
50 switch (Ty->getTypeID()) {
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
54 case Type::UShortTyID: return cShort; // Short operands are class #1
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
63 case Type::ULongTyID: return cLong; // Longs are class #4
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
70 // getClassB - Just like getClass, but treat boolean values as bytes.
71 static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
77 struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
79 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
82 int ReturnAddressIndex; // FrameIndex for the return address
84 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
86 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
89 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
93 X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
98 bool runOnFunction(Function &Fn) {
99 // First pass over the function, lower any unknown intrinsic functions
100 // with the IntrinsicLowering class.
101 LowerUnknownIntrinsicFunctionCalls(Fn);
103 F = &MachineFunction::construct(&Fn, TM);
105 // Create all of the machine basic blocks for the function...
106 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
107 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
111 // Set up a frame object for the return address. This is used by the
112 // llvm.returnaddress & llvm.frameaddress intrinisics.
113 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
115 // Copy incoming arguments off of the stack...
116 LoadArgumentsToVirtualRegs(Fn);
118 // Instruction select everything except PHI nodes
121 // Select the PHI nodes
124 // Insert the FP_REG_KILL instructions into blocks that need them.
131 // We always build a machine code representation for the function
135 virtual const char *getPassName() const {
136 return "X86 Simple Instruction Selection";
139 /// visitBasicBlock - This method is called when we are visiting a new basic
140 /// block. This simply creates a new MachineBasicBlock to emit code into
141 /// and adds it to the current MachineFunction. Subsequent visit* for
142 /// instructions will be invoked for all instructions in the basic block.
144 void visitBasicBlock(BasicBlock &LLVM_BB) {
145 BB = MBBMap[&LLVM_BB];
148 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
149 /// function, lowering any calls to unknown intrinsic functions into the
150 /// equivalent LLVM code.
152 void LowerUnknownIntrinsicFunctionCalls(Function &F);
154 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
155 /// from the stack into virtual registers.
157 void LoadArgumentsToVirtualRegs(Function &F);
159 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
160 /// because we have to generate our sources into the source basic blocks,
161 /// not the current one.
163 void SelectPHINodes();
165 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
166 /// that need them. This only occurs due to the floating point stackifier
167 /// not being aggressive enough to handle arbitrary global stackification.
169 void InsertFPRegKills();
171 // Visitation methods for various instructions. These methods simply emit
172 // fixed X86 code for each instruction.
175 // Control flow operators
176 void visitReturnInst(ReturnInst &RI);
177 void visitBranchInst(BranchInst &BI);
183 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
184 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
186 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
187 const std::vector<ValueRecord> &Args);
188 void visitCallInst(CallInst &I);
189 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
191 // Arithmetic operators
192 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
193 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
194 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
195 void visitMul(BinaryOperator &B);
197 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
198 void visitRem(BinaryOperator &B) { visitDivRem(B); }
199 void visitDivRem(BinaryOperator &B);
202 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
203 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
204 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
206 // Comparison operators...
207 void visitSetCondInst(SetCondInst &I);
208 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
209 MachineBasicBlock *MBB,
210 MachineBasicBlock::iterator MBBI);
211 void visitSelectInst(SelectInst &SI);
214 // Memory Instructions
215 void visitLoadInst(LoadInst &I);
216 void visitStoreInst(StoreInst &I);
217 void visitGetElementPtrInst(GetElementPtrInst &I);
218 void visitAllocaInst(AllocaInst &I);
219 void visitMallocInst(MallocInst &I);
220 void visitFreeInst(FreeInst &I);
223 void visitShiftInst(ShiftInst &I);
224 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
225 void visitCastInst(CastInst &I);
226 void visitVANextInst(VANextInst &I);
227 void visitVAArgInst(VAArgInst &I);
229 void visitInstruction(Instruction &I) {
230 std::cerr << "Cannot instruction select: " << I;
234 /// promote32 - Make a value 32-bits wide, and put it somewhere.
236 void promote32(unsigned targetReg, const ValueRecord &VR);
238 /// getAddressingMode - Get the addressing mode to use to address the
239 /// specified value. The returned value should be used with addFullAddress.
240 void getAddressingMode(Value *Addr, X86AddressMode &AM);
243 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
245 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
246 std::vector<Value*> &GEPOps,
247 std::vector<const Type*> &GEPTypes,
250 /// isGEPFoldable - Return true if the specified GEP can be completely
251 /// folded into the addressing mode of a load/store or lea instruction.
252 bool isGEPFoldable(MachineBasicBlock *MBB,
253 Value *Src, User::op_iterator IdxBegin,
254 User::op_iterator IdxEnd, X86AddressMode &AM);
256 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
257 /// constant expression GEP support.
259 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
260 Value *Src, User::op_iterator IdxBegin,
261 User::op_iterator IdxEnd, unsigned TargetReg);
263 /// emitCastOperation - Common code shared between visitCastInst and
264 /// constant expression cast support.
266 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
267 Value *Src, const Type *DestTy, unsigned TargetReg);
269 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
270 /// and constant expression support.
272 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
273 MachineBasicBlock::iterator IP,
274 Value *Op0, Value *Op1,
275 unsigned OperatorClass, unsigned TargetReg);
277 /// emitBinaryFPOperation - This method handles emission of floating point
278 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
279 void emitBinaryFPOperation(MachineBasicBlock *BB,
280 MachineBasicBlock::iterator IP,
281 Value *Op0, Value *Op1,
282 unsigned OperatorClass, unsigned TargetReg);
284 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
285 Value *Op0, Value *Op1, unsigned TargetReg);
287 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
288 unsigned DestReg, const Type *DestTy,
289 unsigned Op0Reg, unsigned Op1Reg);
290 void doMultiplyConst(MachineBasicBlock *MBB,
291 MachineBasicBlock::iterator MBBI,
292 unsigned DestReg, const Type *DestTy,
293 unsigned Op0Reg, unsigned Op1Val);
295 void emitDivRemOperation(MachineBasicBlock *BB,
296 MachineBasicBlock::iterator IP,
297 Value *Op0, Value *Op1, bool isDiv,
300 /// emitSetCCOperation - Common code shared between visitSetCondInst and
301 /// constant expression support.
303 void emitSetCCOperation(MachineBasicBlock *BB,
304 MachineBasicBlock::iterator IP,
305 Value *Op0, Value *Op1, unsigned Opcode,
308 /// emitShiftOperation - Common code shared between visitShiftInst and
309 /// constant expression support.
311 void emitShiftOperation(MachineBasicBlock *MBB,
312 MachineBasicBlock::iterator IP,
313 Value *Op, Value *ShiftAmount, bool isLeftShift,
314 const Type *ResultTy, unsigned DestReg);
316 /// emitSelectOperation - Common code shared between visitSelectInst and the
317 /// constant expression support.
318 void emitSelectOperation(MachineBasicBlock *MBB,
319 MachineBasicBlock::iterator IP,
320 Value *Cond, Value *TrueVal, Value *FalseVal,
323 /// copyConstantToRegister - Output the instructions required to put the
324 /// specified constant into the specified register.
326 void copyConstantToRegister(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator MBBI,
328 Constant *C, unsigned Reg);
330 void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
331 unsigned LHS, unsigned RHS);
333 /// makeAnotherReg - This method returns the next register number we haven't
336 /// Long values are handled somewhat specially. They are always allocated
337 /// as pairs of 32 bit integer values. The register number returned is the
338 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
339 /// of the long value.
341 unsigned makeAnotherReg(const Type *Ty) {
342 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
343 "Current target doesn't have X86 reg info??");
344 const X86RegisterInfo *MRI =
345 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
346 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
347 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
348 // Create the lower part
349 F->getSSARegMap()->createVirtualRegister(RC);
350 // Create the upper part.
351 return F->getSSARegMap()->createVirtualRegister(RC)-1;
354 // Add the mapping of regnumber => reg class to MachineFunction
355 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
356 return F->getSSARegMap()->createVirtualRegister(RC);
359 /// getReg - This method turns an LLVM value into a register number.
361 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
362 unsigned getReg(Value *V) {
363 // Just append to the end of the current bb.
364 MachineBasicBlock::iterator It = BB->end();
365 return getReg(V, BB, It);
367 unsigned getReg(Value *V, MachineBasicBlock *MBB,
368 MachineBasicBlock::iterator IPt);
370 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
371 /// that is to be statically allocated with the initial stack frame
373 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
377 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
378 /// instruction in the entry block, return it. Otherwise, return a null
380 static AllocaInst *dyn_castFixedAlloca(Value *V) {
381 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
382 BasicBlock *BB = AI->getParent();
383 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
389 /// getReg - This method turns an LLVM value into a register number.
391 unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
392 MachineBasicBlock::iterator IPt) {
393 // If this operand is a constant, emit the code to copy the constant into
394 // the register here...
395 if (Constant *C = dyn_cast<Constant>(V)) {
396 unsigned Reg = makeAnotherReg(V->getType());
397 copyConstantToRegister(MBB, IPt, C, Reg);
399 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
400 // Do not emit noop casts at all, unless it's a double -> float cast.
401 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
402 (CI->getType() != Type::FloatTy ||
403 CI->getOperand(0)->getType() != Type::DoubleTy))
404 return getReg(CI->getOperand(0), MBB, IPt);
405 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
406 // If the alloca address couldn't be folded into the instruction addressing,
407 // emit an explicit LEA as appropriate.
408 unsigned Reg = makeAnotherReg(V->getType());
409 unsigned FI = getFixedSizedAllocaFI(AI);
410 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
414 unsigned &Reg = RegMap[V];
416 Reg = makeAnotherReg(V->getType());
423 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
424 /// that is to be statically allocated with the initial stack frame
426 unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
427 // Already computed this?
428 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
429 if (I != AllocaMap.end() && I->first == AI) return I->second;
431 const Type *Ty = AI->getAllocatedType();
432 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
433 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
434 TySize *= CUI->getValue(); // Get total allocated size...
435 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
437 // Create a new stack object using the frame manager...
438 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
439 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
444 /// copyConstantToRegister - Output the instructions required to put the
445 /// specified constant into the specified register.
447 void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
448 MachineBasicBlock::iterator IP,
449 Constant *C, unsigned R) {
450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
452 switch (CE->getOpcode()) {
453 case Instruction::GetElementPtr:
454 emitGEPOperation(MBB, IP, CE->getOperand(0),
455 CE->op_begin()+1, CE->op_end(), R);
457 case Instruction::Cast:
458 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
461 case Instruction::Xor: ++Class; // FALL THROUGH
462 case Instruction::Or: ++Class; // FALL THROUGH
463 case Instruction::And: ++Class; // FALL THROUGH
464 case Instruction::Sub: ++Class; // FALL THROUGH
465 case Instruction::Add:
466 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
470 case Instruction::Mul:
471 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
474 case Instruction::Div:
475 case Instruction::Rem:
476 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
477 CE->getOpcode() == Instruction::Div, R);
480 case Instruction::SetNE:
481 case Instruction::SetEQ:
482 case Instruction::SetLT:
483 case Instruction::SetGT:
484 case Instruction::SetLE:
485 case Instruction::SetGE:
486 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
490 case Instruction::Shl:
491 case Instruction::Shr:
492 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
493 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
496 case Instruction::Select:
497 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
498 CE->getOperand(2), R);
502 std::cerr << "Offending expr: " << *C << "\n";
503 assert(0 && "Constant expression not yet handled!\n");
507 if (C->getType()->isIntegral()) {
508 unsigned Class = getClassB(C->getType());
510 if (Class == cLong) {
511 // Copy the value into the register pair.
512 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
513 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
514 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
518 assert(Class <= cInt && "Type not handled yet!");
520 static const unsigned IntegralOpcodeTab[] = {
521 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
524 if (C->getType() == Type::BoolTy) {
525 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
527 ConstantInt *CI = cast<ConstantInt>(C);
528 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
530 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
531 if (CFP->isExactlyValue(+0.0))
532 BuildMI(*MBB, IP, X86::FLD0, 0, R);
533 else if (CFP->isExactlyValue(+1.0))
534 BuildMI(*MBB, IP, X86::FLD1, 0, R);
536 // Otherwise we need to spill the constant to memory...
537 MachineConstantPool *CP = F->getConstantPool();
538 unsigned CPI = CP->getConstantPoolIndex(CFP);
539 const Type *Ty = CFP->getType();
541 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
542 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
543 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
546 } else if (isa<ConstantPointerNull>(C)) {
547 // Copy zero (null pointer) to the register.
548 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
549 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
550 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
552 std::cerr << "Offending constant: " << *C << "\n";
553 assert(0 && "Type not handled yet!");
557 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
558 /// the stack into virtual registers.
560 void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
561 // Emit instructions to load the arguments... On entry to a function on the
562 // X86, the stack frame looks like this:
564 // [ESP] -- return address
565 // [ESP + 4] -- first argument (leftmost lexically)
566 // [ESP + 8] -- second argument, if first argument is four bytes in size
569 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
570 MachineFrameInfo *MFI = F->getFrameInfo();
572 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
573 bool ArgLive = !I->use_empty();
574 unsigned Reg = ArgLive ? getReg(*I) : 0;
575 int FI; // Frame object index
577 switch (getClassB(I->getType())) {
580 FI = MFI->CreateFixedObject(1, ArgOffset);
581 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
586 FI = MFI->CreateFixedObject(2, ArgOffset);
587 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
592 FI = MFI->CreateFixedObject(4, ArgOffset);
593 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
598 FI = MFI->CreateFixedObject(8, ArgOffset);
599 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
600 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
602 ArgOffset += 4; // longs require 4 additional bytes
607 if (I->getType() == Type::FloatTy) {
608 Opcode = X86::FLD32m;
609 FI = MFI->CreateFixedObject(4, ArgOffset);
611 Opcode = X86::FLD64m;
612 FI = MFI->CreateFixedObject(8, ArgOffset);
614 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
616 if (I->getType() == Type::DoubleTy)
617 ArgOffset += 4; // doubles require 4 additional bytes
620 assert(0 && "Unhandled argument type!");
622 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
625 // If the function takes variable number of arguments, add a frame offset for
626 // the start of the first vararg value... this is used to expand
628 if (Fn.getFunctionType()->isVarArg())
629 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
633 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
634 /// because we have to generate our sources into the source basic blocks, not
637 void X86ISel::SelectPHINodes() {
638 const TargetInstrInfo &TII = *TM.getInstrInfo();
639 const Function &LF = *F->getFunction(); // The LLVM function...
640 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
641 const BasicBlock *BB = I;
642 MachineBasicBlock &MBB = *MBBMap[I];
644 // Loop over all of the PHI nodes in the LLVM basic block...
645 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
646 for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
647 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
649 // Create a new machine instr PHI node, and insert it.
650 unsigned PHIReg = getReg(*PN);
651 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
652 X86::PHI, PN->getNumOperands(), PHIReg);
654 MachineInstr *LongPhiMI = 0;
655 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
656 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
657 X86::PHI, PN->getNumOperands(), PHIReg+1);
659 // PHIValues - Map of blocks to incoming virtual registers. We use this
660 // so that we only initialize one incoming value for a particular block,
661 // even if the block has multiple entries in the PHI node.
663 std::map<MachineBasicBlock*, unsigned> PHIValues;
665 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
666 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
668 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
669 PHIValues.lower_bound(PredMBB);
671 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
672 // We already inserted an initialization of the register for this
673 // predecessor. Recycle it.
674 ValReg = EntryIt->second;
677 // Get the incoming value into a virtual register.
679 Value *Val = PN->getIncomingValue(i);
681 // If this is a constant or GlobalValue, we may have to insert code
682 // into the basic block to compute it into a virtual register.
683 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
684 // Simple constants get emitted at the end of the basic block,
685 // before any terminator instructions. We "know" that the code to
686 // move a constant into a register will never clobber any flags.
687 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
689 // Because we don't want to clobber any values which might be in
690 // physical registers with the computation of this constant (which
691 // might be arbitrarily complex if it is a constant expression),
692 // just insert the computation at the top of the basic block.
693 MachineBasicBlock::iterator PI = PredMBB->begin();
695 // Skip over any PHI nodes though!
696 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
699 ValReg = getReg(Val, PredMBB, PI);
702 // Remember that we inserted a value for this PHI for this predecessor
703 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
706 PhiMI->addRegOperand(ValReg);
707 PhiMI->addMachineBasicBlockOperand(PredMBB);
709 LongPhiMI->addRegOperand(ValReg+1);
710 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
714 // Now that we emitted all of the incoming values for the PHI node, make
715 // sure to reposition the InsertPoint after the PHI that we just added.
716 // This is needed because we might have inserted a constant into this
717 // block, right after the PHI's which is before the old insert point!
718 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
724 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
725 /// compensation code on critical edges. As such, it requires that we kill all
726 /// FP registers on the exit from any blocks that either ARE critical edges, or
727 /// branch to a block that has incoming critical edges.
729 /// Note that this kill instruction will eventually be eliminated when
730 /// restrictions in the stackifier are relaxed.
732 static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
734 const BasicBlock *BB = MBB->getBasicBlock ();
735 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
736 const BasicBlock *Succ = *SI;
737 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
738 ++PI; // Block have at least one predecessory
739 if (PI != PE) { // If it has exactly one, this isn't crit edge
740 // If this block has more than one predecessor, check all of the
741 // predecessors to see if they have multiple successors. If so, then the
742 // block we are analyzing needs an FPRegKill.
743 for (PI = pred_begin(Succ); PI != PE; ++PI) {
744 const BasicBlock *Pred = *PI;
745 succ_const_iterator SI2 = succ_begin(Pred);
746 ++SI2; // There must be at least one successor of this block.
747 if (SI2 != succ_end(Pred))
748 return true; // Yes, we must insert the kill on this edge.
752 // If we got this far, there is no need to insert the kill instruction.
759 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
760 // need them. This only occurs due to the floating point stackifier not being
761 // aggressive enough to handle arbitrary global stackification.
763 // Currently we insert an FP_REG_KILL instruction into each block that uses or
764 // defines a floating point virtual register.
766 // When the global register allocators (like linear scan) finally update live
767 // variable analysis, we can keep floating point values in registers across
768 // portions of the CFG that do not involve critical edges. This will be a big
769 // win, but we are waiting on the global allocators before we can do this.
771 // With a bit of work, the floating point stackifier pass can be enhanced to
772 // break critical edges as needed (to make a place to put compensation code),
773 // but this will require some infrastructure improvements as well.
775 void X86ISel::InsertFPRegKills() {
776 SSARegMap &RegMap = *F->getSSARegMap();
778 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
779 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
780 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
781 MachineOperand& MO = I->getOperand(i);
782 if (MO.isRegister() && MO.getReg()) {
783 unsigned Reg = MO.getReg();
784 if (MRegisterInfo::isVirtualRegister(Reg))
785 if (RegMap.getRegClass(Reg)->getSize() == 10)
789 // If we haven't found an FP register use or def in this basic block, check
790 // to see if any of our successors has an FP PHI node, which will cause a
791 // copy to be inserted into this block.
792 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
793 SE = BB->succ_end(); SI != SE; ++SI) {
794 MachineBasicBlock *SBB = *SI;
795 for (MachineBasicBlock::iterator I = SBB->begin();
796 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
797 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
803 // Okay, this block uses an FP register. If the block has successors (ie,
804 // it's not an unwind/return), insert the FP_REG_KILL instruction.
805 if (BB->succ_size () && RequiresFPRegKill(BB)) {
806 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
813 void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
814 AM.BaseType = X86AddressMode::RegBase;
815 AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
816 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
817 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
820 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
821 if (CE->getOpcode() == Instruction::GetElementPtr)
822 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
825 } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
826 AM.BaseType = X86AddressMode::FrameIndexBase;
827 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
831 // If it's not foldable, reset addr mode.
832 AM.BaseType = X86AddressMode::RegBase;
833 AM.Base.Reg = getReg(Addr);
834 AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
837 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
838 // it into the conditional branch or select instruction which is the only user
839 // of the cc instruction. This is the case if the conditional branch is the
840 // only user of the setcc. We also don't handle long arguments below, so we
841 // reject them here as well.
843 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
844 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
845 if (SCI->hasOneUse()) {
846 Instruction *User = cast<Instruction>(SCI->use_back());
847 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
848 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
849 SCI->getOpcode() == Instruction::SetEQ ||
850 SCI->getOpcode() == Instruction::SetNE))
856 // Return a fixed numbering for setcc instructions which does not depend on the
857 // order of the opcodes.
859 static unsigned getSetCCNumber(unsigned Opcode) {
861 default: assert(0 && "Unknown setcc instruction!");
862 case Instruction::SetEQ: return 0;
863 case Instruction::SetNE: return 1;
864 case Instruction::SetLT: return 2;
865 case Instruction::SetGE: return 3;
866 case Instruction::SetGT: return 4;
867 case Instruction::SetLE: return 5;
871 // LLVM -> X86 signed X86 unsigned
872 // ----- ---------- ------------
873 // seteq -> sete sete
874 // setne -> setne setne
875 // setlt -> setl setb
876 // setge -> setge setae
877 // setgt -> setg seta
878 // setle -> setle setbe
880 // sets // Used by comparison with 0 optimization
882 static const unsigned SetCCOpcodeTab[2][8] = {
883 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
885 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
886 X86::SETSr, X86::SETNSr },
889 /// emitUCOMr - In the future when we support processors before the P6, this
890 /// wraps the logic for emitting an FUCOMr vs FUCOMIr.
891 void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
892 unsigned LHS, unsigned RHS) {
893 if (0) { // for processors prior to the P6
894 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
895 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
896 BuildMI(*MBB, IP, X86::SAHF, 1);
898 BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
902 // EmitComparison - This function emits a comparison of the two operands,
903 // returning the extended setcc code to use.
904 unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
905 MachineBasicBlock *MBB,
906 MachineBasicBlock::iterator IP) {
907 // The arguments are already supposed to be of the same type.
908 const Type *CompTy = Op0->getType();
909 unsigned Class = getClassB(CompTy);
910 unsigned Op0r = getReg(Op0, MBB, IP);
912 // Special case handling of: cmp R, i
913 if (isa<ConstantPointerNull>(Op1)) {
914 if (OpNum < 2) // seteq/setne -> test
915 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
917 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
920 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
921 if (Class == cByte || Class == cShort || Class == cInt) {
922 unsigned Op1v = CI->getRawValue();
924 // Mask off any upper bits of the constant, if there are any...
925 Op1v &= (1ULL << (8 << Class)) - 1;
927 // If this is a comparison against zero, emit more efficient code. We
928 // can't handle unsigned comparisons against zero unless they are == or
929 // !=. These should have been strength reduced already anyway.
930 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
931 static const unsigned TESTTab[] = {
932 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
934 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
936 if (OpNum == 2) return 6; // Map jl -> js
937 if (OpNum == 3) return 7; // Map jg -> jns
941 static const unsigned CMPTab[] = {
942 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
945 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
948 assert(Class == cLong && "Unknown integer class!");
949 unsigned LowCst = CI->getRawValue();
950 unsigned HiCst = CI->getRawValue() >> 32;
951 if (OpNum < 2) { // seteq, setne
952 unsigned LoTmp = Op0r;
954 LoTmp = makeAnotherReg(Type::IntTy);
955 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
957 unsigned HiTmp = Op0r+1;
959 HiTmp = makeAnotherReg(Type::IntTy);
960 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
962 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
963 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
966 // Emit a sequence of code which compares the high and low parts once
967 // each, then uses a conditional move to handle the overflow case. For
968 // example, a setlt for long would generate code like this:
970 // AL = lo(op1) < lo(op2) // Always unsigned comparison
971 // BL = hi(op1) < hi(op2) // Signedness depends on operands
972 // dest = hi(op1) == hi(op2) ? BL : AL;
975 // FIXME: This would be much better if we had hierarchical register
976 // classes! Until then, hardcode registers so that we can deal with
977 // their aliases (because we don't have conditional byte moves).
979 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
980 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
981 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
982 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
983 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
984 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
985 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
987 // NOTE: visitSetCondInst knows that the value is dumped into the BL
988 // register at this point for long values...
994 // Special case handling of comparison against +/- 0.0
995 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
996 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
997 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
998 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
999 BuildMI(*MBB, IP, X86::SAHF, 1);
1003 unsigned Op1r = getReg(Op1, MBB, IP);
1005 default: assert(0 && "Unknown type class!");
1006 // Emit: cmp <var1>, <var2> (do the comparison). We can
1007 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1010 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
1013 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
1016 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1019 emitUCOMr(MBB, IP, Op0r, Op1r);
1023 if (OpNum < 2) { // seteq, setne
1024 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1025 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1026 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1027 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1028 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1029 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1030 break; // Allow the sete or setne to be generated from flags set by OR
1032 // Emit a sequence of code which compares the high and low parts once
1033 // each, then uses a conditional move to handle the overflow case. For
1034 // example, a setlt for long would generate code like this:
1036 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1037 // BL = hi(op1) < hi(op2) // Always unsigned comparison
1038 // dest = hi(op1) == hi(op2) ? BL : AL;
1041 // FIXME: This would be much better if we had hierarchical register
1042 // classes! Until then, hardcode registers so that we can deal with their
1043 // aliases (because we don't have conditional byte moves).
1045 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1046 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1047 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
1048 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1049 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1050 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1051 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1053 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1054 // register at this point for long values...
1061 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1062 /// register, then move it to wherever the result should be.
1064 void X86ISel::visitSetCondInst(SetCondInst &I) {
1065 if (canFoldSetCCIntoBranchOrSelect(&I))
1066 return; // Fold this into a branch or select.
1068 unsigned DestReg = getReg(I);
1069 MachineBasicBlock::iterator MII = BB->end();
1070 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1074 /// emitSetCCOperation - Common code shared between visitSetCondInst and
1075 /// constant expression support.
1077 void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1078 MachineBasicBlock::iterator IP,
1079 Value *Op0, Value *Op1, unsigned Opcode,
1080 unsigned TargetReg) {
1081 unsigned OpNum = getSetCCNumber(Opcode);
1082 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
1084 const Type *CompTy = Op0->getType();
1085 unsigned CompClass = getClassB(CompTy);
1086 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1088 if (CompClass != cLong || OpNum < 2) {
1089 // Handle normal comparisons with a setcc instruction...
1090 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1092 // Handle long comparisons by copying the value which is already in BL into
1093 // the register we want...
1094 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1098 void X86ISel::visitSelectInst(SelectInst &SI) {
1099 unsigned DestReg = getReg(SI);
1100 MachineBasicBlock::iterator MII = BB->end();
1101 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1102 SI.getFalseValue(), DestReg);
1105 /// emitSelect - Common code shared between visitSelectInst and the constant
1106 /// expression support.
1107 void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1108 MachineBasicBlock::iterator IP,
1109 Value *Cond, Value *TrueVal, Value *FalseVal,
1111 unsigned SelectClass = getClassB(TrueVal->getType());
1113 // We don't support 8-bit conditional moves. If we have incoming constants,
1114 // transform them into 16-bit constants to avoid having a run-time conversion.
1115 if (SelectClass == cByte) {
1116 if (Constant *T = dyn_cast<Constant>(TrueVal))
1117 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1118 if (Constant *F = dyn_cast<Constant>(FalseVal))
1119 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1122 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1123 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1124 if (TrueReg == FalseReg) {
1125 static const unsigned Opcode[] = {
1126 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1128 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1129 if (SelectClass == cLong)
1130 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1135 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1136 // We successfully folded the setcc into the select instruction.
1138 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1139 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1142 const Type *CompTy = SCI->getOperand(0)->getType();
1143 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1145 // LLVM -> X86 signed X86 unsigned
1146 // ----- ---------- ------------
1147 // seteq -> cmovNE cmovNE
1148 // setne -> cmovE cmovE
1149 // setlt -> cmovGE cmovAE
1150 // setge -> cmovL cmovB
1151 // setgt -> cmovLE cmovBE
1152 // setle -> cmovG cmovA
1154 // cmovNS // Used by comparison with 0 optimization
1157 switch (SelectClass) {
1158 default: assert(0 && "Unknown value class!");
1160 // Annoyingly, we don't have a full set of floating point conditional
1162 static const unsigned OpcodeTab[2][8] = {
1163 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1164 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1165 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1167 Opcode = OpcodeTab[isSigned][OpNum];
1169 // If opcode == 0, we hit a case that we don't support. Output a setcc
1170 // and compare the result against zero.
1172 unsigned CompClass = getClassB(CompTy);
1174 if (CompClass != cLong || OpNum < 2) {
1175 CondReg = makeAnotherReg(Type::BoolTy);
1176 // Handle normal comparisons with a setcc instruction...
1177 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1179 // Long comparisons end up in the BL register.
1183 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1184 Opcode = X86::FCMOVE;
1190 static const unsigned OpcodeTab[2][8] = {
1191 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1192 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1193 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1194 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1196 Opcode = OpcodeTab[isSigned][OpNum];
1201 static const unsigned OpcodeTab[2][8] = {
1202 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1203 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1204 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1205 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1207 Opcode = OpcodeTab[isSigned][OpNum];
1212 // Get the value being branched on, and use it to set the condition codes.
1213 unsigned CondReg = getReg(Cond, MBB, IP);
1214 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1215 switch (SelectClass) {
1216 default: assert(0 && "Unknown value class!");
1217 case cFP: Opcode = X86::FCMOVE; break;
1219 case cShort: Opcode = X86::CMOVE16rr; break;
1221 case cLong: Opcode = X86::CMOVE32rr; break;
1225 unsigned RealDestReg = DestReg;
1228 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1229 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1230 // cmove, then truncate the result.
1231 if (SelectClass == cByte) {
1232 DestReg = makeAnotherReg(Type::ShortTy);
1233 if (getClassB(TrueVal->getType()) == cByte) {
1234 // Promote the true value, by storing it into AL, and reading from AX.
1235 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1236 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1237 TrueReg = makeAnotherReg(Type::ShortTy);
1238 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1240 if (getClassB(FalseVal->getType()) == cByte) {
1241 // Promote the true value, by storing it into CL, and reading from CX.
1242 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1243 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1244 FalseReg = makeAnotherReg(Type::ShortTy);
1245 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1249 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1251 switch (SelectClass) {
1253 // We did the computation with 16-bit registers. Truncate back to our
1254 // result by copying into AX then copying out AL.
1255 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1256 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1259 // Move the upper half of the value as well.
1260 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1267 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1268 /// operand, in the specified target register.
1270 void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1271 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1273 Value *Val = VR.Val;
1274 const Type *Ty = VR.Ty;
1276 if (Constant *C = dyn_cast<Constant>(Val)) {
1277 Val = ConstantExpr::getCast(C, Type::IntTy);
1281 // If this is a simple constant, just emit a MOVri directly to avoid the
1283 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1284 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1285 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1290 // Make sure we have the register number for this value...
1291 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1293 switch (getClassB(Ty)) {
1295 // Extend value into target register (8->32)
1297 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1299 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1302 // Extend value into target register (16->32)
1304 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1306 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1309 // Move value into target register (32->32)
1310 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1313 assert(0 && "Unpromotable operand class in promote32");
1317 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1318 /// we have the following possibilities:
1320 /// ret void: No return value, simply emit a 'ret' instruction
1321 /// ret sbyte, ubyte : Extend value into EAX and return
1322 /// ret short, ushort: Extend value into EAX and return
1323 /// ret int, uint : Move value into EAX and return
1324 /// ret pointer : Move value into EAX and return
1325 /// ret long, ulong : Move value into EAX/EDX and return
1326 /// ret float/double : Top of FP stack
1328 void X86ISel::visitReturnInst(ReturnInst &I) {
1329 if (I.getNumOperands() == 0) {
1330 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1334 Value *RetVal = I.getOperand(0);
1335 switch (getClassB(RetVal->getType())) {
1336 case cByte: // integral return values: extend or move into EAX and return
1339 promote32(X86::EAX, ValueRecord(RetVal));
1340 // Declare that EAX is live on exit
1341 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1343 case cFP: { // Floats & Doubles: Return in ST(0)
1344 unsigned RetReg = getReg(RetVal);
1345 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1346 // Declare that top-of-stack is live on exit
1347 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1351 unsigned RetReg = getReg(RetVal);
1352 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1353 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1354 // Declare that EAX & EDX are live on exit
1355 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1360 visitInstruction(I);
1362 // Emit a 'ret' instruction
1363 BuildMI(BB, X86::RET, 0);
1366 // getBlockAfter - Return the basic block which occurs lexically after the
1368 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1369 Function::iterator I = BB; ++I; // Get iterator to next block
1370 return I != BB->getParent()->end() ? &*I : 0;
1373 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1374 /// that since code layout is frozen at this point, that if we are trying to
1375 /// jump to a block that is the immediate successor of the current block, we can
1376 /// just make a fall-through (but we don't currently).
1378 void X86ISel::visitBranchInst(BranchInst &BI) {
1379 // Update machine-CFG edges
1380 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1381 if (BI.isConditional())
1382 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1384 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1386 if (!BI.isConditional()) { // Unconditional branch?
1387 if (BI.getSuccessor(0) != NextBB)
1388 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1392 // See if we can fold the setcc into the branch itself...
1393 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1395 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1396 // computed some other way...
1397 unsigned condReg = getReg(BI.getCondition());
1398 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1399 if (BI.getSuccessor(1) == NextBB) {
1400 if (BI.getSuccessor(0) != NextBB)
1401 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1403 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1405 if (BI.getSuccessor(0) != NextBB)
1406 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1411 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1412 MachineBasicBlock::iterator MII = BB->end();
1413 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1415 const Type *CompTy = SCI->getOperand(0)->getType();
1416 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1419 // LLVM -> X86 signed X86 unsigned
1420 // ----- ---------- ------------
1428 // js // Used by comparison with 0 optimization
1431 static const unsigned OpcodeTab[2][8] = {
1432 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1433 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1434 X86::JS, X86::JNS },
1437 if (BI.getSuccessor(0) != NextBB) {
1438 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1439 .addMBB(MBBMap[BI.getSuccessor(0)]);
1440 if (BI.getSuccessor(1) != NextBB)
1441 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1443 // Change to the inverse condition...
1444 if (BI.getSuccessor(1) != NextBB) {
1446 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1447 .addMBB(MBBMap[BI.getSuccessor(1)]);
1453 /// doCall - This emits an abstract call instruction, setting up the arguments
1454 /// and the return value as appropriate. For the actual function call itself,
1455 /// it inserts the specified CallMI instruction into the stream.
1457 void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1458 const std::vector<ValueRecord> &Args) {
1459 // Count how many bytes are to be pushed on the stack...
1460 unsigned NumBytes = 0;
1462 if (!Args.empty()) {
1463 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1464 switch (getClassB(Args[i].Ty)) {
1465 case cByte: case cShort: case cInt:
1466 NumBytes += 4; break;
1468 NumBytes += 8; break;
1470 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1472 default: assert(0 && "Unknown class!");
1475 // Adjust the stack pointer for the new arguments...
1476 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1478 // Arguments go on the stack in reverse order, as specified by the ABI.
1479 unsigned ArgOffset = 0;
1480 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1482 switch (getClassB(Args[i].Ty)) {
1484 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1485 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1486 .addImm(Args[i].Val == ConstantBool::True);
1491 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1492 // Zero/Sign extend constant, then stuff into memory.
1493 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1494 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1495 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1496 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1498 // Promote arg to 32 bits wide into a temporary register...
1499 ArgReg = makeAnotherReg(Type::UIntTy);
1500 promote32(ArgReg, Args[i]);
1501 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1502 X86::ESP, ArgOffset).addReg(ArgReg);
1506 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1507 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1508 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1509 X86::ESP, ArgOffset).addImm(Val);
1510 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1511 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1512 X86::ESP, ArgOffset).addImm(0);
1514 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1515 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1516 X86::ESP, ArgOffset).addReg(ArgReg);
1520 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1521 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1522 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1523 X86::ESP, ArgOffset).addImm(Val & ~0U);
1524 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1525 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1527 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1528 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1529 X86::ESP, ArgOffset).addReg(ArgReg);
1530 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1531 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1533 ArgOffset += 4; // 8 byte entry, not 4.
1537 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1538 if (Args[i].Ty == Type::FloatTy) {
1539 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1540 X86::ESP, ArgOffset).addReg(ArgReg);
1542 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1543 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1544 X86::ESP, ArgOffset).addReg(ArgReg);
1545 ArgOffset += 4; // 8 byte entry, not 4.
1549 default: assert(0 && "Unknown class!");
1554 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1557 BB->push_back(CallMI);
1559 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1561 // If there is a return value, scavenge the result from the location the call
1564 if (Ret.Ty != Type::VoidTy) {
1565 unsigned DestClass = getClassB(Ret.Ty);
1566 switch (DestClass) {
1570 // Integral results are in %eax, or the appropriate portion
1572 static const unsigned regRegMove[] = {
1573 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1575 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1576 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1579 case cFP: // Floating-point return values live in %ST(0)
1580 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1582 case cLong: // Long values are left in EDX:EAX
1583 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1584 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1586 default: assert(0 && "Unknown class!");
1592 /// visitCallInst - Push args on stack and do a procedure call instruction.
1593 void X86ISel::visitCallInst(CallInst &CI) {
1594 MachineInstr *TheCall;
1595 if (Function *F = CI.getCalledFunction()) {
1596 // Is it an intrinsic function call?
1597 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1598 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1602 // Emit a CALL instruction with PC-relative displacement.
1603 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1604 } else { // Emit an indirect call...
1605 unsigned Reg = getReg(CI.getCalledValue());
1606 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1609 std::vector<ValueRecord> Args;
1610 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1611 Args.push_back(ValueRecord(CI.getOperand(i)));
1613 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1614 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1617 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1618 /// function, lowering any calls to unknown intrinsic functions into the
1619 /// equivalent LLVM code.
1621 void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1622 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1623 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1624 if (CallInst *CI = dyn_cast<CallInst>(I++))
1625 if (Function *F = CI->getCalledFunction())
1626 switch (F->getIntrinsicID()) {
1627 case Intrinsic::not_intrinsic:
1628 case Intrinsic::vastart:
1629 case Intrinsic::vacopy:
1630 case Intrinsic::vaend:
1631 case Intrinsic::returnaddress:
1632 case Intrinsic::frameaddress:
1633 case Intrinsic::memcpy:
1634 case Intrinsic::memset:
1635 case Intrinsic::isunordered:
1636 case Intrinsic::readport:
1637 case Intrinsic::writeport:
1638 // We directly implement these intrinsics
1640 case Intrinsic::readio: {
1641 // On X86, memory operations are in-order. Lower this intrinsic
1642 // into a volatile load.
1643 Instruction *Before = CI->getPrev();
1644 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1645 CI->replaceAllUsesWith(LI);
1646 BB->getInstList().erase(CI);
1649 case Intrinsic::writeio: {
1650 // On X86, memory operations are in-order. Lower this intrinsic
1651 // into a volatile store.
1652 Instruction *Before = CI->getPrev();
1653 StoreInst *LI = new StoreInst(CI->getOperand(1),
1654 CI->getOperand(2), true, CI);
1655 CI->replaceAllUsesWith(LI);
1656 BB->getInstList().erase(CI);
1660 // All other intrinsic calls we must lower.
1661 Instruction *Before = CI->getPrev();
1662 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1663 if (Before) { // Move iterator to instruction after call
1671 void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1672 unsigned TmpReg1, TmpReg2;
1674 case Intrinsic::vastart:
1675 // Get the address of the first vararg value...
1676 TmpReg1 = getReg(CI);
1677 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1680 case Intrinsic::vacopy:
1681 TmpReg1 = getReg(CI);
1682 TmpReg2 = getReg(CI.getOperand(1));
1683 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1685 case Intrinsic::vaend: return; // Noop on X86
1687 case Intrinsic::returnaddress:
1688 case Intrinsic::frameaddress:
1689 TmpReg1 = getReg(CI);
1690 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1691 if (ID == Intrinsic::returnaddress) {
1692 // Just load the return address
1693 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1694 ReturnAddressIndex);
1696 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1697 ReturnAddressIndex, -4);
1700 // Values other than zero are not implemented yet.
1701 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1705 case Intrinsic::isunordered:
1706 TmpReg1 = getReg(CI.getOperand(1));
1707 TmpReg2 = getReg(CI.getOperand(2));
1708 emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1709 TmpReg2 = getReg(CI);
1710 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1713 case Intrinsic::memcpy: {
1714 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1716 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1717 Align = AlignC->getRawValue();
1718 if (Align == 0) Align = 1;
1721 // Turn the byte code into # iterations
1724 switch (Align & 3) {
1725 case 2: // WORD aligned
1726 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1727 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1729 CountReg = makeAnotherReg(Type::IntTy);
1730 unsigned ByteReg = getReg(CI.getOperand(3));
1731 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1733 Opcode = X86::REP_MOVSW;
1735 case 0: // DWORD aligned
1736 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1737 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1739 CountReg = makeAnotherReg(Type::IntTy);
1740 unsigned ByteReg = getReg(CI.getOperand(3));
1741 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1743 Opcode = X86::REP_MOVSD;
1745 default: // BYTE aligned
1746 CountReg = getReg(CI.getOperand(3));
1747 Opcode = X86::REP_MOVSB;
1751 // No matter what the alignment is, we put the source in ESI, the
1752 // destination in EDI, and the count in ECX.
1753 TmpReg1 = getReg(CI.getOperand(1));
1754 TmpReg2 = getReg(CI.getOperand(2));
1755 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1756 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1757 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1758 BuildMI(BB, Opcode, 0);
1761 case Intrinsic::memset: {
1762 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1764 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1765 Align = AlignC->getRawValue();
1766 if (Align == 0) Align = 1;
1769 // Turn the byte code into # iterations
1772 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1773 unsigned Val = ValC->getRawValue() & 255;
1775 // If the value is a constant, then we can potentially use larger copies.
1776 switch (Align & 3) {
1777 case 2: // WORD aligned
1778 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1779 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1781 CountReg = makeAnotherReg(Type::IntTy);
1782 unsigned ByteReg = getReg(CI.getOperand(3));
1783 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1785 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1786 Opcode = X86::REP_STOSW;
1788 case 0: // DWORD aligned
1789 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1790 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1792 CountReg = makeAnotherReg(Type::IntTy);
1793 unsigned ByteReg = getReg(CI.getOperand(3));
1794 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1796 Val = (Val << 8) | Val;
1797 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1798 Opcode = X86::REP_STOSD;
1800 default: // BYTE aligned
1801 CountReg = getReg(CI.getOperand(3));
1802 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1803 Opcode = X86::REP_STOSB;
1807 // If it's not a constant value we are storing, just fall back. We could
1808 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1809 unsigned ValReg = getReg(CI.getOperand(2));
1810 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1811 CountReg = getReg(CI.getOperand(3));
1812 Opcode = X86::REP_STOSB;
1815 // No matter what the alignment is, we put the source in ESI, the
1816 // destination in EDI, and the count in ECX.
1817 TmpReg1 = getReg(CI.getOperand(1));
1818 //TmpReg2 = getReg(CI.getOperand(2));
1819 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1820 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1821 BuildMI(BB, Opcode, 0);
1825 case Intrinsic::readport: {
1826 // First, determine that the size of the operand falls within the acceptable
1827 // range for this architecture.
1829 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
1830 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1834 // Now, move the I/O port address into the DX register and use the IN
1835 // instruction to get the input data.
1837 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1838 unsigned DestReg = getReg(CI);
1840 // If the port is a single-byte constant, use the immediate form.
1841 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1842 if ((C->getRawValue() & 255) == C->getRawValue()) {
1845 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1846 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1849 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1850 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1853 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1854 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1859 unsigned Reg = getReg(CI.getOperand(1));
1860 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1863 BuildMI(BB, X86::IN8rr, 0);
1864 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1867 BuildMI(BB, X86::IN16rr, 0);
1868 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1871 BuildMI(BB, X86::IN32rr, 0);
1872 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1875 std::cerr << "Cannot do input on this data type";
1881 case Intrinsic::writeport: {
1882 // First, determine that the size of the operand falls within the
1883 // acceptable range for this architecture.
1884 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1885 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1889 unsigned Class = getClassB(CI.getOperand(1)->getType());
1890 unsigned ValReg = getReg(CI.getOperand(1));
1893 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1896 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1899 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1902 std::cerr << "llvm.writeport: invalid data type for X86 target";
1907 // If the port is a single-byte constant, use the immediate form.
1908 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1909 if ((C->getRawValue() & 255) == C->getRawValue()) {
1910 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1911 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1915 // Otherwise, move the I/O port address into the DX register and the value
1916 // to write into the AL/AX/EAX register.
1917 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1918 unsigned Reg = getReg(CI.getOperand(2));
1919 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1920 BuildMI(BB, Opc[Class], 0);
1924 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1928 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1929 if (LI.getParent() != User.getParent())
1931 BasicBlock::iterator It = &LI;
1932 // Check all of the instructions between the load and the user. We should
1933 // really use alias analysis here, but for now we just do something simple.
1934 for (++It; It != BasicBlock::iterator(&User); ++It) {
1935 switch (It->getOpcode()) {
1936 case Instruction::Free:
1937 case Instruction::Store:
1938 case Instruction::Call:
1939 case Instruction::Invoke:
1941 case Instruction::Load:
1942 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1950 /// visitSimpleBinary - Implement simple binary operators for integral types...
1951 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1954 void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1955 unsigned DestReg = getReg(B);
1956 MachineBasicBlock::iterator MI = BB->end();
1957 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1958 unsigned Class = getClassB(B.getType());
1960 // Special case: op Reg, load [mem]
1961 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
1963 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
1964 if (!B.swapOperands())
1965 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1967 if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
1968 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1972 static const unsigned OpcodeTab[][3] = {
1973 // Arithmetic operators
1974 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1975 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1977 // Bitwise operators
1978 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1979 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1980 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1982 Opcode = OpcodeTab[OperatorClass][Class];
1984 static const unsigned OpcodeTab[][2] = {
1985 { X86::FADD32m, X86::FADD64m }, // ADD
1986 { X86::FSUB32m, X86::FSUB64m }, // SUB
1988 const Type *Ty = Op0->getType();
1989 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1990 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
1993 unsigned Op0r = getReg(Op0);
1994 if (AllocaInst *AI =
1995 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
1996 unsigned FI = getFixedSizedAllocaFI(AI);
1997 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2001 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
2003 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
2008 // If this is a floating point subtract, check to see if we can fold the first
2010 if (Class == cFP && OperatorClass == 1 &&
2011 isa<LoadInst>(Op0) &&
2012 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2013 const Type *Ty = Op0->getType();
2014 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2015 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2017 unsigned Op1r = getReg(Op1);
2018 if (AllocaInst *AI =
2019 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2020 unsigned FI = getFixedSizedAllocaFI(AI);
2021 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2024 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
2026 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
2031 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
2035 /// emitBinaryFPOperation - This method handles emission of floating point
2036 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
2037 void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2038 MachineBasicBlock::iterator IP,
2039 Value *Op0, Value *Op1,
2040 unsigned OperatorClass, unsigned DestReg) {
2041 // Special case: op Reg, <const fp>
2042 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2043 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2044 // Create a constant pool entry for this constant.
2045 MachineConstantPool *CP = F->getConstantPool();
2046 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2047 const Type *Ty = Op1->getType();
2049 static const unsigned OpcodeTab[][4] = {
2050 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2051 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2054 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2055 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2056 unsigned Op0r = getReg(Op0, BB, IP);
2057 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2058 DestReg).addReg(Op0r), CPI);
2062 // Special case: R1 = op <const fp>, R2
2063 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2064 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2066 unsigned op1Reg = getReg(Op1, BB, IP);
2067 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2069 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
2070 // R1 = op CST, R2 --> R1 = opr R2, CST
2072 // Create a constant pool entry for this constant.
2073 MachineConstantPool *CP = F->getConstantPool();
2074 unsigned CPI = CP->getConstantPoolIndex(CFP);
2075 const Type *Ty = CFP->getType();
2077 static const unsigned OpcodeTab[][4] = {
2078 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2079 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2082 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2083 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2084 unsigned Op1r = getReg(Op1, BB, IP);
2085 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2086 DestReg).addReg(Op1r), CPI);
2091 static const unsigned OpcodeTab[4] = {
2092 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2095 unsigned Opcode = OpcodeTab[OperatorClass];
2096 unsigned Op0r = getReg(Op0, BB, IP);
2097 unsigned Op1r = getReg(Op1, BB, IP);
2098 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2101 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2102 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2105 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2106 /// and constant expression support.
2108 void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2109 MachineBasicBlock::iterator IP,
2110 Value *Op0, Value *Op1,
2111 unsigned OperatorClass,
2113 unsigned Class = getClassB(Op0->getType());
2116 assert(OperatorClass < 2 && "No logical ops for FP!");
2117 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2121 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2122 if (OperatorClass == 1) {
2123 static unsigned const NEGTab[] = {
2124 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2127 // sub 0, X -> neg X
2128 if (CI->isNullValue()) {
2129 unsigned op1Reg = getReg(Op1, MBB, IP);
2130 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2132 if (Class == cLong) {
2133 // We just emitted: Dl = neg Sl
2134 // Now emit : T = addc Sh, 0
2136 unsigned T = makeAnotherReg(Type::IntTy);
2137 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2138 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2141 } else if (Op1->hasOneUse() && Class != cLong) {
2142 // sub C, X -> tmp = neg X; DestReg = add tmp, C. This is better
2143 // than copying C into a temporary register, because of register
2144 // pressure (tmp and destreg can share a register.
2145 static unsigned const ADDRITab[] = {
2146 X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2148 unsigned op1Reg = getReg(Op1, MBB, IP);
2149 unsigned Tmp = makeAnotherReg(Op0->getType());
2150 BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
2151 BuildMI(*MBB, IP, ADDRITab[Class], 2,
2152 DestReg).addReg(Tmp).addImm(CI->getRawValue());
2157 // Special case: op Reg, <const int>
2158 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
2159 unsigned Op0r = getReg(Op0, MBB, IP);
2161 // xor X, -1 -> not X
2162 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
2163 static unsigned const NOTTab[] = {
2164 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2166 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
2167 if (Class == cLong) // Invert the top part too
2168 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
2172 // add X, -1 -> dec X
2173 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2174 // Note that we can't use dec for 64-bit decrements, because it does not
2175 // set the carry flag!
2176 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
2177 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2181 // add X, 1 -> inc X
2182 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2183 // Note that we can't use inc for 64-bit increments, because it does not
2184 // set the carry flag!
2185 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
2186 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
2190 static const unsigned OpcodeTab[][5] = {
2191 // Arithmetic operators
2192 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2193 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
2195 // Bitwise operators
2196 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2197 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2198 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
2201 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2202 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
2204 if (Class != cLong) {
2205 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2209 // If this is a long value and the high or low bits have a special
2210 // property, emit some special cases.
2211 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2213 // If the constant is zero in the low 32-bits, just copy the low part
2214 // across and apply the normal 32-bit operation to the high parts. There
2215 // will be no carry or borrow into the top.
2217 if (OperatorClass != 2) // All but and...
2218 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2220 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2221 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2222 .addReg(Op0r+1).addImm(Op1h);
2226 // If this is a logical operation and the top 32-bits are zero, just
2227 // operate on the lower 32.
2228 if (Op1h == 0 && OperatorClass > 1) {
2229 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2230 .addReg(Op0r).addImm(Op1l);
2231 if (OperatorClass != 2) // All but and
2232 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2234 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2238 // TODO: We could handle lots of other special cases here, such as AND'ing
2239 // with 0xFFFFFFFF00000000 -> noop, etc.
2241 // Otherwise, code generate the full operation with a constant.
2242 static const unsigned TopTab[] = {
2243 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2246 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2247 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2248 .addReg(Op0r+1).addImm(Op1h);
2252 // Finally, handle the general case now.
2253 static const unsigned OpcodeTab[][5] = {
2254 // Arithmetic operators
2255 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2256 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
2258 // Bitwise operators
2259 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2260 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2261 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
2264 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2265 unsigned Op0r = getReg(Op0, MBB, IP);
2266 unsigned Op1r = getReg(Op1, MBB, IP);
2267 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2269 if (Class == cLong) { // Handle the upper 32 bits of long values...
2270 static const unsigned TopTab[] = {
2271 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2273 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2274 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2278 /// doMultiply - Emit appropriate instructions to multiply together the
2279 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2280 /// result should be given as DestTy.
2282 void X86ISel::doMultiply(MachineBasicBlock *MBB,
2283 MachineBasicBlock::iterator MBBI,
2284 unsigned DestReg, const Type *DestTy,
2285 unsigned op0Reg, unsigned op1Reg) {
2286 unsigned Class = getClass(DestTy);
2290 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2291 .addReg(op0Reg).addReg(op1Reg);
2294 // Must use the MUL instruction, which forces use of AL...
2295 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2296 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2297 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2300 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2304 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2305 // returns zero when the input is not exactly a power of two.
2306 static unsigned ExactLog2(unsigned Val) {
2307 if (Val == 0 || (Val & (Val-1))) return 0;
2317 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2318 /// 16, or 32-bit integer multiply by a constant.
2319 void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2320 MachineBasicBlock::iterator IP,
2321 unsigned DestReg, const Type *DestTy,
2322 unsigned op0Reg, unsigned ConstRHS) {
2323 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2324 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2325 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
2326 static const unsigned NEGrTab[] = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
2328 unsigned Class = getClass(DestTy);
2331 // Handle special cases here.
2334 TmpReg = makeAnotherReg(DestTy);
2335 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2336 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2339 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2342 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2345 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2348 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2353 if (Class == cInt) {
2355 AM.BaseType = X86AddressMode::RegBase;
2356 AM.Base.Reg = op0Reg;
2357 AM.Scale = ConstRHS-1;
2358 AM.IndexReg = op0Reg;
2360 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
2366 if (Class == cInt) {
2367 TmpReg = makeAnotherReg(DestTy);
2369 AM.BaseType = X86AddressMode::RegBase;
2370 AM.Base.Reg = op0Reg;
2371 AM.Scale = -ConstRHS-1;
2372 AM.IndexReg = op0Reg;
2374 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
2375 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2380 // If the element size is exactly a power of 2, use a shift to get it.
2381 if (unsigned Shift = ExactLog2(ConstRHS)) {
2383 default: assert(0 && "Unknown class for this function!");
2385 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2388 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2391 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2396 // If the element size is a negative power of 2, use a shift/neg to get it.
2397 if (unsigned Shift = ExactLog2(-ConstRHS)) {
2398 TmpReg = makeAnotherReg(DestTy);
2399 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2401 default: assert(0 && "Unknown class for this function!");
2403 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2406 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2409 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2414 if (Class == cShort) {
2415 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2417 } else if (Class == cInt) {
2418 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2422 // Most general case, emit a normal multiply...
2423 TmpReg = makeAnotherReg(DestTy);
2424 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2426 // Emit a MUL to multiply the register holding the index by
2427 // elementSize, putting the result in OffsetReg.
2428 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2431 /// visitMul - Multiplies are not simple binary operators because they must deal
2432 /// with the EAX register explicitly.
2434 void X86ISel::visitMul(BinaryOperator &I) {
2435 unsigned ResultReg = getReg(I);
2437 Value *Op0 = I.getOperand(0);
2438 Value *Op1 = I.getOperand(1);
2440 // Fold loads into floating point multiplies.
2441 if (getClass(Op0->getType()) == cFP) {
2442 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2443 if (!I.swapOperands())
2444 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2445 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2446 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2447 const Type *Ty = Op0->getType();
2448 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2449 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2451 unsigned Op0r = getReg(Op0);
2452 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2453 unsigned FI = getFixedSizedAllocaFI(AI);
2454 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2457 getAddressingMode(LI->getOperand(0), AM);
2459 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2465 MachineBasicBlock::iterator IP = BB->end();
2466 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2469 void X86ISel::emitMultiply(MachineBasicBlock *MBB,
2470 MachineBasicBlock::iterator IP,
2471 Value *Op0, Value *Op1, unsigned DestReg) {
2472 MachineBasicBlock &BB = *MBB;
2473 TypeClass Class = getClass(Op0->getType());
2475 // Simple scalar multiply?
2476 unsigned Op0Reg = getReg(Op0, &BB, IP);
2481 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2482 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2483 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
2485 unsigned Op1Reg = getReg(Op1, &BB, IP);
2486 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2490 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2496 // Long value. We have to do things the hard way...
2497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2498 unsigned CLow = CI->getRawValue();
2499 unsigned CHi = CI->getRawValue() >> 32;
2502 // If the low part of the constant is all zeros, things are simple.
2503 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2504 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2508 // Multiply the two low parts... capturing carry into EDX
2509 unsigned OverflowReg = 0;
2511 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2513 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2514 OverflowReg = makeAnotherReg(Type::UIntTy);
2515 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2516 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2517 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
2519 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2520 BuildMI(BB, IP, X86::MOV32rr, 1,
2521 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2524 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2525 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2527 unsigned AHBLplusOverflowReg;
2529 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2530 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2531 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2533 AHBLplusOverflowReg = AHBLReg;
2537 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2539 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2540 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2542 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2543 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2548 // General 64x64 multiply
2550 unsigned Op1Reg = getReg(Op1, &BB, IP);
2551 // Multiply the two low parts... capturing carry into EDX
2552 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2553 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2555 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2556 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2557 BuildMI(BB, IP, X86::MOV32rr, 1,
2558 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2560 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2561 BuildMI(BB, IP, X86::IMUL32rr, 2,
2562 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2564 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2565 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2566 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2568 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2569 BuildMI(BB, IP, X86::IMUL32rr, 2,
2570 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2572 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2573 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2577 /// visitDivRem - Handle division and remainder instructions... these
2578 /// instruction both require the same instructions to be generated, they just
2579 /// select the result from a different register. Note that both of these
2580 /// instructions work differently for signed and unsigned operands.
2582 void X86ISel::visitDivRem(BinaryOperator &I) {
2583 unsigned ResultReg = getReg(I);
2584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2586 // Fold loads into floating point divides.
2587 if (getClass(Op0->getType()) == cFP) {
2588 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2589 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2590 const Type *Ty = Op0->getType();
2591 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2592 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2594 unsigned Op0r = getReg(Op0);
2595 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2596 unsigned FI = getFixedSizedAllocaFI(AI);
2597 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2600 getAddressingMode(LI->getOperand(0), AM);
2602 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2607 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2608 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2609 const Type *Ty = Op0->getType();
2610 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2611 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2613 unsigned Op1r = getReg(Op1);
2614 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2615 unsigned FI = getFixedSizedAllocaFI(AI);
2616 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2619 getAddressingMode(LI->getOperand(0), AM);
2620 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
2627 MachineBasicBlock::iterator IP = BB->end();
2628 emitDivRemOperation(BB, IP, Op0, Op1,
2629 I.getOpcode() == Instruction::Div, ResultReg);
2632 void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2633 MachineBasicBlock::iterator IP,
2634 Value *Op0, Value *Op1, bool isDiv,
2635 unsigned ResultReg) {
2636 const Type *Ty = Op0->getType();
2637 unsigned Class = getClass(Ty);
2639 case cFP: // Floating point divide
2641 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2643 } else { // Floating point remainder...
2644 unsigned Op0Reg = getReg(Op0, BB, IP);
2645 unsigned Op1Reg = getReg(Op1, BB, IP);
2646 MachineInstr *TheCall =
2647 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2648 std::vector<ValueRecord> Args;
2649 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2650 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2651 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2655 static const char *FnName[] =
2656 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2657 unsigned Op0Reg = getReg(Op0, BB, IP);
2658 unsigned Op1Reg = getReg(Op1, BB, IP);
2659 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2660 MachineInstr *TheCall =
2661 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2663 std::vector<ValueRecord> Args;
2664 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2665 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2666 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2669 case cByte: case cShort: case cInt:
2670 break; // Small integrals, handled below...
2671 default: assert(0 && "Unknown class!");
2674 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2675 static const unsigned NEGOpcode[]={ X86::NEG8r, X86::NEG16r, X86::NEG32r };
2676 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2677 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2678 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2680 // Special case signed division by power of 2.
2681 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2683 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2684 int V = CI->getValue();
2686 if (V == 1) { // X /s 1 => X
2687 unsigned Op0Reg = getReg(Op0, BB, IP);
2688 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2692 if (V == -1) { // X /s -1 => -X
2693 unsigned Op0Reg = getReg(Op0, BB, IP);
2694 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2698 if (V == 2 || V == -2) { // X /s 2
2699 static const unsigned CMPOpcode[] = {
2700 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2702 static const unsigned SBBOpcode[] = {
2703 X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2705 unsigned Op0Reg = getReg(Op0, BB, IP);
2706 unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2707 BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2709 unsigned TmpReg = makeAnotherReg(Op0->getType());
2710 BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2712 unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2713 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2715 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2721 if (V < 0) { // Not a positive power of 2?
2723 isNeg = true; // Maybe it's a negative power of 2.
2725 if (unsigned Log = ExactLog2(V)) {
2727 unsigned Op0Reg = getReg(Op0, BB, IP);
2728 unsigned TmpReg = makeAnotherReg(Op0->getType());
2729 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2730 .addReg(Op0Reg).addImm(Log-1);
2731 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2732 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2733 .addReg(TmpReg).addImm(32-Log);
2734 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2735 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2736 .addReg(Op0Reg).addReg(TmpReg2);
2738 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2739 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2740 .addReg(TmpReg3).addImm(Log);
2742 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2746 assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2747 int V = CI->getValue();
2749 if (V == 2 || V == -2) { // X % 2, X % -2
2750 static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2751 static const unsigned BaseReg[] = { X86::AL , X86::AX , X86::EAX };
2752 static const unsigned SExtReg[] = { X86::AH , X86::DX , X86::EDX };
2753 static const unsigned ANDOpcode[] = {
2754 X86::AND8ri, X86::AND16ri, X86::AND32ri
2756 static const unsigned XOROpcode[] = {
2757 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2759 static const unsigned SUBOpcode[] = {
2760 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2763 // Sign extend result into reg of -1 or 0.
2764 unsigned Op0Reg = getReg(Op0, BB, IP);
2765 BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2766 BuildMI(*BB, IP, SExtOpcode[Class], 0);
2767 unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2768 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2770 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2771 BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2773 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2774 BuildMI(*BB, IP, XOROpcode[Class], 2,
2775 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2776 BuildMI(*BB, IP, SUBOpcode[Class], 2,
2777 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2782 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
2783 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2784 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2786 static const unsigned DivOpcode[][4] = {
2787 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2788 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
2791 unsigned Reg = Regs[Class];
2792 unsigned ExtReg = ExtRegs[Class];
2794 // Put the first operand into one of the A registers...
2795 unsigned Op0Reg = getReg(Op0, BB, IP);
2796 unsigned Op1Reg = getReg(Op1, BB, IP);
2797 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2799 if (Ty->isSigned()) {
2800 // Emit a sign extension instruction...
2801 unsigned ShiftResult = makeAnotherReg(Op0->getType());
2802 BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2803 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2805 // Emit the appropriate divide or remainder instruction...
2806 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
2808 // If unsigned, emit a zeroing instruction... (reg = 0)
2809 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2811 // Emit the appropriate divide or remainder instruction...
2812 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2815 // Figure out which register we want to pick the result out of...
2816 unsigned DestReg = isDiv ? Reg : ExtReg;
2818 // Put the result into the destination register...
2819 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2823 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2824 /// for constant immediate shift values, and for constant immediate
2825 /// shift values equal to 1. Even the general case is sort of special,
2826 /// because the shift amount has to be in CL, not just any old register.
2828 void X86ISel::visitShiftInst(ShiftInst &I) {
2829 MachineBasicBlock::iterator IP = BB->end ();
2830 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2831 I.getOpcode () == Instruction::Shl, I.getType (),
2835 /// emitShiftOperation - Common code shared between visitShiftInst and
2836 /// constant expression support.
2837 void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
2838 MachineBasicBlock::iterator IP,
2839 Value *Op, Value *ShiftAmount,
2840 bool isLeftShift, const Type *ResultTy,
2842 unsigned SrcReg = getReg (Op, MBB, IP);
2843 bool isSigned = ResultTy->isSigned ();
2844 unsigned Class = getClass (ResultTy);
2846 static const unsigned ConstantOperand[][4] = {
2847 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2848 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2849 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2850 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
2853 static const unsigned NonConstantOperand[][4] = {
2854 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2855 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2856 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2857 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
2860 // Longs, as usual, are handled specially...
2861 if (Class == cLong) {
2862 // If we have a constant shift, we can generate much more efficient code
2863 // than otherwise...
2865 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2866 unsigned Amount = CUI->getValue();
2868 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2870 BuildMI(*MBB, IP, Opc[3], 3,
2871 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2872 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2874 BuildMI(*MBB, IP, Opc[3], 3,
2875 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2876 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2878 } else { // Shifting more than 32 bits
2882 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2883 DestReg + 1).addReg(SrcReg).addImm(Amount);
2885 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2887 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2890 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2891 DestReg).addReg(SrcReg+1).addImm(Amount);
2893 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2895 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2899 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2901 if (!isLeftShift && isSigned) {
2902 // If this is a SHR of a Long, then we need to do funny sign extension
2903 // stuff. TmpReg gets the value to use as the high-part if we are
2904 // shifting more than 32 bits.
2905 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
2907 // Other shifts use a fixed zero value if the shift is more than 32
2909 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2912 // Initialize CL with the shift amount...
2913 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2914 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2916 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2917 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2919 // TmpReg2 = shld inHi, inLo
2920 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2922 // TmpReg3 = shl inLo, CL
2923 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2925 // Set the flags to indicate whether the shift was by more than 32 bits.
2926 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2928 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2929 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2930 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2931 // DestLo = (>32) ? TmpReg : TmpReg3;
2932 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2933 DestReg).addReg(TmpReg3).addReg(TmpReg);
2935 // TmpReg2 = shrd inLo, inHi
2936 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2938 // TmpReg3 = s[ah]r inHi, CL
2939 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2942 // Set the flags to indicate whether the shift was by more than 32 bits.
2943 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2945 // DestLo = (>32) ? TmpReg3 : TmpReg2;
2946 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2947 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2949 // DestHi = (>32) ? TmpReg : TmpReg3;
2950 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2951 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2957 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2958 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2959 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2961 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2962 BuildMI(*MBB, IP, Opc[Class], 2,
2963 DestReg).addReg(SrcReg).addImm(CUI->getValue());
2964 } else { // The shift amount is non-constant.
2965 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2966 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2968 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2969 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2974 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2975 /// instruction. The load and store instructions are the only place where we
2976 /// need to worry about the memory layout of the target machine.
2978 void X86ISel::visitLoadInst(LoadInst &I) {
2979 // Check to see if this load instruction is going to be folded into a binary
2980 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2981 // pattern matching instruction selector be nice?
2982 unsigned Class = getClassB(I.getType());
2983 if (I.hasOneUse()) {
2984 Instruction *User = cast<Instruction>(I.use_back());
2985 switch (User->getOpcode()) {
2986 case Instruction::Cast:
2987 // If this is a cast from a signed-integer type to a floating point type,
2988 // fold the cast here.
2989 if (getClassB(User->getType()) == cFP &&
2990 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
2991 I.getType() == Type::LongTy)) {
2992 unsigned DestReg = getReg(User);
2993 static const unsigned Opcode[] = {
2994 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
2997 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2998 unsigned FI = getFixedSizedAllocaFI(AI);
2999 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3002 getAddressingMode(I.getOperand(0), AM);
3003 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
3011 case Instruction::Add:
3012 case Instruction::Sub:
3013 case Instruction::And:
3014 case Instruction::Or:
3015 case Instruction::Xor:
3016 if (Class == cLong) User = 0;
3018 case Instruction::Mul:
3019 case Instruction::Div:
3020 if (Class != cFP) User = 0;
3021 break; // Folding only implemented for floating point.
3022 default: User = 0; break;
3026 // Okay, we found a user. If the load is the first operand and there is
3027 // no second operand load, reverse the operand ordering. Note that this
3028 // can fail for a subtract (ie, no change will be made).
3029 bool Swapped = false;
3030 if (!isa<LoadInst>(User->getOperand(1)))
3031 Swapped = !cast<BinaryOperator>(User)->swapOperands();
3033 // Okay, now that everything is set up, if this load is used by the second
3034 // operand, and if there are no instructions that invalidate the load
3035 // before the binary operator, eliminate the load.
3036 if (User->getOperand(1) == &I &&
3037 isSafeToFoldLoadIntoInstruction(I, *User))
3038 return; // Eliminate the load!
3040 // If this is a floating point sub or div, we won't be able to swap the
3041 // operands, but we will still be able to eliminate the load.
3042 if (Class == cFP && User->getOperand(0) == &I &&
3043 !isa<LoadInst>(User->getOperand(1)) &&
3044 (User->getOpcode() == Instruction::Sub ||
3045 User->getOpcode() == Instruction::Div) &&
3046 isSafeToFoldLoadIntoInstruction(I, *User))
3047 return; // Eliminate the load!
3049 // If we swapped the operands to the instruction, but couldn't fold the
3050 // load anyway, swap them back. We don't want to break add X, int
3052 if (Swapped) cast<BinaryOperator>(User)->swapOperands();
3056 static const unsigned Opcodes[] = {
3057 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
3059 unsigned Opcode = Opcodes[Class];
3060 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
3062 unsigned DestReg = getReg(I);
3064 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3065 unsigned FI = getFixedSizedAllocaFI(AI);
3066 if (Class == cLong) {
3067 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3068 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3070 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3074 getAddressingMode(I.getOperand(0), AM);
3076 if (Class == cLong) {
3077 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3079 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
3081 addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
3086 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3089 void X86ISel::visitStoreInst(StoreInst &I) {
3091 getAddressingMode(I.getOperand(1), AM);
3093 const Type *ValTy = I.getOperand(0)->getType();
3094 unsigned Class = getClassB(ValTy);
3096 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3097 uint64_t Val = CI->getRawValue();
3098 if (Class == cLong) {
3099 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3101 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
3103 static const unsigned Opcodes[] = {
3104 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
3106 unsigned Opcode = Opcodes[Class];
3107 addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
3109 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
3110 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
3111 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
3112 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
3113 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3114 // Store constant FP values with integer instructions to avoid having to
3115 // load the constants from the constant pool then do a store.
3116 if (CFP->getType() == Type::FloatTy) {
3121 V.F = CFP->getValue();
3122 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
3128 V.F = CFP->getValue();
3129 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3131 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
3132 unsigned(V.I >> 32));
3135 } else if (Class == cLong) {
3136 unsigned ValReg = getReg(I.getOperand(0));
3137 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3139 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
3141 unsigned ValReg = getReg(I.getOperand(0));
3142 static const unsigned Opcodes[] = {
3143 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3145 unsigned Opcode = Opcodes[Class];
3146 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
3148 addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
3153 /// visitCastInst - Here we have various kinds of copying with or without sign
3154 /// extension going on.
3156 void X86ISel::visitCastInst(CastInst &CI) {
3157 Value *Op = CI.getOperand(0);
3159 unsigned SrcClass = getClassB(Op->getType());
3160 unsigned DestClass = getClassB(CI.getType());
3161 // Noop casts are not emitted: getReg will return the source operand as the
3162 // register to use for any uses of the noop cast.
3163 if (DestClass == SrcClass) {
3164 // The only detail in this plan is that casts from double -> float are
3165 // truncating operations that we have to codegen through memory (despite
3166 // the fact that the source/dest registers are the same class).
3167 if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3171 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3172 // of the case are GEP instructions, then the cast does not need to be
3173 // generated explicitly, it will be folded into the GEP.
3174 if (DestClass == cLong && SrcClass == cInt) {
3175 bool AllUsesAreGEPs = true;
3176 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3177 if (!isa<GetElementPtrInst>(*I)) {
3178 AllUsesAreGEPs = false;
3182 // No need to codegen this cast if all users are getelementptr instrs...
3183 if (AllUsesAreGEPs) return;
3186 // If this cast converts a load from a short,int, or long integer to a FP
3187 // value, we will have folded this cast away.
3188 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3189 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3190 Op->getType() == Type::LongTy))
3194 unsigned DestReg = getReg(CI);
3195 MachineBasicBlock::iterator MI = BB->end();
3196 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
3199 /// emitCastOperation - Common code shared between visitCastInst and constant
3200 /// expression cast support.
3202 void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3203 MachineBasicBlock::iterator IP,
3204 Value *Src, const Type *DestTy,
3206 const Type *SrcTy = Src->getType();
3207 unsigned SrcClass = getClassB(SrcTy);
3208 unsigned DestClass = getClassB(DestTy);
3209 unsigned SrcReg = getReg(Src, BB, IP);
3211 // Implement casts to bool by using compare on the operand followed by set if
3212 // not zero on the result.
3213 if (DestTy == Type::BoolTy) {
3216 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
3219 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
3222 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
3225 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3226 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
3230 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
3231 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
3232 BuildMI(*BB, IP, X86::SAHF, 1);
3236 // If the zero flag is not set, then the value is true, set the byte to
3238 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
3242 static const unsigned RegRegMove[] = {
3243 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
3246 // Implement casts between values of the same type class (as determined by
3247 // getClass) by using a register-to-register move.
3248 if (SrcClass == DestClass) {
3249 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
3250 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
3251 } else if (SrcClass == cFP) {
3252 if (SrcTy == Type::FloatTy) { // double -> float
3253 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
3254 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
3255 } else { // float -> double
3256 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3257 "Unknown cFP member!");
3258 // Truncate from double to float by storing to memory as short, then
3260 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
3261 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
3262 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3263 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
3265 } else if (SrcClass == cLong) {
3266 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3267 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
3269 assert(0 && "Cannot handle this type of cast instruction!");
3275 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3276 // or zero extension, depending on whether the source type was signed.
3277 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3278 SrcClass < DestClass) {
3279 bool isLong = DestClass == cLong;
3280 if (isLong) DestClass = cInt;
3282 static const unsigned Opc[][4] = {
3283 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3284 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
3287 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
3288 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
3289 DestReg).addReg(SrcReg);
3291 if (isLong) { // Handle upper 32 bits as appropriate...
3292 if (isUnsigned) // Zero out top bits...
3293 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3294 else // Sign extend bottom half...
3295 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
3300 // Special case long -> int ...
3301 if (SrcClass == cLong && DestClass == cInt) {
3302 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3306 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3307 // move out of AX or AL.
3308 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3309 && SrcClass > DestClass) {
3310 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
3311 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3312 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
3316 // Handle casts from integer to floating point now...
3317 if (DestClass == cFP) {
3318 // Promote the integer to a type supported by FLD. We do this because there
3319 // are no unsigned FLD instructions, so we must promote an unsigned value to
3320 // a larger signed value, then use FLD on the larger value.
3322 const Type *PromoteType = 0;
3323 unsigned PromoteOpcode = 0;
3324 unsigned RealDestReg = DestReg;
3325 switch (SrcTy->getTypeID()) {
3326 case Type::BoolTyID:
3327 case Type::SByteTyID:
3328 // We don't have the facilities for directly loading byte sized data from
3329 // memory (even signed). Promote it to 16 bits.
3330 PromoteType = Type::ShortTy;
3331 PromoteOpcode = X86::MOVSX16rr8;
3333 case Type::UByteTyID:
3334 PromoteType = Type::ShortTy;
3335 PromoteOpcode = X86::MOVZX16rr8;
3337 case Type::UShortTyID:
3338 PromoteType = Type::IntTy;
3339 PromoteOpcode = X86::MOVZX32rr16;
3341 case Type::UIntTyID: {
3342 // Make a 64 bit temporary... and zero out the top of it...
3343 unsigned TmpReg = makeAnotherReg(Type::LongTy);
3344 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
3345 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
3346 SrcTy = Type::LongTy;
3351 case Type::ULongTyID:
3352 // Don't fild into the read destination.
3353 DestReg = makeAnotherReg(Type::DoubleTy);
3355 default: // No promotion needed...
3360 unsigned TmpReg = makeAnotherReg(PromoteType);
3361 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
3362 SrcTy = PromoteType;
3363 SrcClass = getClass(PromoteType);
3367 // Spill the integer to memory and reload it from there...
3369 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3371 if (SrcClass == cLong) {
3372 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3373 FrameIdx).addReg(SrcReg);
3374 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3375 FrameIdx, 4).addReg(SrcReg+1);
3377 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
3378 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3379 FrameIdx).addReg(SrcReg);
3382 static const unsigned Op2[] =
3383 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
3384 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
3386 // We need special handling for unsigned 64-bit integer sources. If the
3387 // input number has the "sign bit" set, then we loaded it incorrectly as a
3388 // negative 64-bit number. In this case, add an offset value.
3389 if (SrcTy == Type::ULongTy) {
3390 // Emit a test instruction to see if the dynamic input value was signed.
3391 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
3393 // If the sign bit is set, get a pointer to an offset, otherwise get a
3394 // pointer to a zero.
3395 MachineConstantPool *CP = F->getConstantPool();
3396 unsigned Zero = makeAnotherReg(Type::IntTy);
3397 Constant *Null = Constant::getNullValue(Type::UIntTy);
3398 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
3399 CP->getConstantPoolIndex(Null));
3400 unsigned Offset = makeAnotherReg(Type::IntTy);
3401 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3403 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
3404 CP->getConstantPoolIndex(OffsetCst));
3405 unsigned Addr = makeAnotherReg(Type::IntTy);
3406 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
3408 // Load the constant for an add. FIXME: this could make an 'fadd' that
3409 // reads directly from memory, but we don't support these yet.
3410 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
3411 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
3413 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3414 .addReg(ConstReg).addReg(DestReg);
3420 // Handle casts from floating point to integer now...
3421 if (SrcClass == cFP) {
3422 // Change the floating point control register to use "round towards zero"
3423 // mode when truncating to an integer value.
3425 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3426 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
3428 // Load the old value of the high byte of the control word...
3429 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
3430 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
3433 // Set the high part to be round to zero...
3434 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
3435 CWFrameIdx, 1).addImm(12);
3437 // Reload the modified control word now...
3438 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3440 // Restore the memory image of control word to original value
3441 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
3442 CWFrameIdx, 1).addReg(HighPartOfCW);
3444 // We don't have the facilities for directly storing byte sized data to
3445 // memory. Promote it to 16 bits. We also must promote unsigned values to
3446 // larger classes because we only have signed FP stores.
3447 unsigned StoreClass = DestClass;
3448 const Type *StoreTy = DestTy;
3449 if (StoreClass == cByte || DestTy->isUnsigned())
3450 switch (StoreClass) {
3451 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3452 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3453 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
3454 // The following treatment of cLong may not be perfectly right,
3455 // but it survives chains of casts of the form
3456 // double->ulong->double.
3457 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
3458 default: assert(0 && "Unknown store class!");
3461 // Spill the integer to memory and reload it from there...
3463 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3465 static const unsigned Op1[] =
3466 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
3467 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3468 FrameIdx).addReg(SrcReg);
3470 if (DestClass == cLong) {
3471 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3472 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
3475 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
3476 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
3479 // Reload the original control word now...
3480 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3484 // Anything we haven't handled already, we can't (yet) handle at all.
3485 assert(0 && "Unhandled cast instruction!");
3489 /// visitVANextInst - Implement the va_next instruction...
3491 void X86ISel::visitVANextInst(VANextInst &I) {
3492 unsigned VAList = getReg(I.getOperand(0));
3493 unsigned DestReg = getReg(I);
3496 switch (I.getArgType()->getTypeID()) {
3499 assert(0 && "Error: bad type for va_next instruction!");
3501 case Type::PointerTyID:
3502 case Type::UIntTyID:
3506 case Type::ULongTyID:
3507 case Type::LongTyID:
3508 case Type::DoubleTyID:
3513 // Increment the VAList pointer...
3514 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
3517 void X86ISel::visitVAArgInst(VAArgInst &I) {
3518 unsigned VAList = getReg(I.getOperand(0));
3519 unsigned DestReg = getReg(I);
3521 switch (I.getType()->getTypeID()) {
3524 assert(0 && "Error: bad type for va_next instruction!");
3526 case Type::PointerTyID:
3527 case Type::UIntTyID:
3529 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3531 case Type::ULongTyID:
3532 case Type::LongTyID:
3533 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3534 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
3536 case Type::DoubleTyID:
3537 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
3542 /// visitGetElementPtrInst - instruction-select GEP instructions
3544 void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3545 // If this GEP instruction will be folded into all of its users, we don't need
3546 // to explicitly calculate it!
3548 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
3549 // Check all of the users of the instruction to see if they are loads and
3551 bool AllWillFold = true;
3552 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3553 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3554 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3555 cast<Instruction>(*UI)->getOperand(0) == &I) {
3556 AllWillFold = false;
3560 // If the instruction is foldable, and will be folded into all users, don't
3562 if (AllWillFold) return;
3565 unsigned outputReg = getReg(I);
3566 emitGEPOperation(BB, BB->end(), I.getOperand(0),
3567 I.op_begin()+1, I.op_end(), outputReg);
3570 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3571 /// GEPTypes (the derived types being stepped through at each level). On return
3572 /// from this function, if some indexes of the instruction are representable as
3573 /// an X86 lea instruction, the machine operands are put into the Ops
3574 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3575 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3576 /// addressing mode that only partially consumes the input, the BaseReg input of
3577 /// the addressing mode must be left free.
3579 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3581 void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
3582 MachineBasicBlock::iterator IP,
3583 std::vector<Value*> &GEPOps,
3584 std::vector<const Type*> &GEPTypes,
3585 X86AddressMode &AM) {
3586 const TargetData &TD = TM.getTargetData();
3588 // Clear out the state we are working with...
3589 AM.BaseType = X86AddressMode::RegBase;
3590 AM.Base.Reg = 0; // No base register
3591 AM.Scale = 1; // Unit scale
3592 AM.IndexReg = 0; // No index register
3593 AM.Disp = 0; // No displacement
3595 // While there are GEP indexes that can be folded into the current address,
3596 // keep processing them.
3597 while (!GEPTypes.empty()) {
3598 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3599 // It's a struct access. CUI is the index into the structure,
3600 // which names the field. This index must have unsigned type.
3601 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3603 // Use the TargetData structure to pick out what the layout of the
3604 // structure is in memory. Since the structure index must be constant, we
3605 // can get its value and use it to find the right byte offset from the
3606 // StructLayout class's list of structure member offsets.
3607 AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3608 GEPOps.pop_back(); // Consume a GEP operand
3609 GEPTypes.pop_back();
3611 // It's an array or pointer access: [ArraySize x ElementType].
3612 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3613 Value *idx = GEPOps.back();
3615 // idx is the index into the array. Unlike with structure
3616 // indices, we may not know its actual value at code-generation
3619 // If idx is a constant, fold it into the offset.
3620 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3621 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3622 AM.Disp += TypeSize*CSI->getValue();
3623 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3624 AM.Disp += TypeSize*CUI->getValue();
3626 // If the index reg is already taken, we can't handle this index.
3627 if (AM.IndexReg) return;
3629 // If this is a size that we can handle, then add the index as
3631 case 1: case 2: case 4: case 8:
3632 // These are all acceptable scales on X86.
3633 AM.Scale = TypeSize;
3636 // Otherwise, we can't handle this scale
3640 if (CastInst *CI = dyn_cast<CastInst>(idx))
3641 if (CI->getOperand(0)->getType() == Type::IntTy ||
3642 CI->getOperand(0)->getType() == Type::UIntTy)
3643 idx = CI->getOperand(0);
3645 AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3648 GEPOps.pop_back(); // Consume a GEP operand
3649 GEPTypes.pop_back();
3653 // GEPTypes is empty, which means we have a single operand left. Set it as
3654 // the base register.
3656 assert(AM.Base.Reg == 0);
3658 if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3659 AM.BaseType = X86AddressMode::FrameIndexBase;
3660 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
3665 #if 0 // FIXME: TODO!
3666 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3667 // FIXME: When addressing modes are more powerful/correct, we could load
3668 // global addresses directly as 32-bit immediates.
3672 AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3673 GEPOps.pop_back(); // Consume the last GEP operand
3677 /// isGEPFoldable - Return true if the specified GEP can be completely
3678 /// folded into the addressing mode of a load/store or lea instruction.
3679 bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3680 Value *Src, User::op_iterator IdxBegin,
3681 User::op_iterator IdxEnd, X86AddressMode &AM) {
3683 std::vector<Value*> GEPOps;
3684 GEPOps.resize(IdxEnd-IdxBegin+1);
3686 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3688 std::vector<const Type*>
3689 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3690 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3692 MachineBasicBlock::iterator IP;
3693 if (MBB) IP = MBB->end();
3694 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3696 // We can fold it away iff the getGEPIndex call eliminated all operands.
3697 return GEPOps.empty();
3700 void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3701 MachineBasicBlock::iterator IP,
3702 Value *Src, User::op_iterator IdxBegin,
3703 User::op_iterator IdxEnd, unsigned TargetReg) {
3704 const TargetData &TD = TM.getTargetData();
3706 // If this is a getelementptr null, with all constant integer indices, just
3707 // replace it with TargetReg = 42.
3708 if (isa<ConstantPointerNull>(Src)) {
3709 User::op_iterator I = IdxBegin;
3710 for (; I != IdxEnd; ++I)
3711 if (!isa<ConstantInt>(*I))
3713 if (I == IdxEnd) { // All constant indices
3714 unsigned Offset = TD.getIndexedOffset(Src->getType(),
3715 std::vector<Value*>(IdxBegin, IdxEnd));
3716 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3721 std::vector<Value*> GEPOps;
3722 GEPOps.resize(IdxEnd-IdxBegin+1);
3724 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3726 std::vector<const Type*> GEPTypes;
3727 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3728 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3730 // Keep emitting instructions until we consume the entire GEP instruction.
3731 while (!GEPOps.empty()) {
3732 unsigned OldSize = GEPOps.size();
3734 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3736 if (GEPOps.size() != OldSize) {
3737 // getGEPIndex consumed some of the input. Build an LEA instruction here.
3738 unsigned NextTarget = 0;
3739 if (!GEPOps.empty()) {
3740 assert(AM.Base.Reg == 0 &&
3741 "getGEPIndex should have left the base register open for chaining!");
3742 NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
3745 if (AM.BaseType == X86AddressMode::RegBase &&
3746 AM.IndexReg == 0 && AM.Disp == 0)
3747 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
3749 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
3751 TargetReg = NextTarget;
3752 } else if (GEPTypes.empty()) {
3753 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3754 // all operands are consumed but the base pointer. If so, just load it
3755 // into the register.
3756 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3757 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3759 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3760 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3762 break; // we are now done
3765 // It's an array or pointer access: [ArraySize x ElementType].
3766 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3767 Value *idx = GEPOps.back();
3768 GEPOps.pop_back(); // Consume a GEP operand
3769 GEPTypes.pop_back();
3771 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3772 // operand on X86. Handle this case directly now...
3773 if (CastInst *CI = dyn_cast<CastInst>(idx))
3774 if (CI->getOperand(0)->getType() == Type::IntTy ||
3775 CI->getOperand(0)->getType() == Type::UIntTy)
3776 idx = CI->getOperand(0);
3778 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3779 // must find the size of the pointed-to type (Not coincidentally, the next
3780 // type is the type of the elements in the array).
3781 const Type *ElTy = SqTy->getElementType();
3782 unsigned elementSize = TD.getTypeSize(ElTy);
3784 // If idxReg is a constant, we don't need to perform the multiply!
3785 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3786 if (!CSI->isNullValue()) {
3787 unsigned Offset = elementSize*CSI->getRawValue();
3788 unsigned Reg = makeAnotherReg(Type::UIntTy);
3789 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3790 .addReg(Reg).addImm(Offset);
3791 --IP; // Insert the next instruction before this one.
3792 TargetReg = Reg; // Codegen the rest of the GEP into this
3794 } else if (elementSize == 1) {
3795 // If the element size is 1, we don't have to multiply, just add
3796 unsigned idxReg = getReg(idx, MBB, IP);
3797 unsigned Reg = makeAnotherReg(Type::UIntTy);
3798 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3799 --IP; // Insert the next instruction before this one.
3800 TargetReg = Reg; // Codegen the rest of the GEP into this
3802 unsigned idxReg = getReg(idx, MBB, IP);
3803 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3805 // Make sure we can back the iterator up to point to the first
3806 // instruction emitted.
3807 MachineBasicBlock::iterator BeforeIt = IP;
3808 if (IP == MBB->begin())
3809 BeforeIt = MBB->end();
3812 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3814 // Emit an ADD to add OffsetReg to the basePtr.
3815 unsigned Reg = makeAnotherReg(Type::UIntTy);
3816 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3817 .addReg(Reg).addReg(OffsetReg);
3819 // Step to the first instruction of the multiply.
3820 if (BeforeIt == MBB->end())
3825 TargetReg = Reg; // Codegen the rest of the GEP into this
3831 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3832 /// frame manager, otherwise do it the hard way.
3834 void X86ISel::visitAllocaInst(AllocaInst &I) {
3835 // If this is a fixed size alloca in the entry block for the function, we
3836 // statically stack allocate the space, so we don't need to do anything here.
3838 if (dyn_castFixedAlloca(&I)) return;
3840 // Find the data size of the alloca inst's getAllocatedType.
3841 const Type *Ty = I.getAllocatedType();
3842 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3844 // Create a register to hold the temporary result of multiplying the type size
3845 // constant by the variable amount.
3846 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3847 unsigned SrcReg1 = getReg(I.getArraySize());
3849 // TotalSizeReg = mul <numelements>, <TypeSize>
3850 MachineBasicBlock::iterator MBBI = BB->end();
3851 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
3853 // AddedSize = add <TotalSizeReg>, 15
3854 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3855 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
3857 // AlignedSize = and <AddedSize>, ~15
3858 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3859 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
3861 // Subtract size from stack pointer, thereby allocating some space.
3862 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
3864 // Put a pointer to the space into the result register, by copying
3865 // the stack pointer.
3866 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
3868 // Inform the Frame Information that we have just allocated a variable-sized
3870 F->getFrameInfo()->CreateVariableSizedObject();
3873 /// visitMallocInst - Malloc instructions are code generated into direct calls
3874 /// to the library malloc.
3876 void X86ISel::visitMallocInst(MallocInst &I) {
3877 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3880 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3881 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3883 Arg = makeAnotherReg(Type::UIntTy);
3884 unsigned Op0Reg = getReg(I.getOperand(0));
3885 MachineBasicBlock::iterator MBBI = BB->end();
3886 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
3889 std::vector<ValueRecord> Args;
3890 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3891 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3892 1).addExternalSymbol("malloc", true);
3893 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3897 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3900 void X86ISel::visitFreeInst(FreeInst &I) {
3901 std::vector<ValueRecord> Args;
3902 Args.push_back(ValueRecord(I.getOperand(0)));
3903 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3904 1).addExternalSymbol("free", true);
3905 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3908 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
3909 /// into a machine code representation is a very simple peep-hole fashion. The
3910 /// generated code sucks but the implementation is nice and simple.
3912 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3913 return new X86ISel(TM);