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 X86SelectShift(Instruction *I);
109 bool X86SelectSelect(Instruction *I);
111 bool X86SelectTrunc(Instruction *I);
113 bool X86SelectFPExt(Instruction *I);
114 bool X86SelectFPTrunc(Instruction *I);
116 bool X86SelectExtractValue(Instruction *I);
118 bool X86VisitIntrinsicCall(IntrinsicInst &I);
119 bool X86SelectCall(Instruction *I);
121 CCAssignFn *CCAssignFnForCall(unsigned CC, bool isTailCall = false);
123 const X86InstrInfo *getInstrInfo() const {
124 return getTargetMachine()->getInstrInfo();
126 const X86TargetMachine *getTargetMachine() const {
127 return static_cast<const X86TargetMachine *>(&TM);
130 unsigned TargetMaterializeConstant(Constant *C);
132 unsigned TargetMaterializeAlloca(AllocaInst *C);
134 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
135 /// computed in an SSE register, not on the X87 floating point stack.
136 bool isScalarFPTypeInSSEReg(EVT VT) const {
137 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
138 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
141 bool isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1 = false);
144 } // end anonymous namespace.
146 bool X86FastISel::isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1) {
147 VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
148 if (VT == MVT::Other || !VT.isSimple())
149 // Unhandled type. Halt "fast" selection and bail.
152 // For now, require SSE/SSE2 for performing floating-point operations,
153 // since x87 requires additional work.
154 if (VT == MVT::f64 && !X86ScalarSSEf64)
156 if (VT == MVT::f32 && !X86ScalarSSEf32)
158 // Similarly, no f80 support yet.
161 // We only handle legal types. For example, on x86-32 the instruction
162 // selector contains all of the 64-bit instructions from x86-64,
163 // under the assumption that i64 won't be used if the target doesn't
165 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
168 #include "X86GenCallingConv.inc"
170 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
172 CCAssignFn *X86FastISel::CCAssignFnForCall(unsigned CC, bool isTaillCall) {
173 if (Subtarget->is64Bit()) {
174 if (Subtarget->isTargetWin64())
175 return CC_X86_Win64_C;
180 if (CC == CallingConv::X86_FastCall)
181 return CC_X86_32_FastCall;
182 else if (CC == CallingConv::Fast)
183 return CC_X86_32_FastCC;
188 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
189 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
190 /// Return true and the result register by reference if it is possible.
191 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
192 unsigned &ResultReg) {
193 // Get opcode and regclass of the output for the given load instruction.
195 const TargetRegisterClass *RC = NULL;
196 switch (VT.getSimpleVT().SimpleTy) {
197 default: return false;
201 RC = X86::GR8RegisterClass;
205 RC = X86::GR16RegisterClass;
209 RC = X86::GR32RegisterClass;
212 // Must be in x86-64 mode.
214 RC = X86::GR64RegisterClass;
217 if (Subtarget->hasSSE1()) {
219 RC = X86::FR32RegisterClass;
222 RC = X86::RFP32RegisterClass;
226 if (Subtarget->hasSSE2()) {
228 RC = X86::FR64RegisterClass;
231 RC = X86::RFP64RegisterClass;
235 // No f80 support yet.
239 ResultReg = createResultReg(RC);
240 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
244 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
245 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
246 /// and a displacement offset, or a GlobalAddress,
247 /// i.e. V. Return true if it is possible.
249 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
250 const X86AddressMode &AM) {
251 // Get opcode and regclass of the output for the given store instruction.
253 switch (VT.getSimpleVT().SimpleTy) {
254 case MVT::f80: // No f80 support yet.
255 default: return false;
257 // Mask out all but lowest bit.
258 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
260 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
263 // FALLTHROUGH, handling i1 as i8.
264 case MVT::i8: Opc = X86::MOV8mr; break;
265 case MVT::i16: Opc = X86::MOV16mr; break;
266 case MVT::i32: Opc = X86::MOV32mr; break;
267 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
269 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
272 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
276 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM).addReg(Val);
280 bool X86FastISel::X86FastEmitStore(EVT VT, Value *Val,
281 const X86AddressMode &AM) {
282 // Handle 'null' like i32/i64 0.
283 if (isa<ConstantPointerNull>(Val))
284 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
286 // If this is a store of a simple constant, fold the constant into the store.
287 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
290 switch (VT.getSimpleVT().SimpleTy) {
292 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
293 case MVT::i8: Opc = X86::MOV8mi; break;
294 case MVT::i16: Opc = X86::MOV16mi; break;
295 case MVT::i32: Opc = X86::MOV32mi; break;
297 // Must be a 32-bit sign extended value.
298 if ((int)CI->getSExtValue() == CI->getSExtValue())
299 Opc = X86::MOV64mi32;
304 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM)
305 .addImm(Signed ? CI->getSExtValue() :
311 unsigned ValReg = getRegForValue(Val);
315 return X86FastEmitStore(VT, ValReg, AM);
318 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
319 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
320 /// ISD::SIGN_EXTEND).
321 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
322 unsigned Src, EVT SrcVT,
323 unsigned &ResultReg) {
324 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
333 /// X86SelectAddress - Attempt to fill in an address from the given value.
335 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM) {
337 unsigned Opcode = Instruction::UserOp1;
338 if (Instruction *I = dyn_cast<Instruction>(V)) {
339 Opcode = I->getOpcode();
341 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
342 Opcode = C->getOpcode();
348 case Instruction::BitCast:
349 // Look past bitcasts.
350 return X86SelectAddress(U->getOperand(0), AM);
352 case Instruction::IntToPtr:
353 // Look past no-op inttoptrs.
354 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
355 return X86SelectAddress(U->getOperand(0), AM);
358 case Instruction::PtrToInt:
359 // Look past no-op ptrtoints.
360 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
361 return X86SelectAddress(U->getOperand(0), AM);
364 case Instruction::Alloca: {
365 // Do static allocas.
366 const AllocaInst *A = cast<AllocaInst>(V);
367 DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
368 if (SI != StaticAllocaMap.end()) {
369 AM.BaseType = X86AddressMode::FrameIndexBase;
370 AM.Base.FrameIndex = SI->second;
376 case Instruction::Add: {
377 // Adds of constants are common and easy enough.
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
379 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
380 // They have to fit in the 32-bit signed displacement field though.
382 AM.Disp = (uint32_t)Disp;
383 return X86SelectAddress(U->getOperand(0), AM);
389 case Instruction::GetElementPtr: {
390 // Pattern-match simple GEPs.
391 uint64_t Disp = (int32_t)AM.Disp;
392 unsigned IndexReg = AM.IndexReg;
393 unsigned Scale = AM.Scale;
394 gep_type_iterator GTI = gep_type_begin(U);
395 // Iterate through the indices, folding what we can. Constants can be
396 // folded, and one dynamic index can be handled, if the scale is supported.
397 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
398 i != e; ++i, ++GTI) {
400 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
401 const StructLayout *SL = TD.getStructLayout(STy);
402 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
403 Disp += SL->getElementOffset(Idx);
405 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
407 // Constant-offset addressing.
408 Disp += CI->getSExtValue() * S;
409 } else if (IndexReg == 0 &&
410 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
411 (S == 1 || S == 2 || S == 4 || S == 8)) {
412 // Scaled-index addressing.
414 IndexReg = getRegForGEPIndex(Op);
419 goto unsupported_gep;
422 // Check for displacement overflow.
425 // Ok, the GEP indices were covered by constant-offset and scaled-index
426 // addressing. Update the address state and move on to examining the base.
427 AM.IndexReg = IndexReg;
429 AM.Disp = (uint32_t)Disp;
430 return X86SelectAddress(U->getOperand(0), AM);
432 // Ok, the GEP indices weren't all covered.
437 // Handle constant address.
438 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
439 // Can't handle alternate code models yet.
440 if (TM.getCodeModel() != CodeModel::Small)
443 // RIP-relative addresses can't have additional register operands.
444 if (Subtarget->isPICStyleRIPRel() &&
445 (AM.Base.Reg != 0 || AM.IndexReg != 0))
448 // Can't handle TLS yet.
449 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
450 if (GVar->isThreadLocal())
453 // Okay, we've committed to selecting this global. Set up the basic address.
456 // Allow the subtarget to classify the global.
457 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
459 // If this reference is relative to the pic base, set it now.
460 if (isGlobalRelativeToPICBase(GVFlags)) {
461 // FIXME: How do we know Base.Reg is free??
462 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
465 // Unless the ABI requires an extra load, return a direct reference to
467 if (!isGlobalStubReference(GVFlags)) {
468 if (Subtarget->isPICStyleRIPRel()) {
469 // Use rip-relative addressing if we can. Above we verified that the
470 // base and index registers are unused.
471 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
472 AM.Base.Reg = X86::RIP;
474 AM.GVOpFlags = GVFlags;
478 // Ok, we need to do a load from a stub. If we've already loaded from this
479 // stub, reuse the loaded pointer, otherwise emit the load now.
480 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
482 if (I != LocalValueMap.end() && I->second != 0) {
485 // Issue load from stub.
487 const TargetRegisterClass *RC = NULL;
488 X86AddressMode StubAM;
489 StubAM.Base.Reg = AM.Base.Reg;
491 StubAM.GVOpFlags = GVFlags;
493 if (TLI.getPointerTy() == MVT::i64) {
495 RC = X86::GR64RegisterClass;
497 if (Subtarget->isPICStyleRIPRel())
498 StubAM.Base.Reg = X86::RIP;
501 RC = X86::GR32RegisterClass;
504 LoadReg = createResultReg(RC);
505 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), LoadReg), StubAM);
507 // Prevent loading GV stub multiple times in same MBB.
508 LocalValueMap[V] = LoadReg;
511 // Now construct the final address. Note that the Disp, Scale,
512 // and Index values may already be set here.
513 AM.Base.Reg = LoadReg;
518 // If all else fails, try to materialize the value in a register.
519 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
520 if (AM.Base.Reg == 0) {
521 AM.Base.Reg = getRegForValue(V);
522 return AM.Base.Reg != 0;
524 if (AM.IndexReg == 0) {
525 assert(AM.Scale == 1 && "Scale with no index!");
526 AM.IndexReg = getRegForValue(V);
527 return AM.IndexReg != 0;
534 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
536 bool X86FastISel::X86SelectCallAddress(Value *V, X86AddressMode &AM) {
538 unsigned Opcode = Instruction::UserOp1;
539 if (Instruction *I = dyn_cast<Instruction>(V)) {
540 Opcode = I->getOpcode();
542 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
543 Opcode = C->getOpcode();
549 case Instruction::BitCast:
550 // Look past bitcasts.
551 return X86SelectCallAddress(U->getOperand(0), AM);
553 case Instruction::IntToPtr:
554 // Look past no-op inttoptrs.
555 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
556 return X86SelectCallAddress(U->getOperand(0), AM);
559 case Instruction::PtrToInt:
560 // Look past no-op ptrtoints.
561 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
562 return X86SelectCallAddress(U->getOperand(0), AM);
566 // Handle constant address.
567 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
568 // Can't handle alternate code models yet.
569 if (TM.getCodeModel() != CodeModel::Small)
572 // RIP-relative addresses can't have additional register operands.
573 if (Subtarget->isPICStyleRIPRel() &&
574 (AM.Base.Reg != 0 || AM.IndexReg != 0))
577 // Can't handle TLS or DLLImport.
578 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
579 if (GVar->isThreadLocal() || GVar->hasDLLImportLinkage())
582 // Okay, we've committed to selecting this global. Set up the basic address.
585 // No ABI requires an extra load for anything other than DLLImport, which
586 // we rejected above. Return a direct reference to the global.
587 if (Subtarget->isPICStyleRIPRel()) {
588 // Use rip-relative addressing if we can. Above we verified that the
589 // base and index registers are unused.
590 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
591 AM.Base.Reg = X86::RIP;
592 } else if (Subtarget->isPICStyleStubPIC()) {
593 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
594 } else if (Subtarget->isPICStyleGOT()) {
595 AM.GVOpFlags = X86II::MO_GOTOFF;
601 // If all else fails, try to materialize the value in a register.
602 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
603 if (AM.Base.Reg == 0) {
604 AM.Base.Reg = getRegForValue(V);
605 return AM.Base.Reg != 0;
607 if (AM.IndexReg == 0) {
608 assert(AM.Scale == 1 && "Scale with no index!");
609 AM.IndexReg = getRegForValue(V);
610 return AM.IndexReg != 0;
618 /// X86SelectStore - Select and emit code to implement store instructions.
619 bool X86FastISel::X86SelectStore(Instruction* I) {
621 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
625 if (!X86SelectAddress(I->getOperand(1), AM))
628 return X86FastEmitStore(VT, I->getOperand(0), AM);
631 /// X86SelectLoad - Select and emit code to implement load instructions.
633 bool X86FastISel::X86SelectLoad(Instruction *I) {
635 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
639 if (!X86SelectAddress(I->getOperand(0), AM))
642 unsigned ResultReg = 0;
643 if (X86FastEmitLoad(VT, AM, ResultReg)) {
644 UpdateValueMap(I, ResultReg);
650 static unsigned X86ChooseCmpOpcode(EVT VT) {
651 switch (VT.getSimpleVT().SimpleTy) {
653 case MVT::i8: return X86::CMP8rr;
654 case MVT::i16: return X86::CMP16rr;
655 case MVT::i32: return X86::CMP32rr;
656 case MVT::i64: return X86::CMP64rr;
657 case MVT::f32: return X86::UCOMISSrr;
658 case MVT::f64: return X86::UCOMISDrr;
662 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
663 /// of the comparison, return an opcode that works for the compare (e.g.
664 /// CMP32ri) otherwise return 0.
665 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, ConstantInt *RHSC) {
666 switch (VT.getSimpleVT().SimpleTy) {
667 // Otherwise, we can't fold the immediate into this comparison.
669 case MVT::i8: return X86::CMP8ri;
670 case MVT::i16: return X86::CMP16ri;
671 case MVT::i32: return X86::CMP32ri;
673 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
675 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
676 return X86::CMP64ri32;
681 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, EVT VT) {
682 unsigned Op0Reg = getRegForValue(Op0);
683 if (Op0Reg == 0) return false;
685 // Handle 'null' like i32/i64 0.
686 if (isa<ConstantPointerNull>(Op1))
687 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
689 // We have two options: compare with register or immediate. If the RHS of
690 // the compare is an immediate that we can fold into this compare, use
691 // CMPri, otherwise use CMPrr.
692 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
693 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
694 BuildMI(MBB, DL, TII.get(CompareImmOpc)).addReg(Op0Reg)
695 .addImm(Op1C->getSExtValue());
700 unsigned CompareOpc = X86ChooseCmpOpcode(VT);
701 if (CompareOpc == 0) return false;
703 unsigned Op1Reg = getRegForValue(Op1);
704 if (Op1Reg == 0) return false;
705 BuildMI(MBB, DL, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
710 bool X86FastISel::X86SelectCmp(Instruction *I) {
711 CmpInst *CI = cast<CmpInst>(I);
714 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
717 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
719 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
720 switch (CI->getPredicate()) {
721 case CmpInst::FCMP_OEQ: {
722 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
725 unsigned EReg = createResultReg(&X86::GR8RegClass);
726 unsigned NPReg = createResultReg(&X86::GR8RegClass);
727 BuildMI(MBB, DL, TII.get(X86::SETEr), EReg);
728 BuildMI(MBB, DL, TII.get(X86::SETNPr), NPReg);
730 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
731 UpdateValueMap(I, ResultReg);
734 case CmpInst::FCMP_UNE: {
735 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
738 unsigned NEReg = createResultReg(&X86::GR8RegClass);
739 unsigned PReg = createResultReg(&X86::GR8RegClass);
740 BuildMI(MBB, DL, TII.get(X86::SETNEr), NEReg);
741 BuildMI(MBB, DL, TII.get(X86::SETPr), PReg);
742 BuildMI(MBB, DL, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
743 UpdateValueMap(I, ResultReg);
746 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
747 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
748 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
749 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
750 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
751 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
752 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
753 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
754 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
755 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
756 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
757 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
759 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
760 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
761 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
762 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
763 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
764 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
765 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
766 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
767 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
768 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
773 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
777 // Emit a compare of Op0/Op1.
778 if (!X86FastEmitCompare(Op0, Op1, VT))
781 BuildMI(MBB, DL, TII.get(SetCCOpc), ResultReg);
782 UpdateValueMap(I, ResultReg);
786 bool X86FastISel::X86SelectZExt(Instruction *I) {
787 // Handle zero-extension from i1 to i8, which is common.
788 if (I->getType() == Type::getInt8Ty(I->getContext()) &&
789 I->getOperand(0)->getType() == Type::getInt1Ty(I->getContext())) {
790 unsigned ResultReg = getRegForValue(I->getOperand(0));
791 if (ResultReg == 0) return false;
792 // Set the high bits to zero.
793 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg);
794 if (ResultReg == 0) return false;
795 UpdateValueMap(I, ResultReg);
803 bool X86FastISel::X86SelectBranch(Instruction *I) {
804 // Unconditional branches are selected by tablegen-generated code.
805 // Handle a conditional branch.
806 BranchInst *BI = cast<BranchInst>(I);
807 MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
808 MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
810 // Fold the common case of a conditional branch with a comparison.
811 if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
812 if (CI->hasOneUse()) {
813 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
815 // Try to take advantage of fallthrough opportunities.
816 CmpInst::Predicate Predicate = CI->getPredicate();
817 if (MBB->isLayoutSuccessor(TrueMBB)) {
818 std::swap(TrueMBB, FalseMBB);
819 Predicate = CmpInst::getInversePredicate(Predicate);
822 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
823 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
826 case CmpInst::FCMP_OEQ:
827 std::swap(TrueMBB, FalseMBB);
828 Predicate = CmpInst::FCMP_UNE;
830 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE; break;
831 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA; break;
832 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE; break;
833 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA; break;
834 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE; break;
835 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE; break;
836 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP; break;
837 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP; break;
838 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE; break;
839 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB; break;
840 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE; break;
841 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
842 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
844 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE; break;
845 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE; break;
846 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA; break;
847 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE; break;
848 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
849 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
850 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG; break;
851 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE; break;
852 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL; break;
853 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE; break;
858 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
862 // Emit a compare of the LHS and RHS, setting the flags.
863 if (!X86FastEmitCompare(Op0, Op1, VT))
866 BuildMI(MBB, DL, TII.get(BranchOpc)).addMBB(TrueMBB);
868 if (Predicate == CmpInst::FCMP_UNE) {
869 // X86 requires a second branch to handle UNE (and OEQ,
870 // which is mapped to UNE above).
871 BuildMI(MBB, DL, TII.get(X86::JP)).addMBB(TrueMBB);
874 FastEmitBranch(FalseMBB);
875 MBB->addSuccessor(TrueMBB);
878 } else if (ExtractValueInst *EI =
879 dyn_cast<ExtractValueInst>(BI->getCondition())) {
880 // Check to see if the branch instruction is from an "arithmetic with
881 // overflow" intrinsic. The main way these intrinsics are used is:
883 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
884 // %sum = extractvalue { i32, i1 } %t, 0
885 // %obit = extractvalue { i32, i1 } %t, 1
886 // br i1 %obit, label %overflow, label %normal
888 // The %sum and %obit are converted in an ADD and a SETO/SETB before
889 // reaching the branch. Therefore, we search backwards through the MBB
890 // looking for the SETO/SETB instruction. If an instruction modifies the
891 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
892 // convert the branch into a JO/JB instruction.
893 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
894 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
895 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
896 const MachineInstr *SetMI = 0;
897 unsigned Reg = lookUpRegForValue(EI);
899 for (MachineBasicBlock::const_reverse_iterator
900 RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
901 const MachineInstr &MI = *RI;
903 if (MI.modifiesRegister(Reg)) {
904 unsigned Src, Dst, SrcSR, DstSR;
906 if (getInstrInfo()->isMoveInstr(MI, Src, Dst, SrcSR, DstSR)) {
915 const TargetInstrDesc &TID = MI.getDesc();
916 if (TID.hasUnmodeledSideEffects() ||
917 TID.hasImplicitDefOfPhysReg(X86::EFLAGS))
922 unsigned OpCode = SetMI->getOpcode();
924 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
925 BuildMI(MBB, DL, TII.get(OpCode == X86::SETOr ? X86::JO : X86::JB))
927 FastEmitBranch(FalseMBB);
928 MBB->addSuccessor(TrueMBB);
936 // Otherwise do a clumsy setcc and re-test it.
937 unsigned OpReg = getRegForValue(BI->getCondition());
938 if (OpReg == 0) return false;
940 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
941 BuildMI(MBB, DL, TII.get(X86::JNE)).addMBB(TrueMBB);
942 FastEmitBranch(FalseMBB);
943 MBB->addSuccessor(TrueMBB);
947 bool X86FastISel::X86SelectShift(Instruction *I) {
948 unsigned CReg = 0, OpReg = 0, OpImm = 0;
949 const TargetRegisterClass *RC = NULL;
950 if (I->getType() == Type::getInt8Ty(I->getContext())) {
952 RC = &X86::GR8RegClass;
953 switch (I->getOpcode()) {
954 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
955 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
956 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
957 default: return false;
959 } else if (I->getType() == Type::getInt16Ty(I->getContext())) {
961 RC = &X86::GR16RegClass;
962 switch (I->getOpcode()) {
963 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
964 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
965 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
966 default: return false;
968 } else if (I->getType() == Type::getInt32Ty(I->getContext())) {
970 RC = &X86::GR32RegClass;
971 switch (I->getOpcode()) {
972 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
973 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
974 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
975 default: return false;
977 } else if (I->getType() == Type::getInt64Ty(I->getContext())) {
979 RC = &X86::GR64RegClass;
980 switch (I->getOpcode()) {
981 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
982 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
983 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
984 default: return false;
990 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
991 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
994 unsigned Op0Reg = getRegForValue(I->getOperand(0));
995 if (Op0Reg == 0) return false;
997 // Fold immediate in shl(x,3).
998 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
999 unsigned ResultReg = createResultReg(RC);
1000 BuildMI(MBB, DL, TII.get(OpImm),
1001 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1002 UpdateValueMap(I, ResultReg);
1006 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1007 if (Op1Reg == 0) return false;
1008 TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
1010 // The shift instruction uses X86::CL. If we defined a super-register
1011 // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
1012 // we're doing here.
1013 if (CReg != X86::CL)
1014 BuildMI(MBB, DL, TII.get(TargetInstrInfo::EXTRACT_SUBREG), X86::CL)
1015 .addReg(CReg).addImm(X86::SUBREG_8BIT);
1017 unsigned ResultReg = createResultReg(RC);
1018 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg);
1019 UpdateValueMap(I, ResultReg);
1023 bool X86FastISel::X86SelectSelect(Instruction *I) {
1024 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1025 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1029 const TargetRegisterClass *RC = NULL;
1030 if (VT.getSimpleVT() == MVT::i16) {
1031 Opc = X86::CMOVE16rr;
1032 RC = &X86::GR16RegClass;
1033 } else if (VT.getSimpleVT() == MVT::i32) {
1034 Opc = X86::CMOVE32rr;
1035 RC = &X86::GR32RegClass;
1036 } else if (VT.getSimpleVT() == MVT::i64) {
1037 Opc = X86::CMOVE64rr;
1038 RC = &X86::GR64RegClass;
1043 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1044 if (Op0Reg == 0) return false;
1045 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1046 if (Op1Reg == 0) return false;
1047 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1048 if (Op2Reg == 0) return false;
1050 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
1051 unsigned ResultReg = createResultReg(RC);
1052 BuildMI(MBB, DL, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
1053 UpdateValueMap(I, ResultReg);
1057 bool X86FastISel::X86SelectFPExt(Instruction *I) {
1058 // fpext from float to double.
1059 if (Subtarget->hasSSE2() &&
1060 I->getType() == Type::getDoubleTy(I->getContext())) {
1061 Value *V = I->getOperand(0);
1062 if (V->getType() == Type::getFloatTy(I->getContext())) {
1063 unsigned OpReg = getRegForValue(V);
1064 if (OpReg == 0) return false;
1065 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1066 BuildMI(MBB, DL, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
1067 UpdateValueMap(I, ResultReg);
1075 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
1076 if (Subtarget->hasSSE2()) {
1077 if (I->getType() == Type::getFloatTy(I->getContext())) {
1078 Value *V = I->getOperand(0);
1079 if (V->getType() == Type::getDoubleTy(I->getContext())) {
1080 unsigned OpReg = getRegForValue(V);
1081 if (OpReg == 0) return false;
1082 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1083 BuildMI(MBB, DL, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
1084 UpdateValueMap(I, ResultReg);
1093 bool X86FastISel::X86SelectTrunc(Instruction *I) {
1094 if (Subtarget->is64Bit())
1095 // All other cases should be handled by the tblgen generated code.
1097 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1098 EVT DstVT = TLI.getValueType(I->getType());
1100 // This code only handles truncation to byte right now.
1101 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1102 // All other cases should be handled by the tblgen generated code.
1104 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1105 // All other cases should be handled by the tblgen generated code.
1108 unsigned InputReg = getRegForValue(I->getOperand(0));
1110 // Unhandled operand. Halt "fast" selection and bail.
1113 // First issue a copy to GR16_ABCD or GR32_ABCD.
1114 unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16rr : X86::MOV32rr;
1115 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1116 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1117 unsigned CopyReg = createResultReg(CopyRC);
1118 BuildMI(MBB, DL, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1120 // Then issue an extract_subreg.
1121 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1122 CopyReg, X86::SUBREG_8BIT);
1126 UpdateValueMap(I, ResultReg);
1130 bool X86FastISel::X86SelectExtractValue(Instruction *I) {
1131 ExtractValueInst *EI = cast<ExtractValueInst>(I);
1132 Value *Agg = EI->getAggregateOperand();
1134 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1135 switch (CI->getIntrinsicID()) {
1137 case Intrinsic::sadd_with_overflow:
1138 case Intrinsic::uadd_with_overflow:
1139 // Cheat a little. We know that the registers for "add" and "seto" are
1140 // allocated sequentially. However, we only keep track of the register
1141 // for "add" in the value map. Use extractvalue's index to get the
1142 // correct register for "seto".
1143 UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1151 bool X86FastISel::X86VisitIntrinsicCall(IntrinsicInst &I) {
1152 // FIXME: Handle more intrinsics.
1153 switch (I.getIntrinsicID()) {
1154 default: return false;
1155 case Intrinsic::sadd_with_overflow:
1156 case Intrinsic::uadd_with_overflow: {
1157 // Replace "add with overflow" intrinsics with an "add" instruction followed
1158 // by a seto/setc instruction. Later on, when the "extractvalue"
1159 // instructions are encountered, we use the fact that two registers were
1160 // created sequentially to get the correct registers for the "sum" and the
1162 const Function *Callee = I.getCalledFunction();
1164 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1167 if (!isTypeLegal(RetTy, VT))
1170 Value *Op1 = I.getOperand(1);
1171 Value *Op2 = I.getOperand(2);
1172 unsigned Reg1 = getRegForValue(Op1);
1173 unsigned Reg2 = getRegForValue(Op2);
1175 if (Reg1 == 0 || Reg2 == 0)
1176 // FIXME: Handle values *not* in registers.
1182 else if (VT == MVT::i64)
1187 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1188 BuildMI(MBB, DL, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1189 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1191 // If the add with overflow is an intra-block value then we just want to
1192 // create temporaries for it like normal. If it is a cross-block value then
1193 // UpdateValueMap will return the cross-block register used. Since we
1194 // *really* want the value to be live in the register pair known by
1195 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1196 // the cross block case. In the non-cross-block case, we should just make
1197 // another register for the value.
1198 if (DestReg1 != ResultReg)
1199 ResultReg = DestReg1+1;
1201 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1203 unsigned Opc = X86::SETBr;
1204 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1206 BuildMI(MBB, DL, TII.get(Opc), ResultReg);
1212 bool X86FastISel::X86SelectCall(Instruction *I) {
1213 CallInst *CI = cast<CallInst>(I);
1214 Value *Callee = I->getOperand(0);
1216 // Can't handle inline asm yet.
1217 if (isa<InlineAsm>(Callee))
1220 // Handle intrinsic calls.
1221 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1222 return X86VisitIntrinsicCall(*II);
1224 // Handle only C and fastcc calling conventions for now.
1226 unsigned CC = CS.getCallingConv();
1227 if (CC != CallingConv::C &&
1228 CC != CallingConv::Fast &&
1229 CC != CallingConv::X86_FastCall)
1232 // On X86, -tailcallopt changes the fastcc ABI. FastISel doesn't
1233 // handle this for now.
1234 if (CC == CallingConv::Fast && PerformTailCallOpt)
1237 // Let SDISel handle vararg functions.
1238 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1239 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1240 if (FTy->isVarArg())
1243 // Handle *simple* calls for now.
1244 const Type *RetTy = CS.getType();
1246 if (RetTy == Type::getVoidTy(I->getContext()))
1247 RetVT = MVT::isVoid;
1248 else if (!isTypeLegal(RetTy, RetVT, true))
1251 // Materialize callee address in a register. FIXME: GV address can be
1252 // handled with a CALLpcrel32 instead.
1253 X86AddressMode CalleeAM;
1254 if (!X86SelectCallAddress(Callee, CalleeAM))
1256 unsigned CalleeOp = 0;
1257 GlobalValue *GV = 0;
1258 if (CalleeAM.GV != 0) {
1260 } else if (CalleeAM.Base.Reg != 0) {
1261 CalleeOp = CalleeAM.Base.Reg;
1265 // Allow calls which produce i1 results.
1266 bool AndToI1 = false;
1267 if (RetVT == MVT::i1) {
1272 // Deal with call operands first.
1273 SmallVector<Value*, 8> ArgVals;
1274 SmallVector<unsigned, 8> Args;
1275 SmallVector<EVT, 8> ArgVTs;
1276 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1277 Args.reserve(CS.arg_size());
1278 ArgVals.reserve(CS.arg_size());
1279 ArgVTs.reserve(CS.arg_size());
1280 ArgFlags.reserve(CS.arg_size());
1281 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1283 unsigned Arg = getRegForValue(*i);
1286 ISD::ArgFlagsTy Flags;
1287 unsigned AttrInd = i - CS.arg_begin() + 1;
1288 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1290 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1293 // FIXME: Only handle *easy* calls for now.
1294 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1295 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1296 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1297 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1300 const Type *ArgTy = (*i)->getType();
1302 if (!isTypeLegal(ArgTy, ArgVT))
1304 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1305 Flags.setOrigAlign(OriginalAlignment);
1307 Args.push_back(Arg);
1308 ArgVals.push_back(*i);
1309 ArgVTs.push_back(ArgVT);
1310 ArgFlags.push_back(Flags);
1313 // Analyze operands of the call, assigning locations to each operand.
1314 SmallVector<CCValAssign, 16> ArgLocs;
1315 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1316 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1318 // Get a count of how many bytes are to be pushed on the stack.
1319 unsigned NumBytes = CCInfo.getNextStackOffset();
1321 // Issue CALLSEQ_START
1322 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1323 BuildMI(MBB, DL, TII.get(AdjStackDown)).addImm(NumBytes);
1325 // Process argument: walk the register/memloc assignments, inserting
1327 SmallVector<unsigned, 4> RegArgs;
1328 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1329 CCValAssign &VA = ArgLocs[i];
1330 unsigned Arg = Args[VA.getValNo()];
1331 EVT ArgVT = ArgVTs[VA.getValNo()];
1333 // Promote the value if needed.
1334 switch (VA.getLocInfo()) {
1335 default: llvm_unreachable("Unknown loc info!");
1336 case CCValAssign::Full: break;
1337 case CCValAssign::SExt: {
1338 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1340 assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1342 ArgVT = VA.getLocVT();
1345 case CCValAssign::ZExt: {
1346 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1348 assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1350 ArgVT = VA.getLocVT();
1353 case CCValAssign::AExt: {
1354 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1357 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1360 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1363 assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1364 ArgVT = VA.getLocVT();
1367 case CCValAssign::BCvt: {
1368 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT().getSimpleVT(),
1369 ISD::BIT_CONVERT, Arg);
1370 assert(BC != 0 && "Failed to emit a bitcast!");
1372 ArgVT = VA.getLocVT();
1377 if (VA.isRegLoc()) {
1378 TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1379 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1381 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1383 RegArgs.push_back(VA.getLocReg());
1385 unsigned LocMemOffset = VA.getLocMemOffset();
1387 AM.Base.Reg = StackPtr;
1388 AM.Disp = LocMemOffset;
1389 Value *ArgVal = ArgVals[VA.getValNo()];
1391 // If this is a really simple value, emit this with the Value* version of
1392 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1393 // can cause us to reevaluate the argument.
1394 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1395 X86FastEmitStore(ArgVT, ArgVal, AM);
1397 X86FastEmitStore(ArgVT, Arg, AM);
1401 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1403 if (Subtarget->isPICStyleGOT()) {
1404 TargetRegisterClass *RC = X86::GR32RegisterClass;
1405 unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1406 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1407 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1412 MachineInstrBuilder MIB;
1414 // Register-indirect call.
1415 unsigned CallOpc = Subtarget->is64Bit() ? X86::CALL64r : X86::CALL32r;
1416 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addReg(CalleeOp);
1420 assert(GV && "Not a direct call");
1422 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
1424 // See if we need any target-specific flags on the GV operand.
1425 unsigned char OpFlags = 0;
1427 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1428 // external symbols most go through the PLT in PIC mode. If the symbol
1429 // has hidden or protected visibility, or if it is static or local, then
1430 // we don't need to use the PLT - we can directly call it.
1431 if (Subtarget->isTargetELF() &&
1432 TM.getRelocationModel() == Reloc::PIC_ &&
1433 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1434 OpFlags = X86II::MO_PLT;
1435 } else if (Subtarget->isPICStyleStubAny() &&
1436 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1437 Subtarget->getDarwinVers() < 9) {
1438 // PC-relative references to external symbols should go through $stub,
1439 // unless we're building with the leopard linker or later, which
1440 // automatically synthesizes these stubs.
1441 OpFlags = X86II::MO_DARWIN_STUB;
1445 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addGlobalAddress(GV, 0, OpFlags);
1448 // Add an implicit use GOT pointer in EBX.
1449 if (Subtarget->isPICStyleGOT())
1450 MIB.addReg(X86::EBX);
1452 // Add implicit physical register uses to the call.
1453 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1454 MIB.addReg(RegArgs[i]);
1456 // Issue CALLSEQ_END
1457 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1458 BuildMI(MBB, DL, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1460 // Now handle call return value (if any).
1461 if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1462 SmallVector<CCValAssign, 16> RVLocs;
1463 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1464 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1466 // Copy all of the result registers out of their specified physreg.
1467 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1468 EVT CopyVT = RVLocs[0].getValVT();
1469 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1470 TargetRegisterClass *SrcRC = DstRC;
1472 // If this is a call to a function that returns an fp value on the x87 fp
1473 // stack, but where we prefer to use the value in xmm registers, copy it
1474 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1475 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1476 RVLocs[0].getLocReg() == X86::ST1) &&
1477 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1479 SrcRC = X86::RSTRegisterClass;
1480 DstRC = X86::RFP80RegisterClass;
1483 unsigned ResultReg = createResultReg(DstRC);
1484 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1485 RVLocs[0].getLocReg(), DstRC, SrcRC);
1486 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1488 if (CopyVT != RVLocs[0].getValVT()) {
1489 // Round the F80 the right size, which also moves to the appropriate xmm
1490 // register. This is accomplished by storing the F80 value in memory and
1491 // then loading it back. Ewww...
1492 EVT ResVT = RVLocs[0].getValVT();
1493 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1494 unsigned MemSize = ResVT.getSizeInBits()/8;
1495 int FI = MFI.CreateStackObject(MemSize, MemSize);
1496 addFrameReference(BuildMI(MBB, DL, TII.get(Opc)), FI).addReg(ResultReg);
1497 DstRC = ResVT == MVT::f32
1498 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1499 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1500 ResultReg = createResultReg(DstRC);
1501 addFrameReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg), FI);
1505 // Mask out all but lowest bit for some call which produces an i1.
1506 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1508 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1509 ResultReg = AndResult;
1512 UpdateValueMap(I, ResultReg);
1520 X86FastISel::TargetSelectInstruction(Instruction *I) {
1521 switch (I->getOpcode()) {
1523 case Instruction::Load:
1524 return X86SelectLoad(I);
1525 case Instruction::Store:
1526 return X86SelectStore(I);
1527 case Instruction::ICmp:
1528 case Instruction::FCmp:
1529 return X86SelectCmp(I);
1530 case Instruction::ZExt:
1531 return X86SelectZExt(I);
1532 case Instruction::Br:
1533 return X86SelectBranch(I);
1534 case Instruction::Call:
1535 return X86SelectCall(I);
1536 case Instruction::LShr:
1537 case Instruction::AShr:
1538 case Instruction::Shl:
1539 return X86SelectShift(I);
1540 case Instruction::Select:
1541 return X86SelectSelect(I);
1542 case Instruction::Trunc:
1543 return X86SelectTrunc(I);
1544 case Instruction::FPExt:
1545 return X86SelectFPExt(I);
1546 case Instruction::FPTrunc:
1547 return X86SelectFPTrunc(I);
1548 case Instruction::ExtractValue:
1549 return X86SelectExtractValue(I);
1550 case Instruction::IntToPtr: // Deliberate fall-through.
1551 case Instruction::PtrToInt: {
1552 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1553 EVT DstVT = TLI.getValueType(I->getType());
1554 if (DstVT.bitsGT(SrcVT))
1555 return X86SelectZExt(I);
1556 if (DstVT.bitsLT(SrcVT))
1557 return X86SelectTrunc(I);
1558 unsigned Reg = getRegForValue(I->getOperand(0));
1559 if (Reg == 0) return false;
1560 UpdateValueMap(I, Reg);
1568 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1570 if (!isTypeLegal(C->getType(), VT))
1573 // Get opcode and regclass of the output for the given load instruction.
1575 const TargetRegisterClass *RC = NULL;
1576 switch (VT.getSimpleVT().SimpleTy) {
1577 default: return false;
1580 RC = X86::GR8RegisterClass;
1584 RC = X86::GR16RegisterClass;
1588 RC = X86::GR32RegisterClass;
1591 // Must be in x86-64 mode.
1593 RC = X86::GR64RegisterClass;
1596 if (Subtarget->hasSSE1()) {
1598 RC = X86::FR32RegisterClass;
1600 Opc = X86::LD_Fp32m;
1601 RC = X86::RFP32RegisterClass;
1605 if (Subtarget->hasSSE2()) {
1607 RC = X86::FR64RegisterClass;
1609 Opc = X86::LD_Fp64m;
1610 RC = X86::RFP64RegisterClass;
1614 // No f80 support yet.
1618 // Materialize addresses with LEA instructions.
1619 if (isa<GlobalValue>(C)) {
1621 if (X86SelectAddress(C, AM)) {
1622 if (TLI.getPointerTy() == MVT::i32)
1626 unsigned ResultReg = createResultReg(RC);
1627 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1633 // MachineConstantPool wants an explicit alignment.
1634 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1636 // Alignment of vector types. FIXME!
1637 Align = TD.getTypeAllocSize(C->getType());
1640 // x86-32 PIC requires a PIC base register for constant pools.
1641 unsigned PICBase = 0;
1642 unsigned char OpFlag = 0;
1643 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1644 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1645 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1646 } else if (Subtarget->isPICStyleGOT()) {
1647 OpFlag = X86II::MO_GOTOFF;
1648 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1649 } else if (Subtarget->isPICStyleRIPRel() &&
1650 TM.getCodeModel() == CodeModel::Small) {
1654 // Create the load from the constant pool.
1655 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1656 unsigned ResultReg = createResultReg(RC);
1657 addConstantPoolReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg),
1658 MCPOffset, PICBase, OpFlag);
1663 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1664 // Fail on dynamic allocas. At this point, getRegForValue has already
1665 // checked its CSE maps, so if we're here trying to handle a dynamic
1666 // alloca, we're not going to succeed. X86SelectAddress has a
1667 // check for dynamic allocas, because it's called directly from
1668 // various places, but TargetMaterializeAlloca also needs a check
1669 // in order to avoid recursion between getRegForValue,
1670 // X86SelectAddrss, and TargetMaterializeAlloca.
1671 if (!StaticAllocaMap.count(C))
1675 if (!X86SelectAddress(C, AM))
1677 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1678 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1679 unsigned ResultReg = createResultReg(RC);
1680 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1685 llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1686 MachineModuleInfo *mmi,
1688 DenseMap<const Value *, unsigned> &vm,
1689 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1690 DenseMap<const AllocaInst *, int> &am
1692 , SmallSet<Instruction*, 8> &cil
1695 return new X86FastISel(mf, mmi, dw, vm, bm, am