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 "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
46 class X86FastISel final : public FastISel {
47 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
48 /// make the right decision when generating code for different targets.
49 const X86Subtarget *Subtarget;
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
60 const TargetLibraryInfo *libInfo)
61 : FastISel(funcInfo, libInfo) {
62 Subtarget = &TM.getSubtarget<X86Subtarget>();
63 X86ScalarSSEf64 = Subtarget->hasSSE2();
64 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 bool TargetSelectInstruction(const Instruction *I) override;
69 /// \brief The specified machine instr operand is a vreg, and that
70 /// vreg is being provided by the specified load instruction. If possible,
71 /// try to fold the load as an operand to the instruction, returning true if
73 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74 const LoadInst *LI) override;
76 bool FastLowerArguments() override;
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
86 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
87 MachineMemOperand *MMO = nullptr, bool Aligned = false);
88 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
89 const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
95 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
96 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
98 bool X86SelectLoad(const Instruction *I);
100 bool X86SelectStore(const Instruction *I);
102 bool X86SelectRet(const Instruction *I);
104 bool X86SelectCmp(const Instruction *I);
106 bool X86SelectZExt(const Instruction *I);
108 bool X86SelectBranch(const Instruction *I);
110 bool X86SelectShift(const Instruction *I);
112 bool X86SelectDivRem(const Instruction *I);
114 bool X86SelectSelect(const Instruction *I);
116 bool X86SelectTrunc(const Instruction *I);
118 bool X86SelectFPExt(const Instruction *I);
119 bool X86SelectFPTrunc(const Instruction *I);
121 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
122 bool X86SelectCall(const Instruction *I);
124 bool DoSelectCall(const Instruction *I, const char *MemIntName);
126 const X86InstrInfo *getInstrInfo() const {
127 return getTargetMachine()->getInstrInfo();
129 const X86TargetMachine *getTargetMachine() const {
130 return static_cast<const X86TargetMachine *>(&TM);
133 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
135 unsigned TargetMaterializeConstant(const Constant *C) override;
137 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
139 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
141 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
142 /// computed in an SSE register, not on the X87 floating point stack.
143 bool isScalarFPTypeInSSEReg(EVT VT) const {
144 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
145 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
148 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
150 bool IsMemcpySmall(uint64_t Len);
152 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
153 X86AddressMode SrcAM, uint64_t Len);
156 } // end anonymous namespace.
158 static std::pair<X86::CondCode, bool>
159 getX86ConditonCode(CmpInst::Predicate Predicate) {
160 X86::CondCode CC = X86::COND_INVALID;
161 bool NeedSwap = false;
164 // Floating-point Predicates
165 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
166 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
167 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
168 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
169 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
170 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
171 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
172 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
173 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
174 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
175 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
176 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
177 case CmpInst::FCMP_OEQ: // fall-through
178 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
180 // Integer Predicates
181 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
182 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
183 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
184 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
185 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
186 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
187 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
188 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
189 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
190 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
193 return std::make_pair(CC, NeedSwap);
196 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
197 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
198 if (evt == MVT::Other || !evt.isSimple())
199 // Unhandled type. Halt "fast" selection and bail.
202 VT = evt.getSimpleVT();
203 // For now, require SSE/SSE2 for performing floating-point operations,
204 // since x87 requires additional work.
205 if (VT == MVT::f64 && !X86ScalarSSEf64)
207 if (VT == MVT::f32 && !X86ScalarSSEf32)
209 // Similarly, no f80 support yet.
212 // We only handle legal types. For example, on x86-32 the instruction
213 // selector contains all of the 64-bit instructions from x86-64,
214 // under the assumption that i64 won't be used if the target doesn't
216 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
219 #include "X86GenCallingConv.inc"
221 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
222 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
223 /// Return true and the result register by reference if it is possible.
224 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
225 MachineMemOperand *MMO, unsigned &ResultReg) {
226 // Get opcode and regclass of the output for the given load instruction.
228 const TargetRegisterClass *RC = nullptr;
229 switch (VT.getSimpleVT().SimpleTy) {
230 default: return false;
234 RC = &X86::GR8RegClass;
238 RC = &X86::GR16RegClass;
242 RC = &X86::GR32RegClass;
245 // Must be in x86-64 mode.
247 RC = &X86::GR64RegClass;
250 if (X86ScalarSSEf32) {
251 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
252 RC = &X86::FR32RegClass;
255 RC = &X86::RFP32RegClass;
259 if (X86ScalarSSEf64) {
260 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
261 RC = &X86::FR64RegClass;
264 RC = &X86::RFP64RegClass;
268 // No f80 support yet.
272 ResultReg = createResultReg(RC);
273 MachineInstrBuilder MIB =
274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
275 addFullAddress(MIB, AM);
277 MIB->addMemOperand(*FuncInfo.MF, MMO);
281 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
282 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
283 /// and a displacement offset, or a GlobalAddress,
284 /// i.e. V. Return true if it is possible.
285 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
286 const X86AddressMode &AM,
287 MachineMemOperand *MMO, bool Aligned) {
288 // Get opcode and regclass of the output for the given store instruction.
290 switch (VT.getSimpleVT().SimpleTy) {
291 case MVT::f80: // No f80 support yet.
292 default: return false;
294 // Mask out all but lowest bit.
295 unsigned AndResult = createResultReg(&X86::GR8RegClass);
296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
297 TII.get(X86::AND8ri), AndResult)
298 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
301 // FALLTHROUGH, handling i1 as i8.
302 case MVT::i8: Opc = X86::MOV8mr; break;
303 case MVT::i16: Opc = X86::MOV16mr; break;
304 case MVT::i32: Opc = X86::MOV32mr; break;
305 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
307 Opc = X86ScalarSSEf32 ?
308 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
311 Opc = X86ScalarSSEf64 ?
312 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
316 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
318 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
322 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
324 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
331 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
333 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
337 MachineInstrBuilder MIB =
338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
339 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
341 MIB->addMemOperand(*FuncInfo.MF, MMO);
346 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
347 const X86AddressMode &AM,
348 MachineMemOperand *MMO, bool Aligned) {
349 // Handle 'null' like i32/i64 0.
350 if (isa<ConstantPointerNull>(Val))
351 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
353 // If this is a store of a simple constant, fold the constant into the store.
354 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
357 switch (VT.getSimpleVT().SimpleTy) {
359 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
360 case MVT::i8: Opc = X86::MOV8mi; break;
361 case MVT::i16: Opc = X86::MOV16mi; break;
362 case MVT::i32: Opc = X86::MOV32mi; break;
364 // Must be a 32-bit sign extended value.
365 if (isInt<32>(CI->getSExtValue()))
366 Opc = X86::MOV64mi32;
371 MachineInstrBuilder MIB =
372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
373 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
374 : CI->getZExtValue());
376 MIB->addMemOperand(*FuncInfo.MF, MMO);
381 unsigned ValReg = getRegForValue(Val);
385 bool ValKill = hasTrivialKill(Val);
386 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
389 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
390 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
391 /// ISD::SIGN_EXTEND).
392 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
393 unsigned Src, EVT SrcVT,
394 unsigned &ResultReg) {
395 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
396 Src, /*TODO: Kill=*/false);
404 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
405 // Handle constant address.
406 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
407 // Can't handle alternate code models yet.
408 if (TM.getCodeModel() != CodeModel::Small)
411 // Can't handle TLS yet.
412 if (GV->isThreadLocal())
415 // RIP-relative addresses can't have additional register operands, so if
416 // we've already folded stuff into the addressing mode, just force the
417 // global value into its own register, which we can use as the basereg.
418 if (!Subtarget->isPICStyleRIPRel() ||
419 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
420 // Okay, we've committed to selecting this global. Set up the address.
423 // Allow the subtarget to classify the global.
424 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
426 // If this reference is relative to the pic base, set it now.
427 if (isGlobalRelativeToPICBase(GVFlags)) {
428 // FIXME: How do we know Base.Reg is free??
429 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
432 // Unless the ABI requires an extra load, return a direct reference to
434 if (!isGlobalStubReference(GVFlags)) {
435 if (Subtarget->isPICStyleRIPRel()) {
436 // Use rip-relative addressing if we can. Above we verified that the
437 // base and index registers are unused.
438 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
439 AM.Base.Reg = X86::RIP;
441 AM.GVOpFlags = GVFlags;
445 // Ok, we need to do a load from a stub. If we've already loaded from
446 // this stub, reuse the loaded pointer, otherwise emit the load now.
447 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
449 if (I != LocalValueMap.end() && I->second != 0) {
452 // Issue load from stub.
454 const TargetRegisterClass *RC = nullptr;
455 X86AddressMode StubAM;
456 StubAM.Base.Reg = AM.Base.Reg;
458 StubAM.GVOpFlags = GVFlags;
460 // Prepare for inserting code in the local-value area.
461 SavePoint SaveInsertPt = enterLocalValueArea();
463 if (TLI.getPointerTy() == MVT::i64) {
465 RC = &X86::GR64RegClass;
467 if (Subtarget->isPICStyleRIPRel())
468 StubAM.Base.Reg = X86::RIP;
471 RC = &X86::GR32RegClass;
474 LoadReg = createResultReg(RC);
475 MachineInstrBuilder LoadMI =
476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
477 addFullAddress(LoadMI, StubAM);
479 // Ok, back to normal mode.
480 leaveLocalValueArea(SaveInsertPt);
482 // Prevent loading GV stub multiple times in same MBB.
483 LocalValueMap[V] = LoadReg;
486 // Now construct the final address. Note that the Disp, Scale,
487 // and Index values may already be set here.
488 AM.Base.Reg = LoadReg;
494 // If all else fails, try to materialize the value in a register.
495 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
496 if (AM.Base.Reg == 0) {
497 AM.Base.Reg = getRegForValue(V);
498 return AM.Base.Reg != 0;
500 if (AM.IndexReg == 0) {
501 assert(AM.Scale == 1 && "Scale with no index!");
502 AM.IndexReg = getRegForValue(V);
503 return AM.IndexReg != 0;
510 /// X86SelectAddress - Attempt to fill in an address from the given value.
512 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
513 SmallVector<const Value *, 32> GEPs;
515 const User *U = nullptr;
516 unsigned Opcode = Instruction::UserOp1;
517 if (const Instruction *I = dyn_cast<Instruction>(V)) {
518 // Don't walk into other basic blocks; it's possible we haven't
519 // visited them yet, so the instructions may not yet be assigned
520 // virtual registers.
521 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
522 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
523 Opcode = I->getOpcode();
526 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
527 Opcode = C->getOpcode();
531 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
532 if (Ty->getAddressSpace() > 255)
533 // Fast instruction selection doesn't support the special
539 case Instruction::BitCast:
540 // Look past bitcasts.
541 return X86SelectAddress(U->getOperand(0), AM);
543 case Instruction::IntToPtr:
544 // Look past no-op inttoptrs.
545 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
546 return X86SelectAddress(U->getOperand(0), AM);
549 case Instruction::PtrToInt:
550 // Look past no-op ptrtoints.
551 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
552 return X86SelectAddress(U->getOperand(0), AM);
555 case Instruction::Alloca: {
556 // Do static allocas.
557 const AllocaInst *A = cast<AllocaInst>(V);
558 DenseMap<const AllocaInst*, int>::iterator SI =
559 FuncInfo.StaticAllocaMap.find(A);
560 if (SI != FuncInfo.StaticAllocaMap.end()) {
561 AM.BaseType = X86AddressMode::FrameIndexBase;
562 AM.Base.FrameIndex = SI->second;
568 case Instruction::Add: {
569 // Adds of constants are common and easy enough.
570 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
571 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
572 // They have to fit in the 32-bit signed displacement field though.
573 if (isInt<32>(Disp)) {
574 AM.Disp = (uint32_t)Disp;
575 return X86SelectAddress(U->getOperand(0), AM);
581 case Instruction::GetElementPtr: {
582 X86AddressMode SavedAM = AM;
584 // Pattern-match simple GEPs.
585 uint64_t Disp = (int32_t)AM.Disp;
586 unsigned IndexReg = AM.IndexReg;
587 unsigned Scale = AM.Scale;
588 gep_type_iterator GTI = gep_type_begin(U);
589 // Iterate through the indices, folding what we can. Constants can be
590 // folded, and one dynamic index can be handled, if the scale is supported.
591 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
592 i != e; ++i, ++GTI) {
593 const Value *Op = *i;
594 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
595 const StructLayout *SL = DL.getStructLayout(STy);
596 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
600 // A array/variable index is always of the form i*S where S is the
601 // constant scale size. See if we can push the scale into immediates.
602 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
604 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
605 // Constant-offset addressing.
606 Disp += CI->getSExtValue() * S;
609 if (canFoldAddIntoGEP(U, Op)) {
610 // A compatible add with a constant operand. Fold the constant.
612 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
613 Disp += CI->getSExtValue() * S;
614 // Iterate on the other operand.
615 Op = cast<AddOperator>(Op)->getOperand(0);
619 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
620 (S == 1 || S == 2 || S == 4 || S == 8)) {
621 // Scaled-index addressing.
623 IndexReg = getRegForGEPIndex(Op).first;
629 goto unsupported_gep;
633 // Check for displacement overflow.
634 if (!isInt<32>(Disp))
637 AM.IndexReg = IndexReg;
639 AM.Disp = (uint32_t)Disp;
642 if (const GetElementPtrInst *GEP =
643 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
644 // Ok, the GEP indices were covered by constant-offset and scaled-index
645 // addressing. Update the address state and move on to examining the base.
648 } else if (X86SelectAddress(U->getOperand(0), AM)) {
652 // If we couldn't merge the gep value into this addr mode, revert back to
653 // our address and just match the value instead of completely failing.
656 for (SmallVectorImpl<const Value *>::reverse_iterator
657 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
658 if (handleConstantAddresses(*I, AM))
663 // Ok, the GEP indices weren't all covered.
668 return handleConstantAddresses(V, AM);
671 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
673 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
674 const User *U = nullptr;
675 unsigned Opcode = Instruction::UserOp1;
676 const Instruction *I = dyn_cast<Instruction>(V);
677 // Record if the value is defined in the same basic block.
679 // This information is crucial to know whether or not folding an
681 // Indeed, FastISel generates or reuses a virtual register for all
682 // operands of all instructions it selects. Obviously, the definition and
683 // its uses must use the same virtual register otherwise the produced
684 // code is incorrect.
685 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
686 // registers for values that are alive across basic blocks. This ensures
687 // that the values are consistently set between across basic block, even
688 // if different instruction selection mechanisms are used (e.g., a mix of
689 // SDISel and FastISel).
690 // For values local to a basic block, the instruction selection process
691 // generates these virtual registers with whatever method is appropriate
692 // for its needs. In particular, FastISel and SDISel do not share the way
693 // local virtual registers are set.
694 // Therefore, this is impossible (or at least unsafe) to share values
695 // between basic blocks unless they use the same instruction selection
696 // method, which is not guarantee for X86.
697 // Moreover, things like hasOneUse could not be used accurately, if we
698 // allow to reference values across basic blocks whereas they are not
699 // alive across basic blocks initially.
702 Opcode = I->getOpcode();
704 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
705 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
706 Opcode = C->getOpcode();
712 case Instruction::BitCast:
713 // Look past bitcasts if its operand is in the same BB.
715 return X86SelectCallAddress(U->getOperand(0), AM);
718 case Instruction::IntToPtr:
719 // Look past no-op inttoptrs if its operand is in the same BB.
721 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
722 return X86SelectCallAddress(U->getOperand(0), AM);
725 case Instruction::PtrToInt:
726 // Look past no-op ptrtoints if its operand is in the same BB.
728 TLI.getValueType(U->getType()) == TLI.getPointerTy())
729 return X86SelectCallAddress(U->getOperand(0), AM);
733 // Handle constant address.
734 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
735 // Can't handle alternate code models yet.
736 if (TM.getCodeModel() != CodeModel::Small)
739 // RIP-relative addresses can't have additional register operands.
740 if (Subtarget->isPICStyleRIPRel() &&
741 (AM.Base.Reg != 0 || AM.IndexReg != 0))
744 // Can't handle DbgLocLImport.
745 if (GV->hasDLLImportStorageClass())
749 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
750 if (GVar->isThreadLocal())
753 // Okay, we've committed to selecting this global. Set up the basic address.
756 // No ABI requires an extra load for anything other than DLLImport, which
757 // we rejected above. Return a direct reference to the global.
758 if (Subtarget->isPICStyleRIPRel()) {
759 // Use rip-relative addressing if we can. Above we verified that the
760 // base and index registers are unused.
761 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
762 AM.Base.Reg = X86::RIP;
763 } else if (Subtarget->isPICStyleStubPIC()) {
764 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
765 } else if (Subtarget->isPICStyleGOT()) {
766 AM.GVOpFlags = X86II::MO_GOTOFF;
772 // If all else fails, try to materialize the value in a register.
773 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
774 if (AM.Base.Reg == 0) {
775 AM.Base.Reg = getRegForValue(V);
776 return AM.Base.Reg != 0;
778 if (AM.IndexReg == 0) {
779 assert(AM.Scale == 1 && "Scale with no index!");
780 AM.IndexReg = getRegForValue(V);
781 return AM.IndexReg != 0;
789 /// X86SelectStore - Select and emit code to implement store instructions.
790 bool X86FastISel::X86SelectStore(const Instruction *I) {
791 // Atomic stores need special handling.
792 const StoreInst *S = cast<StoreInst>(I);
797 const Value *Val = S->getValueOperand();
798 const Value *Ptr = S->getPointerOperand();
801 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
804 unsigned Alignment = S->getAlignment();
805 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
806 if (Alignment == 0) // Ensure that codegen never sees alignment 0
807 Alignment = ABIAlignment;
808 bool Aligned = Alignment >= ABIAlignment;
811 if (!X86SelectAddress(Ptr, AM))
814 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
817 /// X86SelectRet - Select and emit code to implement ret instructions.
818 bool X86FastISel::X86SelectRet(const Instruction *I) {
819 const ReturnInst *Ret = cast<ReturnInst>(I);
820 const Function &F = *I->getParent()->getParent();
821 const X86MachineFunctionInfo *X86MFInfo =
822 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
824 if (!FuncInfo.CanLowerReturn)
827 CallingConv::ID CC = F.getCallingConv();
828 if (CC != CallingConv::C &&
829 CC != CallingConv::Fast &&
830 CC != CallingConv::X86_FastCall &&
831 CC != CallingConv::X86_64_SysV)
834 if (Subtarget->isCallingConvWin64(CC))
837 // Don't handle popping bytes on return for now.
838 if (X86MFInfo->getBytesToPopOnReturn() != 0)
841 // fastcc with -tailcallopt is intended to provide a guaranteed
842 // tail call optimization. Fastisel doesn't know how to do that.
843 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
846 // Let SDISel handle vararg functions.
850 // Build a list of return value registers.
851 SmallVector<unsigned, 4> RetRegs;
853 if (Ret->getNumOperands() > 0) {
854 SmallVector<ISD::OutputArg, 4> Outs;
855 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
857 // Analyze operands of the call, assigning locations to each operand.
858 SmallVector<CCValAssign, 16> ValLocs;
859 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
861 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
863 const Value *RV = Ret->getOperand(0);
864 unsigned Reg = getRegForValue(RV);
868 // Only handle a single return value for now.
869 if (ValLocs.size() != 1)
872 CCValAssign &VA = ValLocs[0];
874 // Don't bother handling odd stuff for now.
875 if (VA.getLocInfo() != CCValAssign::Full)
877 // Only handle register returns for now.
881 // The calling-convention tables for x87 returns don't tell
883 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
886 unsigned SrcReg = Reg + VA.getValNo();
887 EVT SrcVT = TLI.getValueType(RV->getType());
888 EVT DstVT = VA.getValVT();
889 // Special handling for extended integers.
890 if (SrcVT != DstVT) {
891 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
894 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
897 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
899 if (SrcVT == MVT::i1) {
900 if (Outs[0].Flags.isSExt())
902 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
905 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
907 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
908 SrcReg, /*TODO: Kill=*/false);
912 unsigned DstReg = VA.getLocReg();
913 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
914 // Avoid a cross-class copy. This is very unlikely.
915 if (!SrcRC->contains(DstReg))
917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
918 DstReg).addReg(SrcReg);
920 // Add register to return instruction.
921 RetRegs.push_back(VA.getLocReg());
924 // The x86-64 ABI for returning structs by value requires that we copy
925 // the sret argument into %rax for the return. We saved the argument into
926 // a virtual register in the entry block, so now we copy the value out
927 // and into %rax. We also do the same with %eax for Win32.
928 if (F.hasStructRetAttr() &&
929 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
930 unsigned Reg = X86MFInfo->getSRetReturnReg();
932 "SRetReturnReg should have been set in LowerFormalArguments()!");
933 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
934 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
936 RetRegs.push_back(RetReg);
940 MachineInstrBuilder MIB =
941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
942 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
943 MIB.addReg(RetRegs[i], RegState::Implicit);
947 /// X86SelectLoad - Select and emit code to implement load instructions.
949 bool X86FastISel::X86SelectLoad(const Instruction *I) {
950 const LoadInst *LI = cast<LoadInst>(I);
952 // Atomic loads need special handling.
957 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
960 const Value *Ptr = LI->getPointerOperand();
963 if (!X86SelectAddress(Ptr, AM))
966 unsigned ResultReg = 0;
967 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
970 UpdateValueMap(I, ResultReg);
974 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
975 bool HasAVX = Subtarget->hasAVX();
976 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
977 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
979 switch (VT.getSimpleVT().SimpleTy) {
981 case MVT::i8: return X86::CMP8rr;
982 case MVT::i16: return X86::CMP16rr;
983 case MVT::i32: return X86::CMP32rr;
984 case MVT::i64: return X86::CMP64rr;
986 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
988 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
992 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
993 /// of the comparison, return an opcode that works for the compare (e.g.
994 /// CMP32ri) otherwise return 0.
995 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
996 switch (VT.getSimpleVT().SimpleTy) {
997 // Otherwise, we can't fold the immediate into this comparison.
999 case MVT::i8: return X86::CMP8ri;
1000 case MVT::i16: return X86::CMP16ri;
1001 case MVT::i32: return X86::CMP32ri;
1003 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1005 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1006 return X86::CMP64ri32;
1011 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1013 unsigned Op0Reg = getRegForValue(Op0);
1014 if (Op0Reg == 0) return false;
1016 // Handle 'null' like i32/i64 0.
1017 if (isa<ConstantPointerNull>(Op1))
1018 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1020 // We have two options: compare with register or immediate. If the RHS of
1021 // the compare is an immediate that we can fold into this compare, use
1022 // CMPri, otherwise use CMPrr.
1023 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1024 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1025 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1027 .addImm(Op1C->getSExtValue());
1032 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1033 if (CompareOpc == 0) return false;
1035 unsigned Op1Reg = getRegForValue(Op1);
1036 if (Op1Reg == 0) return false;
1037 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1044 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1045 const CmpInst *CI = cast<CmpInst>(I);
1048 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1051 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1052 static unsigned SETFOpcTable[2][2] = {
1053 { X86::SETEr, X86::SETNPr },
1054 { X86::SETNEr, X86::SETPr }
1056 unsigned *SETFOpc = nullptr;
1057 switch (CI->getPredicate()) {
1059 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1060 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1063 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
1065 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1068 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1069 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1072 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::AND8rr),
1075 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1076 UpdateValueMap(I, ResultReg);
1081 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1082 std::tie(CC, SwapArgs) = getX86ConditonCode(CI->getPredicate());
1083 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1084 unsigned Opc = X86::getSETFromCond(CC);
1086 const Value *LHS = CI->getOperand(0);
1087 const Value *RHS = CI->getOperand(1);
1089 std::swap(LHS, RHS);
1091 // Emit a compare of Op0/Op1.
1092 if (!X86FastEmitCompare(LHS, RHS, VT))
1095 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1096 UpdateValueMap(I, ResultReg);
1100 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1101 EVT DstVT = TLI.getValueType(I->getType());
1102 if (!TLI.isTypeLegal(DstVT))
1105 unsigned ResultReg = getRegForValue(I->getOperand(0));
1109 // Handle zero-extension from i1 to i8, which is common.
1110 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1111 if (SrcVT.SimpleTy == MVT::i1) {
1112 // Set the high bits to zero.
1113 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1120 if (DstVT == MVT::i64) {
1121 // Handle extension to 64-bits via sub-register shenanigans.
1124 switch (SrcVT.SimpleTy) {
1125 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1126 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1127 case MVT::i32: MovInst = X86::MOV32rr; break;
1128 default: llvm_unreachable("Unexpected zext to i64 source type");
1131 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1135 ResultReg = createResultReg(&X86::GR64RegClass);
1136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1138 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1139 } else if (DstVT != MVT::i8) {
1140 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1141 ResultReg, /*Kill=*/true);
1146 UpdateValueMap(I, ResultReg);
1151 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1152 // Unconditional branches are selected by tablegen-generated code.
1153 // Handle a conditional branch.
1154 const BranchInst *BI = cast<BranchInst>(I);
1155 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1156 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1158 // Fold the common case of a conditional branch with a comparison
1159 // in the same block (values defined on other blocks may not have
1160 // initialized registers).
1161 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1162 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1163 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1165 // Try to take advantage of fallthrough opportunities.
1166 CmpInst::Predicate Predicate = CI->getPredicate();
1167 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1168 std::swap(TrueMBB, FalseMBB);
1169 Predicate = CmpInst::getInversePredicate(Predicate);
1172 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1173 // code check. Instead two branch instructions are required to check all
1174 // the flags. First we change the predicate to a supported conditon code,
1175 // which will be the first branch. Later one we will emit the second
1177 bool NeedExtraBranch = false;
1178 switch (Predicate) {
1180 case CmpInst::FCMP_OEQ:
1181 std::swap(TrueMBB, FalseMBB); // fall-through
1182 case CmpInst::FCMP_UNE:
1183 NeedExtraBranch = true;
1184 Predicate = CmpInst::FCMP_ONE;
1189 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1190 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1191 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1192 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1194 BranchOpc = X86::GetCondBranchFromCond(CC);
1195 const Value *CmpLHS = CI->getOperand(0);
1196 const Value *CmpRHS = CI->getOperand(1);
1198 std::swap(CmpLHS, CmpRHS);
1200 // Emit a compare of the LHS and RHS, setting the flags.
1201 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1204 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1207 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1209 if (NeedExtraBranch) {
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1214 // Obtain the branch weight and add the TrueBB to the successor list.
1215 uint32_t BranchWeight = 0;
1217 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1218 TrueMBB->getBasicBlock());
1219 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1221 // Emits an unconditional branch to the FalseBB, obtains the branch
1222 // weight, andd adds it to the successor list.
1223 FastEmitBranch(FalseMBB, DbgLoc);
1227 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1228 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1229 // typically happen for _Bool and C++ bools.
1231 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1232 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1233 unsigned TestOpc = 0;
1234 switch (SourceVT.SimpleTy) {
1236 case MVT::i8: TestOpc = X86::TEST8ri; break;
1237 case MVT::i16: TestOpc = X86::TEST16ri; break;
1238 case MVT::i32: TestOpc = X86::TEST32ri; break;
1239 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1242 unsigned OpReg = getRegForValue(TI->getOperand(0));
1243 if (OpReg == 0) return false;
1244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1245 .addReg(OpReg).addImm(1);
1247 unsigned JmpOpc = X86::JNE_4;
1248 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1249 std::swap(TrueMBB, FalseMBB);
1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1255 FastEmitBranch(FalseMBB, DbgLoc);
1256 uint32_t BranchWeight = 0;
1258 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1259 TrueMBB->getBasicBlock());
1260 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1266 // Otherwise do a clumsy setcc and re-test it.
1267 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1268 // in an explicit cast, so make sure to handle that correctly.
1269 unsigned OpReg = getRegForValue(BI->getCondition());
1270 if (OpReg == 0) return false;
1272 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1273 .addReg(OpReg).addImm(1);
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1276 FastEmitBranch(FalseMBB, DbgLoc);
1277 uint32_t BranchWeight = 0;
1279 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1280 TrueMBB->getBasicBlock());
1281 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1285 bool X86FastISel::X86SelectShift(const Instruction *I) {
1286 unsigned CReg = 0, OpReg = 0;
1287 const TargetRegisterClass *RC = nullptr;
1288 if (I->getType()->isIntegerTy(8)) {
1290 RC = &X86::GR8RegClass;
1291 switch (I->getOpcode()) {
1292 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1293 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1294 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1295 default: return false;
1297 } else if (I->getType()->isIntegerTy(16)) {
1299 RC = &X86::GR16RegClass;
1300 switch (I->getOpcode()) {
1301 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1302 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1303 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1304 default: return false;
1306 } else if (I->getType()->isIntegerTy(32)) {
1308 RC = &X86::GR32RegClass;
1309 switch (I->getOpcode()) {
1310 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1311 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1312 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1313 default: return false;
1315 } else if (I->getType()->isIntegerTy(64)) {
1317 RC = &X86::GR64RegClass;
1318 switch (I->getOpcode()) {
1319 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1320 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1321 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1322 default: return false;
1329 if (!isTypeLegal(I->getType(), VT))
1332 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1333 if (Op0Reg == 0) return false;
1335 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1336 if (Op1Reg == 0) return false;
1337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1338 CReg).addReg(Op1Reg);
1340 // The shift instruction uses X86::CL. If we defined a super-register
1341 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1342 if (CReg != X86::CL)
1343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1344 TII.get(TargetOpcode::KILL), X86::CL)
1345 .addReg(CReg, RegState::Kill);
1347 unsigned ResultReg = createResultReg(RC);
1348 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1350 UpdateValueMap(I, ResultReg);
1354 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1355 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1356 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1357 const static bool S = true; // IsSigned
1358 const static bool U = false; // !IsSigned
1359 const static unsigned Copy = TargetOpcode::COPY;
1360 // For the X86 DIV/IDIV instruction, in most cases the dividend
1361 // (numerator) must be in a specific register pair highreg:lowreg,
1362 // producing the quotient in lowreg and the remainder in highreg.
1363 // For most data types, to set up the instruction, the dividend is
1364 // copied into lowreg, and lowreg is sign-extended or zero-extended
1365 // into highreg. The exception is i8, where the dividend is defined
1366 // as a single register rather than a register pair, and we
1367 // therefore directly sign-extend or zero-extend the dividend into
1368 // lowreg, instead of copying, and ignore the highreg.
1369 const static struct DivRemEntry {
1370 // The following portion depends only on the data type.
1371 const TargetRegisterClass *RC;
1372 unsigned LowInReg; // low part of the register pair
1373 unsigned HighInReg; // high part of the register pair
1374 // The following portion depends on both the data type and the operation.
1375 struct DivRemResult {
1376 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1377 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1378 // highreg, or copying a zero into highreg.
1379 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1380 // zero/sign-extending into lowreg for i8.
1381 unsigned DivRemResultReg; // Register containing the desired result.
1382 bool IsOpSigned; // Whether to use signed or unsigned form.
1383 } ResultTable[NumOps];
1384 } OpTable[NumTypes] = {
1385 { &X86::GR8RegClass, X86::AX, 0, {
1386 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1387 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1388 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1389 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1392 { &X86::GR16RegClass, X86::AX, X86::DX, {
1393 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1394 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1395 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1396 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1399 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1400 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1401 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1402 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1403 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1406 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1407 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1408 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1409 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1410 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1416 if (!isTypeLegal(I->getType(), VT))
1419 unsigned TypeIndex, OpIndex;
1420 switch (VT.SimpleTy) {
1421 default: return false;
1422 case MVT::i8: TypeIndex = 0; break;
1423 case MVT::i16: TypeIndex = 1; break;
1424 case MVT::i32: TypeIndex = 2; break;
1425 case MVT::i64: TypeIndex = 3;
1426 if (!Subtarget->is64Bit())
1431 switch (I->getOpcode()) {
1432 default: llvm_unreachable("Unexpected div/rem opcode");
1433 case Instruction::SDiv: OpIndex = 0; break;
1434 case Instruction::SRem: OpIndex = 1; break;
1435 case Instruction::UDiv: OpIndex = 2; break;
1436 case Instruction::URem: OpIndex = 3; break;
1439 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1440 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1441 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1444 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1448 // Move op0 into low-order input register.
1449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1450 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1451 // Zero-extend or sign-extend into high-order input register.
1452 if (OpEntry.OpSignExtend) {
1453 if (OpEntry.IsOpSigned)
1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1455 TII.get(OpEntry.OpSignExtend));
1457 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1458 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1459 TII.get(X86::MOV32r0), Zero32);
1461 // Copy the zero into the appropriate sub/super/identical physical
1462 // register. Unfortunately the operations needed are not uniform enough to
1463 // fit neatly into the table above.
1464 if (VT.SimpleTy == MVT::i16) {
1465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1466 TII.get(Copy), TypeEntry.HighInReg)
1467 .addReg(Zero32, 0, X86::sub_16bit);
1468 } else if (VT.SimpleTy == MVT::i32) {
1469 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1470 TII.get(Copy), TypeEntry.HighInReg)
1472 } else if (VT.SimpleTy == MVT::i64) {
1473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1474 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1475 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1479 // Generate the DIV/IDIV instruction.
1480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1481 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1482 // For i8 remainder, we can't reference AH directly, as we'll end
1483 // up with bogus copies like %R9B = COPY %AH. Reference AX
1484 // instead to prevent AH references in a REX instruction.
1486 // The current assumption of the fast register allocator is that isel
1487 // won't generate explicit references to the GPR8_NOREX registers. If
1488 // the allocator and/or the backend get enhanced to be more robust in
1489 // that regard, this can be, and should be, removed.
1490 unsigned ResultReg = 0;
1491 if ((I->getOpcode() == Instruction::SRem ||
1492 I->getOpcode() == Instruction::URem) &&
1493 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1494 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1495 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1496 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1497 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1499 // Shift AX right by 8 bits instead of using AH.
1500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1501 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1503 // Now reference the 8-bit subreg of the result.
1504 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1505 /*Kill=*/true, X86::sub_8bit);
1507 // Copy the result out of the physreg if we haven't already.
1509 ResultReg = createResultReg(TypeEntry.RC);
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1511 .addReg(OpEntry.DivRemResultReg);
1513 UpdateValueMap(I, ResultReg);
1518 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1520 if (!isTypeLegal(I->getType(), VT))
1523 // We only use cmov here, if we don't have a cmov instruction bail.
1524 if (!Subtarget->hasCMov()) return false;
1527 const TargetRegisterClass *RC = nullptr;
1528 if (VT == MVT::i16) {
1529 Opc = X86::CMOVE16rr;
1530 RC = &X86::GR16RegClass;
1531 } else if (VT == MVT::i32) {
1532 Opc = X86::CMOVE32rr;
1533 RC = &X86::GR32RegClass;
1534 } else if (VT == MVT::i64) {
1535 Opc = X86::CMOVE64rr;
1536 RC = &X86::GR64RegClass;
1541 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1542 if (Op0Reg == 0) return false;
1543 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1544 if (Op1Reg == 0) return false;
1545 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1546 if (Op2Reg == 0) return false;
1548 // Selects operate on i1, however, Op0Reg is 8 bits width and may contain
1549 // garbage. Indeed, only the less significant bit is supposed to be accurate.
1550 // If we read more than the lsb, we may see non-zero values whereas lsb
1551 // is zero. Therefore, we have to truncate Op0Reg to i1 for the select.
1552 // This is achieved by performing TEST against 1.
1553 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1554 .addReg(Op0Reg).addImm(1);
1555 unsigned ResultReg = createResultReg(RC);
1556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1557 .addReg(Op1Reg).addReg(Op2Reg);
1558 UpdateValueMap(I, ResultReg);
1562 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1563 // fpext from float to double.
1564 if (X86ScalarSSEf64 &&
1565 I->getType()->isDoubleTy()) {
1566 const Value *V = I->getOperand(0);
1567 if (V->getType()->isFloatTy()) {
1568 unsigned OpReg = getRegForValue(V);
1569 if (OpReg == 0) return false;
1570 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1571 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1572 TII.get(X86::CVTSS2SDrr), ResultReg)
1574 UpdateValueMap(I, ResultReg);
1582 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1583 if (X86ScalarSSEf64) {
1584 if (I->getType()->isFloatTy()) {
1585 const Value *V = I->getOperand(0);
1586 if (V->getType()->isDoubleTy()) {
1587 unsigned OpReg = getRegForValue(V);
1588 if (OpReg == 0) return false;
1589 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1590 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1591 TII.get(X86::CVTSD2SSrr), ResultReg)
1593 UpdateValueMap(I, ResultReg);
1602 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1603 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1604 EVT DstVT = TLI.getValueType(I->getType());
1606 // This code only handles truncation to byte.
1607 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1609 if (!TLI.isTypeLegal(SrcVT))
1612 unsigned InputReg = getRegForValue(I->getOperand(0));
1614 // Unhandled operand. Halt "fast" selection and bail.
1617 if (SrcVT == MVT::i8) {
1618 // Truncate from i8 to i1; no code needed.
1619 UpdateValueMap(I, InputReg);
1623 if (!Subtarget->is64Bit()) {
1624 // If we're on x86-32; we can't extract an i8 from a general register.
1625 // First issue a copy to GR16_ABCD or GR32_ABCD.
1626 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1627 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1628 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1629 unsigned CopyReg = createResultReg(CopyRC);
1630 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1631 CopyReg).addReg(InputReg);
1635 // Issue an extract_subreg.
1636 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1637 InputReg, /*Kill=*/true,
1642 UpdateValueMap(I, ResultReg);
1646 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1647 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1650 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1651 X86AddressMode SrcAM, uint64_t Len) {
1653 // Make sure we don't bloat code by inlining very large memcpy's.
1654 if (!IsMemcpySmall(Len))
1657 bool i64Legal = Subtarget->is64Bit();
1659 // We don't care about alignment here since we just emit integer accesses.
1662 if (Len >= 8 && i64Legal)
1673 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
1674 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
1675 assert(RV && "Failed to emit load or store??");
1677 unsigned Size = VT.getSizeInBits()/8;
1679 DestAM.Disp += Size;
1686 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
1687 switch (I.getIntrinsicID()) {
1688 case Intrinsic::sadd_with_overflow:
1689 case Intrinsic::uadd_with_overflow:
1690 case Intrinsic::smul_with_overflow:
1691 case Intrinsic::umul_with_overflow:
1698 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1699 // FIXME: Handle more intrinsics.
1700 switch (I.getIntrinsicID()) {
1701 default: return false;
1702 case Intrinsic::frameaddress: {
1703 Type *RetTy = I.getCalledFunction()->getReturnType();
1706 if (!isTypeLegal(RetTy, VT))
1710 const TargetRegisterClass *RC = nullptr;
1712 switch (VT.SimpleTy) {
1713 default: llvm_unreachable("Invalid result type for frameaddress.");
1714 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
1715 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
1718 // This needs to be set before we call getFrameRegister, otherwise we get
1719 // the wrong frame register.
1720 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1721 MFI->setFrameAddressIsTaken(true);
1723 const X86RegisterInfo *RegInfo =
1724 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
1725 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
1726 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
1727 (FrameReg == X86::EBP && VT == MVT::i32)) &&
1728 "Invalid Frame Register!");
1730 // Always make a copy of the frame register to to a vreg first, so that we
1731 // never directly reference the frame register (the TwoAddressInstruction-
1732 // Pass doesn't like that).
1733 unsigned SrcReg = createResultReg(RC);
1734 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1735 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
1737 // Now recursively load from the frame address.
1738 // movq (%rbp), %rax
1739 // movq (%rax), %rax
1740 // movq (%rax), %rax
1743 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
1745 DestReg = createResultReg(RC);
1746 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1747 TII.get(Opc), DestReg), SrcReg);
1751 UpdateValueMap(&I, SrcReg);
1754 case Intrinsic::memcpy: {
1755 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1756 // Don't handle volatile or variable length memcpys.
1757 if (MCI.isVolatile())
1760 if (isa<ConstantInt>(MCI.getLength())) {
1761 // Small memcpy's are common enough that we want to do them
1762 // without a call if possible.
1763 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1764 if (IsMemcpySmall(Len)) {
1765 X86AddressMode DestAM, SrcAM;
1766 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1767 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1769 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1774 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1775 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1778 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1781 return DoSelectCall(&I, "memcpy");
1783 case Intrinsic::memset: {
1784 const MemSetInst &MSI = cast<MemSetInst>(I);
1786 if (MSI.isVolatile())
1789 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1790 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1793 if (MSI.getDestAddressSpace() > 255)
1796 return DoSelectCall(&I, "memset");
1798 case Intrinsic::stackprotector: {
1799 // Emit code to store the stack guard onto the stack.
1800 EVT PtrTy = TLI.getPointerTy();
1802 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1803 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1805 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
1807 // Grab the frame index.
1809 if (!X86SelectAddress(Slot, AM)) return false;
1810 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1813 case Intrinsic::dbg_declare: {
1814 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1816 assert(DI->getAddress() && "Null address should be checked earlier!");
1817 if (!X86SelectAddress(DI->getAddress(), AM))
1819 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1820 // FIXME may need to add RegState::Debug to any registers produced,
1821 // although ESP/EBP should be the only ones at the moment.
1822 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
1823 addImm(0).addMetadata(DI->getVariable());
1826 case Intrinsic::trap: {
1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
1830 case Intrinsic::sqrt: {
1831 if (!Subtarget->hasSSE1())
1834 Type *RetTy = I.getCalledFunction()->getReturnType();
1837 if (!isTypeLegal(RetTy, VT))
1840 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
1841 // is not generated by FastISel yet.
1842 // FIXME: Update this code once tablegen can handle it.
1843 static const unsigned SqrtOpc[2][2] = {
1844 {X86::SQRTSSr, X86::VSQRTSSr},
1845 {X86::SQRTSDr, X86::VSQRTSDr}
1847 bool HasAVX = Subtarget->hasAVX();
1849 const TargetRegisterClass *RC;
1850 switch (VT.SimpleTy) {
1851 default: return false;
1852 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
1853 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
1856 const Value *SrcVal = I.getArgOperand(0);
1857 unsigned SrcReg = getRegForValue(SrcVal);
1862 unsigned ImplicitDefReg = 0;
1864 ImplicitDefReg = createResultReg(RC);
1865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1866 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
1869 unsigned ResultReg = createResultReg(RC);
1870 MachineInstrBuilder MIB;
1871 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1875 MIB.addReg(ImplicitDefReg);
1879 UpdateValueMap(&I, ResultReg);
1882 case Intrinsic::sadd_with_overflow:
1883 case Intrinsic::uadd_with_overflow:
1884 case Intrinsic::ssub_with_overflow:
1885 case Intrinsic::usub_with_overflow:
1886 case Intrinsic::smul_with_overflow:
1887 case Intrinsic::umul_with_overflow: {
1888 // This implements the basic lowering of the xalu with overflow intrinsics
1889 // into add/sub/mul folowed by either seto or setb.
1890 const Function *Callee = I.getCalledFunction();
1891 auto *Ty = cast<StructType>(Callee->getReturnType());
1892 Type *RetTy = Ty->getTypeAtIndex(0U);
1893 Type *CondTy = Ty->getTypeAtIndex(1);
1896 if (!isTypeLegal(RetTy, VT))
1899 if (VT < MVT::i8 || VT > MVT::i64)
1902 const Value *LHS = I.getArgOperand(0);
1903 const Value *RHS = I.getArgOperand(1);
1905 // Canonicalize immediates to the RHS.
1906 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1907 isCommutativeIntrinsic(I))
1908 std::swap(LHS, RHS);
1910 unsigned BaseOpc, CondOpc;
1911 switch (I.getIntrinsicID()) {
1912 default: llvm_unreachable("Unexpected intrinsic!");
1913 case Intrinsic::sadd_with_overflow:
1914 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
1915 case Intrinsic::uadd_with_overflow:
1916 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
1917 case Intrinsic::ssub_with_overflow:
1918 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
1919 case Intrinsic::usub_with_overflow:
1920 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
1921 case Intrinsic::smul_with_overflow:
1922 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
1923 case Intrinsic::umul_with_overflow:
1924 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
1927 unsigned LHSReg = getRegForValue(LHS);
1930 bool LHSIsKill = hasTrivialKill(LHS);
1932 unsigned ResultReg = 0;
1933 // Check if we have an immediate version.
1934 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
1935 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
1942 RHSReg = getRegForValue(RHS);
1945 RHSIsKill = hasTrivialKill(RHS);
1946 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
1950 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
1951 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
1952 static const unsigned MULOpc[] =
1953 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
1954 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
1955 // First copy the first operand into RAX, which is an implicit input to
1956 // the X86::MUL*r instruction.
1957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1958 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
1959 .addReg(LHSReg, getKillRegState(LHSIsKill));
1960 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
1961 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
1967 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
1968 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
1969 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
1972 UpdateValueMap(&I, ResultReg, 2);
1975 case Intrinsic::x86_sse_cvttss2si:
1976 case Intrinsic::x86_sse_cvttss2si64:
1977 case Intrinsic::x86_sse2_cvttsd2si:
1978 case Intrinsic::x86_sse2_cvttsd2si64: {
1980 switch (I.getIntrinsicID()) {
1981 default: llvm_unreachable("Unexpected intrinsic.");
1982 case Intrinsic::x86_sse_cvttss2si:
1983 case Intrinsic::x86_sse_cvttss2si64:
1984 if (!Subtarget->hasSSE1())
1986 IsInputDouble = false;
1988 case Intrinsic::x86_sse2_cvttsd2si:
1989 case Intrinsic::x86_sse2_cvttsd2si64:
1990 if (!Subtarget->hasSSE2())
1992 IsInputDouble = true;
1996 Type *RetTy = I.getCalledFunction()->getReturnType();
1998 if (!isTypeLegal(RetTy, VT))
2001 static const unsigned CvtOpc[2][2][2] = {
2002 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2003 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2004 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2005 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2007 bool HasAVX = Subtarget->hasAVX();
2009 switch (VT.SimpleTy) {
2010 default: llvm_unreachable("Unexpected result type.");
2011 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2012 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2015 // Check if we can fold insertelement instructions into the convert.
2016 const Value *Op = I.getArgOperand(0);
2017 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2018 const Value *Index = IE->getOperand(2);
2019 if (!isa<ConstantInt>(Index))
2021 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2024 Op = IE->getOperand(1);
2027 Op = IE->getOperand(0);
2030 unsigned Reg = getRegForValue(Op);
2034 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2035 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2038 UpdateValueMap(&I, ResultReg);
2044 bool X86FastISel::FastLowerArguments() {
2045 if (!FuncInfo.CanLowerReturn)
2048 const Function *F = FuncInfo.Fn;
2052 CallingConv::ID CC = F->getCallingConv();
2053 if (CC != CallingConv::C)
2056 if (Subtarget->isCallingConvWin64(CC))
2059 if (!Subtarget->is64Bit())
2062 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2063 unsigned GPRCnt = 0;
2064 unsigned FPRCnt = 0;
2066 for (auto const &Arg : F->args()) {
2067 // The first argument is at index 1.
2069 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2070 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2071 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2072 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2075 Type *ArgTy = Arg.getType();
2076 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2079 EVT ArgVT = TLI.getValueType(ArgTy);
2080 if (!ArgVT.isSimple()) return false;
2081 switch (ArgVT.getSimpleVT().SimpleTy) {
2082 default: return false;
2089 if (!Subtarget->hasSSE1())
2102 static const MCPhysReg GPR32ArgRegs[] = {
2103 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2105 static const MCPhysReg GPR64ArgRegs[] = {
2106 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2108 static const MCPhysReg XMMArgRegs[] = {
2109 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2110 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2113 unsigned GPRIdx = 0;
2114 unsigned FPRIdx = 0;
2115 for (auto const &Arg : F->args()) {
2116 MVT VT = TLI.getSimpleValueType(Arg.getType());
2117 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2119 switch (VT.SimpleTy) {
2120 default: llvm_unreachable("Unexpected value type.");
2121 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2122 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2123 case MVT::f32: // fall-through
2124 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2126 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2127 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2128 // Without this, EmitLiveInCopies may eliminate the livein if its only
2129 // use is a bitcast (which isn't turned into an instruction).
2130 unsigned ResultReg = createResultReg(RC);
2131 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2132 TII.get(TargetOpcode::COPY), ResultReg)
2133 .addReg(DstReg, getKillRegState(true));
2134 UpdateValueMap(&Arg, ResultReg);
2139 bool X86FastISel::X86SelectCall(const Instruction *I) {
2140 const CallInst *CI = cast<CallInst>(I);
2141 const Value *Callee = CI->getCalledValue();
2143 // Can't handle inline asm yet.
2144 if (isa<InlineAsm>(Callee))
2147 // Handle intrinsic calls.
2148 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2149 return X86VisitIntrinsicCall(*II);
2151 // Allow SelectionDAG isel to handle tail calls.
2152 if (cast<CallInst>(I)->isTailCall())
2155 return DoSelectCall(I, nullptr);
2158 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2159 const ImmutableCallSite &CS) {
2160 if (Subtarget.is64Bit())
2162 if (Subtarget.getTargetTriple().isOSMSVCRT())
2164 CallingConv::ID CC = CS.getCallingConv();
2165 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2167 if (!CS.paramHasAttr(1, Attribute::StructRet))
2169 if (CS.paramHasAttr(1, Attribute::InReg))
2174 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2175 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2176 const CallInst *CI = cast<CallInst>(I);
2177 const Value *Callee = CI->getCalledValue();
2179 // Handle only C and fastcc calling conventions for now.
2180 ImmutableCallSite CS(CI);
2181 CallingConv::ID CC = CS.getCallingConv();
2182 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2183 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2184 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2185 CC != CallingConv::X86_64_SysV)
2188 // fastcc with -tailcallopt is intended to provide a guaranteed
2189 // tail call optimization. Fastisel doesn't know how to do that.
2190 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2193 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2194 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2195 bool isVarArg = FTy->isVarArg();
2197 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2198 // x86-32. Special handling for x86-64 is implemented.
2199 if (isVarArg && isWin64)
2202 // Don't know about inalloca yet.
2203 if (CS.hasInAllocaArgument())
2206 // Fast-isel doesn't know about callee-pop yet.
2207 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2208 TM.Options.GuaranteedTailCallOpt))
2211 // Check whether the function can return without sret-demotion.
2212 SmallVector<ISD::OutputArg, 4> Outs;
2213 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2214 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2215 *FuncInfo.MF, FTy->isVarArg(),
2216 Outs, FTy->getContext());
2217 if (!CanLowerReturn)
2220 // Materialize callee address in a register. FIXME: GV address can be
2221 // handled with a CALLpcrel32 instead.
2222 X86AddressMode CalleeAM;
2223 if (!X86SelectCallAddress(Callee, CalleeAM))
2225 unsigned CalleeOp = 0;
2226 const GlobalValue *GV = nullptr;
2227 if (CalleeAM.GV != nullptr) {
2229 } else if (CalleeAM.Base.Reg != 0) {
2230 CalleeOp = CalleeAM.Base.Reg;
2234 // Deal with call operands first.
2235 SmallVector<const Value *, 8> ArgVals;
2236 SmallVector<unsigned, 8> Args;
2237 SmallVector<MVT, 8> ArgVTs;
2238 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2239 unsigned arg_size = CS.arg_size();
2240 Args.reserve(arg_size);
2241 ArgVals.reserve(arg_size);
2242 ArgVTs.reserve(arg_size);
2243 ArgFlags.reserve(arg_size);
2244 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2246 // If we're lowering a mem intrinsic instead of a regular call, skip the
2247 // last two arguments, which should not passed to the underlying functions.
2248 if (MemIntName && e-i <= 2)
2251 ISD::ArgFlagsTy Flags;
2252 unsigned AttrInd = i - CS.arg_begin() + 1;
2253 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2255 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2258 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2259 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2260 Type *ElementTy = Ty->getElementType();
2261 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2262 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2264 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2266 Flags.setByValSize(FrameSize);
2267 Flags.setByValAlign(FrameAlign);
2268 if (!IsMemcpySmall(FrameSize))
2272 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2274 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2277 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2278 // instruction. This is safe because it is common to all fastisel supported
2279 // calling conventions on x86.
2280 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2281 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2282 CI->getBitWidth() == 16) {
2284 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2286 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2292 // Passing bools around ends up doing a trunc to i1 and passing it.
2293 // Codegen this as an argument + "and 1".
2294 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2295 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2296 ArgVal->hasOneUse()) {
2297 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2298 ArgReg = getRegForValue(ArgVal);
2299 if (ArgReg == 0) return false;
2302 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2304 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2305 ArgVal->hasOneUse(), 1);
2307 ArgReg = getRegForValue(ArgVal);
2310 if (ArgReg == 0) return false;
2312 Type *ArgTy = ArgVal->getType();
2314 if (!isTypeLegal(ArgTy, ArgVT))
2316 if (ArgVT == MVT::x86mmx)
2318 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2319 Flags.setOrigAlign(OriginalAlignment);
2321 Args.push_back(ArgReg);
2322 ArgVals.push_back(ArgVal);
2323 ArgVTs.push_back(ArgVT);
2324 ArgFlags.push_back(Flags);
2327 // Analyze operands of the call, assigning locations to each operand.
2328 SmallVector<CCValAssign, 16> ArgLocs;
2329 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2330 I->getParent()->getContext());
2332 // Allocate shadow area for Win64
2334 CCInfo.AllocateStack(32, 8);
2336 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2338 // Get a count of how many bytes are to be pushed on the stack.
2339 unsigned NumBytes = CCInfo.getNextStackOffset();
2341 // Issue CALLSEQ_START
2342 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2346 // Process argument: walk the register/memloc assignments, inserting
2348 SmallVector<unsigned, 4> RegArgs;
2349 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2350 CCValAssign &VA = ArgLocs[i];
2351 unsigned Arg = Args[VA.getValNo()];
2352 EVT ArgVT = ArgVTs[VA.getValNo()];
2354 // Promote the value if needed.
2355 switch (VA.getLocInfo()) {
2356 case CCValAssign::Full: break;
2357 case CCValAssign::SExt: {
2358 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2359 "Unexpected extend");
2360 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2362 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2363 ArgVT = VA.getLocVT();
2366 case CCValAssign::ZExt: {
2367 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2368 "Unexpected extend");
2369 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2371 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2372 ArgVT = VA.getLocVT();
2375 case CCValAssign::AExt: {
2376 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2377 "Unexpected extend");
2378 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2381 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2384 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2387 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2388 ArgVT = VA.getLocVT();
2391 case CCValAssign::BCvt: {
2392 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2393 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2394 assert(BC != 0 && "Failed to emit a bitcast!");
2396 ArgVT = VA.getLocVT();
2399 case CCValAssign::VExt:
2400 // VExt has not been implemented, so this should be impossible to reach
2401 // for now. However, fallback to Selection DAG isel once implemented.
2403 case CCValAssign::Indirect:
2404 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2407 case CCValAssign::FPExt:
2408 llvm_unreachable("Unexpected loc info!");
2411 if (VA.isRegLoc()) {
2412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2413 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2414 RegArgs.push_back(VA.getLocReg());
2416 unsigned LocMemOffset = VA.getLocMemOffset();
2418 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2419 getTargetMachine()->getRegisterInfo());
2420 AM.Base.Reg = RegInfo->getStackRegister();
2421 AM.Disp = LocMemOffset;
2422 const Value *ArgVal = ArgVals[VA.getValNo()];
2423 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2425 if (Flags.isByVal()) {
2426 X86AddressMode SrcAM;
2427 SrcAM.Base.Reg = Arg;
2428 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2429 assert(Res && "memcpy length already checked!"); (void)Res;
2430 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2431 // If this is a really simple value, emit this with the Value* version
2432 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2433 // as it can cause us to reevaluate the argument.
2434 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2437 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2443 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2445 if (Subtarget->isPICStyleGOT()) {
2446 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2448 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2451 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2452 // Count the number of XMM registers allocated.
2453 static const MCPhysReg XMMArgRegs[] = {
2454 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2455 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2457 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2458 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2459 X86::AL).addImm(NumXMMRegs);
2463 MachineInstrBuilder MIB;
2465 // Register-indirect call.
2467 if (Subtarget->is64Bit())
2468 CallOpc = X86::CALL64r;
2470 CallOpc = X86::CALL32r;
2471 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2476 assert(GV && "Not a direct call");
2478 if (Subtarget->is64Bit())
2479 CallOpc = X86::CALL64pcrel32;
2481 CallOpc = X86::CALLpcrel32;
2483 // See if we need any target-specific flags on the GV operand.
2484 unsigned char OpFlags = 0;
2486 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2487 // external symbols most go through the PLT in PIC mode. If the symbol
2488 // has hidden or protected visibility, or if it is static or local, then
2489 // we don't need to use the PLT - we can directly call it.
2490 if (Subtarget->isTargetELF() &&
2491 TM.getRelocationModel() == Reloc::PIC_ &&
2492 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2493 OpFlags = X86II::MO_PLT;
2494 } else if (Subtarget->isPICStyleStubAny() &&
2495 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2496 (!Subtarget->getTargetTriple().isMacOSX() ||
2497 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2498 // PC-relative references to external symbols should go through $stub,
2499 // unless we're building with the leopard linker or later, which
2500 // automatically synthesizes these stubs.
2501 OpFlags = X86II::MO_DARWIN_STUB;
2505 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2507 MIB.addExternalSymbol(MemIntName, OpFlags);
2509 MIB.addGlobalAddress(GV, 0, OpFlags);
2512 // Add a register mask with the call-preserved registers.
2513 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2514 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2516 // Add an implicit use GOT pointer in EBX.
2517 if (Subtarget->isPICStyleGOT())
2518 MIB.addReg(X86::EBX, RegState::Implicit);
2520 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2521 MIB.addReg(X86::AL, RegState::Implicit);
2523 // Add implicit physical register uses to the call.
2524 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2525 MIB.addReg(RegArgs[i], RegState::Implicit);
2527 // Issue CALLSEQ_END
2528 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2529 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2531 .addImm(NumBytes).addImm(NumBytesCallee);
2533 // Build info for return calling conv lowering code.
2534 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2535 SmallVector<ISD::InputArg, 32> Ins;
2536 SmallVector<EVT, 4> RetTys;
2537 ComputeValueVTs(TLI, I->getType(), RetTys);
2538 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2540 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2541 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2542 for (unsigned j = 0; j != NumRegs; ++j) {
2543 ISD::InputArg MyFlags;
2544 MyFlags.VT = RegisterVT;
2545 MyFlags.Used = !CS.getInstruction()->use_empty();
2546 if (CS.paramHasAttr(0, Attribute::SExt))
2547 MyFlags.Flags.setSExt();
2548 if (CS.paramHasAttr(0, Attribute::ZExt))
2549 MyFlags.Flags.setZExt();
2550 if (CS.paramHasAttr(0, Attribute::InReg))
2551 MyFlags.Flags.setInReg();
2552 Ins.push_back(MyFlags);
2556 // Now handle call return values.
2557 SmallVector<unsigned, 4> UsedRegs;
2558 SmallVector<CCValAssign, 16> RVLocs;
2559 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2560 I->getParent()->getContext());
2561 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2562 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2563 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2564 EVT CopyVT = RVLocs[i].getValVT();
2565 unsigned CopyReg = ResultReg + i;
2567 // If this is a call to a function that returns an fp value on the x87 fp
2568 // stack, but where we prefer to use the value in xmm registers, copy it
2569 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2570 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2571 RVLocs[i].getLocReg() == X86::ST1)) {
2572 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2574 CopyReg = createResultReg(&X86::RFP80RegClass);
2576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2577 TII.get(X86::FpPOP_RETVAL), CopyReg);
2579 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2580 TII.get(TargetOpcode::COPY),
2581 CopyReg).addReg(RVLocs[i].getLocReg());
2582 UsedRegs.push_back(RVLocs[i].getLocReg());
2585 if (CopyVT != RVLocs[i].getValVT()) {
2586 // Round the F80 the right size, which also moves to the appropriate xmm
2587 // register. This is accomplished by storing the F80 value in memory and
2588 // then loading it back. Ewww...
2589 EVT ResVT = RVLocs[i].getValVT();
2590 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2591 unsigned MemSize = ResVT.getSizeInBits()/8;
2592 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2593 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2596 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2597 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2598 TII.get(Opc), ResultReg + i), FI);
2603 UpdateValueMap(I, ResultReg, RVLocs.size());
2605 // Set all unused physreg defs as dead.
2606 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2613 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2614 switch (I->getOpcode()) {
2616 case Instruction::Load:
2617 return X86SelectLoad(I);
2618 case Instruction::Store:
2619 return X86SelectStore(I);
2620 case Instruction::Ret:
2621 return X86SelectRet(I);
2622 case Instruction::ICmp:
2623 case Instruction::FCmp:
2624 return X86SelectCmp(I);
2625 case Instruction::ZExt:
2626 return X86SelectZExt(I);
2627 case Instruction::Br:
2628 return X86SelectBranch(I);
2629 case Instruction::Call:
2630 return X86SelectCall(I);
2631 case Instruction::LShr:
2632 case Instruction::AShr:
2633 case Instruction::Shl:
2634 return X86SelectShift(I);
2635 case Instruction::SDiv:
2636 case Instruction::UDiv:
2637 case Instruction::SRem:
2638 case Instruction::URem:
2639 return X86SelectDivRem(I);
2640 case Instruction::Select:
2641 return X86SelectSelect(I);
2642 case Instruction::Trunc:
2643 return X86SelectTrunc(I);
2644 case Instruction::FPExt:
2645 return X86SelectFPExt(I);
2646 case Instruction::FPTrunc:
2647 return X86SelectFPTrunc(I);
2648 case Instruction::IntToPtr: // Deliberate fall-through.
2649 case Instruction::PtrToInt: {
2650 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2651 EVT DstVT = TLI.getValueType(I->getType());
2652 if (DstVT.bitsGT(SrcVT))
2653 return X86SelectZExt(I);
2654 if (DstVT.bitsLT(SrcVT))
2655 return X86SelectTrunc(I);
2656 unsigned Reg = getRegForValue(I->getOperand(0));
2657 if (Reg == 0) return false;
2658 UpdateValueMap(I, Reg);
2666 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2668 if (!isTypeLegal(C->getType(), VT))
2671 // Can't handle alternate code models yet.
2672 if (TM.getCodeModel() != CodeModel::Small)
2675 // Get opcode and regclass of the output for the given load instruction.
2677 const TargetRegisterClass *RC = nullptr;
2678 switch (VT.SimpleTy) {
2682 RC = &X86::GR8RegClass;
2686 RC = &X86::GR16RegClass;
2690 RC = &X86::GR32RegClass;
2693 // Must be in x86-64 mode.
2695 RC = &X86::GR64RegClass;
2698 if (X86ScalarSSEf32) {
2699 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2700 RC = &X86::FR32RegClass;
2702 Opc = X86::LD_Fp32m;
2703 RC = &X86::RFP32RegClass;
2707 if (X86ScalarSSEf64) {
2708 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2709 RC = &X86::FR64RegClass;
2711 Opc = X86::LD_Fp64m;
2712 RC = &X86::RFP64RegClass;
2716 // No f80 support yet.
2720 // Materialize addresses with LEA instructions.
2721 if (isa<GlobalValue>(C)) {
2722 // LEA can only handle 32 bit immediates. Currently this happens pretty
2723 // rarely, so rather than deal with it just bail out of fast isel. If any
2724 // architectures endis up needing to use this path a lot then fast isel
2725 // could get the address with a MOV64ri and use that to load the value.
2726 if (TM.getRelocationModel() == Reloc::Static && Subtarget->is64Bit())
2730 if (X86SelectAddress(C, AM)) {
2731 // If the expression is just a basereg, then we're done, otherwise we need
2733 if (AM.BaseType == X86AddressMode::RegBase &&
2734 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
2737 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2738 unsigned ResultReg = createResultReg(RC);
2739 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2740 TII.get(Opc), ResultReg), AM);
2746 // MachineConstantPool wants an explicit alignment.
2747 unsigned Align = DL.getPrefTypeAlignment(C->getType());
2749 // Alignment of vector types. FIXME!
2750 Align = DL.getTypeAllocSize(C->getType());
2753 // x86-32 PIC requires a PIC base register for constant pools.
2754 unsigned PICBase = 0;
2755 unsigned char OpFlag = 0;
2756 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2757 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2758 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2759 } else if (Subtarget->isPICStyleGOT()) {
2760 OpFlag = X86II::MO_GOTOFF;
2761 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2762 } else if (Subtarget->isPICStyleRIPRel() &&
2763 TM.getCodeModel() == CodeModel::Small) {
2767 // Create the load from the constant pool.
2768 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2769 unsigned ResultReg = createResultReg(RC);
2770 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2771 TII.get(Opc), ResultReg),
2772 MCPOffset, PICBase, OpFlag);
2777 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2778 // Fail on dynamic allocas. At this point, getRegForValue has already
2779 // checked its CSE maps, so if we're here trying to handle a dynamic
2780 // alloca, we're not going to succeed. X86SelectAddress has a
2781 // check for dynamic allocas, because it's called directly from
2782 // various places, but TargetMaterializeAlloca also needs a check
2783 // in order to avoid recursion between getRegForValue,
2784 // X86SelectAddrss, and TargetMaterializeAlloca.
2785 if (!FuncInfo.StaticAllocaMap.count(C))
2787 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2790 if (!X86SelectAddress(C, AM))
2792 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2793 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2794 unsigned ResultReg = createResultReg(RC);
2795 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2796 TII.get(Opc), ResultReg), AM);
2800 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2802 if (!isTypeLegal(CF->getType(), VT))
2805 // Get opcode and regclass for the given zero.
2807 const TargetRegisterClass *RC = nullptr;
2808 switch (VT.SimpleTy) {
2811 if (X86ScalarSSEf32) {
2812 Opc = X86::FsFLD0SS;
2813 RC = &X86::FR32RegClass;
2815 Opc = X86::LD_Fp032;
2816 RC = &X86::RFP32RegClass;
2820 if (X86ScalarSSEf64) {
2821 Opc = X86::FsFLD0SD;
2822 RC = &X86::FR64RegClass;
2824 Opc = X86::LD_Fp064;
2825 RC = &X86::RFP64RegClass;
2829 // No f80 support yet.
2833 unsigned ResultReg = createResultReg(RC);
2834 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
2839 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2840 const LoadInst *LI) {
2841 const Value *Ptr = LI->getPointerOperand();
2843 if (!X86SelectAddress(Ptr, AM))
2846 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2848 unsigned Size = DL.getTypeAllocSize(LI->getType());
2849 unsigned Alignment = LI->getAlignment();
2851 if (Alignment == 0) // Ensure that codegen never sees alignment 0
2852 Alignment = DL.getABITypeAlignment(LI->getType());
2854 SmallVector<MachineOperand, 8> AddrOps;
2855 AM.getFullAddress(AddrOps);
2857 MachineInstr *Result =
2858 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2862 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
2863 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2864 MI->eraseFromParent();
2870 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2871 const TargetLibraryInfo *libInfo) {
2872 return new X86FastISel(funcInfo, libInfo);