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 // The target-independent selection algorithm in FastISel already knows how
2069 // to select a SINT_TO_FP if the target is SSE but not AVX.
2070 // Early exit if the subtarget doesn't have AVX.
2071 if (!Subtarget->hasAVX())
2074 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2077 // Select integer to float/double conversion.
2078 unsigned OpReg = getRegForValue(I->getOperand(0));
2082 const TargetRegisterClass *RC = nullptr;
2085 if (I->getType()->isDoubleTy()) {
2086 // sitofp int -> double
2087 Opcode = X86::VCVTSI2SDrr;
2088 RC = &X86::FR64RegClass;
2089 } else if (I->getType()->isFloatTy()) {
2090 // sitofp int -> float
2091 Opcode = X86::VCVTSI2SSrr;
2092 RC = &X86::FR32RegClass;
2096 unsigned ImplicitDefReg = createResultReg(RC);
2097 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2098 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2099 unsigned ResultReg =
2100 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2101 updateValueMap(I, ResultReg);
2105 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2106 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2108 const TargetRegisterClass *RC) {
2109 assert((I->getOpcode() == Instruction::FPExt ||
2110 I->getOpcode() == Instruction::FPTrunc) &&
2111 "Instruction must be an FPExt or FPTrunc!");
2113 unsigned OpReg = getRegForValue(I->getOperand(0));
2117 unsigned ResultReg = createResultReg(RC);
2118 MachineInstrBuilder MIB;
2119 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2121 if (Subtarget->hasAVX())
2124 updateValueMap(I, ResultReg);
2128 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2129 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2130 I->getOperand(0)->getType()->isFloatTy()) {
2131 // fpext from float to double.
2132 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2133 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2139 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2140 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2141 I->getOperand(0)->getType()->isDoubleTy()) {
2142 // fptrunc from double to float.
2143 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2144 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2150 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2151 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2152 EVT DstVT = TLI.getValueType(I->getType());
2154 // This code only handles truncation to byte.
2155 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2157 if (!TLI.isTypeLegal(SrcVT))
2160 unsigned InputReg = getRegForValue(I->getOperand(0));
2162 // Unhandled operand. Halt "fast" selection and bail.
2165 if (SrcVT == MVT::i8) {
2166 // Truncate from i8 to i1; no code needed.
2167 updateValueMap(I, InputReg);
2171 if (!Subtarget->is64Bit()) {
2172 // If we're on x86-32; we can't extract an i8 from a general register.
2173 // First issue a copy to GR16_ABCD or GR32_ABCD.
2174 const TargetRegisterClass *CopyRC =
2175 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2176 unsigned CopyReg = createResultReg(CopyRC);
2177 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2178 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2182 // Issue an extract_subreg.
2183 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2184 InputReg, /*Kill=*/true,
2189 updateValueMap(I, ResultReg);
2193 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2194 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2197 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2198 X86AddressMode SrcAM, uint64_t Len) {
2200 // Make sure we don't bloat code by inlining very large memcpy's.
2201 if (!IsMemcpySmall(Len))
2204 bool i64Legal = Subtarget->is64Bit();
2206 // We don't care about alignment here since we just emit integer accesses.
2209 if (Len >= 8 && i64Legal)
2219 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2220 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2221 assert(RV && "Failed to emit load or store??");
2223 unsigned Size = VT.getSizeInBits()/8;
2225 DestAM.Disp += Size;
2232 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2233 // FIXME: Handle more intrinsics.
2234 switch (II->getIntrinsicID()) {
2235 default: return false;
2236 case Intrinsic::convert_from_fp16:
2237 case Intrinsic::convert_to_fp16: {
2238 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C())
2241 const Value *Op = II->getArgOperand(0);
2242 unsigned InputReg = getRegForValue(Op);
2246 // F16C only allows converting from float to half and from half to float.
2247 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2248 if (IsFloatToHalf) {
2249 if (!Op->getType()->isFloatTy())
2252 if (!II->getType()->isFloatTy())
2256 unsigned ResultReg = 0;
2257 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2258 if (IsFloatToHalf) {
2259 // 'InputReg' is implicitly promoted from register class FR32 to
2260 // register class VR128 by method 'constrainOperandRegClass' which is
2261 // directly called by 'fastEmitInst_ri'.
2262 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2263 // used to provide rounding control.
2264 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2266 // Move the lower 32-bits of ResultReg to another register of class GR32.
2267 ResultReg = createResultReg(&X86::GR32RegClass);
2268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2269 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2270 .addReg(InputReg, RegState::Kill);
2272 // The result value is in the lower 16-bits of ResultReg.
2273 unsigned RegIdx = X86::sub_16bit;
2274 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2276 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2277 // Explicitly sign-extend the input to 32-bit.
2278 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2281 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2282 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2283 InputReg, /*Kill=*/true);
2285 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2287 // The result value is in the lower 32-bits of ResultReg.
2288 // Emit an explicit copy from register class VR128 to register class FR32.
2289 ResultReg = createResultReg(&X86::FR32RegClass);
2290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2291 TII.get(TargetOpcode::COPY), ResultReg)
2292 .addReg(InputReg, RegState::Kill);
2295 updateValueMap(II, ResultReg);
2298 case Intrinsic::frameaddress: {
2299 MachineFunction *MF = FuncInfo.MF;
2300 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2303 Type *RetTy = II->getCalledFunction()->getReturnType();
2306 if (!isTypeLegal(RetTy, VT))
2310 const TargetRegisterClass *RC = nullptr;
2312 switch (VT.SimpleTy) {
2313 default: llvm_unreachable("Invalid result type for frameaddress.");
2314 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2315 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2318 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2319 // we get the wrong frame register.
2320 MachineFrameInfo *MFI = MF->getFrameInfo();
2321 MFI->setFrameAddressIsTaken(true);
2323 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2324 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2325 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2326 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2327 "Invalid Frame Register!");
2329 // Always make a copy of the frame register to to a vreg first, so that we
2330 // never directly reference the frame register (the TwoAddressInstruction-
2331 // Pass doesn't like that).
2332 unsigned SrcReg = createResultReg(RC);
2333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2334 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2336 // Now recursively load from the frame address.
2337 // movq (%rbp), %rax
2338 // movq (%rax), %rax
2339 // movq (%rax), %rax
2342 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2344 DestReg = createResultReg(RC);
2345 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2346 TII.get(Opc), DestReg), SrcReg);
2350 updateValueMap(II, SrcReg);
2353 case Intrinsic::memcpy: {
2354 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2355 // Don't handle volatile or variable length memcpys.
2356 if (MCI->isVolatile())
2359 if (isa<ConstantInt>(MCI->getLength())) {
2360 // Small memcpy's are common enough that we want to do them
2361 // without a call if possible.
2362 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2363 if (IsMemcpySmall(Len)) {
2364 X86AddressMode DestAM, SrcAM;
2365 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2366 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2368 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2373 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2374 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2377 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2380 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2382 case Intrinsic::memset: {
2383 const MemSetInst *MSI = cast<MemSetInst>(II);
2385 if (MSI->isVolatile())
2388 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2389 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2392 if (MSI->getDestAddressSpace() > 255)
2395 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2397 case Intrinsic::stackprotector: {
2398 // Emit code to store the stack guard onto the stack.
2399 EVT PtrTy = TLI.getPointerTy();
2401 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2402 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2404 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2406 // Grab the frame index.
2408 if (!X86SelectAddress(Slot, AM)) return false;
2409 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2412 case Intrinsic::dbg_declare: {
2413 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2415 assert(DI->getAddress() && "Null address should be checked earlier!");
2416 if (!X86SelectAddress(DI->getAddress(), AM))
2418 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2419 // FIXME may need to add RegState::Debug to any registers produced,
2420 // although ESP/EBP should be the only ones at the moment.
2421 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2422 "Expected inlined-at fields to agree");
2423 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2425 .addMetadata(DI->getVariable())
2426 .addMetadata(DI->getExpression());
2429 case Intrinsic::trap: {
2430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2433 case Intrinsic::sqrt: {
2434 if (!Subtarget->hasSSE1())
2437 Type *RetTy = II->getCalledFunction()->getReturnType();
2440 if (!isTypeLegal(RetTy, VT))
2443 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2444 // is not generated by FastISel yet.
2445 // FIXME: Update this code once tablegen can handle it.
2446 static const unsigned SqrtOpc[2][2] = {
2447 {X86::SQRTSSr, X86::VSQRTSSr},
2448 {X86::SQRTSDr, X86::VSQRTSDr}
2450 bool HasAVX = Subtarget->hasAVX();
2452 const TargetRegisterClass *RC;
2453 switch (VT.SimpleTy) {
2454 default: return false;
2455 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2456 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2459 const Value *SrcVal = II->getArgOperand(0);
2460 unsigned SrcReg = getRegForValue(SrcVal);
2465 unsigned ImplicitDefReg = 0;
2467 ImplicitDefReg = createResultReg(RC);
2468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2469 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2472 unsigned ResultReg = createResultReg(RC);
2473 MachineInstrBuilder MIB;
2474 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2478 MIB.addReg(ImplicitDefReg);
2482 updateValueMap(II, ResultReg);
2485 case Intrinsic::sadd_with_overflow:
2486 case Intrinsic::uadd_with_overflow:
2487 case Intrinsic::ssub_with_overflow:
2488 case Intrinsic::usub_with_overflow:
2489 case Intrinsic::smul_with_overflow:
2490 case Intrinsic::umul_with_overflow: {
2491 // This implements the basic lowering of the xalu with overflow intrinsics
2492 // into add/sub/mul followed by either seto or setb.
2493 const Function *Callee = II->getCalledFunction();
2494 auto *Ty = cast<StructType>(Callee->getReturnType());
2495 Type *RetTy = Ty->getTypeAtIndex(0U);
2496 Type *CondTy = Ty->getTypeAtIndex(1);
2499 if (!isTypeLegal(RetTy, VT))
2502 if (VT < MVT::i8 || VT > MVT::i64)
2505 const Value *LHS = II->getArgOperand(0);
2506 const Value *RHS = II->getArgOperand(1);
2508 // Canonicalize immediate to the RHS.
2509 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2510 isCommutativeIntrinsic(II))
2511 std::swap(LHS, RHS);
2513 bool UseIncDec = false;
2514 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2517 unsigned BaseOpc, CondOpc;
2518 switch (II->getIntrinsicID()) {
2519 default: llvm_unreachable("Unexpected intrinsic!");
2520 case Intrinsic::sadd_with_overflow:
2521 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2522 CondOpc = X86::SETOr;
2524 case Intrinsic::uadd_with_overflow:
2525 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2526 case Intrinsic::ssub_with_overflow:
2527 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2528 CondOpc = X86::SETOr;
2530 case Intrinsic::usub_with_overflow:
2531 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2532 case Intrinsic::smul_with_overflow:
2533 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2534 case Intrinsic::umul_with_overflow:
2535 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2538 unsigned LHSReg = getRegForValue(LHS);
2541 bool LHSIsKill = hasTrivialKill(LHS);
2543 unsigned ResultReg = 0;
2544 // Check if we have an immediate version.
2545 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2546 static const unsigned Opc[2][4] = {
2547 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2548 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2551 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2552 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2553 bool IsDec = BaseOpc == X86ISD::DEC;
2554 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2555 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2556 .addReg(LHSReg, getKillRegState(LHSIsKill));
2558 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2559 CI->getZExtValue());
2565 RHSReg = getRegForValue(RHS);
2568 RHSIsKill = hasTrivialKill(RHS);
2569 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2573 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2575 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2576 static const unsigned MULOpc[] =
2577 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2578 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2579 // First copy the first operand into RAX, which is an implicit input to
2580 // the X86::MUL*r instruction.
2581 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2582 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2583 .addReg(LHSReg, getKillRegState(LHSIsKill));
2584 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2585 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2586 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2587 static const unsigned MULOpc[] =
2588 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2589 if (VT == MVT::i8) {
2590 // Copy the first operand into AL, which is an implicit input to the
2591 // X86::IMUL8r instruction.
2592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2593 TII.get(TargetOpcode::COPY), X86::AL)
2594 .addReg(LHSReg, getKillRegState(LHSIsKill));
2595 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2598 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2599 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2606 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2607 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2611 updateValueMap(II, ResultReg, 2);
2614 case Intrinsic::x86_sse_cvttss2si:
2615 case Intrinsic::x86_sse_cvttss2si64:
2616 case Intrinsic::x86_sse2_cvttsd2si:
2617 case Intrinsic::x86_sse2_cvttsd2si64: {
2619 switch (II->getIntrinsicID()) {
2620 default: llvm_unreachable("Unexpected intrinsic.");
2621 case Intrinsic::x86_sse_cvttss2si:
2622 case Intrinsic::x86_sse_cvttss2si64:
2623 if (!Subtarget->hasSSE1())
2625 IsInputDouble = false;
2627 case Intrinsic::x86_sse2_cvttsd2si:
2628 case Intrinsic::x86_sse2_cvttsd2si64:
2629 if (!Subtarget->hasSSE2())
2631 IsInputDouble = true;
2635 Type *RetTy = II->getCalledFunction()->getReturnType();
2637 if (!isTypeLegal(RetTy, VT))
2640 static const unsigned CvtOpc[2][2][2] = {
2641 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2642 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2643 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2644 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2646 bool HasAVX = Subtarget->hasAVX();
2648 switch (VT.SimpleTy) {
2649 default: llvm_unreachable("Unexpected result type.");
2650 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2651 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2654 // Check if we can fold insertelement instructions into the convert.
2655 const Value *Op = II->getArgOperand(0);
2656 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2657 const Value *Index = IE->getOperand(2);
2658 if (!isa<ConstantInt>(Index))
2660 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2663 Op = IE->getOperand(1);
2666 Op = IE->getOperand(0);
2669 unsigned Reg = getRegForValue(Op);
2673 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2674 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2677 updateValueMap(II, ResultReg);
2683 bool X86FastISel::fastLowerArguments() {
2684 if (!FuncInfo.CanLowerReturn)
2687 const Function *F = FuncInfo.Fn;
2691 CallingConv::ID CC = F->getCallingConv();
2692 if (CC != CallingConv::C)
2695 if (Subtarget->isCallingConvWin64(CC))
2698 if (!Subtarget->is64Bit())
2701 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2702 unsigned GPRCnt = 0;
2703 unsigned FPRCnt = 0;
2705 for (auto const &Arg : F->args()) {
2706 // The first argument is at index 1.
2708 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2709 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2710 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2711 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2714 Type *ArgTy = Arg.getType();
2715 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2718 EVT ArgVT = TLI.getValueType(ArgTy);
2719 if (!ArgVT.isSimple()) return false;
2720 switch (ArgVT.getSimpleVT().SimpleTy) {
2721 default: return false;
2728 if (!Subtarget->hasSSE1())
2741 static const MCPhysReg GPR32ArgRegs[] = {
2742 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2744 static const MCPhysReg GPR64ArgRegs[] = {
2745 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2747 static const MCPhysReg XMMArgRegs[] = {
2748 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2749 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2752 unsigned GPRIdx = 0;
2753 unsigned FPRIdx = 0;
2754 for (auto const &Arg : F->args()) {
2755 MVT VT = TLI.getSimpleValueType(Arg.getType());
2756 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2758 switch (VT.SimpleTy) {
2759 default: llvm_unreachable("Unexpected value type.");
2760 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2761 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2762 case MVT::f32: // fall-through
2763 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2765 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2766 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2767 // Without this, EmitLiveInCopies may eliminate the livein if its only
2768 // use is a bitcast (which isn't turned into an instruction).
2769 unsigned ResultReg = createResultReg(RC);
2770 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2771 TII.get(TargetOpcode::COPY), ResultReg)
2772 .addReg(DstReg, getKillRegState(true));
2773 updateValueMap(&Arg, ResultReg);
2778 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2780 ImmutableCallSite *CS) {
2781 if (Subtarget->is64Bit())
2783 if (Subtarget->getTargetTriple().isOSMSVCRT())
2785 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2786 CC == CallingConv::HiPE)
2788 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2790 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2795 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2796 auto &OutVals = CLI.OutVals;
2797 auto &OutFlags = CLI.OutFlags;
2798 auto &OutRegs = CLI.OutRegs;
2799 auto &Ins = CLI.Ins;
2800 auto &InRegs = CLI.InRegs;
2801 CallingConv::ID CC = CLI.CallConv;
2802 bool &IsTailCall = CLI.IsTailCall;
2803 bool IsVarArg = CLI.IsVarArg;
2804 const Value *Callee = CLI.Callee;
2805 const char *SymName = CLI.SymName;
2807 bool Is64Bit = Subtarget->is64Bit();
2808 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2810 // Handle only C, fastcc, and webkit_js calling conventions for now.
2812 default: return false;
2813 case CallingConv::C:
2814 case CallingConv::Fast:
2815 case CallingConv::WebKit_JS:
2816 case CallingConv::X86_FastCall:
2817 case CallingConv::X86_64_Win64:
2818 case CallingConv::X86_64_SysV:
2822 // Allow SelectionDAG isel to handle tail calls.
2826 // fastcc with -tailcallopt is intended to provide a guaranteed
2827 // tail call optimization. Fastisel doesn't know how to do that.
2828 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2831 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2832 // x86-32. Special handling for x86-64 is implemented.
2833 if (IsVarArg && IsWin64)
2836 // Don't know about inalloca yet.
2837 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2840 // Fast-isel doesn't know about callee-pop yet.
2841 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2842 TM.Options.GuaranteedTailCallOpt))
2845 SmallVector<MVT, 16> OutVTs;
2846 SmallVector<unsigned, 16> ArgRegs;
2848 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2849 // instruction. This is safe because it is common to all FastISel supported
2850 // calling conventions on x86.
2851 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2852 Value *&Val = OutVals[i];
2853 ISD::ArgFlagsTy Flags = OutFlags[i];
2854 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2855 if (CI->getBitWidth() < 32) {
2857 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2859 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2863 // Passing bools around ends up doing a trunc to i1 and passing it.
2864 // Codegen this as an argument + "and 1".
2866 auto *TI = dyn_cast<TruncInst>(Val);
2868 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2869 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2871 Value *PrevVal = TI->getOperand(0);
2872 ResultReg = getRegForValue(PrevVal);
2877 if (!isTypeLegal(PrevVal->getType(), VT))
2881 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2883 if (!isTypeLegal(Val->getType(), VT))
2885 ResultReg = getRegForValue(Val);
2891 ArgRegs.push_back(ResultReg);
2892 OutVTs.push_back(VT);
2895 // Analyze operands of the call, assigning locations to each operand.
2896 SmallVector<CCValAssign, 16> ArgLocs;
2897 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2899 // Allocate shadow area for Win64
2901 CCInfo.AllocateStack(32, 8);
2903 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2905 // Get a count of how many bytes are to be pushed on the stack.
2906 unsigned NumBytes = CCInfo.getNextStackOffset();
2908 // Issue CALLSEQ_START
2909 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2910 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2911 .addImm(NumBytes).addImm(0);
2913 // Walk the register/memloc assignments, inserting copies/loads.
2914 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2915 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2916 CCValAssign const &VA = ArgLocs[i];
2917 const Value *ArgVal = OutVals[VA.getValNo()];
2918 MVT ArgVT = OutVTs[VA.getValNo()];
2920 if (ArgVT == MVT::x86mmx)
2923 unsigned ArgReg = ArgRegs[VA.getValNo()];
2925 // Promote the value if needed.
2926 switch (VA.getLocInfo()) {
2927 case CCValAssign::Full: break;
2928 case CCValAssign::SExt: {
2929 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2930 "Unexpected extend");
2931 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2933 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2934 ArgVT = VA.getLocVT();
2937 case CCValAssign::ZExt: {
2938 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2939 "Unexpected extend");
2940 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2942 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2943 ArgVT = VA.getLocVT();
2946 case CCValAssign::AExt: {
2947 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2948 "Unexpected extend");
2949 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2952 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2955 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2958 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2959 ArgVT = VA.getLocVT();
2962 case CCValAssign::BCvt: {
2963 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2964 /*TODO: Kill=*/false);
2965 assert(ArgReg && "Failed to emit a bitcast!");
2966 ArgVT = VA.getLocVT();
2969 case CCValAssign::VExt:
2970 // VExt has not been implemented, so this should be impossible to reach
2971 // for now. However, fallback to Selection DAG isel once implemented.
2973 case CCValAssign::AExtUpper:
2974 case CCValAssign::SExtUpper:
2975 case CCValAssign::ZExtUpper:
2976 case CCValAssign::FPExt:
2977 llvm_unreachable("Unexpected loc info!");
2978 case CCValAssign::Indirect:
2979 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2984 if (VA.isRegLoc()) {
2985 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2986 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2987 OutRegs.push_back(VA.getLocReg());
2989 assert(VA.isMemLoc());
2991 // Don't emit stores for undef values.
2992 if (isa<UndefValue>(ArgVal))
2995 unsigned LocMemOffset = VA.getLocMemOffset();
2997 AM.Base.Reg = RegInfo->getStackRegister();
2998 AM.Disp = LocMemOffset;
2999 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3000 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3001 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3002 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3003 ArgVT.getStoreSize(), Alignment);
3004 if (Flags.isByVal()) {
3005 X86AddressMode SrcAM;
3006 SrcAM.Base.Reg = ArgReg;
3007 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3009 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3010 // If this is a really simple value, emit this with the Value* version
3011 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3012 // as it can cause us to reevaluate the argument.
3013 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3016 bool ValIsKill = hasTrivialKill(ArgVal);
3017 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3023 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3025 if (Subtarget->isPICStyleGOT()) {
3026 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3028 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3031 if (Is64Bit && IsVarArg && !IsWin64) {
3032 // From AMD64 ABI document:
3033 // For calls that may call functions that use varargs or stdargs
3034 // (prototype-less calls or calls to functions containing ellipsis (...) in
3035 // the declaration) %al is used as hidden argument to specify the number
3036 // of SSE registers used. The contents of %al do not need to match exactly
3037 // the number of registers, but must be an ubound on the number of SSE
3038 // registers used and is in the range 0 - 8 inclusive.
3040 // Count the number of XMM registers allocated.
3041 static const MCPhysReg XMMArgRegs[] = {
3042 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3043 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3045 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3046 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3047 && "SSE registers cannot be used when SSE is disabled");
3048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3049 X86::AL).addImm(NumXMMRegs);
3052 // Materialize callee address in a register. FIXME: GV address can be
3053 // handled with a CALLpcrel32 instead.
3054 X86AddressMode CalleeAM;
3055 if (!X86SelectCallAddress(Callee, CalleeAM))
3058 unsigned CalleeOp = 0;
3059 const GlobalValue *GV = nullptr;
3060 if (CalleeAM.GV != nullptr) {
3062 } else if (CalleeAM.Base.Reg != 0) {
3063 CalleeOp = CalleeAM.Base.Reg;
3068 MachineInstrBuilder MIB;
3070 // Register-indirect call.
3071 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3072 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3076 assert(GV && "Not a direct call");
3077 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3079 // See if we need any target-specific flags on the GV operand.
3080 unsigned char OpFlags = 0;
3082 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3083 // external symbols most go through the PLT in PIC mode. If the symbol
3084 // has hidden or protected visibility, or if it is static or local, then
3085 // we don't need to use the PLT - we can directly call it.
3086 if (Subtarget->isTargetELF() &&
3087 TM.getRelocationModel() == Reloc::PIC_ &&
3088 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3089 OpFlags = X86II::MO_PLT;
3090 } else if (Subtarget->isPICStyleStubAny() &&
3091 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3092 (!Subtarget->getTargetTriple().isMacOSX() ||
3093 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3094 // PC-relative references to external symbols should go through $stub,
3095 // unless we're building with the leopard linker or later, which
3096 // automatically synthesizes these stubs.
3097 OpFlags = X86II::MO_DARWIN_STUB;
3100 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3102 MIB.addExternalSymbol(SymName, OpFlags);
3104 MIB.addGlobalAddress(GV, 0, OpFlags);
3107 // Add a register mask operand representing the call-preserved registers.
3108 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3109 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3111 // Add an implicit use GOT pointer in EBX.
3112 if (Subtarget->isPICStyleGOT())
3113 MIB.addReg(X86::EBX, RegState::Implicit);
3115 if (Is64Bit && IsVarArg && !IsWin64)
3116 MIB.addReg(X86::AL, RegState::Implicit);
3118 // Add implicit physical register uses to the call.
3119 for (auto Reg : OutRegs)
3120 MIB.addReg(Reg, RegState::Implicit);
3122 // Issue CALLSEQ_END
3123 unsigned NumBytesForCalleeToPop =
3124 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3125 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3126 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3127 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3129 // Now handle call return values.
3130 SmallVector<CCValAssign, 16> RVLocs;
3131 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3132 CLI.RetTy->getContext());
3133 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3135 // Copy all of the result registers out of their specified physreg.
3136 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3137 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3138 CCValAssign &VA = RVLocs[i];
3139 EVT CopyVT = VA.getValVT();
3140 unsigned CopyReg = ResultReg + i;
3142 // If this is x86-64, and we disabled SSE, we can't return FP values
3143 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3144 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3145 report_fatal_error("SSE register return with SSE disabled");
3148 // If we prefer to use the value in xmm registers, copy it out as f80 and
3149 // use a truncate to move it from fp stack reg to xmm reg.
3150 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3151 isScalarFPTypeInSSEReg(VA.getValVT())) {
3153 CopyReg = createResultReg(&X86::RFP80RegClass);
3156 // Copy out the result.
3157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3158 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3159 InRegs.push_back(VA.getLocReg());
3161 // Round the f80 to the right size, which also moves it to the appropriate
3162 // xmm register. This is accomplished by storing the f80 value in memory
3163 // and then loading it back.
3164 if (CopyVT != VA.getValVT()) {
3165 EVT ResVT = VA.getValVT();
3166 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3167 unsigned MemSize = ResVT.getSizeInBits()/8;
3168 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3169 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3172 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3173 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3174 TII.get(Opc), ResultReg + i), FI);
3178 CLI.ResultReg = ResultReg;
3179 CLI.NumResultRegs = RVLocs.size();
3186 X86FastISel::fastSelectInstruction(const Instruction *I) {
3187 switch (I->getOpcode()) {
3189 case Instruction::Load:
3190 return X86SelectLoad(I);
3191 case Instruction::Store:
3192 return X86SelectStore(I);
3193 case Instruction::Ret:
3194 return X86SelectRet(I);
3195 case Instruction::ICmp:
3196 case Instruction::FCmp:
3197 return X86SelectCmp(I);
3198 case Instruction::ZExt:
3199 return X86SelectZExt(I);
3200 case Instruction::Br:
3201 return X86SelectBranch(I);
3202 case Instruction::LShr:
3203 case Instruction::AShr:
3204 case Instruction::Shl:
3205 return X86SelectShift(I);
3206 case Instruction::SDiv:
3207 case Instruction::UDiv:
3208 case Instruction::SRem:
3209 case Instruction::URem:
3210 return X86SelectDivRem(I);
3211 case Instruction::Select:
3212 return X86SelectSelect(I);
3213 case Instruction::Trunc:
3214 return X86SelectTrunc(I);
3215 case Instruction::FPExt:
3216 return X86SelectFPExt(I);
3217 case Instruction::FPTrunc:
3218 return X86SelectFPTrunc(I);
3219 case Instruction::SIToFP:
3220 return X86SelectSIToFP(I);
3221 case Instruction::IntToPtr: // Deliberate fall-through.
3222 case Instruction::PtrToInt: {
3223 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3224 EVT DstVT = TLI.getValueType(I->getType());
3225 if (DstVT.bitsGT(SrcVT))
3226 return X86SelectZExt(I);
3227 if (DstVT.bitsLT(SrcVT))
3228 return X86SelectTrunc(I);
3229 unsigned Reg = getRegForValue(I->getOperand(0));
3230 if (Reg == 0) return false;
3231 updateValueMap(I, Reg);
3239 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3243 uint64_t Imm = CI->getZExtValue();
3245 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3246 switch (VT.SimpleTy) {
3247 default: llvm_unreachable("Unexpected value type");
3250 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3253 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3258 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3260 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3261 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3268 switch (VT.SimpleTy) {
3269 default: llvm_unreachable("Unexpected value type");
3270 case MVT::i1: VT = MVT::i8; // fall-through
3271 case MVT::i8: Opc = X86::MOV8ri; break;
3272 case MVT::i16: Opc = X86::MOV16ri; break;
3273 case MVT::i32: Opc = X86::MOV32ri; break;
3275 if (isUInt<32>(Imm))
3277 else if (isInt<32>(Imm))
3278 Opc = X86::MOV64ri32;
3284 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3285 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3286 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3287 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3288 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3289 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3292 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3295 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3296 if (CFP->isNullValue())
3297 return fastMaterializeFloatZero(CFP);
3299 // Can't handle alternate code models yet.
3300 CodeModel::Model CM = TM.getCodeModel();
3301 if (CM != CodeModel::Small && CM != CodeModel::Large)
3304 // Get opcode and regclass of the output for the given load instruction.
3306 const TargetRegisterClass *RC = nullptr;
3307 switch (VT.SimpleTy) {
3310 if (X86ScalarSSEf32) {
3311 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3312 RC = &X86::FR32RegClass;
3314 Opc = X86::LD_Fp32m;
3315 RC = &X86::RFP32RegClass;
3319 if (X86ScalarSSEf64) {
3320 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3321 RC = &X86::FR64RegClass;
3323 Opc = X86::LD_Fp64m;
3324 RC = &X86::RFP64RegClass;
3328 // No f80 support yet.
3332 // MachineConstantPool wants an explicit alignment.
3333 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3335 // Alignment of vector types. FIXME!
3336 Align = DL.getTypeAllocSize(CFP->getType());
3339 // x86-32 PIC requires a PIC base register for constant pools.
3340 unsigned PICBase = 0;
3341 unsigned char OpFlag = 0;
3342 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3343 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3344 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3345 } else if (Subtarget->isPICStyleGOT()) {
3346 OpFlag = X86II::MO_GOTOFF;
3347 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3348 } else if (Subtarget->isPICStyleRIPRel() &&
3349 TM.getCodeModel() == CodeModel::Small) {
3353 // Create the load from the constant pool.
3354 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3355 unsigned ResultReg = createResultReg(RC);
3357 if (CM == CodeModel::Large) {
3358 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3359 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3361 .addConstantPoolIndex(CPI, 0, OpFlag);
3362 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3363 TII.get(Opc), ResultReg);
3364 addDirectMem(MIB, AddrReg);
3365 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3366 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3367 TM.getDataLayout()->getPointerSize(), Align);
3368 MIB->addMemOperand(*FuncInfo.MF, MMO);
3372 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3373 TII.get(Opc), ResultReg),
3374 CPI, PICBase, OpFlag);
3378 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3379 // Can't handle alternate code models yet.
3380 if (TM.getCodeModel() != CodeModel::Small)
3383 // Materialize addresses with LEA/MOV instructions.
3385 if (X86SelectAddress(GV, AM)) {
3386 // If the expression is just a basereg, then we're done, otherwise we need
3388 if (AM.BaseType == X86AddressMode::RegBase &&
3389 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3392 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3393 if (TM.getRelocationModel() == Reloc::Static &&
3394 TLI.getPointerTy() == MVT::i64) {
3395 // The displacement code could be more than 32 bits away so we need to use
3396 // an instruction with a 64 bit immediate
3397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3399 .addGlobalAddress(GV);
3401 unsigned Opc = TLI.getPointerTy() == MVT::i32
3402 ? (Subtarget->isTarget64BitILP32()
3403 ? X86::LEA64_32r : X86::LEA32r)
3405 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3406 TII.get(Opc), ResultReg), AM);
3413 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3414 EVT CEVT = TLI.getValueType(C->getType(), true);
3416 // Only handle simple types.
3417 if (!CEVT.isSimple())
3419 MVT VT = CEVT.getSimpleVT();
3421 if (const auto *CI = dyn_cast<ConstantInt>(C))
3422 return X86MaterializeInt(CI, VT);
3423 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3424 return X86MaterializeFP(CFP, VT);
3425 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3426 return X86MaterializeGV(GV, VT);
3431 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3432 // Fail on dynamic allocas. At this point, getRegForValue has already
3433 // checked its CSE maps, so if we're here trying to handle a dynamic
3434 // alloca, we're not going to succeed. X86SelectAddress has a
3435 // check for dynamic allocas, because it's called directly from
3436 // various places, but targetMaterializeAlloca also needs a check
3437 // in order to avoid recursion between getRegForValue,
3438 // X86SelectAddrss, and targetMaterializeAlloca.
3439 if (!FuncInfo.StaticAllocaMap.count(C))
3441 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3444 if (!X86SelectAddress(C, AM))
3446 unsigned Opc = TLI.getPointerTy() == MVT::i32
3447 ? (Subtarget->isTarget64BitILP32()
3448 ? X86::LEA64_32r : X86::LEA32r)
3450 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3451 unsigned ResultReg = createResultReg(RC);
3452 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3453 TII.get(Opc), ResultReg), AM);
3457 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3459 if (!isTypeLegal(CF->getType(), VT))
3462 // Get opcode and regclass for the given zero.
3464 const TargetRegisterClass *RC = nullptr;
3465 switch (VT.SimpleTy) {
3468 if (X86ScalarSSEf32) {
3469 Opc = X86::FsFLD0SS;
3470 RC = &X86::FR32RegClass;
3472 Opc = X86::LD_Fp032;
3473 RC = &X86::RFP32RegClass;
3477 if (X86ScalarSSEf64) {
3478 Opc = X86::FsFLD0SD;
3479 RC = &X86::FR64RegClass;
3481 Opc = X86::LD_Fp064;
3482 RC = &X86::RFP64RegClass;
3486 // No f80 support yet.
3490 unsigned ResultReg = createResultReg(RC);
3491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3496 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3497 const LoadInst *LI) {
3498 const Value *Ptr = LI->getPointerOperand();
3500 if (!X86SelectAddress(Ptr, AM))
3503 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3505 unsigned Size = DL.getTypeAllocSize(LI->getType());
3506 unsigned Alignment = LI->getAlignment();
3508 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3509 Alignment = DL.getABITypeAlignment(LI->getType());
3511 SmallVector<MachineOperand, 8> AddrOps;
3512 AM.getFullAddress(AddrOps);
3514 MachineInstr *Result =
3515 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3516 Size, Alignment, /*AllowCommute=*/true);
3520 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3521 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3522 MI->eraseFromParent();
3528 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3529 const TargetLibraryInfo *libInfo) {
3530 return new X86FastISel(funcInfo, libInfo);