1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Target/TargetOptions.h"
39 class X86FastISel : public FastISel {
40 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
41 /// make the right decision when generating code for different targets.
42 const X86Subtarget *Subtarget;
44 /// StackPtr - Register used as the stack pointer.
48 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
49 /// floating point ops.
50 /// When SSE is available, use it for f32 operations.
51 /// When SSE2 is available, use it for f64 operations.
56 explicit X86FastISel(MachineFunction &mf,
57 MachineModuleInfo *mmi,
59 DenseMap<const Value *, unsigned> &vm,
60 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
61 DenseMap<const AllocaInst *, int> &am
63 , SmallSet<Instruction*, 8> &cil
66 : FastISel(mf, mmi, dw, vm, bm, am
71 Subtarget = &TM.getSubtarget<X86Subtarget>();
72 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
77 virtual bool TargetSelectInstruction(Instruction *I);
79 #include "X86GenFastISel.inc"
82 bool X86FastEmitCompare(Value *LHS, Value *RHS, EVT VT);
84 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
86 bool X86FastEmitStore(EVT VT, Value *Val,
87 const X86AddressMode &AM);
88 bool X86FastEmitStore(EVT VT, unsigned Val,
89 const X86AddressMode &AM);
91 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
94 bool X86SelectAddress(Value *V, X86AddressMode &AM);
95 bool X86SelectCallAddress(Value *V, X86AddressMode &AM);
97 bool X86SelectLoad(Instruction *I);
99 bool X86SelectStore(Instruction *I);
101 bool X86SelectCmp(Instruction *I);
103 bool X86SelectZExt(Instruction *I);
105 bool X86SelectBranch(Instruction *I);
107 bool X86SelectOR(Instruction *I);
109 bool X86SelectShift(Instruction *I);
111 bool X86SelectSelect(Instruction *I);
113 bool X86SelectTrunc(Instruction *I);
115 bool X86SelectFPExt(Instruction *I);
116 bool X86SelectFPTrunc(Instruction *I);
118 bool X86SelectExtractValue(Instruction *I);
120 bool X86VisitIntrinsicCall(IntrinsicInst &I);
121 bool X86SelectCall(Instruction *I);
123 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool isTailCall = false);
125 const X86InstrInfo *getInstrInfo() const {
126 return getTargetMachine()->getInstrInfo();
128 const X86TargetMachine *getTargetMachine() const {
129 return static_cast<const X86TargetMachine *>(&TM);
132 unsigned TargetMaterializeConstant(Constant *C);
134 unsigned TargetMaterializeAlloca(AllocaInst *C);
136 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
137 /// computed in an SSE register, not on the X87 floating point stack.
138 bool isScalarFPTypeInSSEReg(EVT VT) const {
139 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
140 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
143 bool isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1 = false);
146 } // end anonymous namespace.
148 bool X86FastISel::isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1) {
149 VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
150 if (VT == MVT::Other || !VT.isSimple())
151 // Unhandled type. Halt "fast" selection and bail.
154 // For now, require SSE/SSE2 for performing floating-point operations,
155 // since x87 requires additional work.
156 if (VT == MVT::f64 && !X86ScalarSSEf64)
158 if (VT == MVT::f32 && !X86ScalarSSEf32)
160 // Similarly, no f80 support yet.
163 // We only handle legal types. For example, on x86-32 the instruction
164 // selector contains all of the 64-bit instructions from x86-64,
165 // under the assumption that i64 won't be used if the target doesn't
167 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
170 #include "X86GenCallingConv.inc"
172 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
174 CCAssignFn *X86FastISel::CCAssignFnForCall(CallingConv::ID CC,
176 if (Subtarget->is64Bit()) {
177 if (Subtarget->isTargetWin64())
178 return CC_X86_Win64_C;
183 if (CC == CallingConv::X86_FastCall)
184 return CC_X86_32_FastCall;
185 else if (CC == CallingConv::Fast)
186 return CC_X86_32_FastCC;
191 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
192 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
193 /// Return true and the result register by reference if it is possible.
194 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
195 unsigned &ResultReg) {
196 // Get opcode and regclass of the output for the given load instruction.
198 const TargetRegisterClass *RC = NULL;
199 switch (VT.getSimpleVT().SimpleTy) {
200 default: return false;
204 RC = X86::GR8RegisterClass;
208 RC = X86::GR16RegisterClass;
212 RC = X86::GR32RegisterClass;
215 // Must be in x86-64 mode.
217 RC = X86::GR64RegisterClass;
220 if (Subtarget->hasSSE1()) {
222 RC = X86::FR32RegisterClass;
225 RC = X86::RFP32RegisterClass;
229 if (Subtarget->hasSSE2()) {
231 RC = X86::FR64RegisterClass;
234 RC = X86::RFP64RegisterClass;
238 // No f80 support yet.
242 ResultReg = createResultReg(RC);
243 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
247 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
248 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
249 /// and a displacement offset, or a GlobalAddress,
250 /// i.e. V. Return true if it is possible.
252 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
253 const X86AddressMode &AM) {
254 // Get opcode and regclass of the output for the given store instruction.
256 switch (VT.getSimpleVT().SimpleTy) {
257 case MVT::f80: // No f80 support yet.
258 default: return false;
260 // Mask out all but lowest bit.
261 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
263 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
266 // FALLTHROUGH, handling i1 as i8.
267 case MVT::i8: Opc = X86::MOV8mr; break;
268 case MVT::i16: Opc = X86::MOV16mr; break;
269 case MVT::i32: Opc = X86::MOV32mr; break;
270 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
272 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
275 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
279 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM).addReg(Val);
283 bool X86FastISel::X86FastEmitStore(EVT VT, Value *Val,
284 const X86AddressMode &AM) {
285 // Handle 'null' like i32/i64 0.
286 if (isa<ConstantPointerNull>(Val))
287 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
289 // If this is a store of a simple constant, fold the constant into the store.
290 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
293 switch (VT.getSimpleVT().SimpleTy) {
295 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
296 case MVT::i8: Opc = X86::MOV8mi; break;
297 case MVT::i16: Opc = X86::MOV16mi; break;
298 case MVT::i32: Opc = X86::MOV32mi; break;
300 // Must be a 32-bit sign extended value.
301 if ((int)CI->getSExtValue() == CI->getSExtValue())
302 Opc = X86::MOV64mi32;
307 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM)
308 .addImm(Signed ? CI->getSExtValue() :
314 unsigned ValReg = getRegForValue(Val);
318 return X86FastEmitStore(VT, ValReg, AM);
321 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
322 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
323 /// ISD::SIGN_EXTEND).
324 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
325 unsigned Src, EVT SrcVT,
326 unsigned &ResultReg) {
327 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
336 /// X86SelectAddress - Attempt to fill in an address from the given value.
338 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM) {
340 unsigned Opcode = Instruction::UserOp1;
341 if (Instruction *I = dyn_cast<Instruction>(V)) {
342 Opcode = I->getOpcode();
344 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
345 Opcode = C->getOpcode();
351 case Instruction::BitCast:
352 // Look past bitcasts.
353 return X86SelectAddress(U->getOperand(0), AM);
355 case Instruction::IntToPtr:
356 // Look past no-op inttoptrs.
357 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
358 return X86SelectAddress(U->getOperand(0), AM);
361 case Instruction::PtrToInt:
362 // Look past no-op ptrtoints.
363 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
364 return X86SelectAddress(U->getOperand(0), AM);
367 case Instruction::Alloca: {
368 // Do static allocas.
369 const AllocaInst *A = cast<AllocaInst>(V);
370 DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
371 if (SI != StaticAllocaMap.end()) {
372 AM.BaseType = X86AddressMode::FrameIndexBase;
373 AM.Base.FrameIndex = SI->second;
379 case Instruction::Add: {
380 // Adds of constants are common and easy enough.
381 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
382 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
383 // They have to fit in the 32-bit signed displacement field though.
385 AM.Disp = (uint32_t)Disp;
386 return X86SelectAddress(U->getOperand(0), AM);
392 case Instruction::GetElementPtr: {
393 // Pattern-match simple GEPs.
394 uint64_t Disp = (int32_t)AM.Disp;
395 unsigned IndexReg = AM.IndexReg;
396 unsigned Scale = AM.Scale;
397 gep_type_iterator GTI = gep_type_begin(U);
398 // Iterate through the indices, folding what we can. Constants can be
399 // folded, and one dynamic index can be handled, if the scale is supported.
400 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
401 i != e; ++i, ++GTI) {
403 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
404 const StructLayout *SL = TD.getStructLayout(STy);
405 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
406 Disp += SL->getElementOffset(Idx);
408 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
410 // Constant-offset addressing.
411 Disp += CI->getSExtValue() * S;
412 } else if (IndexReg == 0 &&
413 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
414 (S == 1 || S == 2 || S == 4 || S == 8)) {
415 // Scaled-index addressing.
417 IndexReg = getRegForGEPIndex(Op);
422 goto unsupported_gep;
425 // Check for displacement overflow.
428 // Ok, the GEP indices were covered by constant-offset and scaled-index
429 // addressing. Update the address state and move on to examining the base.
430 AM.IndexReg = IndexReg;
432 AM.Disp = (uint32_t)Disp;
433 return X86SelectAddress(U->getOperand(0), AM);
435 // Ok, the GEP indices weren't all covered.
440 // Handle constant address.
441 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
442 // Can't handle alternate code models yet.
443 if (TM.getCodeModel() != CodeModel::Small)
446 // RIP-relative addresses can't have additional register operands.
447 if (Subtarget->isPICStyleRIPRel() &&
448 (AM.Base.Reg != 0 || AM.IndexReg != 0))
451 // Can't handle TLS yet.
452 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
453 if (GVar->isThreadLocal())
456 // Okay, we've committed to selecting this global. Set up the basic address.
459 // Allow the subtarget to classify the global.
460 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
462 // If this reference is relative to the pic base, set it now.
463 if (isGlobalRelativeToPICBase(GVFlags)) {
464 // FIXME: How do we know Base.Reg is free??
465 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
468 // Unless the ABI requires an extra load, return a direct reference to
470 if (!isGlobalStubReference(GVFlags)) {
471 if (Subtarget->isPICStyleRIPRel()) {
472 // Use rip-relative addressing if we can. Above we verified that the
473 // base and index registers are unused.
474 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
475 AM.Base.Reg = X86::RIP;
477 AM.GVOpFlags = GVFlags;
481 // Ok, we need to do a load from a stub. If we've already loaded from this
482 // stub, reuse the loaded pointer, otherwise emit the load now.
483 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
485 if (I != LocalValueMap.end() && I->second != 0) {
488 // Issue load from stub.
490 const TargetRegisterClass *RC = NULL;
491 X86AddressMode StubAM;
492 StubAM.Base.Reg = AM.Base.Reg;
494 StubAM.GVOpFlags = GVFlags;
496 if (TLI.getPointerTy() == MVT::i64) {
498 RC = X86::GR64RegisterClass;
500 if (Subtarget->isPICStyleRIPRel())
501 StubAM.Base.Reg = X86::RIP;
504 RC = X86::GR32RegisterClass;
507 LoadReg = createResultReg(RC);
508 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), LoadReg), StubAM);
510 // Prevent loading GV stub multiple times in same MBB.
511 LocalValueMap[V] = LoadReg;
514 // Now construct the final address. Note that the Disp, Scale,
515 // and Index values may already be set here.
516 AM.Base.Reg = LoadReg;
521 // If all else fails, try to materialize the value in a register.
522 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
523 if (AM.Base.Reg == 0) {
524 AM.Base.Reg = getRegForValue(V);
525 return AM.Base.Reg != 0;
527 if (AM.IndexReg == 0) {
528 assert(AM.Scale == 1 && "Scale with no index!");
529 AM.IndexReg = getRegForValue(V);
530 return AM.IndexReg != 0;
537 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
539 bool X86FastISel::X86SelectCallAddress(Value *V, X86AddressMode &AM) {
541 unsigned Opcode = Instruction::UserOp1;
542 if (Instruction *I = dyn_cast<Instruction>(V)) {
543 Opcode = I->getOpcode();
545 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
546 Opcode = C->getOpcode();
552 case Instruction::BitCast:
553 // Look past bitcasts.
554 return X86SelectCallAddress(U->getOperand(0), AM);
556 case Instruction::IntToPtr:
557 // Look past no-op inttoptrs.
558 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
559 return X86SelectCallAddress(U->getOperand(0), AM);
562 case Instruction::PtrToInt:
563 // Look past no-op ptrtoints.
564 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
565 return X86SelectCallAddress(U->getOperand(0), AM);
569 // Handle constant address.
570 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
571 // Can't handle alternate code models yet.
572 if (TM.getCodeModel() != CodeModel::Small)
575 // RIP-relative addresses can't have additional register operands.
576 if (Subtarget->isPICStyleRIPRel() &&
577 (AM.Base.Reg != 0 || AM.IndexReg != 0))
580 // Can't handle TLS or DLLImport.
581 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
582 if (GVar->isThreadLocal() || GVar->hasDLLImportLinkage())
585 // Okay, we've committed to selecting this global. Set up the basic address.
588 // No ABI requires an extra load for anything other than DLLImport, which
589 // we rejected above. Return a direct reference to the global.
590 if (Subtarget->isPICStyleRIPRel()) {
591 // Use rip-relative addressing if we can. Above we verified that the
592 // base and index registers are unused.
593 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
594 AM.Base.Reg = X86::RIP;
595 } else if (Subtarget->isPICStyleStubPIC()) {
596 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
597 } else if (Subtarget->isPICStyleGOT()) {
598 AM.GVOpFlags = X86II::MO_GOTOFF;
604 // If all else fails, try to materialize the value in a register.
605 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
606 if (AM.Base.Reg == 0) {
607 AM.Base.Reg = getRegForValue(V);
608 return AM.Base.Reg != 0;
610 if (AM.IndexReg == 0) {
611 assert(AM.Scale == 1 && "Scale with no index!");
612 AM.IndexReg = getRegForValue(V);
613 return AM.IndexReg != 0;
621 /// X86SelectStore - Select and emit code to implement store instructions.
622 bool X86FastISel::X86SelectStore(Instruction* I) {
624 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
628 if (!X86SelectAddress(I->getOperand(1), AM))
631 return X86FastEmitStore(VT, I->getOperand(0), AM);
634 /// X86SelectLoad - Select and emit code to implement load instructions.
636 bool X86FastISel::X86SelectLoad(Instruction *I) {
638 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
642 if (!X86SelectAddress(I->getOperand(0), AM))
645 unsigned ResultReg = 0;
646 if (X86FastEmitLoad(VT, AM, ResultReg)) {
647 UpdateValueMap(I, ResultReg);
653 static unsigned X86ChooseCmpOpcode(EVT VT) {
654 switch (VT.getSimpleVT().SimpleTy) {
656 case MVT::i8: return X86::CMP8rr;
657 case MVT::i16: return X86::CMP16rr;
658 case MVT::i32: return X86::CMP32rr;
659 case MVT::i64: return X86::CMP64rr;
660 case MVT::f32: return X86::UCOMISSrr;
661 case MVT::f64: return X86::UCOMISDrr;
665 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
666 /// of the comparison, return an opcode that works for the compare (e.g.
667 /// CMP32ri) otherwise return 0.
668 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, ConstantInt *RHSC) {
669 switch (VT.getSimpleVT().SimpleTy) {
670 // Otherwise, we can't fold the immediate into this comparison.
672 case MVT::i8: return X86::CMP8ri;
673 case MVT::i16: return X86::CMP16ri;
674 case MVT::i32: return X86::CMP32ri;
676 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
678 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
679 return X86::CMP64ri32;
684 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, EVT VT) {
685 unsigned Op0Reg = getRegForValue(Op0);
686 if (Op0Reg == 0) return false;
688 // Handle 'null' like i32/i64 0.
689 if (isa<ConstantPointerNull>(Op1))
690 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
692 // We have two options: compare with register or immediate. If the RHS of
693 // the compare is an immediate that we can fold into this compare, use
694 // CMPri, otherwise use CMPrr.
695 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
696 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
697 BuildMI(MBB, DL, TII.get(CompareImmOpc)).addReg(Op0Reg)
698 .addImm(Op1C->getSExtValue());
703 unsigned CompareOpc = X86ChooseCmpOpcode(VT);
704 if (CompareOpc == 0) return false;
706 unsigned Op1Reg = getRegForValue(Op1);
707 if (Op1Reg == 0) return false;
708 BuildMI(MBB, DL, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
713 bool X86FastISel::X86SelectCmp(Instruction *I) {
714 CmpInst *CI = cast<CmpInst>(I);
717 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
720 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
722 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
723 switch (CI->getPredicate()) {
724 case CmpInst::FCMP_OEQ: {
725 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
728 unsigned EReg = createResultReg(&X86::GR8RegClass);
729 unsigned NPReg = createResultReg(&X86::GR8RegClass);
730 BuildMI(MBB, DL, TII.get(X86::SETEr), EReg);
731 BuildMI(MBB, DL, TII.get(X86::SETNPr), NPReg);
733 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
734 UpdateValueMap(I, ResultReg);
737 case CmpInst::FCMP_UNE: {
738 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
741 unsigned NEReg = createResultReg(&X86::GR8RegClass);
742 unsigned PReg = createResultReg(&X86::GR8RegClass);
743 BuildMI(MBB, DL, TII.get(X86::SETNEr), NEReg);
744 BuildMI(MBB, DL, TII.get(X86::SETPr), PReg);
745 BuildMI(MBB, DL, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
746 UpdateValueMap(I, ResultReg);
749 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
750 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
751 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
752 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
753 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
754 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
755 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
756 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
757 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
758 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
759 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
760 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
762 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
763 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
764 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
765 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
766 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
767 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
768 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
769 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
770 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
771 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
776 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
780 // Emit a compare of Op0/Op1.
781 if (!X86FastEmitCompare(Op0, Op1, VT))
784 BuildMI(MBB, DL, TII.get(SetCCOpc), ResultReg);
785 UpdateValueMap(I, ResultReg);
789 bool X86FastISel::X86SelectZExt(Instruction *I) {
790 // Handle zero-extension from i1 to i8, which is common.
791 if (I->getType()->isInteger(8) &&
792 I->getOperand(0)->getType()->isInteger(1)) {
793 unsigned ResultReg = getRegForValue(I->getOperand(0));
794 if (ResultReg == 0) return false;
795 // Set the high bits to zero.
796 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg);
797 if (ResultReg == 0) return false;
798 UpdateValueMap(I, ResultReg);
806 bool X86FastISel::X86SelectBranch(Instruction *I) {
807 // Unconditional branches are selected by tablegen-generated code.
808 // Handle a conditional branch.
809 BranchInst *BI = cast<BranchInst>(I);
810 MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
811 MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
813 // Fold the common case of a conditional branch with a comparison.
814 if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
815 if (CI->hasOneUse()) {
816 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
818 // Try to take advantage of fallthrough opportunities.
819 CmpInst::Predicate Predicate = CI->getPredicate();
820 if (MBB->isLayoutSuccessor(TrueMBB)) {
821 std::swap(TrueMBB, FalseMBB);
822 Predicate = CmpInst::getInversePredicate(Predicate);
825 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
826 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
829 case CmpInst::FCMP_OEQ:
830 std::swap(TrueMBB, FalseMBB);
831 Predicate = CmpInst::FCMP_UNE;
833 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE; break;
834 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA; break;
835 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE; break;
836 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA; break;
837 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE; break;
838 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE; break;
839 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP; break;
840 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP; break;
841 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE; break;
842 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB; break;
843 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE; break;
844 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
845 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
847 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE; break;
848 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE; break;
849 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA; break;
850 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE; break;
851 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
852 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
853 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG; break;
854 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE; break;
855 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL; break;
856 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE; break;
861 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
865 // Emit a compare of the LHS and RHS, setting the flags.
866 if (!X86FastEmitCompare(Op0, Op1, VT))
869 BuildMI(MBB, DL, TII.get(BranchOpc)).addMBB(TrueMBB);
871 if (Predicate == CmpInst::FCMP_UNE) {
872 // X86 requires a second branch to handle UNE (and OEQ,
873 // which is mapped to UNE above).
874 BuildMI(MBB, DL, TII.get(X86::JP)).addMBB(TrueMBB);
877 FastEmitBranch(FalseMBB);
878 MBB->addSuccessor(TrueMBB);
881 } else if (ExtractValueInst *EI =
882 dyn_cast<ExtractValueInst>(BI->getCondition())) {
883 // Check to see if the branch instruction is from an "arithmetic with
884 // overflow" intrinsic. The main way these intrinsics are used is:
886 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
887 // %sum = extractvalue { i32, i1 } %t, 0
888 // %obit = extractvalue { i32, i1 } %t, 1
889 // br i1 %obit, label %overflow, label %normal
891 // The %sum and %obit are converted in an ADD and a SETO/SETB before
892 // reaching the branch. Therefore, we search backwards through the MBB
893 // looking for the SETO/SETB instruction. If an instruction modifies the
894 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
895 // convert the branch into a JO/JB instruction.
896 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
897 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
898 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
899 const MachineInstr *SetMI = 0;
900 unsigned Reg = lookUpRegForValue(EI);
902 for (MachineBasicBlock::const_reverse_iterator
903 RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
904 const MachineInstr &MI = *RI;
906 if (MI.modifiesRegister(Reg)) {
907 unsigned Src, Dst, SrcSR, DstSR;
909 if (getInstrInfo()->isMoveInstr(MI, Src, Dst, SrcSR, DstSR)) {
918 const TargetInstrDesc &TID = MI.getDesc();
919 if (TID.hasUnmodeledSideEffects() ||
920 TID.hasImplicitDefOfPhysReg(X86::EFLAGS))
925 unsigned OpCode = SetMI->getOpcode();
927 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
928 BuildMI(MBB, DL, TII.get(OpCode == X86::SETOr ? X86::JO : X86::JB))
930 FastEmitBranch(FalseMBB);
931 MBB->addSuccessor(TrueMBB);
939 // Otherwise do a clumsy setcc and re-test it.
940 unsigned OpReg = getRegForValue(BI->getCondition());
941 if (OpReg == 0) return false;
943 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
944 BuildMI(MBB, DL, TII.get(X86::JNE)).addMBB(TrueMBB);
945 FastEmitBranch(FalseMBB);
946 MBB->addSuccessor(TrueMBB);
950 bool X86FastISel::X86SelectOR(Instruction *I) {
951 // FIXME: This is necessary because tablegen stopped generate fastisel
952 // patterns after 93152 and 93191 (which turns OR to ADD if the set
953 // bits in the source operands are known not to overlap).
954 const TargetRegisterClass *RC = NULL;
955 unsigned OpReg = 0, OpImm = 0;
956 if (I->getType()->isInteger(16)) {
957 RC = X86::GR16RegisterClass;
958 OpReg = X86::OR16rr; OpImm = X86::OR16ri;
959 } else if (I->getType()->isInteger(32)) {
960 RC = X86::GR32RegisterClass;
961 OpReg = X86::OR32rr; OpImm = X86::OR32ri;
962 } else if (I->getType()->isInteger(64)) {
963 RC = X86::GR64RegisterClass;
964 OpReg = X86::OR32rr; OpImm = X86::OR32ri;
968 unsigned Op0Reg = getRegForValue(I->getOperand(0));
969 if (Op0Reg == 0) return false;
971 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
972 unsigned ResultReg = createResultReg(RC);
973 BuildMI(MBB, DL, TII.get(OpImm), ResultReg).addReg(Op0Reg)
974 .addImm(CI->getZExtValue());
975 UpdateValueMap(I, ResultReg);
979 unsigned Op1Reg = getRegForValue(I->getOperand(1));
980 if (Op1Reg == 0) return false;
982 unsigned ResultReg = createResultReg(RC);
983 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg).addReg(Op1Reg);
984 UpdateValueMap(I, ResultReg);
988 bool X86FastISel::X86SelectShift(Instruction *I) {
989 unsigned CReg = 0, OpReg = 0, OpImm = 0;
990 const TargetRegisterClass *RC = NULL;
991 if (I->getType()->isInteger(8)) {
993 RC = &X86::GR8RegClass;
994 switch (I->getOpcode()) {
995 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
996 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
997 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
998 default: return false;
1000 } else if (I->getType()->isInteger(16)) {
1002 RC = &X86::GR16RegClass;
1003 switch (I->getOpcode()) {
1004 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
1005 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
1006 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
1007 default: return false;
1009 } else if (I->getType()->isInteger(32)) {
1011 RC = &X86::GR32RegClass;
1012 switch (I->getOpcode()) {
1013 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
1014 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
1015 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
1016 default: return false;
1018 } else if (I->getType()->isInteger(64)) {
1020 RC = &X86::GR64RegClass;
1021 switch (I->getOpcode()) {
1022 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
1023 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
1024 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
1025 default: return false;
1031 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1032 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1035 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1036 if (Op0Reg == 0) return false;
1038 // Fold immediate in shl(x,3).
1039 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1040 unsigned ResultReg = createResultReg(RC);
1041 BuildMI(MBB, DL, TII.get(OpImm),
1042 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1043 UpdateValueMap(I, ResultReg);
1047 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1048 if (Op1Reg == 0) return false;
1049 TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
1051 // The shift instruction uses X86::CL. If we defined a super-register
1052 // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
1053 // we're doing here.
1054 if (CReg != X86::CL)
1055 BuildMI(MBB, DL, TII.get(TargetInstrInfo::EXTRACT_SUBREG), X86::CL)
1056 .addReg(CReg).addImm(X86::SUBREG_8BIT);
1058 unsigned ResultReg = createResultReg(RC);
1059 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg);
1060 UpdateValueMap(I, ResultReg);
1064 bool X86FastISel::X86SelectSelect(Instruction *I) {
1065 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1066 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1070 const TargetRegisterClass *RC = NULL;
1071 if (VT.getSimpleVT() == MVT::i16) {
1072 Opc = X86::CMOVE16rr;
1073 RC = &X86::GR16RegClass;
1074 } else if (VT.getSimpleVT() == MVT::i32) {
1075 Opc = X86::CMOVE32rr;
1076 RC = &X86::GR32RegClass;
1077 } else if (VT.getSimpleVT() == MVT::i64) {
1078 Opc = X86::CMOVE64rr;
1079 RC = &X86::GR64RegClass;
1084 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1085 if (Op0Reg == 0) return false;
1086 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1087 if (Op1Reg == 0) return false;
1088 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1089 if (Op2Reg == 0) return false;
1091 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
1092 unsigned ResultReg = createResultReg(RC);
1093 BuildMI(MBB, DL, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
1094 UpdateValueMap(I, ResultReg);
1098 bool X86FastISel::X86SelectFPExt(Instruction *I) {
1099 // fpext from float to double.
1100 if (Subtarget->hasSSE2() &&
1101 I->getType()->isDoubleTy()) {
1102 Value *V = I->getOperand(0);
1103 if (V->getType()->isFloatTy()) {
1104 unsigned OpReg = getRegForValue(V);
1105 if (OpReg == 0) return false;
1106 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1107 BuildMI(MBB, DL, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
1108 UpdateValueMap(I, ResultReg);
1116 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
1117 if (Subtarget->hasSSE2()) {
1118 if (I->getType()->isFloatTy()) {
1119 Value *V = I->getOperand(0);
1120 if (V->getType()->isDoubleTy()) {
1121 unsigned OpReg = getRegForValue(V);
1122 if (OpReg == 0) return false;
1123 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1124 BuildMI(MBB, DL, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
1125 UpdateValueMap(I, ResultReg);
1134 bool X86FastISel::X86SelectTrunc(Instruction *I) {
1135 if (Subtarget->is64Bit())
1136 // All other cases should be handled by the tblgen generated code.
1138 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1139 EVT DstVT = TLI.getValueType(I->getType());
1141 // This code only handles truncation to byte right now.
1142 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1143 // All other cases should be handled by the tblgen generated code.
1145 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1146 // All other cases should be handled by the tblgen generated code.
1149 unsigned InputReg = getRegForValue(I->getOperand(0));
1151 // Unhandled operand. Halt "fast" selection and bail.
1154 // First issue a copy to GR16_ABCD or GR32_ABCD.
1155 unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16rr : X86::MOV32rr;
1156 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1157 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1158 unsigned CopyReg = createResultReg(CopyRC);
1159 BuildMI(MBB, DL, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1161 // Then issue an extract_subreg.
1162 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1163 CopyReg, X86::SUBREG_8BIT);
1167 UpdateValueMap(I, ResultReg);
1171 bool X86FastISel::X86SelectExtractValue(Instruction *I) {
1172 ExtractValueInst *EI = cast<ExtractValueInst>(I);
1173 Value *Agg = EI->getAggregateOperand();
1175 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1176 switch (CI->getIntrinsicID()) {
1178 case Intrinsic::sadd_with_overflow:
1179 case Intrinsic::uadd_with_overflow:
1180 // Cheat a little. We know that the registers for "add" and "seto" are
1181 // allocated sequentially. However, we only keep track of the register
1182 // for "add" in the value map. Use extractvalue's index to get the
1183 // correct register for "seto".
1184 UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1192 bool X86FastISel::X86VisitIntrinsicCall(IntrinsicInst &I) {
1193 // FIXME: Handle more intrinsics.
1194 switch (I.getIntrinsicID()) {
1195 default: return false;
1196 case Intrinsic::sadd_with_overflow:
1197 case Intrinsic::uadd_with_overflow: {
1198 // Replace "add with overflow" intrinsics with an "add" instruction followed
1199 // by a seto/setc instruction. Later on, when the "extractvalue"
1200 // instructions are encountered, we use the fact that two registers were
1201 // created sequentially to get the correct registers for the "sum" and the
1203 const Function *Callee = I.getCalledFunction();
1205 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1208 if (!isTypeLegal(RetTy, VT))
1211 Value *Op1 = I.getOperand(1);
1212 Value *Op2 = I.getOperand(2);
1213 unsigned Reg1 = getRegForValue(Op1);
1214 unsigned Reg2 = getRegForValue(Op2);
1216 if (Reg1 == 0 || Reg2 == 0)
1217 // FIXME: Handle values *not* in registers.
1223 else if (VT == MVT::i64)
1228 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1229 BuildMI(MBB, DL, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1230 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1232 // If the add with overflow is an intra-block value then we just want to
1233 // create temporaries for it like normal. If it is a cross-block value then
1234 // UpdateValueMap will return the cross-block register used. Since we
1235 // *really* want the value to be live in the register pair known by
1236 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1237 // the cross block case. In the non-cross-block case, we should just make
1238 // another register for the value.
1239 if (DestReg1 != ResultReg)
1240 ResultReg = DestReg1+1;
1242 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1244 unsigned Opc = X86::SETBr;
1245 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1247 BuildMI(MBB, DL, TII.get(Opc), ResultReg);
1253 bool X86FastISel::X86SelectCall(Instruction *I) {
1254 CallInst *CI = cast<CallInst>(I);
1255 Value *Callee = I->getOperand(0);
1257 // Can't handle inline asm yet.
1258 if (isa<InlineAsm>(Callee))
1261 // Handle intrinsic calls.
1262 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1263 return X86VisitIntrinsicCall(*II);
1265 // Handle only C and fastcc calling conventions for now.
1267 CallingConv::ID CC = CS.getCallingConv();
1268 if (CC != CallingConv::C &&
1269 CC != CallingConv::Fast &&
1270 CC != CallingConv::X86_FastCall)
1273 // fastcc with -tailcallopt is intended to provide a guaranteed
1274 // tail call optimization. Fastisel doesn't know how to do that.
1275 if (CC == CallingConv::Fast && PerformTailCallOpt)
1278 // Let SDISel handle vararg functions.
1279 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1280 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1281 if (FTy->isVarArg())
1284 // Handle *simple* calls for now.
1285 const Type *RetTy = CS.getType();
1287 if (RetTy->isVoidTy())
1288 RetVT = MVT::isVoid;
1289 else if (!isTypeLegal(RetTy, RetVT, true))
1292 // Materialize callee address in a register. FIXME: GV address can be
1293 // handled with a CALLpcrel32 instead.
1294 X86AddressMode CalleeAM;
1295 if (!X86SelectCallAddress(Callee, CalleeAM))
1297 unsigned CalleeOp = 0;
1298 GlobalValue *GV = 0;
1299 if (CalleeAM.GV != 0) {
1301 } else if (CalleeAM.Base.Reg != 0) {
1302 CalleeOp = CalleeAM.Base.Reg;
1306 // Allow calls which produce i1 results.
1307 bool AndToI1 = false;
1308 if (RetVT == MVT::i1) {
1313 // Deal with call operands first.
1314 SmallVector<Value*, 8> ArgVals;
1315 SmallVector<unsigned, 8> Args;
1316 SmallVector<EVT, 8> ArgVTs;
1317 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1318 Args.reserve(CS.arg_size());
1319 ArgVals.reserve(CS.arg_size());
1320 ArgVTs.reserve(CS.arg_size());
1321 ArgFlags.reserve(CS.arg_size());
1322 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1324 unsigned Arg = getRegForValue(*i);
1327 ISD::ArgFlagsTy Flags;
1328 unsigned AttrInd = i - CS.arg_begin() + 1;
1329 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1331 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1334 // FIXME: Only handle *easy* calls for now.
1335 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1336 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1337 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1338 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1341 const Type *ArgTy = (*i)->getType();
1343 if (!isTypeLegal(ArgTy, ArgVT))
1345 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1346 Flags.setOrigAlign(OriginalAlignment);
1348 Args.push_back(Arg);
1349 ArgVals.push_back(*i);
1350 ArgVTs.push_back(ArgVT);
1351 ArgFlags.push_back(Flags);
1354 // Analyze operands of the call, assigning locations to each operand.
1355 SmallVector<CCValAssign, 16> ArgLocs;
1356 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1357 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1359 // Get a count of how many bytes are to be pushed on the stack.
1360 unsigned NumBytes = CCInfo.getNextStackOffset();
1362 // Issue CALLSEQ_START
1363 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1364 BuildMI(MBB, DL, TII.get(AdjStackDown)).addImm(NumBytes);
1366 // Process argument: walk the register/memloc assignments, inserting
1368 SmallVector<unsigned, 4> RegArgs;
1369 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1370 CCValAssign &VA = ArgLocs[i];
1371 unsigned Arg = Args[VA.getValNo()];
1372 EVT ArgVT = ArgVTs[VA.getValNo()];
1374 // Promote the value if needed.
1375 switch (VA.getLocInfo()) {
1376 default: llvm_unreachable("Unknown loc info!");
1377 case CCValAssign::Full: break;
1378 case CCValAssign::SExt: {
1379 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1381 assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1383 ArgVT = VA.getLocVT();
1386 case CCValAssign::ZExt: {
1387 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1389 assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1391 ArgVT = VA.getLocVT();
1394 case CCValAssign::AExt: {
1395 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1398 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1401 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1404 assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1405 ArgVT = VA.getLocVT();
1408 case CCValAssign::BCvt: {
1409 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT().getSimpleVT(),
1410 ISD::BIT_CONVERT, Arg);
1411 assert(BC != 0 && "Failed to emit a bitcast!");
1413 ArgVT = VA.getLocVT();
1418 if (VA.isRegLoc()) {
1419 TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1420 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1422 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1424 RegArgs.push_back(VA.getLocReg());
1426 unsigned LocMemOffset = VA.getLocMemOffset();
1428 AM.Base.Reg = StackPtr;
1429 AM.Disp = LocMemOffset;
1430 Value *ArgVal = ArgVals[VA.getValNo()];
1432 // If this is a really simple value, emit this with the Value* version of
1433 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1434 // can cause us to reevaluate the argument.
1435 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1436 X86FastEmitStore(ArgVT, ArgVal, AM);
1438 X86FastEmitStore(ArgVT, Arg, AM);
1442 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1444 if (Subtarget->isPICStyleGOT()) {
1445 TargetRegisterClass *RC = X86::GR32RegisterClass;
1446 unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1447 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1448 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1453 MachineInstrBuilder MIB;
1455 // Register-indirect call.
1456 unsigned CallOpc = Subtarget->is64Bit() ? X86::CALL64r : X86::CALL32r;
1457 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addReg(CalleeOp);
1461 assert(GV && "Not a direct call");
1463 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
1465 // See if we need any target-specific flags on the GV operand.
1466 unsigned char OpFlags = 0;
1468 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1469 // external symbols most go through the PLT in PIC mode. If the symbol
1470 // has hidden or protected visibility, or if it is static or local, then
1471 // we don't need to use the PLT - we can directly call it.
1472 if (Subtarget->isTargetELF() &&
1473 TM.getRelocationModel() == Reloc::PIC_ &&
1474 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1475 OpFlags = X86II::MO_PLT;
1476 } else if (Subtarget->isPICStyleStubAny() &&
1477 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1478 Subtarget->getDarwinVers() < 9) {
1479 // PC-relative references to external symbols should go through $stub,
1480 // unless we're building with the leopard linker or later, which
1481 // automatically synthesizes these stubs.
1482 OpFlags = X86II::MO_DARWIN_STUB;
1486 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addGlobalAddress(GV, 0, OpFlags);
1489 // Add an implicit use GOT pointer in EBX.
1490 if (Subtarget->isPICStyleGOT())
1491 MIB.addReg(X86::EBX);
1493 // Add implicit physical register uses to the call.
1494 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1495 MIB.addReg(RegArgs[i]);
1497 // Issue CALLSEQ_END
1498 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1499 BuildMI(MBB, DL, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1501 // Now handle call return value (if any).
1502 if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1503 SmallVector<CCValAssign, 16> RVLocs;
1504 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1505 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1507 // Copy all of the result registers out of their specified physreg.
1508 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1509 EVT CopyVT = RVLocs[0].getValVT();
1510 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1511 TargetRegisterClass *SrcRC = DstRC;
1513 // If this is a call to a function that returns an fp value on the x87 fp
1514 // stack, but where we prefer to use the value in xmm registers, copy it
1515 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1516 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1517 RVLocs[0].getLocReg() == X86::ST1) &&
1518 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1520 SrcRC = X86::RSTRegisterClass;
1521 DstRC = X86::RFP80RegisterClass;
1524 unsigned ResultReg = createResultReg(DstRC);
1525 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1526 RVLocs[0].getLocReg(), DstRC, SrcRC);
1527 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1529 if (CopyVT != RVLocs[0].getValVT()) {
1530 // Round the F80 the right size, which also moves to the appropriate xmm
1531 // register. This is accomplished by storing the F80 value in memory and
1532 // then loading it back. Ewww...
1533 EVT ResVT = RVLocs[0].getValVT();
1534 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1535 unsigned MemSize = ResVT.getSizeInBits()/8;
1536 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1537 addFrameReference(BuildMI(MBB, DL, TII.get(Opc)), FI).addReg(ResultReg);
1538 DstRC = ResVT == MVT::f32
1539 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1540 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1541 ResultReg = createResultReg(DstRC);
1542 addFrameReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg), FI);
1546 // Mask out all but lowest bit for some call which produces an i1.
1547 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1549 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1550 ResultReg = AndResult;
1553 UpdateValueMap(I, ResultReg);
1561 X86FastISel::TargetSelectInstruction(Instruction *I) {
1562 switch (I->getOpcode()) {
1564 case Instruction::Load:
1565 return X86SelectLoad(I);
1566 case Instruction::Store:
1567 return X86SelectStore(I);
1568 case Instruction::ICmp:
1569 case Instruction::FCmp:
1570 return X86SelectCmp(I);
1571 case Instruction::ZExt:
1572 return X86SelectZExt(I);
1573 case Instruction::Br:
1574 return X86SelectBranch(I);
1575 case Instruction::Call:
1576 return X86SelectCall(I);
1577 case Instruction::Or:
1578 return X86SelectOR(I);
1579 case Instruction::LShr:
1580 case Instruction::AShr:
1581 case Instruction::Shl:
1582 return X86SelectShift(I);
1583 case Instruction::Select:
1584 return X86SelectSelect(I);
1585 case Instruction::Trunc:
1586 return X86SelectTrunc(I);
1587 case Instruction::FPExt:
1588 return X86SelectFPExt(I);
1589 case Instruction::FPTrunc:
1590 return X86SelectFPTrunc(I);
1591 case Instruction::ExtractValue:
1592 return X86SelectExtractValue(I);
1593 case Instruction::IntToPtr: // Deliberate fall-through.
1594 case Instruction::PtrToInt: {
1595 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1596 EVT DstVT = TLI.getValueType(I->getType());
1597 if (DstVT.bitsGT(SrcVT))
1598 return X86SelectZExt(I);
1599 if (DstVT.bitsLT(SrcVT))
1600 return X86SelectTrunc(I);
1601 unsigned Reg = getRegForValue(I->getOperand(0));
1602 if (Reg == 0) return false;
1603 UpdateValueMap(I, Reg);
1611 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1613 if (!isTypeLegal(C->getType(), VT))
1616 // Get opcode and regclass of the output for the given load instruction.
1618 const TargetRegisterClass *RC = NULL;
1619 switch (VT.getSimpleVT().SimpleTy) {
1620 default: return false;
1623 RC = X86::GR8RegisterClass;
1627 RC = X86::GR16RegisterClass;
1631 RC = X86::GR32RegisterClass;
1634 // Must be in x86-64 mode.
1636 RC = X86::GR64RegisterClass;
1639 if (Subtarget->hasSSE1()) {
1641 RC = X86::FR32RegisterClass;
1643 Opc = X86::LD_Fp32m;
1644 RC = X86::RFP32RegisterClass;
1648 if (Subtarget->hasSSE2()) {
1650 RC = X86::FR64RegisterClass;
1652 Opc = X86::LD_Fp64m;
1653 RC = X86::RFP64RegisterClass;
1657 // No f80 support yet.
1661 // Materialize addresses with LEA instructions.
1662 if (isa<GlobalValue>(C)) {
1664 if (X86SelectAddress(C, AM)) {
1665 if (TLI.getPointerTy() == MVT::i32)
1669 unsigned ResultReg = createResultReg(RC);
1670 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1676 // MachineConstantPool wants an explicit alignment.
1677 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1679 // Alignment of vector types. FIXME!
1680 Align = TD.getTypeAllocSize(C->getType());
1683 // x86-32 PIC requires a PIC base register for constant pools.
1684 unsigned PICBase = 0;
1685 unsigned char OpFlag = 0;
1686 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1687 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1688 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1689 } else if (Subtarget->isPICStyleGOT()) {
1690 OpFlag = X86II::MO_GOTOFF;
1691 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1692 } else if (Subtarget->isPICStyleRIPRel() &&
1693 TM.getCodeModel() == CodeModel::Small) {
1697 // Create the load from the constant pool.
1698 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1699 unsigned ResultReg = createResultReg(RC);
1700 addConstantPoolReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg),
1701 MCPOffset, PICBase, OpFlag);
1706 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1707 // Fail on dynamic allocas. At this point, getRegForValue has already
1708 // checked its CSE maps, so if we're here trying to handle a dynamic
1709 // alloca, we're not going to succeed. X86SelectAddress has a
1710 // check for dynamic allocas, because it's called directly from
1711 // various places, but TargetMaterializeAlloca also needs a check
1712 // in order to avoid recursion between getRegForValue,
1713 // X86SelectAddrss, and TargetMaterializeAlloca.
1714 if (!StaticAllocaMap.count(C))
1718 if (!X86SelectAddress(C, AM))
1720 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1721 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1722 unsigned ResultReg = createResultReg(RC);
1723 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1728 llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1729 MachineModuleInfo *mmi,
1731 DenseMap<const Value *, unsigned> &vm,
1732 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1733 DenseMap<const AllocaInst *, int> &am
1735 , SmallSet<Instruction*, 8> &cil
1738 return new X86FastISel(mf, mmi, dw, vm, bm, am