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/MC/MCAsmInfo.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Target/TargetOptions.h"
47 class X86FastISel final : public FastISel {
48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
49 /// make the right decision when generating code for different targets.
50 const X86Subtarget *Subtarget;
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
61 const TargetLibraryInfo *libInfo)
62 : FastISel(funcInfo, libInfo) {
63 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
64 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
68 bool fastSelectInstruction(const Instruction *I) override;
70 /// \brief The specified machine instr operand is a vreg, and that
71 /// vreg is being provided by the specified load instruction. If possible,
72 /// try to fold the load as an operand to the instruction, returning true if
74 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
75 const LoadInst *LI) override;
77 bool fastLowerArguments() override;
78 bool fastLowerCall(CallLoweringInfo &CLI) override;
79 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81 #include "X86GenFastISel.inc"
84 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL);
86 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
87 unsigned &ResultReg, unsigned Alignment = 1);
89 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
91 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
92 const X86AddressMode &AM,
93 MachineMemOperand *MMO = nullptr, bool Aligned = false);
95 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
99 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectLoad(const Instruction *I);
103 bool X86SelectStore(const Instruction *I);
105 bool X86SelectRet(const Instruction *I);
107 bool X86SelectCmp(const Instruction *I);
109 bool X86SelectZExt(const Instruction *I);
111 bool X86SelectBranch(const Instruction *I);
113 bool X86SelectShift(const Instruction *I);
115 bool X86SelectDivRem(const Instruction *I);
117 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
119 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
123 bool X86SelectSelect(const Instruction *I);
125 bool X86SelectTrunc(const Instruction *I);
127 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
128 const TargetRegisterClass *RC);
130 bool X86SelectFPExt(const Instruction *I);
131 bool X86SelectFPTrunc(const Instruction *I);
132 bool X86SelectSIToFP(const Instruction *I);
134 const X86InstrInfo *getInstrInfo() const {
135 return Subtarget->getInstrInfo();
137 const X86TargetMachine *getTargetMachine() const {
138 return static_cast<const X86TargetMachine *>(&TM);
141 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
143 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
144 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
145 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
146 unsigned fastMaterializeConstant(const Constant *C) override;
148 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
150 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
152 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
153 /// computed in an SSE register, not on the X87 floating point stack.
154 bool isScalarFPTypeInSSEReg(EVT VT) const {
155 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
156 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
161 bool IsMemcpySmall(uint64_t Len);
163 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
164 X86AddressMode SrcAM, uint64_t Len);
166 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
170 } // end anonymous namespace.
172 static std::pair<X86::CondCode, bool>
173 getX86ConditionCode(CmpInst::Predicate Predicate) {
174 X86::CondCode CC = X86::COND_INVALID;
175 bool NeedSwap = false;
178 // Floating-point Predicates
179 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
180 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
181 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
182 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
183 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
184 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
185 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
186 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
187 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
188 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
189 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
190 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
191 case CmpInst::FCMP_OEQ: // fall-through
192 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
194 // Integer Predicates
195 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
196 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
197 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
198 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
199 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
200 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
201 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
202 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
203 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
204 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
207 return std::make_pair(CC, NeedSwap);
210 static std::pair<unsigned, bool>
211 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
213 bool NeedSwap = false;
215 // SSE Condition code mapping:
225 default: llvm_unreachable("Unexpected predicate");
226 case CmpInst::FCMP_OEQ: CC = 0; break;
227 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
228 case CmpInst::FCMP_OLT: CC = 1; break;
229 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
230 case CmpInst::FCMP_OLE: CC = 2; break;
231 case CmpInst::FCMP_UNO: CC = 3; break;
232 case CmpInst::FCMP_UNE: CC = 4; break;
233 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
234 case CmpInst::FCMP_UGE: CC = 5; break;
235 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
236 case CmpInst::FCMP_UGT: CC = 6; break;
237 case CmpInst::FCMP_ORD: CC = 7; break;
238 case CmpInst::FCMP_UEQ:
239 case CmpInst::FCMP_ONE: CC = 8; break;
242 return std::make_pair(CC, NeedSwap);
245 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
246 /// into the user. The condition code will only be updated on success.
247 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
249 if (!isa<ExtractValueInst>(Cond))
252 const auto *EV = cast<ExtractValueInst>(Cond);
253 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
256 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
258 const Function *Callee = II->getCalledFunction();
260 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
261 if (!isTypeLegal(RetTy, RetVT))
264 if (RetVT != MVT::i32 && RetVT != MVT::i64)
268 switch (II->getIntrinsicID()) {
269 default: return false;
270 case Intrinsic::sadd_with_overflow:
271 case Intrinsic::ssub_with_overflow:
272 case Intrinsic::smul_with_overflow:
273 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
274 case Intrinsic::uadd_with_overflow:
275 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
278 // Check if both instructions are in the same basic block.
279 if (II->getParent() != I->getParent())
282 // Make sure nothing is in the way
283 BasicBlock::const_iterator Start = I;
284 BasicBlock::const_iterator End = II;
285 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
286 // We only expect extractvalue instructions between the intrinsic and the
287 // instruction to be selected.
288 if (!isa<ExtractValueInst>(Itr))
291 // Check that the extractvalue operand comes from the intrinsic.
292 const auto *EVI = cast<ExtractValueInst>(Itr);
293 if (EVI->getAggregateOperand() != II)
301 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
302 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
303 if (evt == MVT::Other || !evt.isSimple())
304 // Unhandled type. Halt "fast" selection and bail.
307 VT = evt.getSimpleVT();
308 // For now, require SSE/SSE2 for performing floating-point operations,
309 // since x87 requires additional work.
310 if (VT == MVT::f64 && !X86ScalarSSEf64)
312 if (VT == MVT::f32 && !X86ScalarSSEf32)
314 // Similarly, no f80 support yet.
317 // We only handle legal types. For example, on x86-32 the instruction
318 // selector contains all of the 64-bit instructions from x86-64,
319 // under the assumption that i64 won't be used if the target doesn't
321 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
324 #include "X86GenCallingConv.inc"
326 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
327 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
328 /// Return true and the result register by reference if it is possible.
329 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
330 MachineMemOperand *MMO, unsigned &ResultReg,
331 unsigned Alignment) {
332 // Get opcode and regclass of the output for the given load instruction.
334 const TargetRegisterClass *RC = nullptr;
335 switch (VT.getSimpleVT().SimpleTy) {
336 default: return false;
340 RC = &X86::GR8RegClass;
344 RC = &X86::GR16RegClass;
348 RC = &X86::GR32RegClass;
351 // Must be in x86-64 mode.
353 RC = &X86::GR64RegClass;
356 if (X86ScalarSSEf32) {
357 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
358 RC = &X86::FR32RegClass;
361 RC = &X86::RFP32RegClass;
365 if (X86ScalarSSEf64) {
366 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
367 RC = &X86::FR64RegClass;
370 RC = &X86::RFP64RegClass;
374 // No f80 support yet.
378 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
380 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
381 RC = &X86::VR128RegClass;
385 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
387 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
388 RC = &X86::VR128RegClass;
395 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
397 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
398 RC = &X86::VR128RegClass;
402 ResultReg = createResultReg(RC);
403 MachineInstrBuilder MIB =
404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
405 addFullAddress(MIB, AM);
407 MIB->addMemOperand(*FuncInfo.MF, MMO);
411 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
412 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
413 /// and a displacement offset, or a GlobalAddress,
414 /// i.e. V. Return true if it is possible.
415 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
416 const X86AddressMode &AM,
417 MachineMemOperand *MMO, bool Aligned) {
418 // Get opcode and regclass of the output for the given store instruction.
420 switch (VT.getSimpleVT().SimpleTy) {
421 case MVT::f80: // No f80 support yet.
422 default: return false;
424 // Mask out all but lowest bit.
425 unsigned AndResult = createResultReg(&X86::GR8RegClass);
426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
427 TII.get(X86::AND8ri), AndResult)
428 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
431 // FALLTHROUGH, handling i1 as i8.
432 case MVT::i8: Opc = X86::MOV8mr; break;
433 case MVT::i16: Opc = X86::MOV16mr; break;
434 case MVT::i32: Opc = X86::MOV32mr; break;
435 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
437 Opc = X86ScalarSSEf32 ?
438 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
441 Opc = X86ScalarSSEf64 ?
442 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
446 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
448 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
452 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
454 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
461 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
463 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
467 MachineInstrBuilder MIB =
468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
469 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
471 MIB->addMemOperand(*FuncInfo.MF, MMO);
476 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
477 const X86AddressMode &AM,
478 MachineMemOperand *MMO, bool Aligned) {
479 // Handle 'null' like i32/i64 0.
480 if (isa<ConstantPointerNull>(Val))
481 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
483 // If this is a store of a simple constant, fold the constant into the store.
484 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
487 switch (VT.getSimpleVT().SimpleTy) {
489 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
490 case MVT::i8: Opc = X86::MOV8mi; break;
491 case MVT::i16: Opc = X86::MOV16mi; break;
492 case MVT::i32: Opc = X86::MOV32mi; break;
494 // Must be a 32-bit sign extended value.
495 if (isInt<32>(CI->getSExtValue()))
496 Opc = X86::MOV64mi32;
501 MachineInstrBuilder MIB =
502 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
503 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
504 : CI->getZExtValue());
506 MIB->addMemOperand(*FuncInfo.MF, MMO);
511 unsigned ValReg = getRegForValue(Val);
515 bool ValKill = hasTrivialKill(Val);
516 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
519 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
520 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
521 /// ISD::SIGN_EXTEND).
522 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
523 unsigned Src, EVT SrcVT,
524 unsigned &ResultReg) {
525 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
526 Src, /*TODO: Kill=*/false);
534 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
535 // Handle constant address.
536 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
537 // Can't handle alternate code models yet.
538 if (TM.getCodeModel() != CodeModel::Small)
541 // Can't handle TLS yet.
542 if (GV->isThreadLocal())
545 // RIP-relative addresses can't have additional register operands, so if
546 // we've already folded stuff into the addressing mode, just force the
547 // global value into its own register, which we can use as the basereg.
548 if (!Subtarget->isPICStyleRIPRel() ||
549 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
550 // Okay, we've committed to selecting this global. Set up the address.
553 // Allow the subtarget to classify the global.
554 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
556 // If this reference is relative to the pic base, set it now.
557 if (isGlobalRelativeToPICBase(GVFlags)) {
558 // FIXME: How do we know Base.Reg is free??
559 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
562 // Unless the ABI requires an extra load, return a direct reference to
564 if (!isGlobalStubReference(GVFlags)) {
565 if (Subtarget->isPICStyleRIPRel()) {
566 // Use rip-relative addressing if we can. Above we verified that the
567 // base and index registers are unused.
568 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
569 AM.Base.Reg = X86::RIP;
571 AM.GVOpFlags = GVFlags;
575 // Ok, we need to do a load from a stub. If we've already loaded from
576 // this stub, reuse the loaded pointer, otherwise emit the load now.
577 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
579 if (I != LocalValueMap.end() && I->second != 0) {
582 // Issue load from stub.
584 const TargetRegisterClass *RC = nullptr;
585 X86AddressMode StubAM;
586 StubAM.Base.Reg = AM.Base.Reg;
588 StubAM.GVOpFlags = GVFlags;
590 // Prepare for inserting code in the local-value area.
591 SavePoint SaveInsertPt = enterLocalValueArea();
593 if (TLI.getPointerTy() == MVT::i64) {
595 RC = &X86::GR64RegClass;
597 if (Subtarget->isPICStyleRIPRel())
598 StubAM.Base.Reg = X86::RIP;
601 RC = &X86::GR32RegClass;
604 LoadReg = createResultReg(RC);
605 MachineInstrBuilder LoadMI =
606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
607 addFullAddress(LoadMI, StubAM);
609 // Ok, back to normal mode.
610 leaveLocalValueArea(SaveInsertPt);
612 // Prevent loading GV stub multiple times in same MBB.
613 LocalValueMap[V] = LoadReg;
616 // Now construct the final address. Note that the Disp, Scale,
617 // and Index values may already be set here.
618 AM.Base.Reg = LoadReg;
624 // If all else fails, try to materialize the value in a register.
625 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
626 if (AM.Base.Reg == 0) {
627 AM.Base.Reg = getRegForValue(V);
628 return AM.Base.Reg != 0;
630 if (AM.IndexReg == 0) {
631 assert(AM.Scale == 1 && "Scale with no index!");
632 AM.IndexReg = getRegForValue(V);
633 return AM.IndexReg != 0;
640 /// X86SelectAddress - Attempt to fill in an address from the given value.
642 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
643 SmallVector<const Value *, 32> GEPs;
645 const User *U = nullptr;
646 unsigned Opcode = Instruction::UserOp1;
647 if (const Instruction *I = dyn_cast<Instruction>(V)) {
648 // Don't walk into other basic blocks; it's possible we haven't
649 // visited them yet, so the instructions may not yet be assigned
650 // virtual registers.
651 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
652 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
653 Opcode = I->getOpcode();
656 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
657 Opcode = C->getOpcode();
661 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
662 if (Ty->getAddressSpace() > 255)
663 // Fast instruction selection doesn't support the special
669 case Instruction::BitCast:
670 // Look past bitcasts.
671 return X86SelectAddress(U->getOperand(0), AM);
673 case Instruction::IntToPtr:
674 // Look past no-op inttoptrs.
675 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
676 return X86SelectAddress(U->getOperand(0), AM);
679 case Instruction::PtrToInt:
680 // Look past no-op ptrtoints.
681 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
682 return X86SelectAddress(U->getOperand(0), AM);
685 case Instruction::Alloca: {
686 // Do static allocas.
687 const AllocaInst *A = cast<AllocaInst>(V);
688 DenseMap<const AllocaInst *, int>::iterator SI =
689 FuncInfo.StaticAllocaMap.find(A);
690 if (SI != FuncInfo.StaticAllocaMap.end()) {
691 AM.BaseType = X86AddressMode::FrameIndexBase;
692 AM.Base.FrameIndex = SI->second;
698 case Instruction::Add: {
699 // Adds of constants are common and easy enough.
700 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
701 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
702 // They have to fit in the 32-bit signed displacement field though.
703 if (isInt<32>(Disp)) {
704 AM.Disp = (uint32_t)Disp;
705 return X86SelectAddress(U->getOperand(0), AM);
711 case Instruction::GetElementPtr: {
712 X86AddressMode SavedAM = AM;
714 // Pattern-match simple GEPs.
715 uint64_t Disp = (int32_t)AM.Disp;
716 unsigned IndexReg = AM.IndexReg;
717 unsigned Scale = AM.Scale;
718 gep_type_iterator GTI = gep_type_begin(U);
719 // Iterate through the indices, folding what we can. Constants can be
720 // folded, and one dynamic index can be handled, if the scale is supported.
721 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
722 i != e; ++i, ++GTI) {
723 const Value *Op = *i;
724 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
725 const StructLayout *SL = DL.getStructLayout(STy);
726 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
730 // A array/variable index is always of the form i*S where S is the
731 // constant scale size. See if we can push the scale into immediates.
732 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
734 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
735 // Constant-offset addressing.
736 Disp += CI->getSExtValue() * S;
739 if (canFoldAddIntoGEP(U, Op)) {
740 // A compatible add with a constant operand. Fold the constant.
742 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
743 Disp += CI->getSExtValue() * S;
744 // Iterate on the other operand.
745 Op = cast<AddOperator>(Op)->getOperand(0);
749 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
750 (S == 1 || S == 2 || S == 4 || S == 8)) {
751 // Scaled-index addressing.
753 IndexReg = getRegForGEPIndex(Op).first;
759 goto unsupported_gep;
763 // Check for displacement overflow.
764 if (!isInt<32>(Disp))
767 AM.IndexReg = IndexReg;
769 AM.Disp = (uint32_t)Disp;
772 if (const GetElementPtrInst *GEP =
773 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
774 // Ok, the GEP indices were covered by constant-offset and scaled-index
775 // addressing. Update the address state and move on to examining the base.
778 } else if (X86SelectAddress(U->getOperand(0), AM)) {
782 // If we couldn't merge the gep value into this addr mode, revert back to
783 // our address and just match the value instead of completely failing.
786 for (SmallVectorImpl<const Value *>::reverse_iterator
787 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
788 if (handleConstantAddresses(*I, AM))
793 // Ok, the GEP indices weren't all covered.
798 return handleConstantAddresses(V, AM);
801 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
803 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
804 const User *U = nullptr;
805 unsigned Opcode = Instruction::UserOp1;
806 const Instruction *I = dyn_cast<Instruction>(V);
807 // Record if the value is defined in the same basic block.
809 // This information is crucial to know whether or not folding an
811 // Indeed, FastISel generates or reuses a virtual register for all
812 // operands of all instructions it selects. Obviously, the definition and
813 // its uses must use the same virtual register otherwise the produced
814 // code is incorrect.
815 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
816 // registers for values that are alive across basic blocks. This ensures
817 // that the values are consistently set between across basic block, even
818 // if different instruction selection mechanisms are used (e.g., a mix of
819 // SDISel and FastISel).
820 // For values local to a basic block, the instruction selection process
821 // generates these virtual registers with whatever method is appropriate
822 // for its needs. In particular, FastISel and SDISel do not share the way
823 // local virtual registers are set.
824 // Therefore, this is impossible (or at least unsafe) to share values
825 // between basic blocks unless they use the same instruction selection
826 // method, which is not guarantee for X86.
827 // Moreover, things like hasOneUse could not be used accurately, if we
828 // allow to reference values across basic blocks whereas they are not
829 // alive across basic blocks initially.
832 Opcode = I->getOpcode();
834 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
835 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
836 Opcode = C->getOpcode();
842 case Instruction::BitCast:
843 // Look past bitcasts if its operand is in the same BB.
845 return X86SelectCallAddress(U->getOperand(0), AM);
848 case Instruction::IntToPtr:
849 // Look past no-op inttoptrs if its operand is in the same BB.
851 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
852 return X86SelectCallAddress(U->getOperand(0), AM);
855 case Instruction::PtrToInt:
856 // Look past no-op ptrtoints if its operand is in the same BB.
858 TLI.getValueType(U->getType()) == TLI.getPointerTy())
859 return X86SelectCallAddress(U->getOperand(0), AM);
863 // Handle constant address.
864 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
865 // Can't handle alternate code models yet.
866 if (TM.getCodeModel() != CodeModel::Small)
869 // RIP-relative addresses can't have additional register operands.
870 if (Subtarget->isPICStyleRIPRel() &&
871 (AM.Base.Reg != 0 || AM.IndexReg != 0))
874 // Can't handle DLL Import.
875 if (GV->hasDLLImportStorageClass())
879 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
880 if (GVar->isThreadLocal())
883 // Okay, we've committed to selecting this global. Set up the basic address.
886 // No ABI requires an extra load for anything other than DLLImport, which
887 // we rejected above. Return a direct reference to the global.
888 if (Subtarget->isPICStyleRIPRel()) {
889 // Use rip-relative addressing if we can. Above we verified that the
890 // base and index registers are unused.
891 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
892 AM.Base.Reg = X86::RIP;
893 } else if (Subtarget->isPICStyleStubPIC()) {
894 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
895 } else if (Subtarget->isPICStyleGOT()) {
896 AM.GVOpFlags = X86II::MO_GOTOFF;
902 // If all else fails, try to materialize the value in a register.
903 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
904 if (AM.Base.Reg == 0) {
905 AM.Base.Reg = getRegForValue(V);
906 return AM.Base.Reg != 0;
908 if (AM.IndexReg == 0) {
909 assert(AM.Scale == 1 && "Scale with no index!");
910 AM.IndexReg = getRegForValue(V);
911 return AM.IndexReg != 0;
919 /// X86SelectStore - Select and emit code to implement store instructions.
920 bool X86FastISel::X86SelectStore(const Instruction *I) {
921 // Atomic stores need special handling.
922 const StoreInst *S = cast<StoreInst>(I);
927 const Value *Val = S->getValueOperand();
928 const Value *Ptr = S->getPointerOperand();
931 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
934 unsigned Alignment = S->getAlignment();
935 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
936 if (Alignment == 0) // Ensure that codegen never sees alignment 0
937 Alignment = ABIAlignment;
938 bool Aligned = Alignment >= ABIAlignment;
941 if (!X86SelectAddress(Ptr, AM))
944 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
947 /// X86SelectRet - Select and emit code to implement ret instructions.
948 bool X86FastISel::X86SelectRet(const Instruction *I) {
949 const ReturnInst *Ret = cast<ReturnInst>(I);
950 const Function &F = *I->getParent()->getParent();
951 const X86MachineFunctionInfo *X86MFInfo =
952 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
954 if (!FuncInfo.CanLowerReturn)
957 CallingConv::ID CC = F.getCallingConv();
958 if (CC != CallingConv::C &&
959 CC != CallingConv::Fast &&
960 CC != CallingConv::X86_FastCall &&
961 CC != CallingConv::X86_64_SysV)
964 if (Subtarget->isCallingConvWin64(CC))
967 // Don't handle popping bytes on return for now.
968 if (X86MFInfo->getBytesToPopOnReturn() != 0)
971 // fastcc with -tailcallopt is intended to provide a guaranteed
972 // tail call optimization. Fastisel doesn't know how to do that.
973 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
976 // Let SDISel handle vararg functions.
980 // Build a list of return value registers.
981 SmallVector<unsigned, 4> RetRegs;
983 if (Ret->getNumOperands() > 0) {
984 SmallVector<ISD::OutputArg, 4> Outs;
985 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
987 // Analyze operands of the call, assigning locations to each operand.
988 SmallVector<CCValAssign, 16> ValLocs;
989 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
990 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
992 const Value *RV = Ret->getOperand(0);
993 unsigned Reg = getRegForValue(RV);
997 // Only handle a single return value for now.
998 if (ValLocs.size() != 1)
1001 CCValAssign &VA = ValLocs[0];
1003 // Don't bother handling odd stuff for now.
1004 if (VA.getLocInfo() != CCValAssign::Full)
1006 // Only handle register returns for now.
1010 // The calling-convention tables for x87 returns don't tell
1012 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1015 unsigned SrcReg = Reg + VA.getValNo();
1016 EVT SrcVT = TLI.getValueType(RV->getType());
1017 EVT DstVT = VA.getValVT();
1018 // Special handling for extended integers.
1019 if (SrcVT != DstVT) {
1020 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1023 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1026 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1028 if (SrcVT == MVT::i1) {
1029 if (Outs[0].Flags.isSExt())
1031 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1034 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1036 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1037 SrcReg, /*TODO: Kill=*/false);
1041 unsigned DstReg = VA.getLocReg();
1042 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1043 // Avoid a cross-class copy. This is very unlikely.
1044 if (!SrcRC->contains(DstReg))
1046 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1047 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1049 // Add register to return instruction.
1050 RetRegs.push_back(VA.getLocReg());
1053 // The x86-64 ABI for returning structs by value requires that we copy
1054 // the sret argument into %rax for the return. We saved the argument into
1055 // a virtual register in the entry block, so now we copy the value out
1056 // and into %rax. We also do the same with %eax for Win32.
1057 if (F.hasStructRetAttr() &&
1058 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1059 unsigned Reg = X86MFInfo->getSRetReturnReg();
1061 "SRetReturnReg should have been set in LowerFormalArguments()!");
1062 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1064 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1065 RetRegs.push_back(RetReg);
1068 // Now emit the RET.
1069 MachineInstrBuilder MIB =
1070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1071 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1072 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1073 MIB.addReg(RetRegs[i], RegState::Implicit);
1077 /// X86SelectLoad - Select and emit code to implement load instructions.
1079 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1080 const LoadInst *LI = cast<LoadInst>(I);
1082 // Atomic loads need special handling.
1087 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1090 const Value *Ptr = LI->getPointerOperand();
1093 if (!X86SelectAddress(Ptr, AM))
1096 unsigned Alignment = LI->getAlignment();
1097 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1098 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1099 Alignment = ABIAlignment;
1101 unsigned ResultReg = 0;
1102 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1106 updateValueMap(I, ResultReg);
1110 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1111 bool HasAVX = Subtarget->hasAVX();
1112 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1113 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1115 switch (VT.getSimpleVT().SimpleTy) {
1117 case MVT::i8: return X86::CMP8rr;
1118 case MVT::i16: return X86::CMP16rr;
1119 case MVT::i32: return X86::CMP32rr;
1120 case MVT::i64: return X86::CMP64rr;
1122 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1124 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1128 /// If we have a comparison with RHS as the RHS of the comparison, return an
1129 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1130 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1131 int64_t Val = RHSC->getSExtValue();
1132 switch (VT.getSimpleVT().SimpleTy) {
1133 // Otherwise, we can't fold the immediate into this comparison.
1140 return X86::CMP16ri8;
1141 return X86::CMP16ri;
1144 return X86::CMP32ri8;
1145 return X86::CMP32ri;
1148 return X86::CMP64ri8;
1149 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1152 return X86::CMP64ri32;
1157 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1158 EVT VT, DebugLoc CurDbgLoc) {
1159 unsigned Op0Reg = getRegForValue(Op0);
1160 if (Op0Reg == 0) return false;
1162 // Handle 'null' like i32/i64 0.
1163 if (isa<ConstantPointerNull>(Op1))
1164 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1166 // We have two options: compare with register or immediate. If the RHS of
1167 // the compare is an immediate that we can fold into this compare, use
1168 // CMPri, otherwise use CMPrr.
1169 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1170 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1173 .addImm(Op1C->getSExtValue());
1178 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1179 if (CompareOpc == 0) return false;
1181 unsigned Op1Reg = getRegForValue(Op1);
1182 if (Op1Reg == 0) return false;
1183 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1190 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1191 const CmpInst *CI = cast<CmpInst>(I);
1194 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1197 // Try to optimize or fold the cmp.
1198 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1199 unsigned ResultReg = 0;
1200 switch (Predicate) {
1202 case CmpInst::FCMP_FALSE: {
1203 ResultReg = createResultReg(&X86::GR32RegClass);
1204 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1206 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1212 case CmpInst::FCMP_TRUE: {
1213 ResultReg = createResultReg(&X86::GR8RegClass);
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1215 ResultReg).addImm(1);
1221 updateValueMap(I, ResultReg);
1225 const Value *LHS = CI->getOperand(0);
1226 const Value *RHS = CI->getOperand(1);
1228 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1229 // We don't have to materialize a zero constant for this case and can just use
1230 // %x again on the RHS.
1231 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1232 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1233 if (RHSC && RHSC->isNullValue())
1237 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1238 static unsigned SETFOpcTable[2][3] = {
1239 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1240 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1242 unsigned *SETFOpc = nullptr;
1243 switch (Predicate) {
1245 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1246 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1249 ResultReg = createResultReg(&X86::GR8RegClass);
1251 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1254 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1255 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1260 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1261 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1262 updateValueMap(I, ResultReg);
1268 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1269 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1270 unsigned Opc = X86::getSETFromCond(CC);
1273 std::swap(LHS, RHS);
1275 // Emit a compare of LHS/RHS.
1276 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1280 updateValueMap(I, ResultReg);
1284 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1285 EVT DstVT = TLI.getValueType(I->getType());
1286 if (!TLI.isTypeLegal(DstVT))
1289 unsigned ResultReg = getRegForValue(I->getOperand(0));
1293 // Handle zero-extension from i1 to i8, which is common.
1294 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1295 if (SrcVT.SimpleTy == MVT::i1) {
1296 // Set the high bits to zero.
1297 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1304 if (DstVT == MVT::i64) {
1305 // Handle extension to 64-bits via sub-register shenanigans.
1308 switch (SrcVT.SimpleTy) {
1309 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1310 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1311 case MVT::i32: MovInst = X86::MOV32rr; break;
1312 default: llvm_unreachable("Unexpected zext to i64 source type");
1315 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1319 ResultReg = createResultReg(&X86::GR64RegClass);
1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1322 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1323 } else if (DstVT != MVT::i8) {
1324 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1325 ResultReg, /*Kill=*/true);
1330 updateValueMap(I, ResultReg);
1334 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1335 // Unconditional branches are selected by tablegen-generated code.
1336 // Handle a conditional branch.
1337 const BranchInst *BI = cast<BranchInst>(I);
1338 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1339 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1341 // Fold the common case of a conditional branch with a comparison
1342 // in the same block (values defined on other blocks may not have
1343 // initialized registers).
1345 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1346 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1347 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1349 // Try to optimize or fold the cmp.
1350 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1351 switch (Predicate) {
1353 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1354 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1357 const Value *CmpLHS = CI->getOperand(0);
1358 const Value *CmpRHS = CI->getOperand(1);
1360 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1362 // We don't have to materialize a zero constant for this case and can just
1363 // use %x again on the RHS.
1364 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1365 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1366 if (CmpRHSC && CmpRHSC->isNullValue())
1370 // Try to take advantage of fallthrough opportunities.
1371 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1372 std::swap(TrueMBB, FalseMBB);
1373 Predicate = CmpInst::getInversePredicate(Predicate);
1376 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1377 // code check. Instead two branch instructions are required to check all
1378 // the flags. First we change the predicate to a supported condition code,
1379 // which will be the first branch. Later one we will emit the second
1381 bool NeedExtraBranch = false;
1382 switch (Predicate) {
1384 case CmpInst::FCMP_OEQ:
1385 std::swap(TrueMBB, FalseMBB); // fall-through
1386 case CmpInst::FCMP_UNE:
1387 NeedExtraBranch = true;
1388 Predicate = CmpInst::FCMP_ONE;
1394 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1395 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1397 BranchOpc = X86::GetCondBranchFromCond(CC);
1399 std::swap(CmpLHS, CmpRHS);
1401 // Emit a compare of the LHS and RHS, setting the flags.
1402 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1408 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1410 if (NeedExtraBranch) {
1411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1415 // Obtain the branch weight and add the TrueBB to the successor list.
1416 uint32_t BranchWeight = 0;
1418 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1419 TrueMBB->getBasicBlock());
1420 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1422 // Emits an unconditional branch to the FalseBB, obtains the branch
1423 // weight, and adds it to the successor list.
1424 fastEmitBranch(FalseMBB, DbgLoc);
1428 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1429 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1430 // typically happen for _Bool and C++ bools.
1432 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1433 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1434 unsigned TestOpc = 0;
1435 switch (SourceVT.SimpleTy) {
1437 case MVT::i8: TestOpc = X86::TEST8ri; break;
1438 case MVT::i16: TestOpc = X86::TEST16ri; break;
1439 case MVT::i32: TestOpc = X86::TEST32ri; break;
1440 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1443 unsigned OpReg = getRegForValue(TI->getOperand(0));
1444 if (OpReg == 0) return false;
1445 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1446 .addReg(OpReg).addImm(1);
1448 unsigned JmpOpc = X86::JNE_1;
1449 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1450 std::swap(TrueMBB, FalseMBB);
1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1456 fastEmitBranch(FalseMBB, DbgLoc);
1457 uint32_t BranchWeight = 0;
1459 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1460 TrueMBB->getBasicBlock());
1461 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1465 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1466 // Fake request the condition, otherwise the intrinsic might be completely
1468 unsigned TmpReg = getRegForValue(BI->getCondition());
1472 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1476 fastEmitBranch(FalseMBB, DbgLoc);
1477 uint32_t BranchWeight = 0;
1479 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1480 TrueMBB->getBasicBlock());
1481 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1485 // Otherwise do a clumsy setcc and re-test it.
1486 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1487 // in an explicit cast, so make sure to handle that correctly.
1488 unsigned OpReg = getRegForValue(BI->getCondition());
1489 if (OpReg == 0) return false;
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1492 .addReg(OpReg).addImm(1);
1493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1495 fastEmitBranch(FalseMBB, DbgLoc);
1496 uint32_t BranchWeight = 0;
1498 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1499 TrueMBB->getBasicBlock());
1500 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1504 bool X86FastISel::X86SelectShift(const Instruction *I) {
1505 unsigned CReg = 0, OpReg = 0;
1506 const TargetRegisterClass *RC = nullptr;
1507 if (I->getType()->isIntegerTy(8)) {
1509 RC = &X86::GR8RegClass;
1510 switch (I->getOpcode()) {
1511 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1512 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1513 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1514 default: return false;
1516 } else if (I->getType()->isIntegerTy(16)) {
1518 RC = &X86::GR16RegClass;
1519 switch (I->getOpcode()) {
1520 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1521 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1522 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1523 default: return false;
1525 } else if (I->getType()->isIntegerTy(32)) {
1527 RC = &X86::GR32RegClass;
1528 switch (I->getOpcode()) {
1529 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1530 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1531 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1532 default: return false;
1534 } else if (I->getType()->isIntegerTy(64)) {
1536 RC = &X86::GR64RegClass;
1537 switch (I->getOpcode()) {
1538 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1539 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1540 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1541 default: return false;
1548 if (!isTypeLegal(I->getType(), VT))
1551 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1552 if (Op0Reg == 0) return false;
1554 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1555 if (Op1Reg == 0) return false;
1556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1557 CReg).addReg(Op1Reg);
1559 // The shift instruction uses X86::CL. If we defined a super-register
1560 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1561 if (CReg != X86::CL)
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1563 TII.get(TargetOpcode::KILL), X86::CL)
1564 .addReg(CReg, RegState::Kill);
1566 unsigned ResultReg = createResultReg(RC);
1567 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1569 updateValueMap(I, ResultReg);
1573 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1574 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1575 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1576 const static bool S = true; // IsSigned
1577 const static bool U = false; // !IsSigned
1578 const static unsigned Copy = TargetOpcode::COPY;
1579 // For the X86 DIV/IDIV instruction, in most cases the dividend
1580 // (numerator) must be in a specific register pair highreg:lowreg,
1581 // producing the quotient in lowreg and the remainder in highreg.
1582 // For most data types, to set up the instruction, the dividend is
1583 // copied into lowreg, and lowreg is sign-extended or zero-extended
1584 // into highreg. The exception is i8, where the dividend is defined
1585 // as a single register rather than a register pair, and we
1586 // therefore directly sign-extend or zero-extend the dividend into
1587 // lowreg, instead of copying, and ignore the highreg.
1588 const static struct DivRemEntry {
1589 // The following portion depends only on the data type.
1590 const TargetRegisterClass *RC;
1591 unsigned LowInReg; // low part of the register pair
1592 unsigned HighInReg; // high part of the register pair
1593 // The following portion depends on both the data type and the operation.
1594 struct DivRemResult {
1595 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1596 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1597 // highreg, or copying a zero into highreg.
1598 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1599 // zero/sign-extending into lowreg for i8.
1600 unsigned DivRemResultReg; // Register containing the desired result.
1601 bool IsOpSigned; // Whether to use signed or unsigned form.
1602 } ResultTable[NumOps];
1603 } OpTable[NumTypes] = {
1604 { &X86::GR8RegClass, X86::AX, 0, {
1605 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1606 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1607 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1608 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1611 { &X86::GR16RegClass, X86::AX, X86::DX, {
1612 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1613 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1614 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1615 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1618 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1619 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1620 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1621 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1622 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1625 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1626 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1627 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1628 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1629 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1635 if (!isTypeLegal(I->getType(), VT))
1638 unsigned TypeIndex, OpIndex;
1639 switch (VT.SimpleTy) {
1640 default: return false;
1641 case MVT::i8: TypeIndex = 0; break;
1642 case MVT::i16: TypeIndex = 1; break;
1643 case MVT::i32: TypeIndex = 2; break;
1644 case MVT::i64: TypeIndex = 3;
1645 if (!Subtarget->is64Bit())
1650 switch (I->getOpcode()) {
1651 default: llvm_unreachable("Unexpected div/rem opcode");
1652 case Instruction::SDiv: OpIndex = 0; break;
1653 case Instruction::SRem: OpIndex = 1; break;
1654 case Instruction::UDiv: OpIndex = 2; break;
1655 case Instruction::URem: OpIndex = 3; break;
1658 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1659 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1660 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1663 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1667 // Move op0 into low-order input register.
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1669 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1670 // Zero-extend or sign-extend into high-order input register.
1671 if (OpEntry.OpSignExtend) {
1672 if (OpEntry.IsOpSigned)
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1674 TII.get(OpEntry.OpSignExtend));
1676 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1678 TII.get(X86::MOV32r0), Zero32);
1680 // Copy the zero into the appropriate sub/super/identical physical
1681 // register. Unfortunately the operations needed are not uniform enough
1682 // to fit neatly into the table above.
1683 if (VT.SimpleTy == MVT::i16) {
1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1685 TII.get(Copy), TypeEntry.HighInReg)
1686 .addReg(Zero32, 0, X86::sub_16bit);
1687 } else if (VT.SimpleTy == MVT::i32) {
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1689 TII.get(Copy), TypeEntry.HighInReg)
1691 } else if (VT.SimpleTy == MVT::i64) {
1692 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1693 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1694 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1698 // Generate the DIV/IDIV instruction.
1699 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1700 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1701 // For i8 remainder, we can't reference AH directly, as we'll end
1702 // up with bogus copies like %R9B = COPY %AH. Reference AX
1703 // instead to prevent AH references in a REX instruction.
1705 // The current assumption of the fast register allocator is that isel
1706 // won't generate explicit references to the GPR8_NOREX registers. If
1707 // the allocator and/or the backend get enhanced to be more robust in
1708 // that regard, this can be, and should be, removed.
1709 unsigned ResultReg = 0;
1710 if ((I->getOpcode() == Instruction::SRem ||
1711 I->getOpcode() == Instruction::URem) &&
1712 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1713 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1714 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1716 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1718 // Shift AX right by 8 bits instead of using AH.
1719 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1720 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1722 // Now reference the 8-bit subreg of the result.
1723 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1724 /*Kill=*/true, X86::sub_8bit);
1726 // Copy the result out of the physreg if we haven't already.
1728 ResultReg = createResultReg(TypeEntry.RC);
1729 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1730 .addReg(OpEntry.DivRemResultReg);
1732 updateValueMap(I, ResultReg);
1737 /// \brief Emit a conditional move instruction (if the are supported) to lower
1739 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1740 // Check if the subtarget supports these instructions.
1741 if (!Subtarget->hasCMov())
1744 // FIXME: Add support for i8.
1745 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1748 const Value *Cond = I->getOperand(0);
1749 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1750 bool NeedTest = true;
1751 X86::CondCode CC = X86::COND_NE;
1753 // Optimize conditions coming from a compare if both instructions are in the
1754 // same basic block (values defined in other basic blocks may not have
1755 // initialized registers).
1756 const auto *CI = dyn_cast<CmpInst>(Cond);
1757 if (CI && (CI->getParent() == I->getParent())) {
1758 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1760 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1761 static unsigned SETFOpcTable[2][3] = {
1762 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1763 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1765 unsigned *SETFOpc = nullptr;
1766 switch (Predicate) {
1768 case CmpInst::FCMP_OEQ:
1769 SETFOpc = &SETFOpcTable[0][0];
1770 Predicate = CmpInst::ICMP_NE;
1772 case CmpInst::FCMP_UNE:
1773 SETFOpc = &SETFOpcTable[1][0];
1774 Predicate = CmpInst::ICMP_NE;
1779 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1780 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1782 const Value *CmpLHS = CI->getOperand(0);
1783 const Value *CmpRHS = CI->getOperand(1);
1785 std::swap(CmpLHS, CmpRHS);
1787 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1788 // Emit a compare of the LHS and RHS, setting the flags.
1789 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1793 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1794 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1795 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1799 auto const &II = TII.get(SETFOpc[2]);
1800 if (II.getNumDefs()) {
1801 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1803 .addReg(FlagReg2).addReg(FlagReg1);
1805 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1806 .addReg(FlagReg2).addReg(FlagReg1);
1810 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1811 // Fake request the condition, otherwise the intrinsic might be completely
1813 unsigned TmpReg = getRegForValue(Cond);
1821 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1822 // garbage. Indeed, only the less significant bit is supposed to be
1823 // accurate. If we read more than the lsb, we may see non-zero values
1824 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1825 // the select. This is achieved by performing TEST against 1.
1826 unsigned CondReg = getRegForValue(Cond);
1829 bool CondIsKill = hasTrivialKill(Cond);
1831 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1832 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1835 const Value *LHS = I->getOperand(1);
1836 const Value *RHS = I->getOperand(2);
1838 unsigned RHSReg = getRegForValue(RHS);
1839 bool RHSIsKill = hasTrivialKill(RHS);
1841 unsigned LHSReg = getRegForValue(LHS);
1842 bool LHSIsKill = hasTrivialKill(LHS);
1844 if (!LHSReg || !RHSReg)
1847 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1848 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1850 updateValueMap(I, ResultReg);
1854 /// \brief Emit SSE or AVX instructions to lower the select.
1856 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1857 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1858 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1859 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1860 // Optimize conditions coming from a compare if both instructions are in the
1861 // same basic block (values defined in other basic blocks may not have
1862 // initialized registers).
1863 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1864 if (!CI || (CI->getParent() != I->getParent()))
1867 if (I->getType() != CI->getOperand(0)->getType() ||
1868 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1869 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1872 const Value *CmpLHS = CI->getOperand(0);
1873 const Value *CmpRHS = CI->getOperand(1);
1874 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1876 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1877 // We don't have to materialize a zero constant for this case and can just use
1878 // %x again on the RHS.
1879 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1880 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1881 if (CmpRHSC && CmpRHSC->isNullValue())
1887 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1892 std::swap(CmpLHS, CmpRHS);
1894 // Choose the SSE instruction sequence based on data type (float or double).
1895 static unsigned OpcTable[2][4] = {
1896 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1897 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1900 unsigned *Opc = nullptr;
1901 switch (RetVT.SimpleTy) {
1902 default: return false;
1903 case MVT::f32: Opc = &OpcTable[0][0]; break;
1904 case MVT::f64: Opc = &OpcTable[1][0]; break;
1907 const Value *LHS = I->getOperand(1);
1908 const Value *RHS = I->getOperand(2);
1910 unsigned LHSReg = getRegForValue(LHS);
1911 bool LHSIsKill = hasTrivialKill(LHS);
1913 unsigned RHSReg = getRegForValue(RHS);
1914 bool RHSIsKill = hasTrivialKill(RHS);
1916 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1917 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1919 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1920 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1922 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1925 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1928 if (Subtarget->hasAVX()) {
1929 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1930 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1931 // uses XMM0 as the selection register. That may need just as many
1932 // instructions as the AND/ANDN/OR sequence due to register moves, so
1934 unsigned CmpOpcode =
1935 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1936 unsigned BlendOpcode =
1937 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1939 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1940 CmpRHSReg, CmpRHSIsKill, CC);
1941 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1942 LHSReg, LHSIsKill, CmpReg, true);
1944 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1945 CmpRHSReg, CmpRHSIsKill, CC);
1946 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1948 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1950 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1951 AndReg, /*IsKill=*/true);
1953 updateValueMap(I, ResultReg);
1957 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1958 // These are pseudo CMOV instructions and will be later expanded into control-
1961 switch (RetVT.SimpleTy) {
1962 default: return false;
1963 case MVT::i8: Opc = X86::CMOV_GR8; break;
1964 case MVT::i16: Opc = X86::CMOV_GR16; break;
1965 case MVT::i32: Opc = X86::CMOV_GR32; break;
1966 case MVT::f32: Opc = X86::CMOV_FR32; break;
1967 case MVT::f64: Opc = X86::CMOV_FR64; break;
1970 const Value *Cond = I->getOperand(0);
1971 X86::CondCode CC = X86::COND_NE;
1973 // Optimize conditions coming from a compare if both instructions are in the
1974 // same basic block (values defined in other basic blocks may not have
1975 // initialized registers).
1976 const auto *CI = dyn_cast<CmpInst>(Cond);
1977 if (CI && (CI->getParent() == I->getParent())) {
1979 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1980 if (CC > X86::LAST_VALID_COND)
1983 const Value *CmpLHS = CI->getOperand(0);
1984 const Value *CmpRHS = CI->getOperand(1);
1987 std::swap(CmpLHS, CmpRHS);
1989 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1990 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1993 unsigned CondReg = getRegForValue(Cond);
1996 bool CondIsKill = hasTrivialKill(Cond);
1997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1998 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2001 const Value *LHS = I->getOperand(1);
2002 const Value *RHS = I->getOperand(2);
2004 unsigned LHSReg = getRegForValue(LHS);
2005 bool LHSIsKill = hasTrivialKill(LHS);
2007 unsigned RHSReg = getRegForValue(RHS);
2008 bool RHSIsKill = hasTrivialKill(RHS);
2010 if (!LHSReg || !RHSReg)
2013 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2015 unsigned ResultReg =
2016 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2017 updateValueMap(I, ResultReg);
2021 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2023 if (!isTypeLegal(I->getType(), RetVT))
2026 // Check if we can fold the select.
2027 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2028 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2029 const Value *Opnd = nullptr;
2030 switch (Predicate) {
2032 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2033 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2035 // No need for a select anymore - this is an unconditional move.
2037 unsigned OpReg = getRegForValue(Opnd);
2040 bool OpIsKill = hasTrivialKill(Opnd);
2041 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2042 unsigned ResultReg = createResultReg(RC);
2043 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2044 TII.get(TargetOpcode::COPY), ResultReg)
2045 .addReg(OpReg, getKillRegState(OpIsKill));
2046 updateValueMap(I, ResultReg);
2051 // First try to use real conditional move instructions.
2052 if (X86FastEmitCMoveSelect(RetVT, I))
2055 // Try to use a sequence of SSE instructions to simulate a conditional move.
2056 if (X86FastEmitSSESelect(RetVT, I))
2059 // Fall-back to pseudo conditional move instructions, which will be later
2060 // converted to control-flow.
2061 if (X86FastEmitPseudoSelect(RetVT, I))
2067 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2068 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2071 // Select integer to float/double conversion.
2072 unsigned OpReg = getRegForValue(I->getOperand(0));
2076 const TargetRegisterClass *RC = nullptr;
2079 if (I->getType()->isDoubleTy()) {
2080 // sitofp int -> double
2081 Opcode = X86::VCVTSI2SDrr;
2082 RC = &X86::FR64RegClass;
2083 } else if (I->getType()->isFloatTy()) {
2084 // sitofp int -> float
2085 Opcode = X86::VCVTSI2SSrr;
2086 RC = &X86::FR32RegClass;
2090 // The target-independent selection algorithm in FastISel already knows how
2091 // to select a SINT_TO_FP if the target is SSE but not AVX. This code is only
2092 // reachable if the subtarget has AVX.
2093 assert(Subtarget->hasAVX() && "Expected a subtarget with AVX!");
2095 unsigned ImplicitDefReg = createResultReg(RC);
2096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2097 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2098 unsigned ResultReg =
2099 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2100 updateValueMap(I, ResultReg);
2104 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2105 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2107 const TargetRegisterClass *RC) {
2108 assert((I->getOpcode() == Instruction::FPExt ||
2109 I->getOpcode() == Instruction::FPTrunc) &&
2110 "Instruction must be an FPExt or FPTrunc!");
2112 unsigned OpReg = getRegForValue(I->getOperand(0));
2116 unsigned ResultReg = createResultReg(RC);
2117 MachineInstrBuilder MIB;
2118 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2120 if (Subtarget->hasAVX())
2123 updateValueMap(I, ResultReg);
2127 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2128 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2129 I->getOperand(0)->getType()->isFloatTy()) {
2130 // fpext from float to double.
2131 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2132 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2138 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2139 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2140 I->getOperand(0)->getType()->isDoubleTy()) {
2141 // fptrunc from double to float.
2142 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2143 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2149 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2150 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2151 EVT DstVT = TLI.getValueType(I->getType());
2153 // This code only handles truncation to byte.
2154 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2156 if (!TLI.isTypeLegal(SrcVT))
2159 unsigned InputReg = getRegForValue(I->getOperand(0));
2161 // Unhandled operand. Halt "fast" selection and bail.
2164 if (SrcVT == MVT::i8) {
2165 // Truncate from i8 to i1; no code needed.
2166 updateValueMap(I, InputReg);
2170 if (!Subtarget->is64Bit()) {
2171 // If we're on x86-32; we can't extract an i8 from a general register.
2172 // First issue a copy to GR16_ABCD or GR32_ABCD.
2173 const TargetRegisterClass *CopyRC =
2174 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2175 unsigned CopyReg = createResultReg(CopyRC);
2176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2177 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2181 // Issue an extract_subreg.
2182 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2183 InputReg, /*Kill=*/true,
2188 updateValueMap(I, ResultReg);
2192 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2193 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2196 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2197 X86AddressMode SrcAM, uint64_t Len) {
2199 // Make sure we don't bloat code by inlining very large memcpy's.
2200 if (!IsMemcpySmall(Len))
2203 bool i64Legal = Subtarget->is64Bit();
2205 // We don't care about alignment here since we just emit integer accesses.
2208 if (Len >= 8 && i64Legal)
2218 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2219 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2220 assert(RV && "Failed to emit load or store??");
2222 unsigned Size = VT.getSizeInBits()/8;
2224 DestAM.Disp += Size;
2231 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2232 // FIXME: Handle more intrinsics.
2233 switch (II->getIntrinsicID()) {
2234 default: return false;
2235 case Intrinsic::convert_from_fp16:
2236 case Intrinsic::convert_to_fp16: {
2237 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C())
2240 const Value *Op = II->getArgOperand(0);
2241 unsigned InputReg = getRegForValue(Op);
2245 // F16C only allows converting from float to half and from half to float.
2246 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2247 if (IsFloatToHalf) {
2248 if (!Op->getType()->isFloatTy())
2251 if (!II->getType()->isFloatTy())
2255 unsigned ResultReg = 0;
2256 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2257 if (IsFloatToHalf) {
2258 // 'InputReg' is implicitly promoted from register class FR32 to
2259 // register class VR128 by method 'constrainOperandRegClass' which is
2260 // directly called by 'fastEmitInst_ri'.
2261 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2262 // used to provide rounding control.
2263 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2265 // Move the lower 32-bits of ResultReg to another register of class GR32.
2266 ResultReg = createResultReg(&X86::GR32RegClass);
2267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2268 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2269 .addReg(InputReg, RegState::Kill);
2271 // The result value is in the lower 16-bits of ResultReg.
2272 unsigned RegIdx = X86::sub_16bit;
2273 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2275 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2276 // Explicitly sign-extend the input to 32-bit.
2277 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2280 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2281 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2282 InputReg, /*Kill=*/true);
2284 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2286 // The result value is in the lower 32-bits of ResultReg.
2287 // Emit an explicit copy from register class VR128 to register class FR32.
2288 ResultReg = createResultReg(&X86::FR32RegClass);
2289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2290 TII.get(TargetOpcode::COPY), ResultReg)
2291 .addReg(InputReg, RegState::Kill);
2294 updateValueMap(II, ResultReg);
2297 case Intrinsic::frameaddress: {
2298 MachineFunction *MF = FuncInfo.MF;
2299 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2302 Type *RetTy = II->getCalledFunction()->getReturnType();
2305 if (!isTypeLegal(RetTy, VT))
2309 const TargetRegisterClass *RC = nullptr;
2311 switch (VT.SimpleTy) {
2312 default: llvm_unreachable("Invalid result type for frameaddress.");
2313 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2314 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2317 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2318 // we get the wrong frame register.
2319 MachineFrameInfo *MFI = MF->getFrameInfo();
2320 MFI->setFrameAddressIsTaken(true);
2322 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2323 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2324 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2325 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2326 "Invalid Frame Register!");
2328 // Always make a copy of the frame register to to a vreg first, so that we
2329 // never directly reference the frame register (the TwoAddressInstruction-
2330 // Pass doesn't like that).
2331 unsigned SrcReg = createResultReg(RC);
2332 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2333 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2335 // Now recursively load from the frame address.
2336 // movq (%rbp), %rax
2337 // movq (%rax), %rax
2338 // movq (%rax), %rax
2341 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2343 DestReg = createResultReg(RC);
2344 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2345 TII.get(Opc), DestReg), SrcReg);
2349 updateValueMap(II, SrcReg);
2352 case Intrinsic::memcpy: {
2353 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2354 // Don't handle volatile or variable length memcpys.
2355 if (MCI->isVolatile())
2358 if (isa<ConstantInt>(MCI->getLength())) {
2359 // Small memcpy's are common enough that we want to do them
2360 // without a call if possible.
2361 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2362 if (IsMemcpySmall(Len)) {
2363 X86AddressMode DestAM, SrcAM;
2364 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2365 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2367 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2372 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2373 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2376 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2379 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2381 case Intrinsic::memset: {
2382 const MemSetInst *MSI = cast<MemSetInst>(II);
2384 if (MSI->isVolatile())
2387 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2388 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2391 if (MSI->getDestAddressSpace() > 255)
2394 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2396 case Intrinsic::stackprotector: {
2397 // Emit code to store the stack guard onto the stack.
2398 EVT PtrTy = TLI.getPointerTy();
2400 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2401 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2403 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2405 // Grab the frame index.
2407 if (!X86SelectAddress(Slot, AM)) return false;
2408 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2411 case Intrinsic::dbg_declare: {
2412 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2414 assert(DI->getAddress() && "Null address should be checked earlier!");
2415 if (!X86SelectAddress(DI->getAddress(), AM))
2417 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2418 // FIXME may need to add RegState::Debug to any registers produced,
2419 // although ESP/EBP should be the only ones at the moment.
2420 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2422 .addMetadata(DI->getVariable())
2423 .addMetadata(DI->getExpression());
2426 case Intrinsic::trap: {
2427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2430 case Intrinsic::sqrt: {
2431 if (!Subtarget->hasSSE1())
2434 Type *RetTy = II->getCalledFunction()->getReturnType();
2437 if (!isTypeLegal(RetTy, VT))
2440 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2441 // is not generated by FastISel yet.
2442 // FIXME: Update this code once tablegen can handle it.
2443 static const unsigned SqrtOpc[2][2] = {
2444 {X86::SQRTSSr, X86::VSQRTSSr},
2445 {X86::SQRTSDr, X86::VSQRTSDr}
2447 bool HasAVX = Subtarget->hasAVX();
2449 const TargetRegisterClass *RC;
2450 switch (VT.SimpleTy) {
2451 default: return false;
2452 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2453 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2456 const Value *SrcVal = II->getArgOperand(0);
2457 unsigned SrcReg = getRegForValue(SrcVal);
2462 unsigned ImplicitDefReg = 0;
2464 ImplicitDefReg = createResultReg(RC);
2465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2466 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2469 unsigned ResultReg = createResultReg(RC);
2470 MachineInstrBuilder MIB;
2471 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2475 MIB.addReg(ImplicitDefReg);
2479 updateValueMap(II, ResultReg);
2482 case Intrinsic::sadd_with_overflow:
2483 case Intrinsic::uadd_with_overflow:
2484 case Intrinsic::ssub_with_overflow:
2485 case Intrinsic::usub_with_overflow:
2486 case Intrinsic::smul_with_overflow:
2487 case Intrinsic::umul_with_overflow: {
2488 // This implements the basic lowering of the xalu with overflow intrinsics
2489 // into add/sub/mul followed by either seto or setb.
2490 const Function *Callee = II->getCalledFunction();
2491 auto *Ty = cast<StructType>(Callee->getReturnType());
2492 Type *RetTy = Ty->getTypeAtIndex(0U);
2493 Type *CondTy = Ty->getTypeAtIndex(1);
2496 if (!isTypeLegal(RetTy, VT))
2499 if (VT < MVT::i8 || VT > MVT::i64)
2502 const Value *LHS = II->getArgOperand(0);
2503 const Value *RHS = II->getArgOperand(1);
2505 // Canonicalize immediate to the RHS.
2506 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2507 isCommutativeIntrinsic(II))
2508 std::swap(LHS, RHS);
2510 bool UseIncDec = false;
2511 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2514 unsigned BaseOpc, CondOpc;
2515 switch (II->getIntrinsicID()) {
2516 default: llvm_unreachable("Unexpected intrinsic!");
2517 case Intrinsic::sadd_with_overflow:
2518 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2519 CondOpc = X86::SETOr;
2521 case Intrinsic::uadd_with_overflow:
2522 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2523 case Intrinsic::ssub_with_overflow:
2524 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2525 CondOpc = X86::SETOr;
2527 case Intrinsic::usub_with_overflow:
2528 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2529 case Intrinsic::smul_with_overflow:
2530 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2531 case Intrinsic::umul_with_overflow:
2532 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2535 unsigned LHSReg = getRegForValue(LHS);
2538 bool LHSIsKill = hasTrivialKill(LHS);
2540 unsigned ResultReg = 0;
2541 // Check if we have an immediate version.
2542 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2543 static const unsigned Opc[2][4] = {
2544 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2545 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2548 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2549 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2550 bool IsDec = BaseOpc == X86ISD::DEC;
2551 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2552 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2553 .addReg(LHSReg, getKillRegState(LHSIsKill));
2555 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2556 CI->getZExtValue());
2562 RHSReg = getRegForValue(RHS);
2565 RHSIsKill = hasTrivialKill(RHS);
2566 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2570 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2572 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2573 static const unsigned MULOpc[] =
2574 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2575 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2576 // First copy the first operand into RAX, which is an implicit input to
2577 // the X86::MUL*r instruction.
2578 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2579 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2580 .addReg(LHSReg, getKillRegState(LHSIsKill));
2581 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2582 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2583 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2584 static const unsigned MULOpc[] =
2585 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2586 if (VT == MVT::i8) {
2587 // Copy the first operand into AL, which is an implicit input to the
2588 // X86::IMUL8r instruction.
2589 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2590 TII.get(TargetOpcode::COPY), X86::AL)
2591 .addReg(LHSReg, getKillRegState(LHSIsKill));
2592 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2595 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2596 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2603 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2604 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2605 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2608 updateValueMap(II, ResultReg, 2);
2611 case Intrinsic::x86_sse_cvttss2si:
2612 case Intrinsic::x86_sse_cvttss2si64:
2613 case Intrinsic::x86_sse2_cvttsd2si:
2614 case Intrinsic::x86_sse2_cvttsd2si64: {
2616 switch (II->getIntrinsicID()) {
2617 default: llvm_unreachable("Unexpected intrinsic.");
2618 case Intrinsic::x86_sse_cvttss2si:
2619 case Intrinsic::x86_sse_cvttss2si64:
2620 if (!Subtarget->hasSSE1())
2622 IsInputDouble = false;
2624 case Intrinsic::x86_sse2_cvttsd2si:
2625 case Intrinsic::x86_sse2_cvttsd2si64:
2626 if (!Subtarget->hasSSE2())
2628 IsInputDouble = true;
2632 Type *RetTy = II->getCalledFunction()->getReturnType();
2634 if (!isTypeLegal(RetTy, VT))
2637 static const unsigned CvtOpc[2][2][2] = {
2638 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2639 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2640 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2641 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2643 bool HasAVX = Subtarget->hasAVX();
2645 switch (VT.SimpleTy) {
2646 default: llvm_unreachable("Unexpected result type.");
2647 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2648 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2651 // Check if we can fold insertelement instructions into the convert.
2652 const Value *Op = II->getArgOperand(0);
2653 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2654 const Value *Index = IE->getOperand(2);
2655 if (!isa<ConstantInt>(Index))
2657 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2660 Op = IE->getOperand(1);
2663 Op = IE->getOperand(0);
2666 unsigned Reg = getRegForValue(Op);
2670 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2674 updateValueMap(II, ResultReg);
2680 bool X86FastISel::fastLowerArguments() {
2681 if (!FuncInfo.CanLowerReturn)
2684 const Function *F = FuncInfo.Fn;
2688 CallingConv::ID CC = F->getCallingConv();
2689 if (CC != CallingConv::C)
2692 if (Subtarget->isCallingConvWin64(CC))
2695 if (!Subtarget->is64Bit())
2698 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2699 unsigned GPRCnt = 0;
2700 unsigned FPRCnt = 0;
2702 for (auto const &Arg : F->args()) {
2703 // The first argument is at index 1.
2705 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2706 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2707 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2708 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2711 Type *ArgTy = Arg.getType();
2712 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2715 EVT ArgVT = TLI.getValueType(ArgTy);
2716 if (!ArgVT.isSimple()) return false;
2717 switch (ArgVT.getSimpleVT().SimpleTy) {
2718 default: return false;
2725 if (!Subtarget->hasSSE1())
2738 static const MCPhysReg GPR32ArgRegs[] = {
2739 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2741 static const MCPhysReg GPR64ArgRegs[] = {
2742 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2744 static const MCPhysReg XMMArgRegs[] = {
2745 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2746 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2749 unsigned GPRIdx = 0;
2750 unsigned FPRIdx = 0;
2751 for (auto const &Arg : F->args()) {
2752 MVT VT = TLI.getSimpleValueType(Arg.getType());
2753 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2755 switch (VT.SimpleTy) {
2756 default: llvm_unreachable("Unexpected value type.");
2757 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2758 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2759 case MVT::f32: // fall-through
2760 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2762 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2763 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2764 // Without this, EmitLiveInCopies may eliminate the livein if its only
2765 // use is a bitcast (which isn't turned into an instruction).
2766 unsigned ResultReg = createResultReg(RC);
2767 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2768 TII.get(TargetOpcode::COPY), ResultReg)
2769 .addReg(DstReg, getKillRegState(true));
2770 updateValueMap(&Arg, ResultReg);
2775 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2777 ImmutableCallSite *CS) {
2778 if (Subtarget->is64Bit())
2780 if (Subtarget->getTargetTriple().isOSMSVCRT())
2782 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2783 CC == CallingConv::HiPE)
2785 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2787 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2792 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2793 auto &OutVals = CLI.OutVals;
2794 auto &OutFlags = CLI.OutFlags;
2795 auto &OutRegs = CLI.OutRegs;
2796 auto &Ins = CLI.Ins;
2797 auto &InRegs = CLI.InRegs;
2798 CallingConv::ID CC = CLI.CallConv;
2799 bool &IsTailCall = CLI.IsTailCall;
2800 bool IsVarArg = CLI.IsVarArg;
2801 const Value *Callee = CLI.Callee;
2802 const char *SymName = CLI.SymName;
2804 bool Is64Bit = Subtarget->is64Bit();
2805 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2807 // Handle only C, fastcc, and webkit_js calling conventions for now.
2809 default: return false;
2810 case CallingConv::C:
2811 case CallingConv::Fast:
2812 case CallingConv::WebKit_JS:
2813 case CallingConv::X86_FastCall:
2814 case CallingConv::X86_64_Win64:
2815 case CallingConv::X86_64_SysV:
2819 // Allow SelectionDAG isel to handle tail calls.
2823 // fastcc with -tailcallopt is intended to provide a guaranteed
2824 // tail call optimization. Fastisel doesn't know how to do that.
2825 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2828 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2829 // x86-32. Special handling for x86-64 is implemented.
2830 if (IsVarArg && IsWin64)
2833 // Don't know about inalloca yet.
2834 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2837 // Fast-isel doesn't know about callee-pop yet.
2838 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2839 TM.Options.GuaranteedTailCallOpt))
2842 SmallVector<MVT, 16> OutVTs;
2843 SmallVector<unsigned, 16> ArgRegs;
2845 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2846 // instruction. This is safe because it is common to all FastISel supported
2847 // calling conventions on x86.
2848 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2849 Value *&Val = OutVals[i];
2850 ISD::ArgFlagsTy Flags = OutFlags[i];
2851 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2852 if (CI->getBitWidth() < 32) {
2854 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2856 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2860 // Passing bools around ends up doing a trunc to i1 and passing it.
2861 // Codegen this as an argument + "and 1".
2863 auto *TI = dyn_cast<TruncInst>(Val);
2865 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2866 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2868 Value *PrevVal = TI->getOperand(0);
2869 ResultReg = getRegForValue(PrevVal);
2874 if (!isTypeLegal(PrevVal->getType(), VT))
2878 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2880 if (!isTypeLegal(Val->getType(), VT))
2882 ResultReg = getRegForValue(Val);
2888 ArgRegs.push_back(ResultReg);
2889 OutVTs.push_back(VT);
2892 // Analyze operands of the call, assigning locations to each operand.
2893 SmallVector<CCValAssign, 16> ArgLocs;
2894 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2896 // Allocate shadow area for Win64
2898 CCInfo.AllocateStack(32, 8);
2900 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2902 // Get a count of how many bytes are to be pushed on the stack.
2903 unsigned NumBytes = CCInfo.getNextStackOffset();
2905 // Issue CALLSEQ_START
2906 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2907 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2908 .addImm(NumBytes).addImm(0);
2910 // Walk the register/memloc assignments, inserting copies/loads.
2911 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2912 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2913 CCValAssign const &VA = ArgLocs[i];
2914 const Value *ArgVal = OutVals[VA.getValNo()];
2915 MVT ArgVT = OutVTs[VA.getValNo()];
2917 if (ArgVT == MVT::x86mmx)
2920 unsigned ArgReg = ArgRegs[VA.getValNo()];
2922 // Promote the value if needed.
2923 switch (VA.getLocInfo()) {
2924 case CCValAssign::Full: break;
2925 case CCValAssign::SExt: {
2926 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2927 "Unexpected extend");
2928 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2930 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2931 ArgVT = VA.getLocVT();
2934 case CCValAssign::ZExt: {
2935 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2936 "Unexpected extend");
2937 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2939 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2940 ArgVT = VA.getLocVT();
2943 case CCValAssign::AExt: {
2944 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2945 "Unexpected extend");
2946 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2949 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2952 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2955 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2956 ArgVT = VA.getLocVT();
2959 case CCValAssign::BCvt: {
2960 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2961 /*TODO: Kill=*/false);
2962 assert(ArgReg && "Failed to emit a bitcast!");
2963 ArgVT = VA.getLocVT();
2966 case CCValAssign::VExt:
2967 // VExt has not been implemented, so this should be impossible to reach
2968 // for now. However, fallback to Selection DAG isel once implemented.
2970 case CCValAssign::AExtUpper:
2971 case CCValAssign::SExtUpper:
2972 case CCValAssign::ZExtUpper:
2973 case CCValAssign::FPExt:
2974 llvm_unreachable("Unexpected loc info!");
2975 case CCValAssign::Indirect:
2976 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2981 if (VA.isRegLoc()) {
2982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2983 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2984 OutRegs.push_back(VA.getLocReg());
2986 assert(VA.isMemLoc());
2988 // Don't emit stores for undef values.
2989 if (isa<UndefValue>(ArgVal))
2992 unsigned LocMemOffset = VA.getLocMemOffset();
2994 AM.Base.Reg = RegInfo->getStackRegister();
2995 AM.Disp = LocMemOffset;
2996 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
2997 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2998 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2999 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3000 ArgVT.getStoreSize(), Alignment);
3001 if (Flags.isByVal()) {
3002 X86AddressMode SrcAM;
3003 SrcAM.Base.Reg = ArgReg;
3004 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3006 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3007 // If this is a really simple value, emit this with the Value* version
3008 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3009 // as it can cause us to reevaluate the argument.
3010 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3013 bool ValIsKill = hasTrivialKill(ArgVal);
3014 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3020 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3022 if (Subtarget->isPICStyleGOT()) {
3023 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3025 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3028 if (Is64Bit && IsVarArg && !IsWin64) {
3029 // From AMD64 ABI document:
3030 // For calls that may call functions that use varargs or stdargs
3031 // (prototype-less calls or calls to functions containing ellipsis (...) in
3032 // the declaration) %al is used as hidden argument to specify the number
3033 // of SSE registers used. The contents of %al do not need to match exactly
3034 // the number of registers, but must be an ubound on the number of SSE
3035 // registers used and is in the range 0 - 8 inclusive.
3037 // Count the number of XMM registers allocated.
3038 static const MCPhysReg XMMArgRegs[] = {
3039 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3040 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3042 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3043 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3044 && "SSE registers cannot be used when SSE is disabled");
3045 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3046 X86::AL).addImm(NumXMMRegs);
3049 // Materialize callee address in a register. FIXME: GV address can be
3050 // handled with a CALLpcrel32 instead.
3051 X86AddressMode CalleeAM;
3052 if (!X86SelectCallAddress(Callee, CalleeAM))
3055 unsigned CalleeOp = 0;
3056 const GlobalValue *GV = nullptr;
3057 if (CalleeAM.GV != nullptr) {
3059 } else if (CalleeAM.Base.Reg != 0) {
3060 CalleeOp = CalleeAM.Base.Reg;
3065 MachineInstrBuilder MIB;
3067 // Register-indirect call.
3068 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3069 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3073 assert(GV && "Not a direct call");
3074 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3076 // See if we need any target-specific flags on the GV operand.
3077 unsigned char OpFlags = 0;
3079 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3080 // external symbols most go through the PLT in PIC mode. If the symbol
3081 // has hidden or protected visibility, or if it is static or local, then
3082 // we don't need to use the PLT - we can directly call it.
3083 if (Subtarget->isTargetELF() &&
3084 TM.getRelocationModel() == Reloc::PIC_ &&
3085 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3086 OpFlags = X86II::MO_PLT;
3087 } else if (Subtarget->isPICStyleStubAny() &&
3088 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3089 (!Subtarget->getTargetTriple().isMacOSX() ||
3090 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3091 // PC-relative references to external symbols should go through $stub,
3092 // unless we're building with the leopard linker or later, which
3093 // automatically synthesizes these stubs.
3094 OpFlags = X86II::MO_DARWIN_STUB;
3097 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3099 MIB.addExternalSymbol(SymName, OpFlags);
3101 MIB.addGlobalAddress(GV, 0, OpFlags);
3104 // Add a register mask operand representing the call-preserved registers.
3105 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3106 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3108 // Add an implicit use GOT pointer in EBX.
3109 if (Subtarget->isPICStyleGOT())
3110 MIB.addReg(X86::EBX, RegState::Implicit);
3112 if (Is64Bit && IsVarArg && !IsWin64)
3113 MIB.addReg(X86::AL, RegState::Implicit);
3115 // Add implicit physical register uses to the call.
3116 for (auto Reg : OutRegs)
3117 MIB.addReg(Reg, RegState::Implicit);
3119 // Issue CALLSEQ_END
3120 unsigned NumBytesForCalleeToPop =
3121 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3122 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3123 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3124 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3126 // Now handle call return values.
3127 SmallVector<CCValAssign, 16> RVLocs;
3128 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3129 CLI.RetTy->getContext());
3130 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3132 // Copy all of the result registers out of their specified physreg.
3133 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3134 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3135 CCValAssign &VA = RVLocs[i];
3136 EVT CopyVT = VA.getValVT();
3137 unsigned CopyReg = ResultReg + i;
3139 // If this is x86-64, and we disabled SSE, we can't return FP values
3140 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3141 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3142 report_fatal_error("SSE register return with SSE disabled");
3145 // If we prefer to use the value in xmm registers, copy it out as f80 and
3146 // use a truncate to move it from fp stack reg to xmm reg.
3147 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3148 isScalarFPTypeInSSEReg(VA.getValVT())) {
3150 CopyReg = createResultReg(&X86::RFP80RegClass);
3153 // Copy out the result.
3154 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3155 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3156 InRegs.push_back(VA.getLocReg());
3158 // Round the f80 to the right size, which also moves it to the appropriate
3159 // xmm register. This is accomplished by storing the f80 value in memory
3160 // and then loading it back.
3161 if (CopyVT != VA.getValVT()) {
3162 EVT ResVT = VA.getValVT();
3163 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3164 unsigned MemSize = ResVT.getSizeInBits()/8;
3165 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3166 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3169 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3170 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3171 TII.get(Opc), ResultReg + i), FI);
3175 CLI.ResultReg = ResultReg;
3176 CLI.NumResultRegs = RVLocs.size();
3183 X86FastISel::fastSelectInstruction(const Instruction *I) {
3184 switch (I->getOpcode()) {
3186 case Instruction::Load:
3187 return X86SelectLoad(I);
3188 case Instruction::Store:
3189 return X86SelectStore(I);
3190 case Instruction::Ret:
3191 return X86SelectRet(I);
3192 case Instruction::ICmp:
3193 case Instruction::FCmp:
3194 return X86SelectCmp(I);
3195 case Instruction::ZExt:
3196 return X86SelectZExt(I);
3197 case Instruction::Br:
3198 return X86SelectBranch(I);
3199 case Instruction::LShr:
3200 case Instruction::AShr:
3201 case Instruction::Shl:
3202 return X86SelectShift(I);
3203 case Instruction::SDiv:
3204 case Instruction::UDiv:
3205 case Instruction::SRem:
3206 case Instruction::URem:
3207 return X86SelectDivRem(I);
3208 case Instruction::Select:
3209 return X86SelectSelect(I);
3210 case Instruction::Trunc:
3211 return X86SelectTrunc(I);
3212 case Instruction::FPExt:
3213 return X86SelectFPExt(I);
3214 case Instruction::FPTrunc:
3215 return X86SelectFPTrunc(I);
3216 case Instruction::SIToFP:
3217 return X86SelectSIToFP(I);
3218 case Instruction::IntToPtr: // Deliberate fall-through.
3219 case Instruction::PtrToInt: {
3220 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3221 EVT DstVT = TLI.getValueType(I->getType());
3222 if (DstVT.bitsGT(SrcVT))
3223 return X86SelectZExt(I);
3224 if (DstVT.bitsLT(SrcVT))
3225 return X86SelectTrunc(I);
3226 unsigned Reg = getRegForValue(I->getOperand(0));
3227 if (Reg == 0) return false;
3228 updateValueMap(I, Reg);
3236 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3240 uint64_t Imm = CI->getZExtValue();
3242 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3243 switch (VT.SimpleTy) {
3244 default: llvm_unreachable("Unexpected value type");
3247 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3250 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3255 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3257 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3258 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3265 switch (VT.SimpleTy) {
3266 default: llvm_unreachable("Unexpected value type");
3267 case MVT::i1: VT = MVT::i8; // fall-through
3268 case MVT::i8: Opc = X86::MOV8ri; break;
3269 case MVT::i16: Opc = X86::MOV16ri; break;
3270 case MVT::i32: Opc = X86::MOV32ri; break;
3272 if (isUInt<32>(Imm))
3274 else if (isInt<32>(Imm))
3275 Opc = X86::MOV64ri32;
3281 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3282 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3283 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3284 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3285 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3286 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3289 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3292 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3293 if (CFP->isNullValue())
3294 return fastMaterializeFloatZero(CFP);
3296 // Can't handle alternate code models yet.
3297 CodeModel::Model CM = TM.getCodeModel();
3298 if (CM != CodeModel::Small && CM != CodeModel::Large)
3301 // Get opcode and regclass of the output for the given load instruction.
3303 const TargetRegisterClass *RC = nullptr;
3304 switch (VT.SimpleTy) {
3307 if (X86ScalarSSEf32) {
3308 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3309 RC = &X86::FR32RegClass;
3311 Opc = X86::LD_Fp32m;
3312 RC = &X86::RFP32RegClass;
3316 if (X86ScalarSSEf64) {
3317 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3318 RC = &X86::FR64RegClass;
3320 Opc = X86::LD_Fp64m;
3321 RC = &X86::RFP64RegClass;
3325 // No f80 support yet.
3329 // MachineConstantPool wants an explicit alignment.
3330 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3332 // Alignment of vector types. FIXME!
3333 Align = DL.getTypeAllocSize(CFP->getType());
3336 // x86-32 PIC requires a PIC base register for constant pools.
3337 unsigned PICBase = 0;
3338 unsigned char OpFlag = 0;
3339 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3340 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3341 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3342 } else if (Subtarget->isPICStyleGOT()) {
3343 OpFlag = X86II::MO_GOTOFF;
3344 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3345 } else if (Subtarget->isPICStyleRIPRel() &&
3346 TM.getCodeModel() == CodeModel::Small) {
3350 // Create the load from the constant pool.
3351 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3352 unsigned ResultReg = createResultReg(RC);
3354 if (CM == CodeModel::Large) {
3355 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3358 .addConstantPoolIndex(CPI, 0, OpFlag);
3359 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3360 TII.get(Opc), ResultReg);
3361 addDirectMem(MIB, AddrReg);
3362 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3363 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3364 TM.getDataLayout()->getPointerSize(), Align);
3365 MIB->addMemOperand(*FuncInfo.MF, MMO);
3369 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3370 TII.get(Opc), ResultReg),
3371 CPI, PICBase, OpFlag);
3375 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3376 // Can't handle alternate code models yet.
3377 if (TM.getCodeModel() != CodeModel::Small)
3380 // Materialize addresses with LEA/MOV instructions.
3382 if (X86SelectAddress(GV, AM)) {
3383 // If the expression is just a basereg, then we're done, otherwise we need
3385 if (AM.BaseType == X86AddressMode::RegBase &&
3386 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3389 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3390 if (TM.getRelocationModel() == Reloc::Static &&
3391 TLI.getPointerTy() == MVT::i64) {
3392 // The displacement code could be more than 32 bits away so we need to use
3393 // an instruction with a 64 bit immediate
3394 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3396 .addGlobalAddress(GV);
3398 unsigned Opc = TLI.getPointerTy() == MVT::i32
3399 ? (Subtarget->isTarget64BitILP32()
3400 ? X86::LEA64_32r : X86::LEA32r)
3402 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3403 TII.get(Opc), ResultReg), AM);
3410 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3411 EVT CEVT = TLI.getValueType(C->getType(), true);
3413 // Only handle simple types.
3414 if (!CEVT.isSimple())
3416 MVT VT = CEVT.getSimpleVT();
3418 if (const auto *CI = dyn_cast<ConstantInt>(C))
3419 return X86MaterializeInt(CI, VT);
3420 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3421 return X86MaterializeFP(CFP, VT);
3422 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3423 return X86MaterializeGV(GV, VT);
3428 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3429 // Fail on dynamic allocas. At this point, getRegForValue has already
3430 // checked its CSE maps, so if we're here trying to handle a dynamic
3431 // alloca, we're not going to succeed. X86SelectAddress has a
3432 // check for dynamic allocas, because it's called directly from
3433 // various places, but targetMaterializeAlloca also needs a check
3434 // in order to avoid recursion between getRegForValue,
3435 // X86SelectAddrss, and targetMaterializeAlloca.
3436 if (!FuncInfo.StaticAllocaMap.count(C))
3438 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3441 if (!X86SelectAddress(C, AM))
3443 unsigned Opc = TLI.getPointerTy() == MVT::i32
3444 ? (Subtarget->isTarget64BitILP32()
3445 ? X86::LEA64_32r : X86::LEA32r)
3447 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3448 unsigned ResultReg = createResultReg(RC);
3449 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3450 TII.get(Opc), ResultReg), AM);
3454 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3456 if (!isTypeLegal(CF->getType(), VT))
3459 // Get opcode and regclass for the given zero.
3461 const TargetRegisterClass *RC = nullptr;
3462 switch (VT.SimpleTy) {
3465 if (X86ScalarSSEf32) {
3466 Opc = X86::FsFLD0SS;
3467 RC = &X86::FR32RegClass;
3469 Opc = X86::LD_Fp032;
3470 RC = &X86::RFP32RegClass;
3474 if (X86ScalarSSEf64) {
3475 Opc = X86::FsFLD0SD;
3476 RC = &X86::FR64RegClass;
3478 Opc = X86::LD_Fp064;
3479 RC = &X86::RFP64RegClass;
3483 // No f80 support yet.
3487 unsigned ResultReg = createResultReg(RC);
3488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3493 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3494 const LoadInst *LI) {
3495 const Value *Ptr = LI->getPointerOperand();
3497 if (!X86SelectAddress(Ptr, AM))
3500 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3502 unsigned Size = DL.getTypeAllocSize(LI->getType());
3503 unsigned Alignment = LI->getAlignment();
3505 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3506 Alignment = DL.getABITypeAlignment(LI->getType());
3508 SmallVector<MachineOperand, 8> AddrOps;
3509 AM.getFullAddress(AddrOps);
3511 MachineInstr *Result =
3512 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3513 Size, Alignment, /*AllowCommute=*/true);
3517 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3518 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3519 MI->eraseFromParent();
3525 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3526 const TargetLibraryInfo *libInfo) {
3527 return new X86FastISel(funcInfo, libInfo);