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 "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/TargetOptions.h"
44 class X86FastISel final : public FastISel {
45 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
46 /// make the right decision when generating code for different targets.
47 const X86Subtarget *Subtarget;
49 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
50 /// floating point ops.
51 /// When SSE is available, use it for f32 operations.
52 /// When SSE2 is available, use it for f64 operations.
57 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
58 const TargetLibraryInfo *libInfo)
59 : FastISel(funcInfo, libInfo) {
60 Subtarget = &TM.getSubtarget<X86Subtarget>();
61 X86ScalarSSEf64 = Subtarget->hasSSE2();
62 X86ScalarSSEf32 = Subtarget->hasSSE1();
65 bool TargetSelectInstruction(const Instruction *I) override;
67 /// \brief The specified machine instr operand is a vreg, and that
68 /// vreg is being provided by the specified load instruction. If possible,
69 /// try to fold the load as an operand to the instruction, returning true if
71 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
72 const LoadInst *LI) override;
74 bool FastLowerArguments() override;
76 #include "X86GenFastISel.inc"
79 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
81 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
83 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
84 bool Aligned = false);
85 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM,
86 bool Aligned = false);
88 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
91 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
92 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
94 bool X86SelectLoad(const Instruction *I);
96 bool X86SelectStore(const Instruction *I);
98 bool X86SelectRet(const Instruction *I);
100 bool X86SelectCmp(const Instruction *I);
102 bool X86SelectZExt(const Instruction *I);
104 bool X86SelectBranch(const Instruction *I);
106 bool X86SelectShift(const Instruction *I);
108 bool X86SelectDivRem(const Instruction *I);
110 bool X86SelectSelect(const Instruction *I);
112 bool X86SelectTrunc(const Instruction *I);
114 bool X86SelectFPExt(const Instruction *I);
115 bool X86SelectFPTrunc(const Instruction *I);
117 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
118 bool X86SelectCall(const Instruction *I);
120 bool DoSelectCall(const Instruction *I, const char *MemIntName);
122 const X86InstrInfo *getInstrInfo() const {
123 return getTargetMachine()->getInstrInfo();
125 const X86TargetMachine *getTargetMachine() const {
126 return static_cast<const X86TargetMachine *>(&TM);
129 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
131 unsigned TargetMaterializeConstant(const Constant *C) override;
133 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
135 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
137 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
138 /// computed in an SSE register, not on the X87 floating point stack.
139 bool isScalarFPTypeInSSEReg(EVT VT) const {
140 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
141 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
144 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
146 bool IsMemcpySmall(uint64_t Len);
148 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
149 X86AddressMode SrcAM, uint64_t Len);
152 } // end anonymous namespace.
154 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
155 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
156 if (evt == MVT::Other || !evt.isSimple())
157 // Unhandled type. Halt "fast" selection and bail.
160 VT = evt.getSimpleVT();
161 // For now, require SSE/SSE2 for performing floating-point operations,
162 // since x87 requires additional work.
163 if (VT == MVT::f64 && !X86ScalarSSEf64)
165 if (VT == MVT::f32 && !X86ScalarSSEf32)
167 // Similarly, no f80 support yet.
170 // We only handle legal types. For example, on x86-32 the instruction
171 // selector contains all of the 64-bit instructions from x86-64,
172 // under the assumption that i64 won't be used if the target doesn't
174 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
177 #include "X86GenCallingConv.inc"
179 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
180 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
181 /// Return true and the result register by reference if it is possible.
182 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
183 unsigned &ResultReg) {
184 // Get opcode and regclass of the output for the given load instruction.
186 const TargetRegisterClass *RC = nullptr;
187 switch (VT.getSimpleVT().SimpleTy) {
188 default: return false;
192 RC = &X86::GR8RegClass;
196 RC = &X86::GR16RegClass;
200 RC = &X86::GR32RegClass;
203 // Must be in x86-64 mode.
205 RC = &X86::GR64RegClass;
208 if (X86ScalarSSEf32) {
209 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
210 RC = &X86::FR32RegClass;
213 RC = &X86::RFP32RegClass;
217 if (X86ScalarSSEf64) {
218 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
219 RC = &X86::FR64RegClass;
222 RC = &X86::RFP64RegClass;
226 // No f80 support yet.
230 ResultReg = createResultReg(RC);
231 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
232 DbgLoc, TII.get(Opc), ResultReg), AM);
236 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
237 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
238 /// and a displacement offset, or a GlobalAddress,
239 /// i.e. V. Return true if it is possible.
241 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg,
242 const X86AddressMode &AM, bool Aligned) {
243 // Get opcode and regclass of the output for the given store instruction.
245 switch (VT.getSimpleVT().SimpleTy) {
246 case MVT::f80: // No f80 support yet.
247 default: return false;
249 // Mask out all but lowest bit.
250 unsigned AndResult = createResultReg(&X86::GR8RegClass);
251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
252 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1);
255 // FALLTHROUGH, handling i1 as i8.
256 case MVT::i8: Opc = X86::MOV8mr; break;
257 case MVT::i16: Opc = X86::MOV16mr; break;
258 case MVT::i32: Opc = X86::MOV32mr; break;
259 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
261 Opc = X86ScalarSSEf32 ?
262 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
265 Opc = X86ScalarSSEf64 ?
266 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
270 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
272 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
276 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
278 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
285 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
287 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
291 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
292 DbgLoc, TII.get(Opc)), AM).addReg(ValReg);
296 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
297 const X86AddressMode &AM, bool Aligned) {
298 // Handle 'null' like i32/i64 0.
299 if (isa<ConstantPointerNull>(Val))
300 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
302 // If this is a store of a simple constant, fold the constant into the store.
303 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
306 switch (VT.getSimpleVT().SimpleTy) {
308 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
309 case MVT::i8: Opc = X86::MOV8mi; break;
310 case MVT::i16: Opc = X86::MOV16mi; break;
311 case MVT::i32: Opc = X86::MOV32mi; break;
313 // Must be a 32-bit sign extended value.
314 if (isInt<32>(CI->getSExtValue()))
315 Opc = X86::MOV64mi32;
320 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
321 DbgLoc, TII.get(Opc)), AM)
322 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
328 unsigned ValReg = getRegForValue(Val);
332 return X86FastEmitStore(VT, ValReg, AM, Aligned);
335 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
336 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
337 /// ISD::SIGN_EXTEND).
338 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
339 unsigned Src, EVT SrcVT,
340 unsigned &ResultReg) {
341 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
342 Src, /*TODO: Kill=*/false);
350 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
351 // Handle constant address.
352 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
353 // Can't handle alternate code models yet.
354 if (TM.getCodeModel() != CodeModel::Small)
357 // Can't handle TLS yet.
358 if (GV->isThreadLocal())
361 // RIP-relative addresses can't have additional register operands, so if
362 // we've already folded stuff into the addressing mode, just force the
363 // global value into its own register, which we can use as the basereg.
364 if (!Subtarget->isPICStyleRIPRel() ||
365 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
366 // Okay, we've committed to selecting this global. Set up the address.
369 // Allow the subtarget to classify the global.
370 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
372 // If this reference is relative to the pic base, set it now.
373 if (isGlobalRelativeToPICBase(GVFlags)) {
374 // FIXME: How do we know Base.Reg is free??
375 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
378 // Unless the ABI requires an extra load, return a direct reference to
380 if (!isGlobalStubReference(GVFlags)) {
381 if (Subtarget->isPICStyleRIPRel()) {
382 // Use rip-relative addressing if we can. Above we verified that the
383 // base and index registers are unused.
384 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
385 AM.Base.Reg = X86::RIP;
387 AM.GVOpFlags = GVFlags;
391 // Ok, we need to do a load from a stub. If we've already loaded from
392 // this stub, reuse the loaded pointer, otherwise emit the load now.
393 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
395 if (I != LocalValueMap.end() && I->second != 0) {
398 // Issue load from stub.
400 const TargetRegisterClass *RC = nullptr;
401 X86AddressMode StubAM;
402 StubAM.Base.Reg = AM.Base.Reg;
404 StubAM.GVOpFlags = GVFlags;
406 // Prepare for inserting code in the local-value area.
407 SavePoint SaveInsertPt = enterLocalValueArea();
409 if (TLI.getPointerTy() == MVT::i64) {
411 RC = &X86::GR64RegClass;
413 if (Subtarget->isPICStyleRIPRel())
414 StubAM.Base.Reg = X86::RIP;
417 RC = &X86::GR32RegClass;
420 LoadReg = createResultReg(RC);
421 MachineInstrBuilder LoadMI =
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
423 addFullAddress(LoadMI, StubAM);
425 // Ok, back to normal mode.
426 leaveLocalValueArea(SaveInsertPt);
428 // Prevent loading GV stub multiple times in same MBB.
429 LocalValueMap[V] = LoadReg;
432 // Now construct the final address. Note that the Disp, Scale,
433 // and Index values may already be set here.
434 AM.Base.Reg = LoadReg;
440 // If all else fails, try to materialize the value in a register.
441 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
442 if (AM.Base.Reg == 0) {
443 AM.Base.Reg = getRegForValue(V);
444 return AM.Base.Reg != 0;
446 if (AM.IndexReg == 0) {
447 assert(AM.Scale == 1 && "Scale with no index!");
448 AM.IndexReg = getRegForValue(V);
449 return AM.IndexReg != 0;
456 /// X86SelectAddress - Attempt to fill in an address from the given value.
458 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
459 SmallVector<const Value *, 32> GEPs;
461 const User *U = nullptr;
462 unsigned Opcode = Instruction::UserOp1;
463 if (const Instruction *I = dyn_cast<Instruction>(V)) {
464 // Don't walk into other basic blocks; it's possible we haven't
465 // visited them yet, so the instructions may not yet be assigned
466 // virtual registers.
467 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
468 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
469 Opcode = I->getOpcode();
472 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
473 Opcode = C->getOpcode();
477 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
478 if (Ty->getAddressSpace() > 255)
479 // Fast instruction selection doesn't support the special
485 case Instruction::BitCast:
486 // Look past bitcasts.
487 return X86SelectAddress(U->getOperand(0), AM);
489 case Instruction::IntToPtr:
490 // Look past no-op inttoptrs.
491 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
492 return X86SelectAddress(U->getOperand(0), AM);
495 case Instruction::PtrToInt:
496 // Look past no-op ptrtoints.
497 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
498 return X86SelectAddress(U->getOperand(0), AM);
501 case Instruction::Alloca: {
502 // Do static allocas.
503 const AllocaInst *A = cast<AllocaInst>(V);
504 DenseMap<const AllocaInst*, int>::iterator SI =
505 FuncInfo.StaticAllocaMap.find(A);
506 if (SI != FuncInfo.StaticAllocaMap.end()) {
507 AM.BaseType = X86AddressMode::FrameIndexBase;
508 AM.Base.FrameIndex = SI->second;
514 case Instruction::Add: {
515 // Adds of constants are common and easy enough.
516 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
517 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
518 // They have to fit in the 32-bit signed displacement field though.
519 if (isInt<32>(Disp)) {
520 AM.Disp = (uint32_t)Disp;
521 return X86SelectAddress(U->getOperand(0), AM);
527 case Instruction::GetElementPtr: {
528 X86AddressMode SavedAM = AM;
530 // Pattern-match simple GEPs.
531 uint64_t Disp = (int32_t)AM.Disp;
532 unsigned IndexReg = AM.IndexReg;
533 unsigned Scale = AM.Scale;
534 gep_type_iterator GTI = gep_type_begin(U);
535 // Iterate through the indices, folding what we can. Constants can be
536 // folded, and one dynamic index can be handled, if the scale is supported.
537 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
538 i != e; ++i, ++GTI) {
539 const Value *Op = *i;
540 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
541 const StructLayout *SL = DL.getStructLayout(STy);
542 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
546 // A array/variable index is always of the form i*S where S is the
547 // constant scale size. See if we can push the scale into immediates.
548 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
550 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
551 // Constant-offset addressing.
552 Disp += CI->getSExtValue() * S;
555 if (canFoldAddIntoGEP(U, Op)) {
556 // A compatible add with a constant operand. Fold the constant.
558 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
559 Disp += CI->getSExtValue() * S;
560 // Iterate on the other operand.
561 Op = cast<AddOperator>(Op)->getOperand(0);
565 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
566 (S == 1 || S == 2 || S == 4 || S == 8)) {
567 // Scaled-index addressing.
569 IndexReg = getRegForGEPIndex(Op).first;
575 goto unsupported_gep;
579 // Check for displacement overflow.
580 if (!isInt<32>(Disp))
583 AM.IndexReg = IndexReg;
585 AM.Disp = (uint32_t)Disp;
588 if (const GetElementPtrInst *GEP =
589 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
590 // Ok, the GEP indices were covered by constant-offset and scaled-index
591 // addressing. Update the address state and move on to examining the base.
594 } else if (X86SelectAddress(U->getOperand(0), AM)) {
598 // If we couldn't merge the gep value into this addr mode, revert back to
599 // our address and just match the value instead of completely failing.
602 for (SmallVectorImpl<const Value *>::reverse_iterator
603 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
604 if (handleConstantAddresses(*I, AM))
609 // Ok, the GEP indices weren't all covered.
614 return handleConstantAddresses(V, AM);
617 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
619 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
620 const User *U = nullptr;
621 unsigned Opcode = Instruction::UserOp1;
622 const Instruction *I = dyn_cast<Instruction>(V);
623 // Record if the value is defined in the same basic block.
625 // This information is crucial to know whether or not folding an
627 // Indeed, FastISel generates or reuses a virtual register for all
628 // operands of all instructions it selects. Obviously, the definition and
629 // its uses must use the same virtual register otherwise the produced
630 // code is incorrect.
631 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
632 // registers for values that are alive across basic blocks. This ensures
633 // that the values are consistently set between across basic block, even
634 // if different instruction selection mechanisms are used (e.g., a mix of
635 // SDISel and FastISel).
636 // For values local to a basic block, the instruction selection process
637 // generates these virtual registers with whatever method is appropriate
638 // for its needs. In particular, FastISel and SDISel do not share the way
639 // local virtual registers are set.
640 // Therefore, this is impossible (or at least unsafe) to share values
641 // between basic blocks unless they use the same instruction selection
642 // method, which is not guarantee for X86.
643 // Moreover, things like hasOneUse could not be used accurately, if we
644 // allow to reference values across basic blocks whereas they are not
645 // alive across basic blocks initially.
648 Opcode = I->getOpcode();
650 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
651 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
652 Opcode = C->getOpcode();
658 case Instruction::BitCast:
659 // Look past bitcasts if its operand is in the same BB.
661 return X86SelectCallAddress(U->getOperand(0), AM);
664 case Instruction::IntToPtr:
665 // Look past no-op inttoptrs if its operand is in the same BB.
667 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
668 return X86SelectCallAddress(U->getOperand(0), AM);
671 case Instruction::PtrToInt:
672 // Look past no-op ptrtoints if its operand is in the same BB.
674 TLI.getValueType(U->getType()) == TLI.getPointerTy())
675 return X86SelectCallAddress(U->getOperand(0), AM);
679 // Handle constant address.
680 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
681 // Can't handle alternate code models yet.
682 if (TM.getCodeModel() != CodeModel::Small)
685 // RIP-relative addresses can't have additional register operands.
686 if (Subtarget->isPICStyleRIPRel() &&
687 (AM.Base.Reg != 0 || AM.IndexReg != 0))
690 // Can't handle DbgLocLImport.
691 if (GV->hasDLLImportStorageClass())
695 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
696 if (GVar->isThreadLocal())
699 // Okay, we've committed to selecting this global. Set up the basic address.
702 // No ABI requires an extra load for anything other than DLLImport, which
703 // we rejected above. Return a direct reference to the global.
704 if (Subtarget->isPICStyleRIPRel()) {
705 // Use rip-relative addressing if we can. Above we verified that the
706 // base and index registers are unused.
707 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
708 AM.Base.Reg = X86::RIP;
709 } else if (Subtarget->isPICStyleStubPIC()) {
710 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
711 } else if (Subtarget->isPICStyleGOT()) {
712 AM.GVOpFlags = X86II::MO_GOTOFF;
718 // If all else fails, try to materialize the value in a register.
719 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
720 if (AM.Base.Reg == 0) {
721 AM.Base.Reg = getRegForValue(V);
722 return AM.Base.Reg != 0;
724 if (AM.IndexReg == 0) {
725 assert(AM.Scale == 1 && "Scale with no index!");
726 AM.IndexReg = getRegForValue(V);
727 return AM.IndexReg != 0;
735 /// X86SelectStore - Select and emit code to implement store instructions.
736 bool X86FastISel::X86SelectStore(const Instruction *I) {
737 // Atomic stores need special handling.
738 const StoreInst *S = cast<StoreInst>(I);
743 unsigned SABIAlignment =
744 DL.getABITypeAlignment(S->getValueOperand()->getType());
745 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment;
748 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
752 if (!X86SelectAddress(I->getOperand(1), AM))
755 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned);
758 /// X86SelectRet - Select and emit code to implement ret instructions.
759 bool X86FastISel::X86SelectRet(const Instruction *I) {
760 const ReturnInst *Ret = cast<ReturnInst>(I);
761 const Function &F = *I->getParent()->getParent();
762 const X86MachineFunctionInfo *X86MFInfo =
763 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
765 if (!FuncInfo.CanLowerReturn)
768 CallingConv::ID CC = F.getCallingConv();
769 if (CC != CallingConv::C &&
770 CC != CallingConv::Fast &&
771 CC != CallingConv::X86_FastCall &&
772 CC != CallingConv::X86_64_SysV)
775 if (Subtarget->isCallingConvWin64(CC))
778 // Don't handle popping bytes on return for now.
779 if (X86MFInfo->getBytesToPopOnReturn() != 0)
782 // fastcc with -tailcallopt is intended to provide a guaranteed
783 // tail call optimization. Fastisel doesn't know how to do that.
784 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
787 // Let SDISel handle vararg functions.
791 // Build a list of return value registers.
792 SmallVector<unsigned, 4> RetRegs;
794 if (Ret->getNumOperands() > 0) {
795 SmallVector<ISD::OutputArg, 4> Outs;
796 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
798 // Analyze operands of the call, assigning locations to each operand.
799 SmallVector<CCValAssign, 16> ValLocs;
800 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
802 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
804 const Value *RV = Ret->getOperand(0);
805 unsigned Reg = getRegForValue(RV);
809 // Only handle a single return value for now.
810 if (ValLocs.size() != 1)
813 CCValAssign &VA = ValLocs[0];
815 // Don't bother handling odd stuff for now.
816 if (VA.getLocInfo() != CCValAssign::Full)
818 // Only handle register returns for now.
822 // The calling-convention tables for x87 returns don't tell
824 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
827 unsigned SrcReg = Reg + VA.getValNo();
828 EVT SrcVT = TLI.getValueType(RV->getType());
829 EVT DstVT = VA.getValVT();
830 // Special handling for extended integers.
831 if (SrcVT != DstVT) {
832 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
835 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
838 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
840 if (SrcVT == MVT::i1) {
841 if (Outs[0].Flags.isSExt())
843 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
846 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
848 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
849 SrcReg, /*TODO: Kill=*/false);
853 unsigned DstReg = VA.getLocReg();
854 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
855 // Avoid a cross-class copy. This is very unlikely.
856 if (!SrcRC->contains(DstReg))
858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
859 DstReg).addReg(SrcReg);
861 // Add register to return instruction.
862 RetRegs.push_back(VA.getLocReg());
865 // The x86-64 ABI for returning structs by value requires that we copy
866 // the sret argument into %rax for the return. We saved the argument into
867 // a virtual register in the entry block, so now we copy the value out
868 // and into %rax. We also do the same with %eax for Win32.
869 if (F.hasStructRetAttr() &&
870 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
871 unsigned Reg = X86MFInfo->getSRetReturnReg();
873 "SRetReturnReg should have been set in LowerFormalArguments()!");
874 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
877 RetRegs.push_back(RetReg);
881 MachineInstrBuilder MIB =
882 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
883 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
884 MIB.addReg(RetRegs[i], RegState::Implicit);
888 /// X86SelectLoad - Select and emit code to implement load instructions.
890 bool X86FastISel::X86SelectLoad(const Instruction *I) {
891 // Atomic loads need special handling.
892 if (cast<LoadInst>(I)->isAtomic())
896 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
900 if (!X86SelectAddress(I->getOperand(0), AM))
903 unsigned ResultReg = 0;
904 if (X86FastEmitLoad(VT, AM, ResultReg)) {
905 UpdateValueMap(I, ResultReg);
911 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
912 bool HasAVX = Subtarget->hasAVX();
913 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
914 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
916 switch (VT.getSimpleVT().SimpleTy) {
918 case MVT::i8: return X86::CMP8rr;
919 case MVT::i16: return X86::CMP16rr;
920 case MVT::i32: return X86::CMP32rr;
921 case MVT::i64: return X86::CMP64rr;
923 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
925 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
929 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
930 /// of the comparison, return an opcode that works for the compare (e.g.
931 /// CMP32ri) otherwise return 0.
932 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
933 switch (VT.getSimpleVT().SimpleTy) {
934 // Otherwise, we can't fold the immediate into this comparison.
936 case MVT::i8: return X86::CMP8ri;
937 case MVT::i16: return X86::CMP16ri;
938 case MVT::i32: return X86::CMP32ri;
940 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
942 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
943 return X86::CMP64ri32;
948 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
950 unsigned Op0Reg = getRegForValue(Op0);
951 if (Op0Reg == 0) return false;
953 // Handle 'null' like i32/i64 0.
954 if (isa<ConstantPointerNull>(Op1))
955 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
957 // We have two options: compare with register or immediate. If the RHS of
958 // the compare is an immediate that we can fold into this compare, use
959 // CMPri, otherwise use CMPrr.
960 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
961 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
964 .addImm(Op1C->getSExtValue());
969 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
970 if (CompareOpc == 0) return false;
972 unsigned Op1Reg = getRegForValue(Op1);
973 if (Op1Reg == 0) return false;
974 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
981 bool X86FastISel::X86SelectCmp(const Instruction *I) {
982 const CmpInst *CI = cast<CmpInst>(I);
985 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
988 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
990 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
991 switch (CI->getPredicate()) {
992 case CmpInst::FCMP_OEQ: {
993 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
996 unsigned EReg = createResultReg(&X86::GR8RegClass);
997 unsigned NPReg = createResultReg(&X86::GR8RegClass);
998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETEr), EReg);
999 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1000 TII.get(X86::SETNPr), NPReg);
1001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1002 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
1003 UpdateValueMap(I, ResultReg);
1006 case CmpInst::FCMP_UNE: {
1007 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1010 unsigned NEReg = createResultReg(&X86::GR8RegClass);
1011 unsigned PReg = createResultReg(&X86::GR8RegClass);
1012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETNEr), NEReg);
1013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETPr), PReg);
1014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::OR8rr),ResultReg)
1015 .addReg(PReg).addReg(NEReg);
1016 UpdateValueMap(I, ResultReg);
1019 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1020 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1021 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
1022 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
1023 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1024 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
1025 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
1026 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1027 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
1028 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
1029 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1030 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1032 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1033 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1034 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1035 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1036 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1037 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1038 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
1039 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
1040 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
1041 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
1046 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1048 std::swap(Op0, Op1);
1050 // Emit a compare of Op0/Op1.
1051 if (!X86FastEmitCompare(Op0, Op1, VT))
1054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SetCCOpc), ResultReg);
1055 UpdateValueMap(I, ResultReg);
1059 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1060 EVT DstVT = TLI.getValueType(I->getType());
1061 if (!TLI.isTypeLegal(DstVT))
1064 unsigned ResultReg = getRegForValue(I->getOperand(0));
1068 // Handle zero-extension from i1 to i8, which is common.
1069 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1070 if (SrcVT.SimpleTy == MVT::i1) {
1071 // Set the high bits to zero.
1072 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1079 if (DstVT == MVT::i64) {
1080 // Handle extension to 64-bits via sub-register shenanigans.
1083 switch (SrcVT.SimpleTy) {
1084 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1085 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1086 case MVT::i32: MovInst = X86::MOV32rr; break;
1087 default: llvm_unreachable("Unexpected zext to i64 source type");
1090 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1094 ResultReg = createResultReg(&X86::GR64RegClass);
1095 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1097 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1098 } else if (DstVT != MVT::i8) {
1099 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1100 ResultReg, /*Kill=*/true);
1105 UpdateValueMap(I, ResultReg);
1110 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1111 // Unconditional branches are selected by tablegen-generated code.
1112 // Handle a conditional branch.
1113 const BranchInst *BI = cast<BranchInst>(I);
1114 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1115 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1117 // Fold the common case of a conditional branch with a comparison
1118 // in the same block (values defined on other blocks may not have
1119 // initialized registers).
1120 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1121 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1122 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1124 // Try to take advantage of fallthrough opportunities.
1125 CmpInst::Predicate Predicate = CI->getPredicate();
1126 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1127 std::swap(TrueMBB, FalseMBB);
1128 Predicate = CmpInst::getInversePredicate(Predicate);
1131 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1132 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1134 switch (Predicate) {
1135 case CmpInst::FCMP_OEQ:
1136 std::swap(TrueMBB, FalseMBB);
1137 Predicate = CmpInst::FCMP_UNE;
1139 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1140 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1141 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1142 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1143 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1144 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1145 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1146 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1147 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1148 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1149 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1150 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1151 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1153 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1154 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1155 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1156 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1157 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1158 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1159 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1160 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1161 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1162 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1167 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1169 std::swap(Op0, Op1);
1171 // Emit a compare of the LHS and RHS, setting the flags.
1172 if (!X86FastEmitCompare(Op0, Op1, VT))
1175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1178 if (Predicate == CmpInst::FCMP_UNE) {
1179 // X86 requires a second branch to handle UNE (and OEQ,
1180 // which is mapped to UNE above).
1181 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1185 FastEmitBranch(FalseMBB, DbgLoc);
1186 FuncInfo.MBB->addSuccessor(TrueMBB);
1189 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1190 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1191 // typically happen for _Bool and C++ bools.
1193 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1194 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1195 unsigned TestOpc = 0;
1196 switch (SourceVT.SimpleTy) {
1198 case MVT::i8: TestOpc = X86::TEST8ri; break;
1199 case MVT::i16: TestOpc = X86::TEST16ri; break;
1200 case MVT::i32: TestOpc = X86::TEST32ri; break;
1201 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1204 unsigned OpReg = getRegForValue(TI->getOperand(0));
1205 if (OpReg == 0) return false;
1206 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1207 .addReg(OpReg).addImm(1);
1209 unsigned JmpOpc = X86::JNE_4;
1210 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1211 std::swap(TrueMBB, FalseMBB);
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1217 FastEmitBranch(FalseMBB, DbgLoc);
1218 FuncInfo.MBB->addSuccessor(TrueMBB);
1224 // Otherwise do a clumsy setcc and re-test it.
1225 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1226 // in an explicit cast, so make sure to handle that correctly.
1227 unsigned OpReg = getRegForValue(BI->getCondition());
1228 if (OpReg == 0) return false;
1230 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1231 .addReg(OpReg).addImm(1);
1232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1234 FastEmitBranch(FalseMBB, DbgLoc);
1235 FuncInfo.MBB->addSuccessor(TrueMBB);
1239 bool X86FastISel::X86SelectShift(const Instruction *I) {
1240 unsigned CReg = 0, OpReg = 0;
1241 const TargetRegisterClass *RC = nullptr;
1242 if (I->getType()->isIntegerTy(8)) {
1244 RC = &X86::GR8RegClass;
1245 switch (I->getOpcode()) {
1246 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1247 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1248 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1249 default: return false;
1251 } else if (I->getType()->isIntegerTy(16)) {
1253 RC = &X86::GR16RegClass;
1254 switch (I->getOpcode()) {
1255 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1256 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1257 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1258 default: return false;
1260 } else if (I->getType()->isIntegerTy(32)) {
1262 RC = &X86::GR32RegClass;
1263 switch (I->getOpcode()) {
1264 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1265 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1266 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1267 default: return false;
1269 } else if (I->getType()->isIntegerTy(64)) {
1271 RC = &X86::GR64RegClass;
1272 switch (I->getOpcode()) {
1273 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1274 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1275 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1276 default: return false;
1283 if (!isTypeLegal(I->getType(), VT))
1286 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1287 if (Op0Reg == 0) return false;
1289 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1290 if (Op1Reg == 0) return false;
1291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1292 CReg).addReg(Op1Reg);
1294 // The shift instruction uses X86::CL. If we defined a super-register
1295 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1296 if (CReg != X86::CL)
1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1298 TII.get(TargetOpcode::KILL), X86::CL)
1299 .addReg(CReg, RegState::Kill);
1301 unsigned ResultReg = createResultReg(RC);
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1304 UpdateValueMap(I, ResultReg);
1308 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1309 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1310 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1311 const static bool S = true; // IsSigned
1312 const static bool U = false; // !IsSigned
1313 const static unsigned Copy = TargetOpcode::COPY;
1314 // For the X86 DIV/IDIV instruction, in most cases the dividend
1315 // (numerator) must be in a specific register pair highreg:lowreg,
1316 // producing the quotient in lowreg and the remainder in highreg.
1317 // For most data types, to set up the instruction, the dividend is
1318 // copied into lowreg, and lowreg is sign-extended or zero-extended
1319 // into highreg. The exception is i8, where the dividend is defined
1320 // as a single register rather than a register pair, and we
1321 // therefore directly sign-extend or zero-extend the dividend into
1322 // lowreg, instead of copying, and ignore the highreg.
1323 const static struct DivRemEntry {
1324 // The following portion depends only on the data type.
1325 const TargetRegisterClass *RC;
1326 unsigned LowInReg; // low part of the register pair
1327 unsigned HighInReg; // high part of the register pair
1328 // The following portion depends on both the data type and the operation.
1329 struct DivRemResult {
1330 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1331 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1332 // highreg, or copying a zero into highreg.
1333 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1334 // zero/sign-extending into lowreg for i8.
1335 unsigned DivRemResultReg; // Register containing the desired result.
1336 bool IsOpSigned; // Whether to use signed or unsigned form.
1337 } ResultTable[NumOps];
1338 } OpTable[NumTypes] = {
1339 { &X86::GR8RegClass, X86::AX, 0, {
1340 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1341 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1342 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1343 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1346 { &X86::GR16RegClass, X86::AX, X86::DX, {
1347 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1348 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1349 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1350 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1353 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1354 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1355 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1356 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1357 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1360 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1361 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1362 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1363 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1364 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1370 if (!isTypeLegal(I->getType(), VT))
1373 unsigned TypeIndex, OpIndex;
1374 switch (VT.SimpleTy) {
1375 default: return false;
1376 case MVT::i8: TypeIndex = 0; break;
1377 case MVT::i16: TypeIndex = 1; break;
1378 case MVT::i32: TypeIndex = 2; break;
1379 case MVT::i64: TypeIndex = 3;
1380 if (!Subtarget->is64Bit())
1385 switch (I->getOpcode()) {
1386 default: llvm_unreachable("Unexpected div/rem opcode");
1387 case Instruction::SDiv: OpIndex = 0; break;
1388 case Instruction::SRem: OpIndex = 1; break;
1389 case Instruction::UDiv: OpIndex = 2; break;
1390 case Instruction::URem: OpIndex = 3; break;
1393 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1394 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1395 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1398 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1402 // Move op0 into low-order input register.
1403 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1404 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1405 // Zero-extend or sign-extend into high-order input register.
1406 if (OpEntry.OpSignExtend) {
1407 if (OpEntry.IsOpSigned)
1408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1409 TII.get(OpEntry.OpSignExtend));
1411 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1413 TII.get(X86::MOV32r0), Zero32);
1415 // Copy the zero into the appropriate sub/super/identical physical
1416 // register. Unfortunately the operations needed are not uniform enough to
1417 // fit neatly into the table above.
1418 if (VT.SimpleTy == MVT::i16) {
1419 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1420 TII.get(Copy), TypeEntry.HighInReg)
1421 .addReg(Zero32, 0, X86::sub_16bit);
1422 } else if (VT.SimpleTy == MVT::i32) {
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1424 TII.get(Copy), TypeEntry.HighInReg)
1426 } else if (VT.SimpleTy == MVT::i64) {
1427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1428 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1429 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1433 // Generate the DIV/IDIV instruction.
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1435 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1436 // For i8 remainder, we can't reference AH directly, as we'll end
1437 // up with bogus copies like %R9B = COPY %AH. Reference AX
1438 // instead to prevent AH references in a REX instruction.
1440 // The current assumption of the fast register allocator is that isel
1441 // won't generate explicit references to the GPR8_NOREX registers. If
1442 // the allocator and/or the backend get enhanced to be more robust in
1443 // that regard, this can be, and should be, removed.
1444 unsigned ResultReg = 0;
1445 if ((I->getOpcode() == Instruction::SRem ||
1446 I->getOpcode() == Instruction::URem) &&
1447 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1448 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1449 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1451 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1453 // Shift AX right by 8 bits instead of using AH.
1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1455 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1457 // Now reference the 8-bit subreg of the result.
1458 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1459 /*Kill=*/true, X86::sub_8bit);
1461 // Copy the result out of the physreg if we haven't already.
1463 ResultReg = createResultReg(TypeEntry.RC);
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1465 .addReg(OpEntry.DivRemResultReg);
1467 UpdateValueMap(I, ResultReg);
1472 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1474 if (!isTypeLegal(I->getType(), VT))
1477 // We only use cmov here, if we don't have a cmov instruction bail.
1478 if (!Subtarget->hasCMov()) return false;
1481 const TargetRegisterClass *RC = nullptr;
1482 if (VT == MVT::i16) {
1483 Opc = X86::CMOVE16rr;
1484 RC = &X86::GR16RegClass;
1485 } else if (VT == MVT::i32) {
1486 Opc = X86::CMOVE32rr;
1487 RC = &X86::GR32RegClass;
1488 } else if (VT == MVT::i64) {
1489 Opc = X86::CMOVE64rr;
1490 RC = &X86::GR64RegClass;
1495 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1496 if (Op0Reg == 0) return false;
1497 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1498 if (Op1Reg == 0) return false;
1499 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1500 if (Op2Reg == 0) return false;
1502 // Selects operate on i1, however, Op0Reg is 8 bits width and may contain
1503 // garbage. Indeed, only the less significant bit is supposed to be accurate.
1504 // If we read more than the lsb, we may see non-zero values whereas lsb
1505 // is zero. Therefore, we have to truncate Op0Reg to i1 for the select.
1506 // This is achieved by performing TEST against 1.
1507 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1508 .addReg(Op0Reg).addImm(1);
1509 unsigned ResultReg = createResultReg(RC);
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1511 .addReg(Op1Reg).addReg(Op2Reg);
1512 UpdateValueMap(I, ResultReg);
1516 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1517 // fpext from float to double.
1518 if (X86ScalarSSEf64 &&
1519 I->getType()->isDoubleTy()) {
1520 const Value *V = I->getOperand(0);
1521 if (V->getType()->isFloatTy()) {
1522 unsigned OpReg = getRegForValue(V);
1523 if (OpReg == 0) return false;
1524 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1526 TII.get(X86::CVTSS2SDrr), ResultReg)
1528 UpdateValueMap(I, ResultReg);
1536 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1537 if (X86ScalarSSEf64) {
1538 if (I->getType()->isFloatTy()) {
1539 const Value *V = I->getOperand(0);
1540 if (V->getType()->isDoubleTy()) {
1541 unsigned OpReg = getRegForValue(V);
1542 if (OpReg == 0) return false;
1543 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1544 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1545 TII.get(X86::CVTSD2SSrr), ResultReg)
1547 UpdateValueMap(I, ResultReg);
1556 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1557 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1558 EVT DstVT = TLI.getValueType(I->getType());
1560 // This code only handles truncation to byte.
1561 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1563 if (!TLI.isTypeLegal(SrcVT))
1566 unsigned InputReg = getRegForValue(I->getOperand(0));
1568 // Unhandled operand. Halt "fast" selection and bail.
1571 if (SrcVT == MVT::i8) {
1572 // Truncate from i8 to i1; no code needed.
1573 UpdateValueMap(I, InputReg);
1577 if (!Subtarget->is64Bit()) {
1578 // If we're on x86-32; we can't extract an i8 from a general register.
1579 // First issue a copy to GR16_ABCD or GR32_ABCD.
1580 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1581 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1582 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1583 unsigned CopyReg = createResultReg(CopyRC);
1584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1585 CopyReg).addReg(InputReg);
1589 // Issue an extract_subreg.
1590 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1591 InputReg, /*Kill=*/true,
1596 UpdateValueMap(I, ResultReg);
1600 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1601 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1604 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1605 X86AddressMode SrcAM, uint64_t Len) {
1607 // Make sure we don't bloat code by inlining very large memcpy's.
1608 if (!IsMemcpySmall(Len))
1611 bool i64Legal = Subtarget->is64Bit();
1613 // We don't care about alignment here since we just emit integer accesses.
1616 if (Len >= 8 && i64Legal)
1627 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1628 RV &= X86FastEmitStore(VT, Reg, DestAM);
1629 assert(RV && "Failed to emit load or store??");
1631 unsigned Size = VT.getSizeInBits()/8;
1633 DestAM.Disp += Size;
1640 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
1641 switch (I.getIntrinsicID()) {
1642 case Intrinsic::sadd_with_overflow:
1643 case Intrinsic::uadd_with_overflow:
1644 case Intrinsic::smul_with_overflow:
1645 case Intrinsic::umul_with_overflow:
1652 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1653 // FIXME: Handle more intrinsics.
1654 switch (I.getIntrinsicID()) {
1655 default: return false;
1656 case Intrinsic::frameaddress: {
1657 Type *RetTy = I.getCalledFunction()->getReturnType();
1660 if (!isTypeLegal(RetTy, VT))
1664 const TargetRegisterClass *RC = nullptr;
1666 switch (VT.SimpleTy) {
1667 default: llvm_unreachable("Invalid result type for frameaddress.");
1668 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
1669 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
1672 // This needs to be set before we call getFrameRegister, otherwise we get
1673 // the wrong frame register.
1674 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1675 MFI->setFrameAddressIsTaken(true);
1677 const X86RegisterInfo *RegInfo =
1678 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
1679 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
1680 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
1681 (FrameReg == X86::EBP && VT == MVT::i32)) &&
1682 "Invalid Frame Register!");
1684 // Always make a copy of the frame register to to a vreg first, so that we
1685 // never directly reference the frame register (the TwoAddressInstruction-
1686 // Pass doesn't like that).
1687 unsigned SrcReg = createResultReg(RC);
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1689 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
1691 // Now recursively load from the frame address.
1692 // movq (%rbp), %rax
1693 // movq (%rax), %rax
1694 // movq (%rax), %rax
1697 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
1699 DestReg = createResultReg(RC);
1700 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1701 TII.get(Opc), DestReg), SrcReg);
1705 UpdateValueMap(&I, SrcReg);
1708 case Intrinsic::memcpy: {
1709 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1710 // Don't handle volatile or variable length memcpys.
1711 if (MCI.isVolatile())
1714 if (isa<ConstantInt>(MCI.getLength())) {
1715 // Small memcpy's are common enough that we want to do them
1716 // without a call if possible.
1717 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1718 if (IsMemcpySmall(Len)) {
1719 X86AddressMode DestAM, SrcAM;
1720 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1721 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1723 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1728 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1729 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1732 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1735 return DoSelectCall(&I, "memcpy");
1737 case Intrinsic::memset: {
1738 const MemSetInst &MSI = cast<MemSetInst>(I);
1740 if (MSI.isVolatile())
1743 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1744 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1747 if (MSI.getDestAddressSpace() > 255)
1750 return DoSelectCall(&I, "memset");
1752 case Intrinsic::stackprotector: {
1753 // Emit code to store the stack guard onto the stack.
1754 EVT PtrTy = TLI.getPointerTy();
1756 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1757 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1759 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
1761 // Grab the frame index.
1763 if (!X86SelectAddress(Slot, AM)) return false;
1764 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1767 case Intrinsic::dbg_declare: {
1768 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1770 assert(DI->getAddress() && "Null address should be checked earlier!");
1771 if (!X86SelectAddress(DI->getAddress(), AM))
1773 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1774 // FIXME may need to add RegState::Debug to any registers produced,
1775 // although ESP/EBP should be the only ones at the moment.
1776 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
1777 addImm(0).addMetadata(DI->getVariable());
1780 case Intrinsic::trap: {
1781 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
1784 case Intrinsic::sadd_with_overflow:
1785 case Intrinsic::uadd_with_overflow:
1786 case Intrinsic::ssub_with_overflow:
1787 case Intrinsic::usub_with_overflow:
1788 case Intrinsic::smul_with_overflow:
1789 case Intrinsic::umul_with_overflow: {
1790 // This implements the basic lowering of the xalu with overflow intrinsics
1791 // into add/sub/mul folowed by either seto or setb.
1792 const Function *Callee = I.getCalledFunction();
1793 auto *Ty = cast<StructType>(Callee->getReturnType());
1794 Type *RetTy = Ty->getTypeAtIndex(0U);
1795 Type *CondTy = Ty->getTypeAtIndex(1);
1798 if (!isTypeLegal(RetTy, VT))
1801 if (VT < MVT::i8 || VT > MVT::i64)
1804 const Value *LHS = I.getArgOperand(0);
1805 const Value *RHS = I.getArgOperand(1);
1807 // Canonicalize immediates to the RHS.
1808 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1809 isCommutativeIntrinsic(I))
1810 std::swap(LHS, RHS);
1812 unsigned BaseOpc, CondOpc;
1813 switch (I.getIntrinsicID()) {
1814 default: llvm_unreachable("Unexpected intrinsic!");
1815 case Intrinsic::sadd_with_overflow:
1816 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
1817 case Intrinsic::uadd_with_overflow:
1818 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
1819 case Intrinsic::ssub_with_overflow:
1820 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
1821 case Intrinsic::usub_with_overflow:
1822 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
1823 case Intrinsic::smul_with_overflow:
1824 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
1825 case Intrinsic::umul_with_overflow:
1826 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
1829 unsigned LHSReg = getRegForValue(LHS);
1832 bool LHSIsKill = hasTrivialKill(LHS);
1834 unsigned ResultReg = 0;
1835 // Check if we have an immediate version.
1836 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
1837 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
1844 RHSReg = getRegForValue(RHS);
1847 RHSIsKill = hasTrivialKill(RHS);
1848 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
1852 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
1853 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
1854 static const unsigned MULOpc[] =
1855 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
1856 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
1857 // First copy the first operand into RAX, which is an implicit input to
1858 // the X86::MUL*r instruction.
1859 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1860 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
1861 .addReg(LHSReg, getKillRegState(LHSIsKill));
1862 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
1863 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
1869 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
1870 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
1871 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
1874 UpdateValueMap(&I, ResultReg, 2);
1880 bool X86FastISel::FastLowerArguments() {
1881 if (!FuncInfo.CanLowerReturn)
1884 const Function *F = FuncInfo.Fn;
1888 CallingConv::ID CC = F->getCallingConv();
1889 if (CC != CallingConv::C)
1892 if (Subtarget->isCallingConvWin64(CC))
1895 if (!Subtarget->is64Bit())
1898 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1899 unsigned GPRCnt = 0;
1900 unsigned FPRCnt = 0;
1902 for (auto const &Arg : F->args()) {
1903 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1904 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1905 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1906 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1909 Type *ArgTy = Arg.getType();
1910 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1913 EVT ArgVT = TLI.getValueType(ArgTy);
1914 if (!ArgVT.isSimple()) return false;
1915 switch (ArgVT.getSimpleVT().SimpleTy) {
1916 default: return false;
1934 static const MCPhysReg GPR32ArgRegs[] = {
1935 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1937 static const MCPhysReg GPR64ArgRegs[] = {
1938 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1940 static const MCPhysReg XMMArgRegs[] = {
1941 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1942 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1945 unsigned GPRIdx = 0;
1946 unsigned FPRIdx = 0;
1947 for (auto const &Arg : F->args()) {
1948 MVT VT = TLI.getSimpleValueType(Arg.getType());
1949 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1951 switch (VT.SimpleTy) {
1952 default: llvm_unreachable("Unexpected value type.");
1953 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
1954 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
1955 case MVT::f32: // fall-through
1956 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
1958 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1959 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1960 // Without this, EmitLiveInCopies may eliminate the livein if its only
1961 // use is a bitcast (which isn't turned into an instruction).
1962 unsigned ResultReg = createResultReg(RC);
1963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1964 TII.get(TargetOpcode::COPY), ResultReg)
1965 .addReg(DstReg, getKillRegState(true));
1966 UpdateValueMap(&Arg, ResultReg);
1971 bool X86FastISel::X86SelectCall(const Instruction *I) {
1972 const CallInst *CI = cast<CallInst>(I);
1973 const Value *Callee = CI->getCalledValue();
1975 // Can't handle inline asm yet.
1976 if (isa<InlineAsm>(Callee))
1979 // Handle intrinsic calls.
1980 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1981 return X86VisitIntrinsicCall(*II);
1983 // Allow SelectionDAG isel to handle tail calls.
1984 if (cast<CallInst>(I)->isTailCall())
1987 return DoSelectCall(I, nullptr);
1990 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1991 const ImmutableCallSite &CS) {
1992 if (Subtarget.is64Bit())
1994 if (Subtarget.getTargetTriple().isOSMSVCRT())
1996 CallingConv::ID CC = CS.getCallingConv();
1997 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1999 if (!CS.paramHasAttr(1, Attribute::StructRet))
2001 if (CS.paramHasAttr(1, Attribute::InReg))
2006 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2007 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2008 const CallInst *CI = cast<CallInst>(I);
2009 const Value *Callee = CI->getCalledValue();
2011 // Handle only C and fastcc calling conventions for now.
2012 ImmutableCallSite CS(CI);
2013 CallingConv::ID CC = CS.getCallingConv();
2014 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2015 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2016 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2017 CC != CallingConv::X86_64_SysV)
2020 // fastcc with -tailcallopt is intended to provide a guaranteed
2021 // tail call optimization. Fastisel doesn't know how to do that.
2022 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2025 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2026 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2027 bool isVarArg = FTy->isVarArg();
2029 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2030 // x86-32. Special handling for x86-64 is implemented.
2031 if (isVarArg && isWin64)
2034 // Don't know about inalloca yet.
2035 if (CS.hasInAllocaArgument())
2038 // Fast-isel doesn't know about callee-pop yet.
2039 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2040 TM.Options.GuaranteedTailCallOpt))
2043 // Check whether the function can return without sret-demotion.
2044 SmallVector<ISD::OutputArg, 4> Outs;
2045 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2046 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2047 *FuncInfo.MF, FTy->isVarArg(),
2048 Outs, FTy->getContext());
2049 if (!CanLowerReturn)
2052 // Materialize callee address in a register. FIXME: GV address can be
2053 // handled with a CALLpcrel32 instead.
2054 X86AddressMode CalleeAM;
2055 if (!X86SelectCallAddress(Callee, CalleeAM))
2057 unsigned CalleeOp = 0;
2058 const GlobalValue *GV = nullptr;
2059 if (CalleeAM.GV != nullptr) {
2061 } else if (CalleeAM.Base.Reg != 0) {
2062 CalleeOp = CalleeAM.Base.Reg;
2066 // Deal with call operands first.
2067 SmallVector<const Value *, 8> ArgVals;
2068 SmallVector<unsigned, 8> Args;
2069 SmallVector<MVT, 8> ArgVTs;
2070 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2071 unsigned arg_size = CS.arg_size();
2072 Args.reserve(arg_size);
2073 ArgVals.reserve(arg_size);
2074 ArgVTs.reserve(arg_size);
2075 ArgFlags.reserve(arg_size);
2076 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2078 // If we're lowering a mem intrinsic instead of a regular call, skip the
2079 // last two arguments, which should not passed to the underlying functions.
2080 if (MemIntName && e-i <= 2)
2083 ISD::ArgFlagsTy Flags;
2084 unsigned AttrInd = i - CS.arg_begin() + 1;
2085 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2087 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2090 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2091 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2092 Type *ElementTy = Ty->getElementType();
2093 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2094 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2096 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2098 Flags.setByValSize(FrameSize);
2099 Flags.setByValAlign(FrameAlign);
2100 if (!IsMemcpySmall(FrameSize))
2104 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2106 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2109 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2110 // instruction. This is safe because it is common to all fastisel supported
2111 // calling conventions on x86.
2112 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2113 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2114 CI->getBitWidth() == 16) {
2116 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2118 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2124 // Passing bools around ends up doing a trunc to i1 and passing it.
2125 // Codegen this as an argument + "and 1".
2126 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2127 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2128 ArgVal->hasOneUse()) {
2129 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2130 ArgReg = getRegForValue(ArgVal);
2131 if (ArgReg == 0) return false;
2134 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2136 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2137 ArgVal->hasOneUse(), 1);
2139 ArgReg = getRegForValue(ArgVal);
2142 if (ArgReg == 0) return false;
2144 Type *ArgTy = ArgVal->getType();
2146 if (!isTypeLegal(ArgTy, ArgVT))
2148 if (ArgVT == MVT::x86mmx)
2150 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2151 Flags.setOrigAlign(OriginalAlignment);
2153 Args.push_back(ArgReg);
2154 ArgVals.push_back(ArgVal);
2155 ArgVTs.push_back(ArgVT);
2156 ArgFlags.push_back(Flags);
2159 // Analyze operands of the call, assigning locations to each operand.
2160 SmallVector<CCValAssign, 16> ArgLocs;
2161 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2162 I->getParent()->getContext());
2164 // Allocate shadow area for Win64
2166 CCInfo.AllocateStack(32, 8);
2168 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2170 // Get a count of how many bytes are to be pushed on the stack.
2171 unsigned NumBytes = CCInfo.getNextStackOffset();
2173 // Issue CALLSEQ_START
2174 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2178 // Process argument: walk the register/memloc assignments, inserting
2180 SmallVector<unsigned, 4> RegArgs;
2181 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2182 CCValAssign &VA = ArgLocs[i];
2183 unsigned Arg = Args[VA.getValNo()];
2184 EVT ArgVT = ArgVTs[VA.getValNo()];
2186 // Promote the value if needed.
2187 switch (VA.getLocInfo()) {
2188 case CCValAssign::Full: break;
2189 case CCValAssign::SExt: {
2190 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2191 "Unexpected extend");
2192 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2194 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2195 ArgVT = VA.getLocVT();
2198 case CCValAssign::ZExt: {
2199 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2200 "Unexpected extend");
2201 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2203 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2204 ArgVT = VA.getLocVT();
2207 case CCValAssign::AExt: {
2208 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2209 "Unexpected extend");
2210 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2213 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2216 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2219 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2220 ArgVT = VA.getLocVT();
2223 case CCValAssign::BCvt: {
2224 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2225 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2226 assert(BC != 0 && "Failed to emit a bitcast!");
2228 ArgVT = VA.getLocVT();
2231 case CCValAssign::VExt:
2232 // VExt has not been implemented, so this should be impossible to reach
2233 // for now. However, fallback to Selection DAG isel once implemented.
2235 case CCValAssign::Indirect:
2236 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2239 case CCValAssign::FPExt:
2240 llvm_unreachable("Unexpected loc info!");
2243 if (VA.isRegLoc()) {
2244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2245 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2246 RegArgs.push_back(VA.getLocReg());
2248 unsigned LocMemOffset = VA.getLocMemOffset();
2250 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2251 getTargetMachine()->getRegisterInfo());
2252 AM.Base.Reg = RegInfo->getStackRegister();
2253 AM.Disp = LocMemOffset;
2254 const Value *ArgVal = ArgVals[VA.getValNo()];
2255 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2257 if (Flags.isByVal()) {
2258 X86AddressMode SrcAM;
2259 SrcAM.Base.Reg = Arg;
2260 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2261 assert(Res && "memcpy length already checked!"); (void)Res;
2262 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2263 // If this is a really simple value, emit this with the Value* version
2264 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2265 // as it can cause us to reevaluate the argument.
2266 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2269 if (!X86FastEmitStore(ArgVT, Arg, AM))
2275 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2277 if (Subtarget->isPICStyleGOT()) {
2278 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2280 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2283 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2284 // Count the number of XMM registers allocated.
2285 static const MCPhysReg XMMArgRegs[] = {
2286 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2287 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2289 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2291 X86::AL).addImm(NumXMMRegs);
2295 MachineInstrBuilder MIB;
2297 // Register-indirect call.
2299 if (Subtarget->is64Bit())
2300 CallOpc = X86::CALL64r;
2302 CallOpc = X86::CALL32r;
2303 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2308 assert(GV && "Not a direct call");
2310 if (Subtarget->is64Bit())
2311 CallOpc = X86::CALL64pcrel32;
2313 CallOpc = X86::CALLpcrel32;
2315 // See if we need any target-specific flags on the GV operand.
2316 unsigned char OpFlags = 0;
2318 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2319 // external symbols most go through the PLT in PIC mode. If the symbol
2320 // has hidden or protected visibility, or if it is static or local, then
2321 // we don't need to use the PLT - we can directly call it.
2322 if (Subtarget->isTargetELF() &&
2323 TM.getRelocationModel() == Reloc::PIC_ &&
2324 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2325 OpFlags = X86II::MO_PLT;
2326 } else if (Subtarget->isPICStyleStubAny() &&
2327 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2328 (!Subtarget->getTargetTriple().isMacOSX() ||
2329 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2330 // PC-relative references to external symbols should go through $stub,
2331 // unless we're building with the leopard linker or later, which
2332 // automatically synthesizes these stubs.
2333 OpFlags = X86II::MO_DARWIN_STUB;
2337 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2339 MIB.addExternalSymbol(MemIntName, OpFlags);
2341 MIB.addGlobalAddress(GV, 0, OpFlags);
2344 // Add a register mask with the call-preserved registers.
2345 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2346 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2348 // Add an implicit use GOT pointer in EBX.
2349 if (Subtarget->isPICStyleGOT())
2350 MIB.addReg(X86::EBX, RegState::Implicit);
2352 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2353 MIB.addReg(X86::AL, RegState::Implicit);
2355 // Add implicit physical register uses to the call.
2356 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2357 MIB.addReg(RegArgs[i], RegState::Implicit);
2359 // Issue CALLSEQ_END
2360 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2361 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2363 .addImm(NumBytes).addImm(NumBytesCallee);
2365 // Build info for return calling conv lowering code.
2366 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2367 SmallVector<ISD::InputArg, 32> Ins;
2368 SmallVector<EVT, 4> RetTys;
2369 ComputeValueVTs(TLI, I->getType(), RetTys);
2370 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2372 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2373 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2374 for (unsigned j = 0; j != NumRegs; ++j) {
2375 ISD::InputArg MyFlags;
2376 MyFlags.VT = RegisterVT;
2377 MyFlags.Used = !CS.getInstruction()->use_empty();
2378 if (CS.paramHasAttr(0, Attribute::SExt))
2379 MyFlags.Flags.setSExt();
2380 if (CS.paramHasAttr(0, Attribute::ZExt))
2381 MyFlags.Flags.setZExt();
2382 if (CS.paramHasAttr(0, Attribute::InReg))
2383 MyFlags.Flags.setInReg();
2384 Ins.push_back(MyFlags);
2388 // Now handle call return values.
2389 SmallVector<unsigned, 4> UsedRegs;
2390 SmallVector<CCValAssign, 16> RVLocs;
2391 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2392 I->getParent()->getContext());
2393 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2394 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2395 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2396 EVT CopyVT = RVLocs[i].getValVT();
2397 unsigned CopyReg = ResultReg + i;
2399 // If this is a call to a function that returns an fp value on the x87 fp
2400 // stack, but where we prefer to use the value in xmm registers, copy it
2401 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2402 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2403 RVLocs[i].getLocReg() == X86::ST1)) {
2404 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2406 CopyReg = createResultReg(&X86::RFP80RegClass);
2408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2409 TII.get(X86::FpPOP_RETVAL), CopyReg);
2411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2412 TII.get(TargetOpcode::COPY),
2413 CopyReg).addReg(RVLocs[i].getLocReg());
2414 UsedRegs.push_back(RVLocs[i].getLocReg());
2417 if (CopyVT != RVLocs[i].getValVT()) {
2418 // Round the F80 the right size, which also moves to the appropriate xmm
2419 // register. This is accomplished by storing the F80 value in memory and
2420 // then loading it back. Ewww...
2421 EVT ResVT = RVLocs[i].getValVT();
2422 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2423 unsigned MemSize = ResVT.getSizeInBits()/8;
2424 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2425 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2428 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2429 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2430 TII.get(Opc), ResultReg + i), FI);
2435 UpdateValueMap(I, ResultReg, RVLocs.size());
2437 // Set all unused physreg defs as dead.
2438 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2445 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2446 switch (I->getOpcode()) {
2448 case Instruction::Load:
2449 return X86SelectLoad(I);
2450 case Instruction::Store:
2451 return X86SelectStore(I);
2452 case Instruction::Ret:
2453 return X86SelectRet(I);
2454 case Instruction::ICmp:
2455 case Instruction::FCmp:
2456 return X86SelectCmp(I);
2457 case Instruction::ZExt:
2458 return X86SelectZExt(I);
2459 case Instruction::Br:
2460 return X86SelectBranch(I);
2461 case Instruction::Call:
2462 return X86SelectCall(I);
2463 case Instruction::LShr:
2464 case Instruction::AShr:
2465 case Instruction::Shl:
2466 return X86SelectShift(I);
2467 case Instruction::SDiv:
2468 case Instruction::UDiv:
2469 case Instruction::SRem:
2470 case Instruction::URem:
2471 return X86SelectDivRem(I);
2472 case Instruction::Select:
2473 return X86SelectSelect(I);
2474 case Instruction::Trunc:
2475 return X86SelectTrunc(I);
2476 case Instruction::FPExt:
2477 return X86SelectFPExt(I);
2478 case Instruction::FPTrunc:
2479 return X86SelectFPTrunc(I);
2480 case Instruction::IntToPtr: // Deliberate fall-through.
2481 case Instruction::PtrToInt: {
2482 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2483 EVT DstVT = TLI.getValueType(I->getType());
2484 if (DstVT.bitsGT(SrcVT))
2485 return X86SelectZExt(I);
2486 if (DstVT.bitsLT(SrcVT))
2487 return X86SelectTrunc(I);
2488 unsigned Reg = getRegForValue(I->getOperand(0));
2489 if (Reg == 0) return false;
2490 UpdateValueMap(I, Reg);
2498 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2500 if (!isTypeLegal(C->getType(), VT))
2503 // Can't handle alternate code models yet.
2504 if (TM.getCodeModel() != CodeModel::Small)
2507 // Get opcode and regclass of the output for the given load instruction.
2509 const TargetRegisterClass *RC = nullptr;
2510 switch (VT.SimpleTy) {
2514 RC = &X86::GR8RegClass;
2518 RC = &X86::GR16RegClass;
2522 RC = &X86::GR32RegClass;
2525 // Must be in x86-64 mode.
2527 RC = &X86::GR64RegClass;
2530 if (X86ScalarSSEf32) {
2531 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2532 RC = &X86::FR32RegClass;
2534 Opc = X86::LD_Fp32m;
2535 RC = &X86::RFP32RegClass;
2539 if (X86ScalarSSEf64) {
2540 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2541 RC = &X86::FR64RegClass;
2543 Opc = X86::LD_Fp64m;
2544 RC = &X86::RFP64RegClass;
2548 // No f80 support yet.
2552 // Materialize addresses with LEA instructions.
2553 if (isa<GlobalValue>(C)) {
2555 if (X86SelectAddress(C, AM)) {
2556 // If the expression is just a basereg, then we're done, otherwise we need
2558 if (AM.BaseType == X86AddressMode::RegBase &&
2559 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
2562 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2563 unsigned ResultReg = createResultReg(RC);
2564 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2565 TII.get(Opc), ResultReg), AM);
2571 // MachineConstantPool wants an explicit alignment.
2572 unsigned Align = DL.getPrefTypeAlignment(C->getType());
2574 // Alignment of vector types. FIXME!
2575 Align = DL.getTypeAllocSize(C->getType());
2578 // x86-32 PIC requires a PIC base register for constant pools.
2579 unsigned PICBase = 0;
2580 unsigned char OpFlag = 0;
2581 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2582 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2583 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2584 } else if (Subtarget->isPICStyleGOT()) {
2585 OpFlag = X86II::MO_GOTOFF;
2586 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2587 } else if (Subtarget->isPICStyleRIPRel() &&
2588 TM.getCodeModel() == CodeModel::Small) {
2592 // Create the load from the constant pool.
2593 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2594 unsigned ResultReg = createResultReg(RC);
2595 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2596 TII.get(Opc), ResultReg),
2597 MCPOffset, PICBase, OpFlag);
2602 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2603 // Fail on dynamic allocas. At this point, getRegForValue has already
2604 // checked its CSE maps, so if we're here trying to handle a dynamic
2605 // alloca, we're not going to succeed. X86SelectAddress has a
2606 // check for dynamic allocas, because it's called directly from
2607 // various places, but TargetMaterializeAlloca also needs a check
2608 // in order to avoid recursion between getRegForValue,
2609 // X86SelectAddrss, and TargetMaterializeAlloca.
2610 if (!FuncInfo.StaticAllocaMap.count(C))
2612 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2615 if (!X86SelectAddress(C, AM))
2617 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2618 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2619 unsigned ResultReg = createResultReg(RC);
2620 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2621 TII.get(Opc), ResultReg), AM);
2625 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2627 if (!isTypeLegal(CF->getType(), VT))
2630 // Get opcode and regclass for the given zero.
2632 const TargetRegisterClass *RC = nullptr;
2633 switch (VT.SimpleTy) {
2636 if (X86ScalarSSEf32) {
2637 Opc = X86::FsFLD0SS;
2638 RC = &X86::FR32RegClass;
2640 Opc = X86::LD_Fp032;
2641 RC = &X86::RFP32RegClass;
2645 if (X86ScalarSSEf64) {
2646 Opc = X86::FsFLD0SD;
2647 RC = &X86::FR64RegClass;
2649 Opc = X86::LD_Fp064;
2650 RC = &X86::RFP64RegClass;
2654 // No f80 support yet.
2658 unsigned ResultReg = createResultReg(RC);
2659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
2664 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2665 const LoadInst *LI) {
2667 if (!X86SelectAddress(LI->getOperand(0), AM))
2670 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2672 unsigned Size = DL.getTypeAllocSize(LI->getType());
2673 unsigned Alignment = LI->getAlignment();
2675 SmallVector<MachineOperand, 8> AddrOps;
2676 AM.getFullAddress(AddrOps);
2678 MachineInstr *Result =
2679 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2680 if (!Result) return false;
2682 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2683 MI->eraseFromParent();
2689 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2690 const TargetLibraryInfo *libInfo) {
2691 return new X86FastISel(funcInfo, libInfo);