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 "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetOptions.h"
43 class X86FastISel : public FastISel {
44 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
45 /// make the right decision when generating code for different targets.
46 const X86Subtarget *Subtarget;
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(FunctionLoweringInfo &funcInfo,
57 const TargetLibraryInfo *libInfo)
58 : FastISel(funcInfo, libInfo) {
59 Subtarget = &TM.getSubtarget<X86Subtarget>();
60 X86ScalarSSEf64 = Subtarget->hasSSE2();
61 X86ScalarSSEf32 = Subtarget->hasSSE1();
64 virtual bool TargetSelectInstruction(const Instruction *I);
66 /// \brief The specified machine instr operand is a vreg, and that
67 /// vreg is being provided by the specified load instruction. If possible,
68 /// try to fold the load as an operand to the instruction, returning true if
70 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
73 virtual bool FastLowerArguments();
75 #include "X86GenFastISel.inc"
78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
83 bool Aligned = false);
84 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM,
85 bool Aligned = false);
87 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
90 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
91 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
93 bool X86SelectLoad(const Instruction *I);
95 bool X86SelectStore(const Instruction *I);
97 bool X86SelectRet(const Instruction *I);
99 bool X86SelectCmp(const Instruction *I);
101 bool X86SelectZExt(const Instruction *I);
103 bool X86SelectBranch(const Instruction *I);
105 bool X86SelectShift(const Instruction *I);
107 bool X86SelectDivRem(const Instruction *I);
109 bool X86SelectSelect(const Instruction *I);
111 bool X86SelectTrunc(const Instruction *I);
113 bool X86SelectFPExt(const Instruction *I);
114 bool X86SelectFPTrunc(const Instruction *I);
116 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
117 bool X86SelectCall(const Instruction *I);
119 bool DoSelectCall(const Instruction *I, const char *MemIntName);
121 const X86InstrInfo *getInstrInfo() const {
122 return getTargetMachine()->getInstrInfo();
124 const X86TargetMachine *getTargetMachine() const {
125 return static_cast<const X86TargetMachine *>(&TM);
128 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
130 unsigned TargetMaterializeConstant(const Constant *C);
132 unsigned TargetMaterializeAlloca(const AllocaInst *C);
134 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
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(Type *Ty, MVT &VT, bool AllowI1 = false);
145 bool IsMemcpySmall(uint64_t Len);
147 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
148 X86AddressMode SrcAM, uint64_t Len);
151 } // end anonymous namespace.
153 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
154 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
155 if (evt == MVT::Other || !evt.isSimple())
156 // Unhandled type. Halt "fast" selection and bail.
159 VT = evt.getSimpleVT();
160 // For now, require SSE/SSE2 for performing floating-point operations,
161 // since x87 requires additional work.
162 if (VT == MVT::f64 && !X86ScalarSSEf64)
164 if (VT == MVT::f32 && !X86ScalarSSEf32)
166 // Similarly, no f80 support yet.
169 // We only handle legal types. For example, on x86-32 the instruction
170 // selector contains all of the 64-bit instructions from x86-64,
171 // under the assumption that i64 won't be used if the target doesn't
173 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
176 #include "X86GenCallingConv.inc"
178 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
179 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
180 /// Return true and the result register by reference if it is possible.
181 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
182 unsigned &ResultReg) {
183 // Get opcode and regclass of the output for the given load instruction.
185 const TargetRegisterClass *RC = NULL;
186 switch (VT.getSimpleVT().SimpleTy) {
187 default: return false;
191 RC = &X86::GR8RegClass;
195 RC = &X86::GR16RegClass;
199 RC = &X86::GR32RegClass;
202 // Must be in x86-64 mode.
204 RC = &X86::GR64RegClass;
207 if (X86ScalarSSEf32) {
208 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
209 RC = &X86::FR32RegClass;
212 RC = &X86::RFP32RegClass;
216 if (X86ScalarSSEf64) {
217 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
218 RC = &X86::FR64RegClass;
221 RC = &X86::RFP64RegClass;
225 // No f80 support yet.
229 ResultReg = createResultReg(RC);
230 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
231 DL, TII.get(Opc), ResultReg), AM);
235 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
236 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
237 /// and a displacement offset, or a GlobalAddress,
238 /// i.e. V. Return true if it is possible.
240 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg,
241 const X86AddressMode &AM, bool Aligned) {
242 // Get opcode and regclass of the output for the given store instruction.
244 switch (VT.getSimpleVT().SimpleTy) {
245 case MVT::f80: // No f80 support yet.
246 default: return false;
248 // Mask out all but lowest bit.
249 unsigned AndResult = createResultReg(&X86::GR8RegClass);
250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
251 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1);
254 // FALLTHROUGH, handling i1 as i8.
255 case MVT::i8: Opc = X86::MOV8mr; break;
256 case MVT::i16: Opc = X86::MOV16mr; break;
257 case MVT::i32: Opc = X86::MOV32mr; break;
258 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
260 Opc = X86ScalarSSEf32 ?
261 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
264 Opc = X86ScalarSSEf64 ?
265 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
269 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
271 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
275 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
277 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
284 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
286 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
290 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
291 DL, TII.get(Opc)), AM).addReg(ValReg);
295 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
296 const X86AddressMode &AM, bool Aligned) {
297 // Handle 'null' like i32/i64 0.
298 if (isa<ConstantPointerNull>(Val))
299 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
301 // If this is a store of a simple constant, fold the constant into the store.
302 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
305 switch (VT.getSimpleVT().SimpleTy) {
307 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
308 case MVT::i8: Opc = X86::MOV8mi; break;
309 case MVT::i16: Opc = X86::MOV16mi; break;
310 case MVT::i32: Opc = X86::MOV32mi; break;
312 // Must be a 32-bit sign extended value.
313 if (isInt<32>(CI->getSExtValue()))
314 Opc = X86::MOV64mi32;
319 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
320 DL, TII.get(Opc)), AM)
321 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
327 unsigned ValReg = getRegForValue(Val);
331 return X86FastEmitStore(VT, ValReg, AM, Aligned);
334 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
335 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
336 /// ISD::SIGN_EXTEND).
337 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
338 unsigned Src, EVT SrcVT,
339 unsigned &ResultReg) {
340 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
341 Src, /*TODO: Kill=*/false);
349 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
350 // Handle constant address.
351 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
352 // Can't handle alternate code models yet.
353 if (TM.getCodeModel() != CodeModel::Small)
356 // Can't handle TLS yet.
357 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
358 if (GVar->isThreadLocal())
361 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
363 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
364 if (const GlobalVariable *GVar =
365 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
366 if (GVar->isThreadLocal())
369 // RIP-relative addresses can't have additional register operands, so if
370 // we've already folded stuff into the addressing mode, just force the
371 // global value into its own register, which we can use as the basereg.
372 if (!Subtarget->isPICStyleRIPRel() ||
373 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
374 // Okay, we've committed to selecting this global. Set up the address.
377 // Allow the subtarget to classify the global.
378 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
380 // If this reference is relative to the pic base, set it now.
381 if (isGlobalRelativeToPICBase(GVFlags)) {
382 // FIXME: How do we know Base.Reg is free??
383 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
386 // Unless the ABI requires an extra load, return a direct reference to
388 if (!isGlobalStubReference(GVFlags)) {
389 if (Subtarget->isPICStyleRIPRel()) {
390 // Use rip-relative addressing if we can. Above we verified that the
391 // base and index registers are unused.
392 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
393 AM.Base.Reg = X86::RIP;
395 AM.GVOpFlags = GVFlags;
399 // Ok, we need to do a load from a stub. If we've already loaded from
400 // this stub, reuse the loaded pointer, otherwise emit the load now.
401 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
403 if (I != LocalValueMap.end() && I->second != 0) {
406 // Issue load from stub.
408 const TargetRegisterClass *RC = NULL;
409 X86AddressMode StubAM;
410 StubAM.Base.Reg = AM.Base.Reg;
412 StubAM.GVOpFlags = GVFlags;
414 // Prepare for inserting code in the local-value area.
415 SavePoint SaveInsertPt = enterLocalValueArea();
417 if (TLI.getPointerTy() == MVT::i64) {
419 RC = &X86::GR64RegClass;
421 if (Subtarget->isPICStyleRIPRel())
422 StubAM.Base.Reg = X86::RIP;
425 RC = &X86::GR32RegClass;
428 LoadReg = createResultReg(RC);
429 MachineInstrBuilder LoadMI =
430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
431 addFullAddress(LoadMI, StubAM);
433 // Ok, back to normal mode.
434 leaveLocalValueArea(SaveInsertPt);
436 // Prevent loading GV stub multiple times in same MBB.
437 LocalValueMap[V] = LoadReg;
440 // Now construct the final address. Note that the Disp, Scale,
441 // and Index values may already be set here.
442 AM.Base.Reg = LoadReg;
448 // If all else fails, try to materialize the value in a register.
449 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
450 if (AM.Base.Reg == 0) {
451 AM.Base.Reg = getRegForValue(V);
452 return AM.Base.Reg != 0;
454 if (AM.IndexReg == 0) {
455 assert(AM.Scale == 1 && "Scale with no index!");
456 AM.IndexReg = getRegForValue(V);
457 return AM.IndexReg != 0;
464 /// X86SelectAddress - Attempt to fill in an address from the given value.
466 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
467 SmallVector<const Value *, 32> GEPs;
469 const User *U = NULL;
470 unsigned Opcode = Instruction::UserOp1;
471 if (const Instruction *I = dyn_cast<Instruction>(V)) {
472 // Don't walk into other basic blocks; it's possible we haven't
473 // visited them yet, so the instructions may not yet be assigned
474 // virtual registers.
475 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
476 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
477 Opcode = I->getOpcode();
480 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
481 Opcode = C->getOpcode();
485 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
486 if (Ty->getAddressSpace() > 255)
487 // Fast instruction selection doesn't support the special
493 case Instruction::BitCast:
494 // Look past bitcasts.
495 return X86SelectAddress(U->getOperand(0), AM);
497 case Instruction::IntToPtr:
498 // Look past no-op inttoptrs.
499 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
500 return X86SelectAddress(U->getOperand(0), AM);
503 case Instruction::PtrToInt:
504 // Look past no-op ptrtoints.
505 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
506 return X86SelectAddress(U->getOperand(0), AM);
509 case Instruction::Alloca: {
510 // Do static allocas.
511 const AllocaInst *A = cast<AllocaInst>(V);
512 DenseMap<const AllocaInst*, int>::iterator SI =
513 FuncInfo.StaticAllocaMap.find(A);
514 if (SI != FuncInfo.StaticAllocaMap.end()) {
515 AM.BaseType = X86AddressMode::FrameIndexBase;
516 AM.Base.FrameIndex = SI->second;
522 case Instruction::Add: {
523 // Adds of constants are common and easy enough.
524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
525 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
526 // They have to fit in the 32-bit signed displacement field though.
527 if (isInt<32>(Disp)) {
528 AM.Disp = (uint32_t)Disp;
529 return X86SelectAddress(U->getOperand(0), AM);
535 case Instruction::GetElementPtr: {
536 X86AddressMode SavedAM = AM;
538 // Pattern-match simple GEPs.
539 uint64_t Disp = (int32_t)AM.Disp;
540 unsigned IndexReg = AM.IndexReg;
541 unsigned Scale = AM.Scale;
542 gep_type_iterator GTI = gep_type_begin(U);
543 // Iterate through the indices, folding what we can. Constants can be
544 // folded, and one dynamic index can be handled, if the scale is supported.
545 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
546 i != e; ++i, ++GTI) {
547 const Value *Op = *i;
548 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
549 const StructLayout *SL = TD.getStructLayout(STy);
550 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
554 // A array/variable index is always of the form i*S where S is the
555 // constant scale size. See if we can push the scale into immediates.
556 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
558 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
559 // Constant-offset addressing.
560 Disp += CI->getSExtValue() * S;
563 if (isa<AddOperator>(Op) &&
564 (!isa<Instruction>(Op) ||
565 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
567 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
568 // An add (in the same block) with a constant operand. Fold the
571 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
572 Disp += CI->getSExtValue() * S;
573 // Iterate on the other operand.
574 Op = cast<AddOperator>(Op)->getOperand(0);
578 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
579 (S == 1 || S == 2 || S == 4 || S == 8)) {
580 // Scaled-index addressing.
582 IndexReg = getRegForGEPIndex(Op).first;
588 goto unsupported_gep;
592 // Check for displacement overflow.
593 if (!isInt<32>(Disp))
596 AM.IndexReg = IndexReg;
598 AM.Disp = (uint32_t)Disp;
601 if (const GetElementPtrInst *GEP =
602 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
603 // Ok, the GEP indices were covered by constant-offset and scaled-index
604 // addressing. Update the address state and move on to examining the base.
607 } else if (X86SelectAddress(U->getOperand(0), AM)) {
611 // If we couldn't merge the gep value into this addr mode, revert back to
612 // our address and just match the value instead of completely failing.
615 for (SmallVectorImpl<const Value *>::reverse_iterator
616 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
617 if (handleConstantAddresses(*I, AM))
622 // Ok, the GEP indices weren't all covered.
627 return handleConstantAddresses(V, AM);
630 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
632 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
633 const User *U = NULL;
634 unsigned Opcode = Instruction::UserOp1;
635 const Instruction *I = dyn_cast<Instruction>(V);
636 // Record if the value is defined in the same basic block.
638 // This information is crucial to know whether or not folding an
640 // Indeed, FastISel generates or reuses a virtual register for all
641 // operands of all instructions it selects. Obviously, the definition and
642 // its uses must use the same virtual register otherwise the produced
643 // code is incorrect.
644 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
645 // registers for values that are alive across basic blocks. This ensures
646 // that the values are consistently set between across basic block, even
647 // if different instruction selection mechanisms are used (e.g., a mix of
648 // SDISel and FastISel).
649 // For values local to a basic block, the instruction selection process
650 // generates these virtual registers with whatever method is appropriate
651 // for its needs. In particular, FastISel and SDISel do not share the way
652 // local virtual registers are set.
653 // Therefore, this is impossible (or at least unsafe) to share values
654 // between basic blocks unless they use the same instruction selection
655 // method, which is not guarantee for X86.
656 // Moreover, things like hasOneUse could not be used accurately, if we
657 // allow to reference values across basic blocks whereas they are not
658 // alive across basic blocks initially.
661 Opcode = I->getOpcode();
663 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
664 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
665 Opcode = C->getOpcode();
671 case Instruction::BitCast:
672 // Look past bitcasts if its operand is in the same BB.
674 return X86SelectCallAddress(U->getOperand(0), AM);
677 case Instruction::IntToPtr:
678 // Look past no-op inttoptrs if its operand is in the same BB.
680 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
681 return X86SelectCallAddress(U->getOperand(0), AM);
684 case Instruction::PtrToInt:
685 // Look past no-op ptrtoints if its operand is in the same BB.
687 TLI.getValueType(U->getType()) == TLI.getPointerTy())
688 return X86SelectCallAddress(U->getOperand(0), AM);
692 // Handle constant address.
693 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
694 // Can't handle alternate code models yet.
695 if (TM.getCodeModel() != CodeModel::Small)
698 // RIP-relative addresses can't have additional register operands.
699 if (Subtarget->isPICStyleRIPRel() &&
700 (AM.Base.Reg != 0 || AM.IndexReg != 0))
703 // Can't handle DLLImport.
704 if (GV->hasDLLImportLinkage())
708 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
709 if (GVar->isThreadLocal())
712 // Okay, we've committed to selecting this global. Set up the basic address.
715 // No ABI requires an extra load for anything other than DLLImport, which
716 // we rejected above. Return a direct reference to the global.
717 if (Subtarget->isPICStyleRIPRel()) {
718 // Use rip-relative addressing if we can. Above we verified that the
719 // base and index registers are unused.
720 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
721 AM.Base.Reg = X86::RIP;
722 } else if (Subtarget->isPICStyleStubPIC()) {
723 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
724 } else if (Subtarget->isPICStyleGOT()) {
725 AM.GVOpFlags = X86II::MO_GOTOFF;
731 // If all else fails, try to materialize the value in a register.
732 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
733 if (AM.Base.Reg == 0) {
734 AM.Base.Reg = getRegForValue(V);
735 return AM.Base.Reg != 0;
737 if (AM.IndexReg == 0) {
738 assert(AM.Scale == 1 && "Scale with no index!");
739 AM.IndexReg = getRegForValue(V);
740 return AM.IndexReg != 0;
748 /// X86SelectStore - Select and emit code to implement store instructions.
749 bool X86FastISel::X86SelectStore(const Instruction *I) {
750 // Atomic stores need special handling.
751 const StoreInst *S = cast<StoreInst>(I);
756 unsigned SABIAlignment =
757 TD.getABITypeAlignment(S->getValueOperand()->getType());
758 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment;
761 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
765 if (!X86SelectAddress(I->getOperand(1), AM))
768 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned);
771 /// X86SelectRet - Select and emit code to implement ret instructions.
772 bool X86FastISel::X86SelectRet(const Instruction *I) {
773 const ReturnInst *Ret = cast<ReturnInst>(I);
774 const Function &F = *I->getParent()->getParent();
775 const X86MachineFunctionInfo *X86MFInfo =
776 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
778 if (!FuncInfo.CanLowerReturn)
781 CallingConv::ID CC = F.getCallingConv();
782 if (CC != CallingConv::C &&
783 CC != CallingConv::Fast &&
784 CC != CallingConv::X86_FastCall &&
785 CC != CallingConv::X86_64_SysV)
788 if (Subtarget->isCallingConvWin64(CC))
791 // Don't handle popping bytes on return for now.
792 if (X86MFInfo->getBytesToPopOnReturn() != 0)
795 // fastcc with -tailcallopt is intended to provide a guaranteed
796 // tail call optimization. Fastisel doesn't know how to do that.
797 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
800 // Let SDISel handle vararg functions.
804 // Build a list of return value registers.
805 SmallVector<unsigned, 4> RetRegs;
807 if (Ret->getNumOperands() > 0) {
808 SmallVector<ISD::OutputArg, 4> Outs;
809 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
811 // Analyze operands of the call, assigning locations to each operand.
812 SmallVector<CCValAssign, 16> ValLocs;
813 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
815 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
817 const Value *RV = Ret->getOperand(0);
818 unsigned Reg = getRegForValue(RV);
822 // Only handle a single return value for now.
823 if (ValLocs.size() != 1)
826 CCValAssign &VA = ValLocs[0];
828 // Don't bother handling odd stuff for now.
829 if (VA.getLocInfo() != CCValAssign::Full)
831 // Only handle register returns for now.
835 // The calling-convention tables for x87 returns don't tell
837 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
840 unsigned SrcReg = Reg + VA.getValNo();
841 EVT SrcVT = TLI.getValueType(RV->getType());
842 EVT DstVT = VA.getValVT();
843 // Special handling for extended integers.
844 if (SrcVT != DstVT) {
845 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
848 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
851 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
853 if (SrcVT == MVT::i1) {
854 if (Outs[0].Flags.isSExt())
856 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
859 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
861 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
862 SrcReg, /*TODO: Kill=*/false);
866 unsigned DstReg = VA.getLocReg();
867 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
868 // Avoid a cross-class copy. This is very unlikely.
869 if (!SrcRC->contains(DstReg))
871 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
872 DstReg).addReg(SrcReg);
874 // Add register to return instruction.
875 RetRegs.push_back(VA.getLocReg());
878 // The x86-64 ABI for returning structs by value requires that we copy
879 // the sret argument into %rax for the return. We saved the argument into
880 // a virtual register in the entry block, so now we copy the value out
881 // and into %rax. We also do the same with %eax for Win32.
882 if (F.hasStructRetAttr() &&
883 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
884 unsigned Reg = X86MFInfo->getSRetReturnReg();
886 "SRetReturnReg should have been set in LowerFormalArguments()!");
887 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
888 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
890 RetRegs.push_back(RetReg);
894 MachineInstrBuilder MIB =
895 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
896 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
897 MIB.addReg(RetRegs[i], RegState::Implicit);
901 /// X86SelectLoad - Select and emit code to implement load instructions.
903 bool X86FastISel::X86SelectLoad(const Instruction *I) {
904 // Atomic loads need special handling.
905 if (cast<LoadInst>(I)->isAtomic())
909 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
913 if (!X86SelectAddress(I->getOperand(0), AM))
916 unsigned ResultReg = 0;
917 if (X86FastEmitLoad(VT, AM, ResultReg)) {
918 UpdateValueMap(I, ResultReg);
924 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
925 bool HasAVX = Subtarget->hasAVX();
926 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
927 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
929 switch (VT.getSimpleVT().SimpleTy) {
931 case MVT::i8: return X86::CMP8rr;
932 case MVT::i16: return X86::CMP16rr;
933 case MVT::i32: return X86::CMP32rr;
934 case MVT::i64: return X86::CMP64rr;
936 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
938 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
942 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
943 /// of the comparison, return an opcode that works for the compare (e.g.
944 /// CMP32ri) otherwise return 0.
945 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
946 switch (VT.getSimpleVT().SimpleTy) {
947 // Otherwise, we can't fold the immediate into this comparison.
949 case MVT::i8: return X86::CMP8ri;
950 case MVT::i16: return X86::CMP16ri;
951 case MVT::i32: return X86::CMP32ri;
953 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
955 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
956 return X86::CMP64ri32;
961 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
963 unsigned Op0Reg = getRegForValue(Op0);
964 if (Op0Reg == 0) return false;
966 // Handle 'null' like i32/i64 0.
967 if (isa<ConstantPointerNull>(Op1))
968 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
970 // We have two options: compare with register or immediate. If the RHS of
971 // the compare is an immediate that we can fold into this compare, use
972 // CMPri, otherwise use CMPrr.
973 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
974 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
977 .addImm(Op1C->getSExtValue());
982 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
983 if (CompareOpc == 0) return false;
985 unsigned Op1Reg = getRegForValue(Op1);
986 if (Op1Reg == 0) return false;
987 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
994 bool X86FastISel::X86SelectCmp(const Instruction *I) {
995 const CmpInst *CI = cast<CmpInst>(I);
998 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1001 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
1003 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1004 switch (CI->getPredicate()) {
1005 case CmpInst::FCMP_OEQ: {
1006 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1009 unsigned EReg = createResultReg(&X86::GR8RegClass);
1010 unsigned NPReg = createResultReg(&X86::GR8RegClass);
1011 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
1012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1013 TII.get(X86::SETNPr), NPReg);
1014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1015 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
1016 UpdateValueMap(I, ResultReg);
1019 case CmpInst::FCMP_UNE: {
1020 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1023 unsigned NEReg = createResultReg(&X86::GR8RegClass);
1024 unsigned PReg = createResultReg(&X86::GR8RegClass);
1025 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
1026 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
1027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
1028 .addReg(PReg).addReg(NEReg);
1029 UpdateValueMap(I, ResultReg);
1032 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1033 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1034 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
1035 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
1036 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1037 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
1038 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
1039 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1040 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
1041 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
1042 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1043 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1045 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1046 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1047 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1048 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1049 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1050 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1051 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
1052 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
1053 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
1054 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
1059 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1061 std::swap(Op0, Op1);
1063 // Emit a compare of Op0/Op1.
1064 if (!X86FastEmitCompare(Op0, Op1, VT))
1067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1068 UpdateValueMap(I, ResultReg);
1072 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1073 EVT DstVT = TLI.getValueType(I->getType());
1074 if (!TLI.isTypeLegal(DstVT))
1077 unsigned ResultReg = getRegForValue(I->getOperand(0));
1081 // Handle zero-extension from i1 to i8, which is common.
1082 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1083 if (SrcVT.SimpleTy == MVT::i1) {
1084 // Set the high bits to zero.
1085 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1092 if (DstVT == MVT::i64) {
1093 // Handle extension to 64-bits via sub-register shenanigans.
1096 switch (SrcVT.SimpleTy) {
1097 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1098 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1099 case MVT::i32: MovInst = X86::MOV32rr; break;
1100 default: llvm_unreachable("Unexpected zext to i64 source type");
1103 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1107 ResultReg = createResultReg(&X86::GR64RegClass);
1108 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1110 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1111 } else if (DstVT != MVT::i8) {
1112 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1113 ResultReg, /*Kill=*/true);
1118 UpdateValueMap(I, ResultReg);
1123 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1124 // Unconditional branches are selected by tablegen-generated code.
1125 // Handle a conditional branch.
1126 const BranchInst *BI = cast<BranchInst>(I);
1127 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1128 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1130 // Fold the common case of a conditional branch with a comparison
1131 // in the same block (values defined on other blocks may not have
1132 // initialized registers).
1133 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1134 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1135 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1137 // Try to take advantage of fallthrough opportunities.
1138 CmpInst::Predicate Predicate = CI->getPredicate();
1139 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1140 std::swap(TrueMBB, FalseMBB);
1141 Predicate = CmpInst::getInversePredicate(Predicate);
1144 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1145 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1147 switch (Predicate) {
1148 case CmpInst::FCMP_OEQ:
1149 std::swap(TrueMBB, FalseMBB);
1150 Predicate = CmpInst::FCMP_UNE;
1152 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1153 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1154 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1155 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1156 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1157 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1158 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1159 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1160 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1161 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1162 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1163 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1164 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1166 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1167 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1168 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1169 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1170 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1171 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1172 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1173 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1174 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1175 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1180 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1182 std::swap(Op0, Op1);
1184 // Emit a compare of the LHS and RHS, setting the flags.
1185 if (!X86FastEmitCompare(Op0, Op1, VT))
1188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1191 if (Predicate == CmpInst::FCMP_UNE) {
1192 // X86 requires a second branch to handle UNE (and OEQ,
1193 // which is mapped to UNE above).
1194 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1198 FastEmitBranch(FalseMBB, DL);
1199 FuncInfo.MBB->addSuccessor(TrueMBB);
1202 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1203 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1204 // typically happen for _Bool and C++ bools.
1206 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1207 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1208 unsigned TestOpc = 0;
1209 switch (SourceVT.SimpleTy) {
1211 case MVT::i8: TestOpc = X86::TEST8ri; break;
1212 case MVT::i16: TestOpc = X86::TEST16ri; break;
1213 case MVT::i32: TestOpc = X86::TEST32ri; break;
1214 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1217 unsigned OpReg = getRegForValue(TI->getOperand(0));
1218 if (OpReg == 0) return false;
1219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1220 .addReg(OpReg).addImm(1);
1222 unsigned JmpOpc = X86::JNE_4;
1223 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1224 std::swap(TrueMBB, FalseMBB);
1228 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1230 FastEmitBranch(FalseMBB, DL);
1231 FuncInfo.MBB->addSuccessor(TrueMBB);
1237 // Otherwise do a clumsy setcc and re-test it.
1238 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1239 // in an explicit cast, so make sure to handle that correctly.
1240 unsigned OpReg = getRegForValue(BI->getCondition());
1241 if (OpReg == 0) return false;
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1244 .addReg(OpReg).addImm(1);
1245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1247 FastEmitBranch(FalseMBB, DL);
1248 FuncInfo.MBB->addSuccessor(TrueMBB);
1252 bool X86FastISel::X86SelectShift(const Instruction *I) {
1253 unsigned CReg = 0, OpReg = 0;
1254 const TargetRegisterClass *RC = NULL;
1255 if (I->getType()->isIntegerTy(8)) {
1257 RC = &X86::GR8RegClass;
1258 switch (I->getOpcode()) {
1259 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1260 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1261 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1262 default: return false;
1264 } else if (I->getType()->isIntegerTy(16)) {
1266 RC = &X86::GR16RegClass;
1267 switch (I->getOpcode()) {
1268 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1269 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1270 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1271 default: return false;
1273 } else if (I->getType()->isIntegerTy(32)) {
1275 RC = &X86::GR32RegClass;
1276 switch (I->getOpcode()) {
1277 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1278 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1279 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1280 default: return false;
1282 } else if (I->getType()->isIntegerTy(64)) {
1284 RC = &X86::GR64RegClass;
1285 switch (I->getOpcode()) {
1286 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1287 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1288 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1289 default: return false;
1296 if (!isTypeLegal(I->getType(), VT))
1299 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1300 if (Op0Reg == 0) return false;
1302 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1303 if (Op1Reg == 0) return false;
1304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1305 CReg).addReg(Op1Reg);
1307 // The shift instruction uses X86::CL. If we defined a super-register
1308 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1309 if (CReg != X86::CL)
1310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1311 TII.get(TargetOpcode::KILL), X86::CL)
1312 .addReg(CReg, RegState::Kill);
1314 unsigned ResultReg = createResultReg(RC);
1315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1317 UpdateValueMap(I, ResultReg);
1321 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1322 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1323 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1324 const static bool S = true; // IsSigned
1325 const static bool U = false; // !IsSigned
1326 const static unsigned Copy = TargetOpcode::COPY;
1327 // For the X86 DIV/IDIV instruction, in most cases the dividend
1328 // (numerator) must be in a specific register pair highreg:lowreg,
1329 // producing the quotient in lowreg and the remainder in highreg.
1330 // For most data types, to set up the instruction, the dividend is
1331 // copied into lowreg, and lowreg is sign-extended or zero-extended
1332 // into highreg. The exception is i8, where the dividend is defined
1333 // as a single register rather than a register pair, and we
1334 // therefore directly sign-extend or zero-extend the dividend into
1335 // lowreg, instead of copying, and ignore the highreg.
1336 const static struct DivRemEntry {
1337 // The following portion depends only on the data type.
1338 const TargetRegisterClass *RC;
1339 unsigned LowInReg; // low part of the register pair
1340 unsigned HighInReg; // high part of the register pair
1341 // The following portion depends on both the data type and the operation.
1342 struct DivRemResult {
1343 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1344 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1345 // highreg, or copying a zero into highreg.
1346 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1347 // zero/sign-extending into lowreg for i8.
1348 unsigned DivRemResultReg; // Register containing the desired result.
1349 bool IsOpSigned; // Whether to use signed or unsigned form.
1350 } ResultTable[NumOps];
1351 } OpTable[NumTypes] = {
1352 { &X86::GR8RegClass, X86::AX, 0, {
1353 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1354 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1355 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1356 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1359 { &X86::GR16RegClass, X86::AX, X86::DX, {
1360 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1361 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1362 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1363 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1366 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1367 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1368 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1369 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1370 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1373 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1374 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1375 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1376 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1377 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1383 if (!isTypeLegal(I->getType(), VT))
1386 unsigned TypeIndex, OpIndex;
1387 switch (VT.SimpleTy) {
1388 default: return false;
1389 case MVT::i8: TypeIndex = 0; break;
1390 case MVT::i16: TypeIndex = 1; break;
1391 case MVT::i32: TypeIndex = 2; break;
1392 case MVT::i64: TypeIndex = 3;
1393 if (!Subtarget->is64Bit())
1398 switch (I->getOpcode()) {
1399 default: llvm_unreachable("Unexpected div/rem opcode");
1400 case Instruction::SDiv: OpIndex = 0; break;
1401 case Instruction::SRem: OpIndex = 1; break;
1402 case Instruction::UDiv: OpIndex = 2; break;
1403 case Instruction::URem: OpIndex = 3; break;
1406 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1407 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1408 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1411 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1415 // Move op0 into low-order input register.
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1417 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1418 // Zero-extend or sign-extend into high-order input register.
1419 if (OpEntry.OpSignExtend) {
1420 if (OpEntry.IsOpSigned)
1421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1422 TII.get(OpEntry.OpSignExtend));
1424 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1426 TII.get(X86::MOV32r0), Zero32);
1428 // Copy the zero into the appropriate sub/super/identical physical
1429 // register. Unfortunately the operations needed are not uniform enough to
1430 // fit neatly into the table above.
1431 if (VT.SimpleTy == MVT::i16) {
1432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1433 TII.get(Copy), TypeEntry.HighInReg)
1434 .addReg(Zero32, 0, X86::sub_16bit);
1435 } else if (VT.SimpleTy == MVT::i32) {
1436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1437 TII.get(Copy), TypeEntry.HighInReg)
1439 } else if (VT.SimpleTy == MVT::i64) {
1440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1441 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1442 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1446 // Generate the DIV/IDIV instruction.
1447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1448 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1449 // For i8 remainder, we can't reference AH directly, as we'll end
1450 // up with bogus copies like %R9B = COPY %AH. Reference AX
1451 // instead to prevent AH references in a REX instruction.
1453 // The current assumption of the fast register allocator is that isel
1454 // won't generate explicit references to the GPR8_NOREX registers. If
1455 // the allocator and/or the backend get enhanced to be more robust in
1456 // that regard, this can be, and should be, removed.
1457 unsigned ResultReg = 0;
1458 if ((I->getOpcode() == Instruction::SRem ||
1459 I->getOpcode() == Instruction::URem) &&
1460 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1461 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1462 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1464 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1466 // Shift AX right by 8 bits instead of using AH.
1467 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri),
1468 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1470 // Now reference the 8-bit subreg of the result.
1471 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1472 /*Kill=*/true, X86::sub_8bit);
1474 // Copy the result out of the physreg if we haven't already.
1476 ResultReg = createResultReg(TypeEntry.RC);
1477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg)
1478 .addReg(OpEntry.DivRemResultReg);
1480 UpdateValueMap(I, ResultReg);
1485 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1487 if (!isTypeLegal(I->getType(), VT))
1490 // We only use cmov here, if we don't have a cmov instruction bail.
1491 if (!Subtarget->hasCMov()) return false;
1494 const TargetRegisterClass *RC = NULL;
1495 if (VT == MVT::i16) {
1496 Opc = X86::CMOVE16rr;
1497 RC = &X86::GR16RegClass;
1498 } else if (VT == MVT::i32) {
1499 Opc = X86::CMOVE32rr;
1500 RC = &X86::GR32RegClass;
1501 } else if (VT == MVT::i64) {
1502 Opc = X86::CMOVE64rr;
1503 RC = &X86::GR64RegClass;
1508 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1509 if (Op0Reg == 0) return false;
1510 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1511 if (Op1Reg == 0) return false;
1512 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1513 if (Op2Reg == 0) return false;
1515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1516 .addReg(Op0Reg).addReg(Op0Reg);
1517 unsigned ResultReg = createResultReg(RC);
1518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1519 .addReg(Op1Reg).addReg(Op2Reg);
1520 UpdateValueMap(I, ResultReg);
1524 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1525 // fpext from float to double.
1526 if (X86ScalarSSEf64 &&
1527 I->getType()->isDoubleTy()) {
1528 const Value *V = I->getOperand(0);
1529 if (V->getType()->isFloatTy()) {
1530 unsigned OpReg = getRegForValue(V);
1531 if (OpReg == 0) return false;
1532 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1533 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1534 TII.get(X86::CVTSS2SDrr), ResultReg)
1536 UpdateValueMap(I, ResultReg);
1544 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1545 if (X86ScalarSSEf64) {
1546 if (I->getType()->isFloatTy()) {
1547 const Value *V = I->getOperand(0);
1548 if (V->getType()->isDoubleTy()) {
1549 unsigned OpReg = getRegForValue(V);
1550 if (OpReg == 0) return false;
1551 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1553 TII.get(X86::CVTSD2SSrr), ResultReg)
1555 UpdateValueMap(I, ResultReg);
1564 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1565 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1566 EVT DstVT = TLI.getValueType(I->getType());
1568 // This code only handles truncation to byte.
1569 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1571 if (!TLI.isTypeLegal(SrcVT))
1574 unsigned InputReg = getRegForValue(I->getOperand(0));
1576 // Unhandled operand. Halt "fast" selection and bail.
1579 if (SrcVT == MVT::i8) {
1580 // Truncate from i8 to i1; no code needed.
1581 UpdateValueMap(I, InputReg);
1585 if (!Subtarget->is64Bit()) {
1586 // If we're on x86-32; we can't extract an i8 from a general register.
1587 // First issue a copy to GR16_ABCD or GR32_ABCD.
1588 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1589 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1590 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1591 unsigned CopyReg = createResultReg(CopyRC);
1592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1593 CopyReg).addReg(InputReg);
1597 // Issue an extract_subreg.
1598 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1599 InputReg, /*Kill=*/true,
1604 UpdateValueMap(I, ResultReg);
1608 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1609 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1612 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1613 X86AddressMode SrcAM, uint64_t Len) {
1615 // Make sure we don't bloat code by inlining very large memcpy's.
1616 if (!IsMemcpySmall(Len))
1619 bool i64Legal = Subtarget->is64Bit();
1621 // We don't care about alignment here since we just emit integer accesses.
1624 if (Len >= 8 && i64Legal)
1635 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1636 RV &= X86FastEmitStore(VT, Reg, DestAM);
1637 assert(RV && "Failed to emit load or store??");
1639 unsigned Size = VT.getSizeInBits()/8;
1641 DestAM.Disp += Size;
1648 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1649 // FIXME: Handle more intrinsics.
1650 switch (I.getIntrinsicID()) {
1651 default: return false;
1652 case Intrinsic::memcpy: {
1653 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1654 // Don't handle volatile or variable length memcpys.
1655 if (MCI.isVolatile())
1658 if (isa<ConstantInt>(MCI.getLength())) {
1659 // Small memcpy's are common enough that we want to do them
1660 // without a call if possible.
1661 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1662 if (IsMemcpySmall(Len)) {
1663 X86AddressMode DestAM, SrcAM;
1664 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1665 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1667 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1672 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1673 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1676 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1679 return DoSelectCall(&I, "memcpy");
1681 case Intrinsic::memset: {
1682 const MemSetInst &MSI = cast<MemSetInst>(I);
1684 if (MSI.isVolatile())
1687 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1688 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1691 if (MSI.getDestAddressSpace() > 255)
1694 return DoSelectCall(&I, "memset");
1696 case Intrinsic::stackprotector: {
1697 // Emit code to store the stack guard onto the stack.
1698 EVT PtrTy = TLI.getPointerTy();
1700 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1701 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1703 // Grab the frame index.
1705 if (!X86SelectAddress(Slot, AM)) return false;
1706 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1709 case Intrinsic::dbg_declare: {
1710 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1712 assert(DI->getAddress() && "Null address should be checked earlier!");
1713 if (!X86SelectAddress(DI->getAddress(), AM))
1715 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1716 // FIXME may need to add RegState::Debug to any registers produced,
1717 // although ESP/EBP should be the only ones at the moment.
1718 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1719 addImm(0).addMetadata(DI->getVariable());
1722 case Intrinsic::trap: {
1723 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1726 case Intrinsic::sadd_with_overflow:
1727 case Intrinsic::uadd_with_overflow: {
1728 // FIXME: Should fold immediates.
1730 // Replace "add with overflow" intrinsics with an "add" instruction followed
1731 // by a seto/setc instruction.
1732 const Function *Callee = I.getCalledFunction();
1734 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1737 if (!isTypeLegal(RetTy, VT))
1740 const Value *Op1 = I.getArgOperand(0);
1741 const Value *Op2 = I.getArgOperand(1);
1742 unsigned Reg1 = getRegForValue(Op1);
1743 unsigned Reg2 = getRegForValue(Op2);
1745 if (Reg1 == 0 || Reg2 == 0)
1746 // FIXME: Handle values *not* in registers.
1752 else if (VT == MVT::i64)
1757 // The call to CreateRegs builds two sequential registers, to store the
1758 // both the returned values.
1759 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1761 .addReg(Reg1).addReg(Reg2);
1763 unsigned Opc = X86::SETBr;
1764 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1766 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1768 UpdateValueMap(&I, ResultReg, 2);
1774 bool X86FastISel::FastLowerArguments() {
1775 if (!FuncInfo.CanLowerReturn)
1778 const Function *F = FuncInfo.Fn;
1782 CallingConv::ID CC = F->getCallingConv();
1783 if (CC != CallingConv::C)
1786 if (Subtarget->isCallingConvWin64(CC))
1789 if (!Subtarget->is64Bit())
1792 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1794 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1795 I != E; ++I, ++Idx) {
1799 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1800 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1801 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1802 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1805 Type *ArgTy = I->getType();
1806 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1809 EVT ArgVT = TLI.getValueType(ArgTy);
1810 if (!ArgVT.isSimple()) return false;
1811 switch (ArgVT.getSimpleVT().SimpleTy) {
1820 static const uint16_t GPR32ArgRegs[] = {
1821 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1823 static const uint16_t GPR64ArgRegs[] = {
1824 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1828 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1829 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1830 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1831 I != E; ++I, ++Idx) {
1832 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1833 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1834 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1835 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1836 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1837 // Without this, EmitLiveInCopies may eliminate the livein if its only
1838 // use is a bitcast (which isn't turned into an instruction).
1839 unsigned ResultReg = createResultReg(RC);
1840 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1841 ResultReg).addReg(DstReg, getKillRegState(true));
1842 UpdateValueMap(I, ResultReg);
1847 bool X86FastISel::X86SelectCall(const Instruction *I) {
1848 const CallInst *CI = cast<CallInst>(I);
1849 const Value *Callee = CI->getCalledValue();
1851 // Can't handle inline asm yet.
1852 if (isa<InlineAsm>(Callee))
1855 // Handle intrinsic calls.
1856 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1857 return X86VisitIntrinsicCall(*II);
1859 // Allow SelectionDAG isel to handle tail calls.
1860 if (cast<CallInst>(I)->isTailCall())
1863 return DoSelectCall(I, 0);
1866 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1867 const ImmutableCallSite &CS) {
1868 if (Subtarget.is64Bit())
1870 if (Subtarget.isTargetWindows())
1872 CallingConv::ID CC = CS.getCallingConv();
1873 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1875 if (!CS.paramHasAttr(1, Attribute::StructRet))
1877 if (CS.paramHasAttr(1, Attribute::InReg))
1882 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1883 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1884 const CallInst *CI = cast<CallInst>(I);
1885 const Value *Callee = CI->getCalledValue();
1887 // Handle only C and fastcc calling conventions for now.
1888 ImmutableCallSite CS(CI);
1889 CallingConv::ID CC = CS.getCallingConv();
1890 bool isWin64 = Subtarget->isCallingConvWin64(CC);
1891 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1892 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
1893 CC != CallingConv::X86_64_SysV)
1896 // fastcc with -tailcallopt is intended to provide a guaranteed
1897 // tail call optimization. Fastisel doesn't know how to do that.
1898 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1901 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1902 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1903 bool isVarArg = FTy->isVarArg();
1905 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1906 // x86-32. Special handling for x86-64 is implemented.
1907 if (isVarArg && isWin64)
1910 // Fast-isel doesn't know about callee-pop yet.
1911 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1912 TM.Options.GuaranteedTailCallOpt))
1915 // Check whether the function can return without sret-demotion.
1916 SmallVector<ISD::OutputArg, 4> Outs;
1917 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1918 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1919 *FuncInfo.MF, FTy->isVarArg(),
1920 Outs, FTy->getContext());
1921 if (!CanLowerReturn)
1924 // Materialize callee address in a register. FIXME: GV address can be
1925 // handled with a CALLpcrel32 instead.
1926 X86AddressMode CalleeAM;
1927 if (!X86SelectCallAddress(Callee, CalleeAM))
1929 unsigned CalleeOp = 0;
1930 const GlobalValue *GV = 0;
1931 if (CalleeAM.GV != 0) {
1933 } else if (CalleeAM.Base.Reg != 0) {
1934 CalleeOp = CalleeAM.Base.Reg;
1938 // Deal with call operands first.
1939 SmallVector<const Value *, 8> ArgVals;
1940 SmallVector<unsigned, 8> Args;
1941 SmallVector<MVT, 8> ArgVTs;
1942 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1943 unsigned arg_size = CS.arg_size();
1944 Args.reserve(arg_size);
1945 ArgVals.reserve(arg_size);
1946 ArgVTs.reserve(arg_size);
1947 ArgFlags.reserve(arg_size);
1948 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1950 // If we're lowering a mem intrinsic instead of a regular call, skip the
1951 // last two arguments, which should not passed to the underlying functions.
1952 if (MemIntName && e-i <= 2)
1955 ISD::ArgFlagsTy Flags;
1956 unsigned AttrInd = i - CS.arg_begin() + 1;
1957 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1959 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1962 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1963 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1964 Type *ElementTy = Ty->getElementType();
1965 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1966 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1968 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1970 Flags.setByValSize(FrameSize);
1971 Flags.setByValAlign(FrameAlign);
1972 if (!IsMemcpySmall(FrameSize))
1976 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1978 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1981 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1982 // instruction. This is safe because it is common to all fastisel supported
1983 // calling conventions on x86.
1984 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1985 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1986 CI->getBitWidth() == 16) {
1988 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1990 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1996 // Passing bools around ends up doing a trunc to i1 and passing it.
1997 // Codegen this as an argument + "and 1".
1998 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1999 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2000 ArgVal->hasOneUse()) {
2001 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2002 ArgReg = getRegForValue(ArgVal);
2003 if (ArgReg == 0) return false;
2006 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2008 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2009 ArgVal->hasOneUse(), 1);
2011 ArgReg = getRegForValue(ArgVal);
2014 if (ArgReg == 0) return false;
2016 Type *ArgTy = ArgVal->getType();
2018 if (!isTypeLegal(ArgTy, ArgVT))
2020 if (ArgVT == MVT::x86mmx)
2022 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2023 Flags.setOrigAlign(OriginalAlignment);
2025 Args.push_back(ArgReg);
2026 ArgVals.push_back(ArgVal);
2027 ArgVTs.push_back(ArgVT);
2028 ArgFlags.push_back(Flags);
2031 // Analyze operands of the call, assigning locations to each operand.
2032 SmallVector<CCValAssign, 16> ArgLocs;
2033 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2034 I->getParent()->getContext());
2036 // Allocate shadow area for Win64
2038 CCInfo.AllocateStack(32, 8);
2040 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2042 // Get a count of how many bytes are to be pushed on the stack.
2043 unsigned NumBytes = CCInfo.getNextStackOffset();
2045 // Issue CALLSEQ_START
2046 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
2050 // Process argument: walk the register/memloc assignments, inserting
2052 SmallVector<unsigned, 4> RegArgs;
2053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2054 CCValAssign &VA = ArgLocs[i];
2055 unsigned Arg = Args[VA.getValNo()];
2056 EVT ArgVT = ArgVTs[VA.getValNo()];
2058 // Promote the value if needed.
2059 switch (VA.getLocInfo()) {
2060 case CCValAssign::Full: break;
2061 case CCValAssign::SExt: {
2062 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2063 "Unexpected extend");
2064 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2066 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2067 ArgVT = VA.getLocVT();
2070 case CCValAssign::ZExt: {
2071 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2072 "Unexpected extend");
2073 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2075 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2076 ArgVT = VA.getLocVT();
2079 case CCValAssign::AExt: {
2080 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2081 "Unexpected extend");
2082 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2085 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2088 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2091 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2092 ArgVT = VA.getLocVT();
2095 case CCValAssign::BCvt: {
2096 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2097 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2098 assert(BC != 0 && "Failed to emit a bitcast!");
2100 ArgVT = VA.getLocVT();
2103 case CCValAssign::VExt:
2104 // VExt has not been implemented, so this should be impossible to reach
2105 // for now. However, fallback to Selection DAG isel once implemented.
2107 case CCValAssign::Indirect:
2108 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2113 if (VA.isRegLoc()) {
2114 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2115 VA.getLocReg()).addReg(Arg);
2116 RegArgs.push_back(VA.getLocReg());
2118 unsigned LocMemOffset = VA.getLocMemOffset();
2120 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2121 getTargetMachine()->getRegisterInfo());
2122 AM.Base.Reg = RegInfo->getStackRegister();
2123 AM.Disp = LocMemOffset;
2124 const Value *ArgVal = ArgVals[VA.getValNo()];
2125 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2127 if (Flags.isByVal()) {
2128 X86AddressMode SrcAM;
2129 SrcAM.Base.Reg = Arg;
2130 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2131 assert(Res && "memcpy length already checked!"); (void)Res;
2132 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2133 // If this is a really simple value, emit this with the Value* version
2134 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2135 // as it can cause us to reevaluate the argument.
2136 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2139 if (!X86FastEmitStore(ArgVT, Arg, AM))
2145 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2147 if (Subtarget->isPICStyleGOT()) {
2148 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2150 X86::EBX).addReg(Base);
2153 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2154 // Count the number of XMM registers allocated.
2155 static const uint16_t XMMArgRegs[] = {
2156 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2157 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2159 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2161 X86::AL).addImm(NumXMMRegs);
2165 MachineInstrBuilder MIB;
2167 // Register-indirect call.
2169 if (Subtarget->is64Bit())
2170 CallOpc = X86::CALL64r;
2172 CallOpc = X86::CALL32r;
2173 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2178 assert(GV && "Not a direct call");
2180 if (Subtarget->is64Bit())
2181 CallOpc = X86::CALL64pcrel32;
2183 CallOpc = X86::CALLpcrel32;
2185 // See if we need any target-specific flags on the GV operand.
2186 unsigned char OpFlags = 0;
2188 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2189 // external symbols most go through the PLT in PIC mode. If the symbol
2190 // has hidden or protected visibility, or if it is static or local, then
2191 // we don't need to use the PLT - we can directly call it.
2192 if (Subtarget->isTargetELF() &&
2193 TM.getRelocationModel() == Reloc::PIC_ &&
2194 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2195 OpFlags = X86II::MO_PLT;
2196 } else if (Subtarget->isPICStyleStubAny() &&
2197 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2198 (!Subtarget->getTargetTriple().isMacOSX() ||
2199 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2200 // PC-relative references to external symbols should go through $stub,
2201 // unless we're building with the leopard linker or later, which
2202 // automatically synthesizes these stubs.
2203 OpFlags = X86II::MO_DARWIN_STUB;
2207 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2209 MIB.addExternalSymbol(MemIntName, OpFlags);
2211 MIB.addGlobalAddress(GV, 0, OpFlags);
2214 // Add a register mask with the call-preserved registers.
2215 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2216 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2218 // Add an implicit use GOT pointer in EBX.
2219 if (Subtarget->isPICStyleGOT())
2220 MIB.addReg(X86::EBX, RegState::Implicit);
2222 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2223 MIB.addReg(X86::AL, RegState::Implicit);
2225 // Add implicit physical register uses to the call.
2226 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2227 MIB.addReg(RegArgs[i], RegState::Implicit);
2229 // Issue CALLSEQ_END
2230 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2231 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2233 .addImm(NumBytes).addImm(NumBytesCallee);
2235 // Build info for return calling conv lowering code.
2236 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2237 SmallVector<ISD::InputArg, 32> Ins;
2238 SmallVector<EVT, 4> RetTys;
2239 ComputeValueVTs(TLI, I->getType(), RetTys);
2240 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2242 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2243 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2244 for (unsigned j = 0; j != NumRegs; ++j) {
2245 ISD::InputArg MyFlags;
2246 MyFlags.VT = RegisterVT;
2247 MyFlags.Used = !CS.getInstruction()->use_empty();
2248 if (CS.paramHasAttr(0, Attribute::SExt))
2249 MyFlags.Flags.setSExt();
2250 if (CS.paramHasAttr(0, Attribute::ZExt))
2251 MyFlags.Flags.setZExt();
2252 if (CS.paramHasAttr(0, Attribute::InReg))
2253 MyFlags.Flags.setInReg();
2254 Ins.push_back(MyFlags);
2258 // Now handle call return values.
2259 SmallVector<unsigned, 4> UsedRegs;
2260 SmallVector<CCValAssign, 16> RVLocs;
2261 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2262 I->getParent()->getContext());
2263 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2264 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2265 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2266 EVT CopyVT = RVLocs[i].getValVT();
2267 unsigned CopyReg = ResultReg + i;
2269 // If this is a call to a function that returns an fp value on the x87 fp
2270 // stack, but where we prefer to use the value in xmm registers, copy it
2271 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2272 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2273 RVLocs[i].getLocReg() == X86::ST1)) {
2274 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2276 CopyReg = createResultReg(&X86::RFP80RegClass);
2278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2282 CopyReg).addReg(RVLocs[i].getLocReg());
2283 UsedRegs.push_back(RVLocs[i].getLocReg());
2286 if (CopyVT != RVLocs[i].getValVT()) {
2287 // Round the F80 the right size, which also moves to the appropriate xmm
2288 // register. This is accomplished by storing the F80 value in memory and
2289 // then loading it back. Ewww...
2290 EVT ResVT = RVLocs[i].getValVT();
2291 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2292 unsigned MemSize = ResVT.getSizeInBits()/8;
2293 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2294 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2297 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2298 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2299 TII.get(Opc), ResultReg + i), FI);
2304 UpdateValueMap(I, ResultReg, RVLocs.size());
2306 // Set all unused physreg defs as dead.
2307 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2314 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2315 switch (I->getOpcode()) {
2317 case Instruction::Load:
2318 return X86SelectLoad(I);
2319 case Instruction::Store:
2320 return X86SelectStore(I);
2321 case Instruction::Ret:
2322 return X86SelectRet(I);
2323 case Instruction::ICmp:
2324 case Instruction::FCmp:
2325 return X86SelectCmp(I);
2326 case Instruction::ZExt:
2327 return X86SelectZExt(I);
2328 case Instruction::Br:
2329 return X86SelectBranch(I);
2330 case Instruction::Call:
2331 return X86SelectCall(I);
2332 case Instruction::LShr:
2333 case Instruction::AShr:
2334 case Instruction::Shl:
2335 return X86SelectShift(I);
2336 case Instruction::SDiv:
2337 case Instruction::UDiv:
2338 case Instruction::SRem:
2339 case Instruction::URem:
2340 return X86SelectDivRem(I);
2341 case Instruction::Select:
2342 return X86SelectSelect(I);
2343 case Instruction::Trunc:
2344 return X86SelectTrunc(I);
2345 case Instruction::FPExt:
2346 return X86SelectFPExt(I);
2347 case Instruction::FPTrunc:
2348 return X86SelectFPTrunc(I);
2349 case Instruction::IntToPtr: // Deliberate fall-through.
2350 case Instruction::PtrToInt: {
2351 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2352 EVT DstVT = TLI.getValueType(I->getType());
2353 if (DstVT.bitsGT(SrcVT))
2354 return X86SelectZExt(I);
2355 if (DstVT.bitsLT(SrcVT))
2356 return X86SelectTrunc(I);
2357 unsigned Reg = getRegForValue(I->getOperand(0));
2358 if (Reg == 0) return false;
2359 UpdateValueMap(I, Reg);
2367 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2369 if (!isTypeLegal(C->getType(), VT))
2372 // Can't handle alternate code models yet.
2373 if (TM.getCodeModel() != CodeModel::Small)
2376 // Get opcode and regclass of the output for the given load instruction.
2378 const TargetRegisterClass *RC = NULL;
2379 switch (VT.SimpleTy) {
2383 RC = &X86::GR8RegClass;
2387 RC = &X86::GR16RegClass;
2391 RC = &X86::GR32RegClass;
2394 // Must be in x86-64 mode.
2396 RC = &X86::GR64RegClass;
2399 if (X86ScalarSSEf32) {
2400 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2401 RC = &X86::FR32RegClass;
2403 Opc = X86::LD_Fp32m;
2404 RC = &X86::RFP32RegClass;
2408 if (X86ScalarSSEf64) {
2409 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2410 RC = &X86::FR64RegClass;
2412 Opc = X86::LD_Fp64m;
2413 RC = &X86::RFP64RegClass;
2417 // No f80 support yet.
2421 // Materialize addresses with LEA instructions.
2422 if (isa<GlobalValue>(C)) {
2424 if (X86SelectAddress(C, AM)) {
2425 // If the expression is just a basereg, then we're done, otherwise we need
2427 if (AM.BaseType == X86AddressMode::RegBase &&
2428 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2431 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2432 unsigned ResultReg = createResultReg(RC);
2433 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2434 TII.get(Opc), ResultReg), AM);
2440 // MachineConstantPool wants an explicit alignment.
2441 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2443 // Alignment of vector types. FIXME!
2444 Align = TD.getTypeAllocSize(C->getType());
2447 // x86-32 PIC requires a PIC base register for constant pools.
2448 unsigned PICBase = 0;
2449 unsigned char OpFlag = 0;
2450 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2451 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2452 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2453 } else if (Subtarget->isPICStyleGOT()) {
2454 OpFlag = X86II::MO_GOTOFF;
2455 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2456 } else if (Subtarget->isPICStyleRIPRel() &&
2457 TM.getCodeModel() == CodeModel::Small) {
2461 // Create the load from the constant pool.
2462 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2463 unsigned ResultReg = createResultReg(RC);
2464 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2465 TII.get(Opc), ResultReg),
2466 MCPOffset, PICBase, OpFlag);
2471 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2472 // Fail on dynamic allocas. At this point, getRegForValue has already
2473 // checked its CSE maps, so if we're here trying to handle a dynamic
2474 // alloca, we're not going to succeed. X86SelectAddress has a
2475 // check for dynamic allocas, because it's called directly from
2476 // various places, but TargetMaterializeAlloca also needs a check
2477 // in order to avoid recursion between getRegForValue,
2478 // X86SelectAddrss, and TargetMaterializeAlloca.
2479 if (!FuncInfo.StaticAllocaMap.count(C))
2483 if (!X86SelectAddress(C, AM))
2485 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2486 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2487 unsigned ResultReg = createResultReg(RC);
2488 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2489 TII.get(Opc), ResultReg), AM);
2493 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2495 if (!isTypeLegal(CF->getType(), VT))
2498 // Get opcode and regclass for the given zero.
2500 const TargetRegisterClass *RC = NULL;
2501 switch (VT.SimpleTy) {
2504 if (X86ScalarSSEf32) {
2505 Opc = X86::FsFLD0SS;
2506 RC = &X86::FR32RegClass;
2508 Opc = X86::LD_Fp032;
2509 RC = &X86::RFP32RegClass;
2513 if (X86ScalarSSEf64) {
2514 Opc = X86::FsFLD0SD;
2515 RC = &X86::FR64RegClass;
2517 Opc = X86::LD_Fp064;
2518 RC = &X86::RFP64RegClass;
2522 // No f80 support yet.
2526 unsigned ResultReg = createResultReg(RC);
2527 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2532 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2533 const LoadInst *LI) {
2535 if (!X86SelectAddress(LI->getOperand(0), AM))
2538 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2540 unsigned Size = TD.getTypeAllocSize(LI->getType());
2541 unsigned Alignment = LI->getAlignment();
2543 SmallVector<MachineOperand, 8> AddrOps;
2544 AM.getFullAddress(AddrOps);
2546 MachineInstr *Result =
2547 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2548 if (Result == 0) return false;
2550 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2551 MI->eraseFromParent();
2557 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2558 const TargetLibraryInfo *libInfo) {
2559 return new X86FastISel(funcInfo, libInfo);