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, X86AddressMode &AM, MachineMemOperand *MMO,
87 unsigned &ResultReg, unsigned Alignment = 1);
89 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
91 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
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,
169 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
173 } // end anonymous namespace.
175 static std::pair<X86::CondCode, bool>
176 getX86ConditionCode(CmpInst::Predicate Predicate) {
177 X86::CondCode CC = X86::COND_INVALID;
178 bool NeedSwap = false;
181 // Floating-point Predicates
182 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
183 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
184 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
185 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
186 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
187 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
188 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
189 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
190 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
191 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
192 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
193 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
194 case CmpInst::FCMP_OEQ: // fall-through
195 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
197 // Integer Predicates
198 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
199 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
200 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
201 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
202 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
203 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
204 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
205 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
206 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
207 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
210 return std::make_pair(CC, NeedSwap);
213 static std::pair<unsigned, bool>
214 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
216 bool NeedSwap = false;
218 // SSE Condition code mapping:
228 default: llvm_unreachable("Unexpected predicate");
229 case CmpInst::FCMP_OEQ: CC = 0; break;
230 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
231 case CmpInst::FCMP_OLT: CC = 1; break;
232 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
233 case CmpInst::FCMP_OLE: CC = 2; break;
234 case CmpInst::FCMP_UNO: CC = 3; break;
235 case CmpInst::FCMP_UNE: CC = 4; break;
236 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
237 case CmpInst::FCMP_UGE: CC = 5; break;
238 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
239 case CmpInst::FCMP_UGT: CC = 6; break;
240 case CmpInst::FCMP_ORD: CC = 7; break;
241 case CmpInst::FCMP_UEQ:
242 case CmpInst::FCMP_ONE: CC = 8; break;
245 return std::make_pair(CC, NeedSwap);
248 /// \brief Adds a complex addressing mode to the given machine instr builder.
249 /// Note, this will constrain the index register. If its not possible to
250 /// constrain the given index register, then a new one will be created. The
251 /// IndexReg field of the addressing mode will be updated to match in this case.
252 const MachineInstrBuilder &
253 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
254 X86AddressMode &AM) {
255 // First constrain the index register. It needs to be a GR64_NOSP.
256 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
257 MIB->getNumOperands() +
259 return ::addFullAddress(MIB, AM);
262 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
263 /// into the user. The condition code will only be updated on success.
264 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
266 if (!isa<ExtractValueInst>(Cond))
269 const auto *EV = cast<ExtractValueInst>(Cond);
270 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
273 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
275 const Function *Callee = II->getCalledFunction();
277 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
278 if (!isTypeLegal(RetTy, RetVT))
281 if (RetVT != MVT::i32 && RetVT != MVT::i64)
285 switch (II->getIntrinsicID()) {
286 default: return false;
287 case Intrinsic::sadd_with_overflow:
288 case Intrinsic::ssub_with_overflow:
289 case Intrinsic::smul_with_overflow:
290 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
291 case Intrinsic::uadd_with_overflow:
292 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
295 // Check if both instructions are in the same basic block.
296 if (II->getParent() != I->getParent())
299 // Make sure nothing is in the way
300 BasicBlock::const_iterator Start = I;
301 BasicBlock::const_iterator End = II;
302 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
303 // We only expect extractvalue instructions between the intrinsic and the
304 // instruction to be selected.
305 if (!isa<ExtractValueInst>(Itr))
308 // Check that the extractvalue operand comes from the intrinsic.
309 const auto *EVI = cast<ExtractValueInst>(Itr);
310 if (EVI->getAggregateOperand() != II)
318 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
319 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
320 if (evt == MVT::Other || !evt.isSimple())
321 // Unhandled type. Halt "fast" selection and bail.
324 VT = evt.getSimpleVT();
325 // For now, require SSE/SSE2 for performing floating-point operations,
326 // since x87 requires additional work.
327 if (VT == MVT::f64 && !X86ScalarSSEf64)
329 if (VT == MVT::f32 && !X86ScalarSSEf32)
331 // Similarly, no f80 support yet.
334 // We only handle legal types. For example, on x86-32 the instruction
335 // selector contains all of the 64-bit instructions from x86-64,
336 // under the assumption that i64 won't be used if the target doesn't
338 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
341 #include "X86GenCallingConv.inc"
343 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
344 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
345 /// Return true and the result register by reference if it is possible.
346 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
347 MachineMemOperand *MMO, unsigned &ResultReg,
348 unsigned Alignment) {
349 // Get opcode and regclass of the output for the given load instruction.
351 const TargetRegisterClass *RC = nullptr;
352 switch (VT.getSimpleVT().SimpleTy) {
353 default: return false;
357 RC = &X86::GR8RegClass;
361 RC = &X86::GR16RegClass;
365 RC = &X86::GR32RegClass;
368 // Must be in x86-64 mode.
370 RC = &X86::GR64RegClass;
373 if (X86ScalarSSEf32) {
374 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
375 RC = &X86::FR32RegClass;
378 RC = &X86::RFP32RegClass;
382 if (X86ScalarSSEf64) {
383 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
384 RC = &X86::FR64RegClass;
387 RC = &X86::RFP64RegClass;
391 // No f80 support yet.
395 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
397 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
398 RC = &X86::VR128RegClass;
402 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
404 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
405 RC = &X86::VR128RegClass;
412 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
414 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
415 RC = &X86::VR128RegClass;
419 ResultReg = createResultReg(RC);
420 MachineInstrBuilder MIB =
421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
422 addFullAddress(MIB, AM);
424 MIB->addMemOperand(*FuncInfo.MF, MMO);
428 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
429 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
430 /// and a displacement offset, or a GlobalAddress,
431 /// i.e. V. Return true if it is possible.
432 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
434 MachineMemOperand *MMO, bool Aligned) {
435 // Get opcode and regclass of the output for the given store instruction.
437 switch (VT.getSimpleVT().SimpleTy) {
438 case MVT::f80: // No f80 support yet.
439 default: return false;
441 // Mask out all but lowest bit.
442 unsigned AndResult = createResultReg(&X86::GR8RegClass);
443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
444 TII.get(X86::AND8ri), AndResult)
445 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
448 // FALLTHROUGH, handling i1 as i8.
449 case MVT::i8: Opc = X86::MOV8mr; break;
450 case MVT::i16: Opc = X86::MOV16mr; break;
451 case MVT::i32: Opc = X86::MOV32mr; break;
452 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
454 Opc = X86ScalarSSEf32 ?
455 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
458 Opc = X86ScalarSSEf64 ?
459 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
463 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
465 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
469 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
471 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
478 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
480 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
484 MachineInstrBuilder MIB =
485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
486 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
488 MIB->addMemOperand(*FuncInfo.MF, MMO);
493 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
495 MachineMemOperand *MMO, bool Aligned) {
496 // Handle 'null' like i32/i64 0.
497 if (isa<ConstantPointerNull>(Val))
498 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
500 // If this is a store of a simple constant, fold the constant into the store.
501 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
504 switch (VT.getSimpleVT().SimpleTy) {
506 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
507 case MVT::i8: Opc = X86::MOV8mi; break;
508 case MVT::i16: Opc = X86::MOV16mi; break;
509 case MVT::i32: Opc = X86::MOV32mi; break;
511 // Must be a 32-bit sign extended value.
512 if (isInt<32>(CI->getSExtValue()))
513 Opc = X86::MOV64mi32;
518 MachineInstrBuilder MIB =
519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
520 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
521 : CI->getZExtValue());
523 MIB->addMemOperand(*FuncInfo.MF, MMO);
528 unsigned ValReg = getRegForValue(Val);
532 bool ValKill = hasTrivialKill(Val);
533 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
536 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
537 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
538 /// ISD::SIGN_EXTEND).
539 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
540 unsigned Src, EVT SrcVT,
541 unsigned &ResultReg) {
542 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
543 Src, /*TODO: Kill=*/false);
551 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
552 // Handle constant address.
553 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
554 // Can't handle alternate code models yet.
555 if (TM.getCodeModel() != CodeModel::Small)
558 // Can't handle TLS yet.
559 if (GV->isThreadLocal())
562 // RIP-relative addresses can't have additional register operands, so if
563 // we've already folded stuff into the addressing mode, just force the
564 // global value into its own register, which we can use as the basereg.
565 if (!Subtarget->isPICStyleRIPRel() ||
566 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
567 // Okay, we've committed to selecting this global. Set up the address.
570 // Allow the subtarget to classify the global.
571 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
573 // If this reference is relative to the pic base, set it now.
574 if (isGlobalRelativeToPICBase(GVFlags)) {
575 // FIXME: How do we know Base.Reg is free??
576 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
579 // Unless the ABI requires an extra load, return a direct reference to
581 if (!isGlobalStubReference(GVFlags)) {
582 if (Subtarget->isPICStyleRIPRel()) {
583 // Use rip-relative addressing if we can. Above we verified that the
584 // base and index registers are unused.
585 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
586 AM.Base.Reg = X86::RIP;
588 AM.GVOpFlags = GVFlags;
592 // Ok, we need to do a load from a stub. If we've already loaded from
593 // this stub, reuse the loaded pointer, otherwise emit the load now.
594 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
596 if (I != LocalValueMap.end() && I->second != 0) {
599 // Issue load from stub.
601 const TargetRegisterClass *RC = nullptr;
602 X86AddressMode StubAM;
603 StubAM.Base.Reg = AM.Base.Reg;
605 StubAM.GVOpFlags = GVFlags;
607 // Prepare for inserting code in the local-value area.
608 SavePoint SaveInsertPt = enterLocalValueArea();
610 if (TLI.getPointerTy() == MVT::i64) {
612 RC = &X86::GR64RegClass;
614 if (Subtarget->isPICStyleRIPRel())
615 StubAM.Base.Reg = X86::RIP;
618 RC = &X86::GR32RegClass;
621 LoadReg = createResultReg(RC);
622 MachineInstrBuilder LoadMI =
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
624 addFullAddress(LoadMI, StubAM);
626 // Ok, back to normal mode.
627 leaveLocalValueArea(SaveInsertPt);
629 // Prevent loading GV stub multiple times in same MBB.
630 LocalValueMap[V] = LoadReg;
633 // Now construct the final address. Note that the Disp, Scale,
634 // and Index values may already be set here.
635 AM.Base.Reg = LoadReg;
641 // If all else fails, try to materialize the value in a register.
642 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
643 if (AM.Base.Reg == 0) {
644 AM.Base.Reg = getRegForValue(V);
645 return AM.Base.Reg != 0;
647 if (AM.IndexReg == 0) {
648 assert(AM.Scale == 1 && "Scale with no index!");
649 AM.IndexReg = getRegForValue(V);
650 return AM.IndexReg != 0;
657 /// X86SelectAddress - Attempt to fill in an address from the given value.
659 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
660 SmallVector<const Value *, 32> GEPs;
662 const User *U = nullptr;
663 unsigned Opcode = Instruction::UserOp1;
664 if (const Instruction *I = dyn_cast<Instruction>(V)) {
665 // Don't walk into other basic blocks; it's possible we haven't
666 // visited them yet, so the instructions may not yet be assigned
667 // virtual registers.
668 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
669 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
670 Opcode = I->getOpcode();
673 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
674 Opcode = C->getOpcode();
678 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
679 if (Ty->getAddressSpace() > 255)
680 // Fast instruction selection doesn't support the special
686 case Instruction::BitCast:
687 // Look past bitcasts.
688 return X86SelectAddress(U->getOperand(0), AM);
690 case Instruction::IntToPtr:
691 // Look past no-op inttoptrs.
692 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
693 return X86SelectAddress(U->getOperand(0), AM);
696 case Instruction::PtrToInt:
697 // Look past no-op ptrtoints.
698 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
699 return X86SelectAddress(U->getOperand(0), AM);
702 case Instruction::Alloca: {
703 // Do static allocas.
704 const AllocaInst *A = cast<AllocaInst>(V);
705 DenseMap<const AllocaInst *, int>::iterator SI =
706 FuncInfo.StaticAllocaMap.find(A);
707 if (SI != FuncInfo.StaticAllocaMap.end()) {
708 AM.BaseType = X86AddressMode::FrameIndexBase;
709 AM.Base.FrameIndex = SI->second;
715 case Instruction::Add: {
716 // Adds of constants are common and easy enough.
717 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
718 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
719 // They have to fit in the 32-bit signed displacement field though.
720 if (isInt<32>(Disp)) {
721 AM.Disp = (uint32_t)Disp;
722 return X86SelectAddress(U->getOperand(0), AM);
728 case Instruction::GetElementPtr: {
729 X86AddressMode SavedAM = AM;
731 // Pattern-match simple GEPs.
732 uint64_t Disp = (int32_t)AM.Disp;
733 unsigned IndexReg = AM.IndexReg;
734 unsigned Scale = AM.Scale;
735 gep_type_iterator GTI = gep_type_begin(U);
736 // Iterate through the indices, folding what we can. Constants can be
737 // folded, and one dynamic index can be handled, if the scale is supported.
738 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
739 i != e; ++i, ++GTI) {
740 const Value *Op = *i;
741 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
742 const StructLayout *SL = DL.getStructLayout(STy);
743 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
747 // A array/variable index is always of the form i*S where S is the
748 // constant scale size. See if we can push the scale into immediates.
749 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
752 // Constant-offset addressing.
753 Disp += CI->getSExtValue() * S;
756 if (canFoldAddIntoGEP(U, Op)) {
757 // A compatible add with a constant operand. Fold the constant.
759 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
760 Disp += CI->getSExtValue() * S;
761 // Iterate on the other operand.
762 Op = cast<AddOperator>(Op)->getOperand(0);
766 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
767 (S == 1 || S == 2 || S == 4 || S == 8)) {
768 // Scaled-index addressing.
770 IndexReg = getRegForGEPIndex(Op).first;
776 goto unsupported_gep;
780 // Check for displacement overflow.
781 if (!isInt<32>(Disp))
784 AM.IndexReg = IndexReg;
786 AM.Disp = (uint32_t)Disp;
789 if (const GetElementPtrInst *GEP =
790 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
791 // Ok, the GEP indices were covered by constant-offset and scaled-index
792 // addressing. Update the address state and move on to examining the base.
795 } else if (X86SelectAddress(U->getOperand(0), AM)) {
799 // If we couldn't merge the gep value into this addr mode, revert back to
800 // our address and just match the value instead of completely failing.
803 for (SmallVectorImpl<const Value *>::reverse_iterator
804 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
805 if (handleConstantAddresses(*I, AM))
810 // Ok, the GEP indices weren't all covered.
815 return handleConstantAddresses(V, AM);
818 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
820 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
821 const User *U = nullptr;
822 unsigned Opcode = Instruction::UserOp1;
823 const Instruction *I = dyn_cast<Instruction>(V);
824 // Record if the value is defined in the same basic block.
826 // This information is crucial to know whether or not folding an
828 // Indeed, FastISel generates or reuses a virtual register for all
829 // operands of all instructions it selects. Obviously, the definition and
830 // its uses must use the same virtual register otherwise the produced
831 // code is incorrect.
832 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
833 // registers for values that are alive across basic blocks. This ensures
834 // that the values are consistently set between across basic block, even
835 // if different instruction selection mechanisms are used (e.g., a mix of
836 // SDISel and FastISel).
837 // For values local to a basic block, the instruction selection process
838 // generates these virtual registers with whatever method is appropriate
839 // for its needs. In particular, FastISel and SDISel do not share the way
840 // local virtual registers are set.
841 // Therefore, this is impossible (or at least unsafe) to share values
842 // between basic blocks unless they use the same instruction selection
843 // method, which is not guarantee for X86.
844 // Moreover, things like hasOneUse could not be used accurately, if we
845 // allow to reference values across basic blocks whereas they are not
846 // alive across basic blocks initially.
849 Opcode = I->getOpcode();
851 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
852 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
853 Opcode = C->getOpcode();
859 case Instruction::BitCast:
860 // Look past bitcasts if its operand is in the same BB.
862 return X86SelectCallAddress(U->getOperand(0), AM);
865 case Instruction::IntToPtr:
866 // Look past no-op inttoptrs if its operand is in the same BB.
868 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
869 return X86SelectCallAddress(U->getOperand(0), AM);
872 case Instruction::PtrToInt:
873 // Look past no-op ptrtoints if its operand is in the same BB.
875 TLI.getValueType(U->getType()) == TLI.getPointerTy())
876 return X86SelectCallAddress(U->getOperand(0), AM);
880 // Handle constant address.
881 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
882 // Can't handle alternate code models yet.
883 if (TM.getCodeModel() != CodeModel::Small)
886 // RIP-relative addresses can't have additional register operands.
887 if (Subtarget->isPICStyleRIPRel() &&
888 (AM.Base.Reg != 0 || AM.IndexReg != 0))
891 // Can't handle DLL Import.
892 if (GV->hasDLLImportStorageClass())
896 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
897 if (GVar->isThreadLocal())
900 // Okay, we've committed to selecting this global. Set up the basic address.
903 // No ABI requires an extra load for anything other than DLLImport, which
904 // we rejected above. Return a direct reference to the global.
905 if (Subtarget->isPICStyleRIPRel()) {
906 // Use rip-relative addressing if we can. Above we verified that the
907 // base and index registers are unused.
908 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
909 AM.Base.Reg = X86::RIP;
910 } else if (Subtarget->isPICStyleStubPIC()) {
911 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
912 } else if (Subtarget->isPICStyleGOT()) {
913 AM.GVOpFlags = X86II::MO_GOTOFF;
919 // If all else fails, try to materialize the value in a register.
920 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
921 if (AM.Base.Reg == 0) {
922 AM.Base.Reg = getRegForValue(V);
923 return AM.Base.Reg != 0;
925 if (AM.IndexReg == 0) {
926 assert(AM.Scale == 1 && "Scale with no index!");
927 AM.IndexReg = getRegForValue(V);
928 return AM.IndexReg != 0;
936 /// X86SelectStore - Select and emit code to implement store instructions.
937 bool X86FastISel::X86SelectStore(const Instruction *I) {
938 // Atomic stores need special handling.
939 const StoreInst *S = cast<StoreInst>(I);
944 const Value *Val = S->getValueOperand();
945 const Value *Ptr = S->getPointerOperand();
948 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
951 unsigned Alignment = S->getAlignment();
952 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
953 if (Alignment == 0) // Ensure that codegen never sees alignment 0
954 Alignment = ABIAlignment;
955 bool Aligned = Alignment >= ABIAlignment;
958 if (!X86SelectAddress(Ptr, AM))
961 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
964 /// X86SelectRet - Select and emit code to implement ret instructions.
965 bool X86FastISel::X86SelectRet(const Instruction *I) {
966 const ReturnInst *Ret = cast<ReturnInst>(I);
967 const Function &F = *I->getParent()->getParent();
968 const X86MachineFunctionInfo *X86MFInfo =
969 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
971 if (!FuncInfo.CanLowerReturn)
974 CallingConv::ID CC = F.getCallingConv();
975 if (CC != CallingConv::C &&
976 CC != CallingConv::Fast &&
977 CC != CallingConv::X86_FastCall &&
978 CC != CallingConv::X86_64_SysV)
981 if (Subtarget->isCallingConvWin64(CC))
984 // Don't handle popping bytes on return for now.
985 if (X86MFInfo->getBytesToPopOnReturn() != 0)
988 // fastcc with -tailcallopt is intended to provide a guaranteed
989 // tail call optimization. Fastisel doesn't know how to do that.
990 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
993 // Let SDISel handle vararg functions.
997 // Build a list of return value registers.
998 SmallVector<unsigned, 4> RetRegs;
1000 if (Ret->getNumOperands() > 0) {
1001 SmallVector<ISD::OutputArg, 4> Outs;
1002 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1004 // Analyze operands of the call, assigning locations to each operand.
1005 SmallVector<CCValAssign, 16> ValLocs;
1006 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1007 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1009 const Value *RV = Ret->getOperand(0);
1010 unsigned Reg = getRegForValue(RV);
1014 // Only handle a single return value for now.
1015 if (ValLocs.size() != 1)
1018 CCValAssign &VA = ValLocs[0];
1020 // Don't bother handling odd stuff for now.
1021 if (VA.getLocInfo() != CCValAssign::Full)
1023 // Only handle register returns for now.
1027 // The calling-convention tables for x87 returns don't tell
1029 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1032 unsigned SrcReg = Reg + VA.getValNo();
1033 EVT SrcVT = TLI.getValueType(RV->getType());
1034 EVT DstVT = VA.getValVT();
1035 // Special handling for extended integers.
1036 if (SrcVT != DstVT) {
1037 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1040 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1043 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1045 if (SrcVT == MVT::i1) {
1046 if (Outs[0].Flags.isSExt())
1048 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1051 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1053 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1054 SrcReg, /*TODO: Kill=*/false);
1058 unsigned DstReg = VA.getLocReg();
1059 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1060 // Avoid a cross-class copy. This is very unlikely.
1061 if (!SrcRC->contains(DstReg))
1063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1064 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1066 // Add register to return instruction.
1067 RetRegs.push_back(VA.getLocReg());
1070 // The x86-64 ABI for returning structs by value requires that we copy
1071 // the sret argument into %rax for the return. We saved the argument into
1072 // a virtual register in the entry block, so now we copy the value out
1073 // and into %rax. We also do the same with %eax for Win32.
1074 if (F.hasStructRetAttr() &&
1075 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1076 unsigned Reg = X86MFInfo->getSRetReturnReg();
1078 "SRetReturnReg should have been set in LowerFormalArguments()!");
1079 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1080 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1081 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1082 RetRegs.push_back(RetReg);
1085 // Now emit the RET.
1086 MachineInstrBuilder MIB =
1087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1088 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1089 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1090 MIB.addReg(RetRegs[i], RegState::Implicit);
1094 /// X86SelectLoad - Select and emit code to implement load instructions.
1096 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1097 const LoadInst *LI = cast<LoadInst>(I);
1099 // Atomic loads need special handling.
1104 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1107 const Value *Ptr = LI->getPointerOperand();
1110 if (!X86SelectAddress(Ptr, AM))
1113 unsigned Alignment = LI->getAlignment();
1114 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1115 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1116 Alignment = ABIAlignment;
1118 unsigned ResultReg = 0;
1119 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1123 updateValueMap(I, ResultReg);
1127 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1128 bool HasAVX = Subtarget->hasAVX();
1129 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1130 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1132 switch (VT.getSimpleVT().SimpleTy) {
1134 case MVT::i8: return X86::CMP8rr;
1135 case MVT::i16: return X86::CMP16rr;
1136 case MVT::i32: return X86::CMP32rr;
1137 case MVT::i64: return X86::CMP64rr;
1139 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1141 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1145 /// If we have a comparison with RHS as the RHS of the comparison, return an
1146 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1147 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1148 int64_t Val = RHSC->getSExtValue();
1149 switch (VT.getSimpleVT().SimpleTy) {
1150 // Otherwise, we can't fold the immediate into this comparison.
1157 return X86::CMP16ri8;
1158 return X86::CMP16ri;
1161 return X86::CMP32ri8;
1162 return X86::CMP32ri;
1165 return X86::CMP64ri8;
1166 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1169 return X86::CMP64ri32;
1174 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1175 EVT VT, DebugLoc CurDbgLoc) {
1176 unsigned Op0Reg = getRegForValue(Op0);
1177 if (Op0Reg == 0) return false;
1179 // Handle 'null' like i32/i64 0.
1180 if (isa<ConstantPointerNull>(Op1))
1181 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1183 // We have two options: compare with register or immediate. If the RHS of
1184 // the compare is an immediate that we can fold into this compare, use
1185 // CMPri, otherwise use CMPrr.
1186 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1187 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1190 .addImm(Op1C->getSExtValue());
1195 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1196 if (CompareOpc == 0) return false;
1198 unsigned Op1Reg = getRegForValue(Op1);
1199 if (Op1Reg == 0) return false;
1200 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1207 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1208 const CmpInst *CI = cast<CmpInst>(I);
1211 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1214 // Try to optimize or fold the cmp.
1215 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1216 unsigned ResultReg = 0;
1217 switch (Predicate) {
1219 case CmpInst::FCMP_FALSE: {
1220 ResultReg = createResultReg(&X86::GR32RegClass);
1221 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1223 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1229 case CmpInst::FCMP_TRUE: {
1230 ResultReg = createResultReg(&X86::GR8RegClass);
1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1232 ResultReg).addImm(1);
1238 updateValueMap(I, ResultReg);
1242 const Value *LHS = CI->getOperand(0);
1243 const Value *RHS = CI->getOperand(1);
1245 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1246 // We don't have to materialize a zero constant for this case and can just use
1247 // %x again on the RHS.
1248 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1249 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1250 if (RHSC && RHSC->isNullValue())
1254 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1255 static unsigned SETFOpcTable[2][3] = {
1256 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1257 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1259 unsigned *SETFOpc = nullptr;
1260 switch (Predicate) {
1262 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1263 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1266 ResultReg = createResultReg(&X86::GR8RegClass);
1268 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1271 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1272 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1278 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1279 updateValueMap(I, ResultReg);
1285 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1286 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1287 unsigned Opc = X86::getSETFromCond(CC);
1290 std::swap(LHS, RHS);
1292 // Emit a compare of LHS/RHS.
1293 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1297 updateValueMap(I, ResultReg);
1301 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1302 EVT DstVT = TLI.getValueType(I->getType());
1303 if (!TLI.isTypeLegal(DstVT))
1306 unsigned ResultReg = getRegForValue(I->getOperand(0));
1310 // Handle zero-extension from i1 to i8, which is common.
1311 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1312 if (SrcVT.SimpleTy == MVT::i1) {
1313 // Set the high bits to zero.
1314 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1321 if (DstVT == MVT::i64) {
1322 // Handle extension to 64-bits via sub-register shenanigans.
1325 switch (SrcVT.SimpleTy) {
1326 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1327 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1328 case MVT::i32: MovInst = X86::MOV32rr; break;
1329 default: llvm_unreachable("Unexpected zext to i64 source type");
1332 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1336 ResultReg = createResultReg(&X86::GR64RegClass);
1337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1339 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1340 } else if (DstVT != MVT::i8) {
1341 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1342 ResultReg, /*Kill=*/true);
1347 updateValueMap(I, ResultReg);
1351 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1352 // Unconditional branches are selected by tablegen-generated code.
1353 // Handle a conditional branch.
1354 const BranchInst *BI = cast<BranchInst>(I);
1355 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1356 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1358 // Fold the common case of a conditional branch with a comparison
1359 // in the same block (values defined on other blocks may not have
1360 // initialized registers).
1362 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1363 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1364 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1366 // Try to optimize or fold the cmp.
1367 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1368 switch (Predicate) {
1370 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1371 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1374 const Value *CmpLHS = CI->getOperand(0);
1375 const Value *CmpRHS = CI->getOperand(1);
1377 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1379 // We don't have to materialize a zero constant for this case and can just
1380 // use %x again on the RHS.
1381 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1382 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1383 if (CmpRHSC && CmpRHSC->isNullValue())
1387 // Try to take advantage of fallthrough opportunities.
1388 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1389 std::swap(TrueMBB, FalseMBB);
1390 Predicate = CmpInst::getInversePredicate(Predicate);
1393 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1394 // code check. Instead two branch instructions are required to check all
1395 // the flags. First we change the predicate to a supported condition code,
1396 // which will be the first branch. Later one we will emit the second
1398 bool NeedExtraBranch = false;
1399 switch (Predicate) {
1401 case CmpInst::FCMP_OEQ:
1402 std::swap(TrueMBB, FalseMBB); // fall-through
1403 case CmpInst::FCMP_UNE:
1404 NeedExtraBranch = true;
1405 Predicate = CmpInst::FCMP_ONE;
1411 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1412 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1414 BranchOpc = X86::GetCondBranchFromCond(CC);
1416 std::swap(CmpLHS, CmpRHS);
1418 // Emit a compare of the LHS and RHS, setting the flags.
1419 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1425 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1427 if (NeedExtraBranch) {
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1432 // Obtain the branch weight and add the TrueBB to the successor list.
1433 uint32_t BranchWeight = 0;
1435 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1436 TrueMBB->getBasicBlock());
1437 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1439 // Emits an unconditional branch to the FalseBB, obtains the branch
1440 // weight, and adds it to the successor list.
1441 fastEmitBranch(FalseMBB, DbgLoc);
1445 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1446 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1447 // typically happen for _Bool and C++ bools.
1449 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1450 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1451 unsigned TestOpc = 0;
1452 switch (SourceVT.SimpleTy) {
1454 case MVT::i8: TestOpc = X86::TEST8ri; break;
1455 case MVT::i16: TestOpc = X86::TEST16ri; break;
1456 case MVT::i32: TestOpc = X86::TEST32ri; break;
1457 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1460 unsigned OpReg = getRegForValue(TI->getOperand(0));
1461 if (OpReg == 0) return false;
1462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1463 .addReg(OpReg).addImm(1);
1465 unsigned JmpOpc = X86::JNE_1;
1466 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1467 std::swap(TrueMBB, FalseMBB);
1471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1473 fastEmitBranch(FalseMBB, DbgLoc);
1474 uint32_t BranchWeight = 0;
1476 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1477 TrueMBB->getBasicBlock());
1478 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1482 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1483 // Fake request the condition, otherwise the intrinsic might be completely
1485 unsigned TmpReg = getRegForValue(BI->getCondition());
1489 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1493 fastEmitBranch(FalseMBB, DbgLoc);
1494 uint32_t BranchWeight = 0;
1496 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1497 TrueMBB->getBasicBlock());
1498 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1502 // Otherwise do a clumsy setcc and re-test it.
1503 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1504 // in an explicit cast, so make sure to handle that correctly.
1505 unsigned OpReg = getRegForValue(BI->getCondition());
1506 if (OpReg == 0) return false;
1508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1509 .addReg(OpReg).addImm(1);
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1512 fastEmitBranch(FalseMBB, DbgLoc);
1513 uint32_t BranchWeight = 0;
1515 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1516 TrueMBB->getBasicBlock());
1517 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1521 bool X86FastISel::X86SelectShift(const Instruction *I) {
1522 unsigned CReg = 0, OpReg = 0;
1523 const TargetRegisterClass *RC = nullptr;
1524 if (I->getType()->isIntegerTy(8)) {
1526 RC = &X86::GR8RegClass;
1527 switch (I->getOpcode()) {
1528 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1529 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1530 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1531 default: return false;
1533 } else if (I->getType()->isIntegerTy(16)) {
1535 RC = &X86::GR16RegClass;
1536 switch (I->getOpcode()) {
1537 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1538 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1539 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1540 default: return false;
1542 } else if (I->getType()->isIntegerTy(32)) {
1544 RC = &X86::GR32RegClass;
1545 switch (I->getOpcode()) {
1546 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1547 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1548 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1549 default: return false;
1551 } else if (I->getType()->isIntegerTy(64)) {
1553 RC = &X86::GR64RegClass;
1554 switch (I->getOpcode()) {
1555 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1556 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1557 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1558 default: return false;
1565 if (!isTypeLegal(I->getType(), VT))
1568 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1569 if (Op0Reg == 0) return false;
1571 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1572 if (Op1Reg == 0) return false;
1573 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1574 CReg).addReg(Op1Reg);
1576 // The shift instruction uses X86::CL. If we defined a super-register
1577 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1578 if (CReg != X86::CL)
1579 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1580 TII.get(TargetOpcode::KILL), X86::CL)
1581 .addReg(CReg, RegState::Kill);
1583 unsigned ResultReg = createResultReg(RC);
1584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1586 updateValueMap(I, ResultReg);
1590 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1591 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1592 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1593 const static bool S = true; // IsSigned
1594 const static bool U = false; // !IsSigned
1595 const static unsigned Copy = TargetOpcode::COPY;
1596 // For the X86 DIV/IDIV instruction, in most cases the dividend
1597 // (numerator) must be in a specific register pair highreg:lowreg,
1598 // producing the quotient in lowreg and the remainder in highreg.
1599 // For most data types, to set up the instruction, the dividend is
1600 // copied into lowreg, and lowreg is sign-extended or zero-extended
1601 // into highreg. The exception is i8, where the dividend is defined
1602 // as a single register rather than a register pair, and we
1603 // therefore directly sign-extend or zero-extend the dividend into
1604 // lowreg, instead of copying, and ignore the highreg.
1605 const static struct DivRemEntry {
1606 // The following portion depends only on the data type.
1607 const TargetRegisterClass *RC;
1608 unsigned LowInReg; // low part of the register pair
1609 unsigned HighInReg; // high part of the register pair
1610 // The following portion depends on both the data type and the operation.
1611 struct DivRemResult {
1612 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1613 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1614 // highreg, or copying a zero into highreg.
1615 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1616 // zero/sign-extending into lowreg for i8.
1617 unsigned DivRemResultReg; // Register containing the desired result.
1618 bool IsOpSigned; // Whether to use signed or unsigned form.
1619 } ResultTable[NumOps];
1620 } OpTable[NumTypes] = {
1621 { &X86::GR8RegClass, X86::AX, 0, {
1622 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1623 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1624 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1625 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1628 { &X86::GR16RegClass, X86::AX, X86::DX, {
1629 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1630 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1631 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1632 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1635 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1636 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1637 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1638 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1639 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1642 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1643 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1644 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1645 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1646 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1652 if (!isTypeLegal(I->getType(), VT))
1655 unsigned TypeIndex, OpIndex;
1656 switch (VT.SimpleTy) {
1657 default: return false;
1658 case MVT::i8: TypeIndex = 0; break;
1659 case MVT::i16: TypeIndex = 1; break;
1660 case MVT::i32: TypeIndex = 2; break;
1661 case MVT::i64: TypeIndex = 3;
1662 if (!Subtarget->is64Bit())
1667 switch (I->getOpcode()) {
1668 default: llvm_unreachable("Unexpected div/rem opcode");
1669 case Instruction::SDiv: OpIndex = 0; break;
1670 case Instruction::SRem: OpIndex = 1; break;
1671 case Instruction::UDiv: OpIndex = 2; break;
1672 case Instruction::URem: OpIndex = 3; break;
1675 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1676 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1677 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1680 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1684 // Move op0 into low-order input register.
1685 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1686 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1687 // Zero-extend or sign-extend into high-order input register.
1688 if (OpEntry.OpSignExtend) {
1689 if (OpEntry.IsOpSigned)
1690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1691 TII.get(OpEntry.OpSignExtend));
1693 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1695 TII.get(X86::MOV32r0), Zero32);
1697 // Copy the zero into the appropriate sub/super/identical physical
1698 // register. Unfortunately the operations needed are not uniform enough
1699 // to fit neatly into the table above.
1700 if (VT.SimpleTy == MVT::i16) {
1701 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1702 TII.get(Copy), TypeEntry.HighInReg)
1703 .addReg(Zero32, 0, X86::sub_16bit);
1704 } else if (VT.SimpleTy == MVT::i32) {
1705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1706 TII.get(Copy), TypeEntry.HighInReg)
1708 } else if (VT.SimpleTy == MVT::i64) {
1709 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1710 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1711 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1715 // Generate the DIV/IDIV instruction.
1716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1717 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1718 // For i8 remainder, we can't reference AH directly, as we'll end
1719 // up with bogus copies like %R9B = COPY %AH. Reference AX
1720 // instead to prevent AH references in a REX instruction.
1722 // The current assumption of the fast register allocator is that isel
1723 // won't generate explicit references to the GPR8_NOREX registers. If
1724 // the allocator and/or the backend get enhanced to be more robust in
1725 // that regard, this can be, and should be, removed.
1726 unsigned ResultReg = 0;
1727 if ((I->getOpcode() == Instruction::SRem ||
1728 I->getOpcode() == Instruction::URem) &&
1729 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1730 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1731 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1732 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1733 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1735 // Shift AX right by 8 bits instead of using AH.
1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1737 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1739 // Now reference the 8-bit subreg of the result.
1740 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1741 /*Kill=*/true, X86::sub_8bit);
1743 // Copy the result out of the physreg if we haven't already.
1745 ResultReg = createResultReg(TypeEntry.RC);
1746 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1747 .addReg(OpEntry.DivRemResultReg);
1749 updateValueMap(I, ResultReg);
1754 /// \brief Emit a conditional move instruction (if the are supported) to lower
1756 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1757 // Check if the subtarget supports these instructions.
1758 if (!Subtarget->hasCMov())
1761 // FIXME: Add support for i8.
1762 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1765 const Value *Cond = I->getOperand(0);
1766 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1767 bool NeedTest = true;
1768 X86::CondCode CC = X86::COND_NE;
1770 // Optimize conditions coming from a compare if both instructions are in the
1771 // same basic block (values defined in other basic blocks may not have
1772 // initialized registers).
1773 const auto *CI = dyn_cast<CmpInst>(Cond);
1774 if (CI && (CI->getParent() == I->getParent())) {
1775 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1777 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1778 static unsigned SETFOpcTable[2][3] = {
1779 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1780 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1782 unsigned *SETFOpc = nullptr;
1783 switch (Predicate) {
1785 case CmpInst::FCMP_OEQ:
1786 SETFOpc = &SETFOpcTable[0][0];
1787 Predicate = CmpInst::ICMP_NE;
1789 case CmpInst::FCMP_UNE:
1790 SETFOpc = &SETFOpcTable[1][0];
1791 Predicate = CmpInst::ICMP_NE;
1796 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1797 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1799 const Value *CmpLHS = CI->getOperand(0);
1800 const Value *CmpRHS = CI->getOperand(1);
1802 std::swap(CmpLHS, CmpRHS);
1804 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1805 // Emit a compare of the LHS and RHS, setting the flags.
1806 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1810 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1811 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1812 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1816 auto const &II = TII.get(SETFOpc[2]);
1817 if (II.getNumDefs()) {
1818 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1820 .addReg(FlagReg2).addReg(FlagReg1);
1822 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1823 .addReg(FlagReg2).addReg(FlagReg1);
1827 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1828 // Fake request the condition, otherwise the intrinsic might be completely
1830 unsigned TmpReg = getRegForValue(Cond);
1838 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1839 // garbage. Indeed, only the less significant bit is supposed to be
1840 // accurate. If we read more than the lsb, we may see non-zero values
1841 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1842 // the select. This is achieved by performing TEST against 1.
1843 unsigned CondReg = getRegForValue(Cond);
1846 bool CondIsKill = hasTrivialKill(Cond);
1848 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1849 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1852 const Value *LHS = I->getOperand(1);
1853 const Value *RHS = I->getOperand(2);
1855 unsigned RHSReg = getRegForValue(RHS);
1856 bool RHSIsKill = hasTrivialKill(RHS);
1858 unsigned LHSReg = getRegForValue(LHS);
1859 bool LHSIsKill = hasTrivialKill(LHS);
1861 if (!LHSReg || !RHSReg)
1864 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1865 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1867 updateValueMap(I, ResultReg);
1871 /// \brief Emit SSE or AVX instructions to lower the select.
1873 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1874 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1875 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1876 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1877 // Optimize conditions coming from a compare if both instructions are in the
1878 // same basic block (values defined in other basic blocks may not have
1879 // initialized registers).
1880 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1881 if (!CI || (CI->getParent() != I->getParent()))
1884 if (I->getType() != CI->getOperand(0)->getType() ||
1885 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1886 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1889 const Value *CmpLHS = CI->getOperand(0);
1890 const Value *CmpRHS = CI->getOperand(1);
1891 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1893 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1894 // We don't have to materialize a zero constant for this case and can just use
1895 // %x again on the RHS.
1896 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1897 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1898 if (CmpRHSC && CmpRHSC->isNullValue())
1904 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1909 std::swap(CmpLHS, CmpRHS);
1911 // Choose the SSE instruction sequence based on data type (float or double).
1912 static unsigned OpcTable[2][4] = {
1913 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1914 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1917 unsigned *Opc = nullptr;
1918 switch (RetVT.SimpleTy) {
1919 default: return false;
1920 case MVT::f32: Opc = &OpcTable[0][0]; break;
1921 case MVT::f64: Opc = &OpcTable[1][0]; break;
1924 const Value *LHS = I->getOperand(1);
1925 const Value *RHS = I->getOperand(2);
1927 unsigned LHSReg = getRegForValue(LHS);
1928 bool LHSIsKill = hasTrivialKill(LHS);
1930 unsigned RHSReg = getRegForValue(RHS);
1931 bool RHSIsKill = hasTrivialKill(RHS);
1933 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1934 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1936 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1937 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1939 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1942 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1945 if (Subtarget->hasAVX()) {
1946 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1947 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1948 // uses XMM0 as the selection register. That may need just as many
1949 // instructions as the AND/ANDN/OR sequence due to register moves, so
1951 unsigned CmpOpcode =
1952 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1953 unsigned BlendOpcode =
1954 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1956 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1957 CmpRHSReg, CmpRHSIsKill, CC);
1958 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1959 LHSReg, LHSIsKill, CmpReg, true);
1961 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1962 CmpRHSReg, CmpRHSIsKill, CC);
1963 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1965 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1967 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1968 AndReg, /*IsKill=*/true);
1970 updateValueMap(I, ResultReg);
1974 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1975 // These are pseudo CMOV instructions and will be later expanded into control-
1978 switch (RetVT.SimpleTy) {
1979 default: return false;
1980 case MVT::i8: Opc = X86::CMOV_GR8; break;
1981 case MVT::i16: Opc = X86::CMOV_GR16; break;
1982 case MVT::i32: Opc = X86::CMOV_GR32; break;
1983 case MVT::f32: Opc = X86::CMOV_FR32; break;
1984 case MVT::f64: Opc = X86::CMOV_FR64; break;
1987 const Value *Cond = I->getOperand(0);
1988 X86::CondCode CC = X86::COND_NE;
1990 // Optimize conditions coming from a compare if both instructions are in the
1991 // same basic block (values defined in other basic blocks may not have
1992 // initialized registers).
1993 const auto *CI = dyn_cast<CmpInst>(Cond);
1994 if (CI && (CI->getParent() == I->getParent())) {
1996 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1997 if (CC > X86::LAST_VALID_COND)
2000 const Value *CmpLHS = CI->getOperand(0);
2001 const Value *CmpRHS = CI->getOperand(1);
2004 std::swap(CmpLHS, CmpRHS);
2006 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
2007 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2010 unsigned CondReg = getRegForValue(Cond);
2013 bool CondIsKill = hasTrivialKill(Cond);
2014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2015 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2018 const Value *LHS = I->getOperand(1);
2019 const Value *RHS = I->getOperand(2);
2021 unsigned LHSReg = getRegForValue(LHS);
2022 bool LHSIsKill = hasTrivialKill(LHS);
2024 unsigned RHSReg = getRegForValue(RHS);
2025 bool RHSIsKill = hasTrivialKill(RHS);
2027 if (!LHSReg || !RHSReg)
2030 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2032 unsigned ResultReg =
2033 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2034 updateValueMap(I, ResultReg);
2038 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2040 if (!isTypeLegal(I->getType(), RetVT))
2043 // Check if we can fold the select.
2044 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2045 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2046 const Value *Opnd = nullptr;
2047 switch (Predicate) {
2049 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2050 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2052 // No need for a select anymore - this is an unconditional move.
2054 unsigned OpReg = getRegForValue(Opnd);
2057 bool OpIsKill = hasTrivialKill(Opnd);
2058 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2059 unsigned ResultReg = createResultReg(RC);
2060 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2061 TII.get(TargetOpcode::COPY), ResultReg)
2062 .addReg(OpReg, getKillRegState(OpIsKill));
2063 updateValueMap(I, ResultReg);
2068 // First try to use real conditional move instructions.
2069 if (X86FastEmitCMoveSelect(RetVT, I))
2072 // Try to use a sequence of SSE instructions to simulate a conditional move.
2073 if (X86FastEmitSSESelect(RetVT, I))
2076 // Fall-back to pseudo conditional move instructions, which will be later
2077 // converted to control-flow.
2078 if (X86FastEmitPseudoSelect(RetVT, I))
2084 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2085 // The target-independent selection algorithm in FastISel already knows how
2086 // to select a SINT_TO_FP if the target is SSE but not AVX.
2087 // Early exit if the subtarget doesn't have AVX.
2088 if (!Subtarget->hasAVX())
2091 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2094 // Select integer to float/double conversion.
2095 unsigned OpReg = getRegForValue(I->getOperand(0));
2099 const TargetRegisterClass *RC = nullptr;
2102 if (I->getType()->isDoubleTy()) {
2103 // sitofp int -> double
2104 Opcode = X86::VCVTSI2SDrr;
2105 RC = &X86::FR64RegClass;
2106 } else if (I->getType()->isFloatTy()) {
2107 // sitofp int -> float
2108 Opcode = X86::VCVTSI2SSrr;
2109 RC = &X86::FR32RegClass;
2113 unsigned ImplicitDefReg = createResultReg(RC);
2114 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2115 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2116 unsigned ResultReg =
2117 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2118 updateValueMap(I, ResultReg);
2122 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2123 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2125 const TargetRegisterClass *RC) {
2126 assert((I->getOpcode() == Instruction::FPExt ||
2127 I->getOpcode() == Instruction::FPTrunc) &&
2128 "Instruction must be an FPExt or FPTrunc!");
2130 unsigned OpReg = getRegForValue(I->getOperand(0));
2134 unsigned ResultReg = createResultReg(RC);
2135 MachineInstrBuilder MIB;
2136 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2138 if (Subtarget->hasAVX())
2141 updateValueMap(I, ResultReg);
2145 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2146 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2147 I->getOperand(0)->getType()->isFloatTy()) {
2148 // fpext from float to double.
2149 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2150 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2156 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2157 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2158 I->getOperand(0)->getType()->isDoubleTy()) {
2159 // fptrunc from double to float.
2160 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2161 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2167 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2168 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2169 EVT DstVT = TLI.getValueType(I->getType());
2171 // This code only handles truncation to byte.
2172 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2174 if (!TLI.isTypeLegal(SrcVT))
2177 unsigned InputReg = getRegForValue(I->getOperand(0));
2179 // Unhandled operand. Halt "fast" selection and bail.
2182 if (SrcVT == MVT::i8) {
2183 // Truncate from i8 to i1; no code needed.
2184 updateValueMap(I, InputReg);
2188 if (!Subtarget->is64Bit()) {
2189 // If we're on x86-32; we can't extract an i8 from a general register.
2190 // First issue a copy to GR16_ABCD or GR32_ABCD.
2191 const TargetRegisterClass *CopyRC =
2192 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2193 unsigned CopyReg = createResultReg(CopyRC);
2194 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2195 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2199 // Issue an extract_subreg.
2200 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2201 InputReg, /*Kill=*/true,
2206 updateValueMap(I, ResultReg);
2210 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2211 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2214 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2215 X86AddressMode SrcAM, uint64_t Len) {
2217 // Make sure we don't bloat code by inlining very large memcpy's.
2218 if (!IsMemcpySmall(Len))
2221 bool i64Legal = Subtarget->is64Bit();
2223 // We don't care about alignment here since we just emit integer accesses.
2226 if (Len >= 8 && i64Legal)
2236 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2237 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2238 assert(RV && "Failed to emit load or store??");
2240 unsigned Size = VT.getSizeInBits()/8;
2242 DestAM.Disp += Size;
2249 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2250 // FIXME: Handle more intrinsics.
2251 switch (II->getIntrinsicID()) {
2252 default: return false;
2253 case Intrinsic::convert_from_fp16:
2254 case Intrinsic::convert_to_fp16: {
2255 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C())
2258 const Value *Op = II->getArgOperand(0);
2259 unsigned InputReg = getRegForValue(Op);
2263 // F16C only allows converting from float to half and from half to float.
2264 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2265 if (IsFloatToHalf) {
2266 if (!Op->getType()->isFloatTy())
2269 if (!II->getType()->isFloatTy())
2273 unsigned ResultReg = 0;
2274 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2275 if (IsFloatToHalf) {
2276 // 'InputReg' is implicitly promoted from register class FR32 to
2277 // register class VR128 by method 'constrainOperandRegClass' which is
2278 // directly called by 'fastEmitInst_ri'.
2279 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2280 // used to provide rounding control.
2281 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2283 // Move the lower 32-bits of ResultReg to another register of class GR32.
2284 ResultReg = createResultReg(&X86::GR32RegClass);
2285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2286 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2287 .addReg(InputReg, RegState::Kill);
2289 // The result value is in the lower 16-bits of ResultReg.
2290 unsigned RegIdx = X86::sub_16bit;
2291 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2293 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2294 // Explicitly sign-extend the input to 32-bit.
2295 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2298 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2299 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2300 InputReg, /*Kill=*/true);
2302 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2304 // The result value is in the lower 32-bits of ResultReg.
2305 // Emit an explicit copy from register class VR128 to register class FR32.
2306 ResultReg = createResultReg(&X86::FR32RegClass);
2307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2308 TII.get(TargetOpcode::COPY), ResultReg)
2309 .addReg(InputReg, RegState::Kill);
2312 updateValueMap(II, ResultReg);
2315 case Intrinsic::frameaddress: {
2316 MachineFunction *MF = FuncInfo.MF;
2317 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2320 Type *RetTy = II->getCalledFunction()->getReturnType();
2323 if (!isTypeLegal(RetTy, VT))
2327 const TargetRegisterClass *RC = nullptr;
2329 switch (VT.SimpleTy) {
2330 default: llvm_unreachable("Invalid result type for frameaddress.");
2331 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2332 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2335 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2336 // we get the wrong frame register.
2337 MachineFrameInfo *MFI = MF->getFrameInfo();
2338 MFI->setFrameAddressIsTaken(true);
2340 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2341 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2342 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2343 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2344 "Invalid Frame Register!");
2346 // Always make a copy of the frame register to to a vreg first, so that we
2347 // never directly reference the frame register (the TwoAddressInstruction-
2348 // Pass doesn't like that).
2349 unsigned SrcReg = createResultReg(RC);
2350 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2351 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2353 // Now recursively load from the frame address.
2354 // movq (%rbp), %rax
2355 // movq (%rax), %rax
2356 // movq (%rax), %rax
2359 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2361 DestReg = createResultReg(RC);
2362 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2363 TII.get(Opc), DestReg), SrcReg);
2367 updateValueMap(II, SrcReg);
2370 case Intrinsic::memcpy: {
2371 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2372 // Don't handle volatile or variable length memcpys.
2373 if (MCI->isVolatile())
2376 if (isa<ConstantInt>(MCI->getLength())) {
2377 // Small memcpy's are common enough that we want to do them
2378 // without a call if possible.
2379 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2380 if (IsMemcpySmall(Len)) {
2381 X86AddressMode DestAM, SrcAM;
2382 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2383 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2385 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2390 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2391 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2394 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2397 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2399 case Intrinsic::memset: {
2400 const MemSetInst *MSI = cast<MemSetInst>(II);
2402 if (MSI->isVolatile())
2405 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2406 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2409 if (MSI->getDestAddressSpace() > 255)
2412 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2414 case Intrinsic::stackprotector: {
2415 // Emit code to store the stack guard onto the stack.
2416 EVT PtrTy = TLI.getPointerTy();
2418 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2419 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2421 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2423 // Grab the frame index.
2425 if (!X86SelectAddress(Slot, AM)) return false;
2426 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2429 case Intrinsic::dbg_declare: {
2430 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2432 assert(DI->getAddress() && "Null address should be checked earlier!");
2433 if (!X86SelectAddress(DI->getAddress(), AM))
2435 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2436 // FIXME may need to add RegState::Debug to any registers produced,
2437 // although ESP/EBP should be the only ones at the moment.
2438 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2439 "Expected inlined-at fields to agree");
2440 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2442 .addMetadata(DI->getVariable())
2443 .addMetadata(DI->getExpression());
2446 case Intrinsic::trap: {
2447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2450 case Intrinsic::sqrt: {
2451 if (!Subtarget->hasSSE1())
2454 Type *RetTy = II->getCalledFunction()->getReturnType();
2457 if (!isTypeLegal(RetTy, VT))
2460 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2461 // is not generated by FastISel yet.
2462 // FIXME: Update this code once tablegen can handle it.
2463 static const unsigned SqrtOpc[2][2] = {
2464 {X86::SQRTSSr, X86::VSQRTSSr},
2465 {X86::SQRTSDr, X86::VSQRTSDr}
2467 bool HasAVX = Subtarget->hasAVX();
2469 const TargetRegisterClass *RC;
2470 switch (VT.SimpleTy) {
2471 default: return false;
2472 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2473 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2476 const Value *SrcVal = II->getArgOperand(0);
2477 unsigned SrcReg = getRegForValue(SrcVal);
2482 unsigned ImplicitDefReg = 0;
2484 ImplicitDefReg = createResultReg(RC);
2485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2486 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2489 unsigned ResultReg = createResultReg(RC);
2490 MachineInstrBuilder MIB;
2491 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2495 MIB.addReg(ImplicitDefReg);
2499 updateValueMap(II, ResultReg);
2502 case Intrinsic::sadd_with_overflow:
2503 case Intrinsic::uadd_with_overflow:
2504 case Intrinsic::ssub_with_overflow:
2505 case Intrinsic::usub_with_overflow:
2506 case Intrinsic::smul_with_overflow:
2507 case Intrinsic::umul_with_overflow: {
2508 // This implements the basic lowering of the xalu with overflow intrinsics
2509 // into add/sub/mul followed by either seto or setb.
2510 const Function *Callee = II->getCalledFunction();
2511 auto *Ty = cast<StructType>(Callee->getReturnType());
2512 Type *RetTy = Ty->getTypeAtIndex(0U);
2513 Type *CondTy = Ty->getTypeAtIndex(1);
2516 if (!isTypeLegal(RetTy, VT))
2519 if (VT < MVT::i8 || VT > MVT::i64)
2522 const Value *LHS = II->getArgOperand(0);
2523 const Value *RHS = II->getArgOperand(1);
2525 // Canonicalize immediate to the RHS.
2526 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2527 isCommutativeIntrinsic(II))
2528 std::swap(LHS, RHS);
2530 bool UseIncDec = false;
2531 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2534 unsigned BaseOpc, CondOpc;
2535 switch (II->getIntrinsicID()) {
2536 default: llvm_unreachable("Unexpected intrinsic!");
2537 case Intrinsic::sadd_with_overflow:
2538 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2539 CondOpc = X86::SETOr;
2541 case Intrinsic::uadd_with_overflow:
2542 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2543 case Intrinsic::ssub_with_overflow:
2544 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2545 CondOpc = X86::SETOr;
2547 case Intrinsic::usub_with_overflow:
2548 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2549 case Intrinsic::smul_with_overflow:
2550 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2551 case Intrinsic::umul_with_overflow:
2552 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2555 unsigned LHSReg = getRegForValue(LHS);
2558 bool LHSIsKill = hasTrivialKill(LHS);
2560 unsigned ResultReg = 0;
2561 // Check if we have an immediate version.
2562 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2563 static const unsigned Opc[2][4] = {
2564 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2565 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2568 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2569 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2570 bool IsDec = BaseOpc == X86ISD::DEC;
2571 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2572 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2573 .addReg(LHSReg, getKillRegState(LHSIsKill));
2575 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2576 CI->getZExtValue());
2582 RHSReg = getRegForValue(RHS);
2585 RHSIsKill = hasTrivialKill(RHS);
2586 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2590 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2592 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2593 static const unsigned MULOpc[] =
2594 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2595 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2596 // First copy the first operand into RAX, which is an implicit input to
2597 // the X86::MUL*r instruction.
2598 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2599 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2600 .addReg(LHSReg, getKillRegState(LHSIsKill));
2601 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2602 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2603 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2604 static const unsigned MULOpc[] =
2605 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2606 if (VT == MVT::i8) {
2607 // Copy the first operand into AL, which is an implicit input to the
2608 // X86::IMUL8r instruction.
2609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2610 TII.get(TargetOpcode::COPY), X86::AL)
2611 .addReg(LHSReg, getKillRegState(LHSIsKill));
2612 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2615 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2616 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2623 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2624 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2628 updateValueMap(II, ResultReg, 2);
2631 case Intrinsic::x86_sse_cvttss2si:
2632 case Intrinsic::x86_sse_cvttss2si64:
2633 case Intrinsic::x86_sse2_cvttsd2si:
2634 case Intrinsic::x86_sse2_cvttsd2si64: {
2636 switch (II->getIntrinsicID()) {
2637 default: llvm_unreachable("Unexpected intrinsic.");
2638 case Intrinsic::x86_sse_cvttss2si:
2639 case Intrinsic::x86_sse_cvttss2si64:
2640 if (!Subtarget->hasSSE1())
2642 IsInputDouble = false;
2644 case Intrinsic::x86_sse2_cvttsd2si:
2645 case Intrinsic::x86_sse2_cvttsd2si64:
2646 if (!Subtarget->hasSSE2())
2648 IsInputDouble = true;
2652 Type *RetTy = II->getCalledFunction()->getReturnType();
2654 if (!isTypeLegal(RetTy, VT))
2657 static const unsigned CvtOpc[2][2][2] = {
2658 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2659 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2660 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2661 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2663 bool HasAVX = Subtarget->hasAVX();
2665 switch (VT.SimpleTy) {
2666 default: llvm_unreachable("Unexpected result type.");
2667 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2668 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2671 // Check if we can fold insertelement instructions into the convert.
2672 const Value *Op = II->getArgOperand(0);
2673 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2674 const Value *Index = IE->getOperand(2);
2675 if (!isa<ConstantInt>(Index))
2677 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2680 Op = IE->getOperand(1);
2683 Op = IE->getOperand(0);
2686 unsigned Reg = getRegForValue(Op);
2690 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2694 updateValueMap(II, ResultReg);
2700 bool X86FastISel::fastLowerArguments() {
2701 if (!FuncInfo.CanLowerReturn)
2704 const Function *F = FuncInfo.Fn;
2708 CallingConv::ID CC = F->getCallingConv();
2709 if (CC != CallingConv::C)
2712 if (Subtarget->isCallingConvWin64(CC))
2715 if (!Subtarget->is64Bit())
2718 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2719 unsigned GPRCnt = 0;
2720 unsigned FPRCnt = 0;
2722 for (auto const &Arg : F->args()) {
2723 // The first argument is at index 1.
2725 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2726 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2727 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2728 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2731 Type *ArgTy = Arg.getType();
2732 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2735 EVT ArgVT = TLI.getValueType(ArgTy);
2736 if (!ArgVT.isSimple()) return false;
2737 switch (ArgVT.getSimpleVT().SimpleTy) {
2738 default: return false;
2745 if (!Subtarget->hasSSE1())
2758 static const MCPhysReg GPR32ArgRegs[] = {
2759 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2761 static const MCPhysReg GPR64ArgRegs[] = {
2762 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2764 static const MCPhysReg XMMArgRegs[] = {
2765 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2766 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2769 unsigned GPRIdx = 0;
2770 unsigned FPRIdx = 0;
2771 for (auto const &Arg : F->args()) {
2772 MVT VT = TLI.getSimpleValueType(Arg.getType());
2773 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2775 switch (VT.SimpleTy) {
2776 default: llvm_unreachable("Unexpected value type.");
2777 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2778 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2779 case MVT::f32: // fall-through
2780 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2782 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2783 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2784 // Without this, EmitLiveInCopies may eliminate the livein if its only
2785 // use is a bitcast (which isn't turned into an instruction).
2786 unsigned ResultReg = createResultReg(RC);
2787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2788 TII.get(TargetOpcode::COPY), ResultReg)
2789 .addReg(DstReg, getKillRegState(true));
2790 updateValueMap(&Arg, ResultReg);
2795 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2797 ImmutableCallSite *CS) {
2798 if (Subtarget->is64Bit())
2800 if (Subtarget->getTargetTriple().isOSMSVCRT())
2802 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2803 CC == CallingConv::HiPE)
2805 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2807 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2812 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2813 auto &OutVals = CLI.OutVals;
2814 auto &OutFlags = CLI.OutFlags;
2815 auto &OutRegs = CLI.OutRegs;
2816 auto &Ins = CLI.Ins;
2817 auto &InRegs = CLI.InRegs;
2818 CallingConv::ID CC = CLI.CallConv;
2819 bool &IsTailCall = CLI.IsTailCall;
2820 bool IsVarArg = CLI.IsVarArg;
2821 const Value *Callee = CLI.Callee;
2822 const char *SymName = CLI.SymName;
2824 bool Is64Bit = Subtarget->is64Bit();
2825 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2827 // Handle only C, fastcc, and webkit_js calling conventions for now.
2829 default: return false;
2830 case CallingConv::C:
2831 case CallingConv::Fast:
2832 case CallingConv::WebKit_JS:
2833 case CallingConv::X86_FastCall:
2834 case CallingConv::X86_64_Win64:
2835 case CallingConv::X86_64_SysV:
2839 // Allow SelectionDAG isel to handle tail calls.
2843 // fastcc with -tailcallopt is intended to provide a guaranteed
2844 // tail call optimization. Fastisel doesn't know how to do that.
2845 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2848 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2849 // x86-32. Special handling for x86-64 is implemented.
2850 if (IsVarArg && IsWin64)
2853 // Don't know about inalloca yet.
2854 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2857 // Fast-isel doesn't know about callee-pop yet.
2858 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2859 TM.Options.GuaranteedTailCallOpt))
2862 SmallVector<MVT, 16> OutVTs;
2863 SmallVector<unsigned, 16> ArgRegs;
2865 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2866 // instruction. This is safe because it is common to all FastISel supported
2867 // calling conventions on x86.
2868 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2869 Value *&Val = OutVals[i];
2870 ISD::ArgFlagsTy Flags = OutFlags[i];
2871 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2872 if (CI->getBitWidth() < 32) {
2874 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2876 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2880 // Passing bools around ends up doing a trunc to i1 and passing it.
2881 // Codegen this as an argument + "and 1".
2883 auto *TI = dyn_cast<TruncInst>(Val);
2885 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2886 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2888 Value *PrevVal = TI->getOperand(0);
2889 ResultReg = getRegForValue(PrevVal);
2894 if (!isTypeLegal(PrevVal->getType(), VT))
2898 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2900 if (!isTypeLegal(Val->getType(), VT))
2902 ResultReg = getRegForValue(Val);
2908 ArgRegs.push_back(ResultReg);
2909 OutVTs.push_back(VT);
2912 // Analyze operands of the call, assigning locations to each operand.
2913 SmallVector<CCValAssign, 16> ArgLocs;
2914 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2916 // Allocate shadow area for Win64
2918 CCInfo.AllocateStack(32, 8);
2920 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2922 // Get a count of how many bytes are to be pushed on the stack.
2923 unsigned NumBytes = CCInfo.getNextStackOffset();
2925 // Issue CALLSEQ_START
2926 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2927 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2928 .addImm(NumBytes).addImm(0);
2930 // Walk the register/memloc assignments, inserting copies/loads.
2931 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2933 CCValAssign const &VA = ArgLocs[i];
2934 const Value *ArgVal = OutVals[VA.getValNo()];
2935 MVT ArgVT = OutVTs[VA.getValNo()];
2937 if (ArgVT == MVT::x86mmx)
2940 unsigned ArgReg = ArgRegs[VA.getValNo()];
2942 // Promote the value if needed.
2943 switch (VA.getLocInfo()) {
2944 case CCValAssign::Full: break;
2945 case CCValAssign::SExt: {
2946 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2947 "Unexpected extend");
2948 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2950 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2951 ArgVT = VA.getLocVT();
2954 case CCValAssign::ZExt: {
2955 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2956 "Unexpected extend");
2957 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2959 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2960 ArgVT = VA.getLocVT();
2963 case CCValAssign::AExt: {
2964 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2965 "Unexpected extend");
2966 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2969 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2972 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2975 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2976 ArgVT = VA.getLocVT();
2979 case CCValAssign::BCvt: {
2980 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2981 /*TODO: Kill=*/false);
2982 assert(ArgReg && "Failed to emit a bitcast!");
2983 ArgVT = VA.getLocVT();
2986 case CCValAssign::VExt:
2987 // VExt has not been implemented, so this should be impossible to reach
2988 // for now. However, fallback to Selection DAG isel once implemented.
2990 case CCValAssign::AExtUpper:
2991 case CCValAssign::SExtUpper:
2992 case CCValAssign::ZExtUpper:
2993 case CCValAssign::FPExt:
2994 llvm_unreachable("Unexpected loc info!");
2995 case CCValAssign::Indirect:
2996 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3001 if (VA.isRegLoc()) {
3002 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3003 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3004 OutRegs.push_back(VA.getLocReg());
3006 assert(VA.isMemLoc());
3008 // Don't emit stores for undef values.
3009 if (isa<UndefValue>(ArgVal))
3012 unsigned LocMemOffset = VA.getLocMemOffset();
3014 AM.Base.Reg = RegInfo->getStackRegister();
3015 AM.Disp = LocMemOffset;
3016 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3017 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3018 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3019 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3020 ArgVT.getStoreSize(), Alignment);
3021 if (Flags.isByVal()) {
3022 X86AddressMode SrcAM;
3023 SrcAM.Base.Reg = ArgReg;
3024 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3026 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3027 // If this is a really simple value, emit this with the Value* version
3028 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3029 // as it can cause us to reevaluate the argument.
3030 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3033 bool ValIsKill = hasTrivialKill(ArgVal);
3034 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3040 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3042 if (Subtarget->isPICStyleGOT()) {
3043 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3045 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3048 if (Is64Bit && IsVarArg && !IsWin64) {
3049 // From AMD64 ABI document:
3050 // For calls that may call functions that use varargs or stdargs
3051 // (prototype-less calls or calls to functions containing ellipsis (...) in
3052 // the declaration) %al is used as hidden argument to specify the number
3053 // of SSE registers used. The contents of %al do not need to match exactly
3054 // the number of registers, but must be an ubound on the number of SSE
3055 // registers used and is in the range 0 - 8 inclusive.
3057 // Count the number of XMM registers allocated.
3058 static const MCPhysReg XMMArgRegs[] = {
3059 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3060 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3062 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3063 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3064 && "SSE registers cannot be used when SSE is disabled");
3065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3066 X86::AL).addImm(NumXMMRegs);
3069 // Materialize callee address in a register. FIXME: GV address can be
3070 // handled with a CALLpcrel32 instead.
3071 X86AddressMode CalleeAM;
3072 if (!X86SelectCallAddress(Callee, CalleeAM))
3075 unsigned CalleeOp = 0;
3076 const GlobalValue *GV = nullptr;
3077 if (CalleeAM.GV != nullptr) {
3079 } else if (CalleeAM.Base.Reg != 0) {
3080 CalleeOp = CalleeAM.Base.Reg;
3085 MachineInstrBuilder MIB;
3087 // Register-indirect call.
3088 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3089 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3093 assert(GV && "Not a direct call");
3094 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3096 // See if we need any target-specific flags on the GV operand.
3097 unsigned char OpFlags = 0;
3099 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3100 // external symbols most go through the PLT in PIC mode. If the symbol
3101 // has hidden or protected visibility, or if it is static or local, then
3102 // we don't need to use the PLT - we can directly call it.
3103 if (Subtarget->isTargetELF() &&
3104 TM.getRelocationModel() == Reloc::PIC_ &&
3105 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3106 OpFlags = X86II::MO_PLT;
3107 } else if (Subtarget->isPICStyleStubAny() &&
3108 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3109 (!Subtarget->getTargetTriple().isMacOSX() ||
3110 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3111 // PC-relative references to external symbols should go through $stub,
3112 // unless we're building with the leopard linker or later, which
3113 // automatically synthesizes these stubs.
3114 OpFlags = X86II::MO_DARWIN_STUB;
3117 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3119 MIB.addExternalSymbol(SymName, OpFlags);
3121 MIB.addGlobalAddress(GV, 0, OpFlags);
3124 // Add a register mask operand representing the call-preserved registers.
3125 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3126 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3128 // Add an implicit use GOT pointer in EBX.
3129 if (Subtarget->isPICStyleGOT())
3130 MIB.addReg(X86::EBX, RegState::Implicit);
3132 if (Is64Bit && IsVarArg && !IsWin64)
3133 MIB.addReg(X86::AL, RegState::Implicit);
3135 // Add implicit physical register uses to the call.
3136 for (auto Reg : OutRegs)
3137 MIB.addReg(Reg, RegState::Implicit);
3139 // Issue CALLSEQ_END
3140 unsigned NumBytesForCalleeToPop =
3141 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3142 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3144 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3146 // Now handle call return values.
3147 SmallVector<CCValAssign, 16> RVLocs;
3148 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3149 CLI.RetTy->getContext());
3150 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3152 // Copy all of the result registers out of their specified physreg.
3153 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3154 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3155 CCValAssign &VA = RVLocs[i];
3156 EVT CopyVT = VA.getValVT();
3157 unsigned CopyReg = ResultReg + i;
3159 // If this is x86-64, and we disabled SSE, we can't return FP values
3160 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3161 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3162 report_fatal_error("SSE register return with SSE disabled");
3165 // If we prefer to use the value in xmm registers, copy it out as f80 and
3166 // use a truncate to move it from fp stack reg to xmm reg.
3167 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3168 isScalarFPTypeInSSEReg(VA.getValVT())) {
3170 CopyReg = createResultReg(&X86::RFP80RegClass);
3173 // Copy out the result.
3174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3175 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3176 InRegs.push_back(VA.getLocReg());
3178 // Round the f80 to the right size, which also moves it to the appropriate
3179 // xmm register. This is accomplished by storing the f80 value in memory
3180 // and then loading it back.
3181 if (CopyVT != VA.getValVT()) {
3182 EVT ResVT = VA.getValVT();
3183 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3184 unsigned MemSize = ResVT.getSizeInBits()/8;
3185 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3186 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3189 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3190 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3191 TII.get(Opc), ResultReg + i), FI);
3195 CLI.ResultReg = ResultReg;
3196 CLI.NumResultRegs = RVLocs.size();
3203 X86FastISel::fastSelectInstruction(const Instruction *I) {
3204 switch (I->getOpcode()) {
3206 case Instruction::Load:
3207 return X86SelectLoad(I);
3208 case Instruction::Store:
3209 return X86SelectStore(I);
3210 case Instruction::Ret:
3211 return X86SelectRet(I);
3212 case Instruction::ICmp:
3213 case Instruction::FCmp:
3214 return X86SelectCmp(I);
3215 case Instruction::ZExt:
3216 return X86SelectZExt(I);
3217 case Instruction::Br:
3218 return X86SelectBranch(I);
3219 case Instruction::LShr:
3220 case Instruction::AShr:
3221 case Instruction::Shl:
3222 return X86SelectShift(I);
3223 case Instruction::SDiv:
3224 case Instruction::UDiv:
3225 case Instruction::SRem:
3226 case Instruction::URem:
3227 return X86SelectDivRem(I);
3228 case Instruction::Select:
3229 return X86SelectSelect(I);
3230 case Instruction::Trunc:
3231 return X86SelectTrunc(I);
3232 case Instruction::FPExt:
3233 return X86SelectFPExt(I);
3234 case Instruction::FPTrunc:
3235 return X86SelectFPTrunc(I);
3236 case Instruction::SIToFP:
3237 return X86SelectSIToFP(I);
3238 case Instruction::IntToPtr: // Deliberate fall-through.
3239 case Instruction::PtrToInt: {
3240 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3241 EVT DstVT = TLI.getValueType(I->getType());
3242 if (DstVT.bitsGT(SrcVT))
3243 return X86SelectZExt(I);
3244 if (DstVT.bitsLT(SrcVT))
3245 return X86SelectTrunc(I);
3246 unsigned Reg = getRegForValue(I->getOperand(0));
3247 if (Reg == 0) return false;
3248 updateValueMap(I, Reg);
3256 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3260 uint64_t Imm = CI->getZExtValue();
3262 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3263 switch (VT.SimpleTy) {
3264 default: llvm_unreachable("Unexpected value type");
3267 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3270 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3275 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3277 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3278 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3285 switch (VT.SimpleTy) {
3286 default: llvm_unreachable("Unexpected value type");
3287 case MVT::i1: VT = MVT::i8; // fall-through
3288 case MVT::i8: Opc = X86::MOV8ri; break;
3289 case MVT::i16: Opc = X86::MOV16ri; break;
3290 case MVT::i32: Opc = X86::MOV32ri; break;
3292 if (isUInt<32>(Imm))
3294 else if (isInt<32>(Imm))
3295 Opc = X86::MOV64ri32;
3301 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3302 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3303 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3305 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3306 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3309 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3312 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3313 if (CFP->isNullValue())
3314 return fastMaterializeFloatZero(CFP);
3316 // Can't handle alternate code models yet.
3317 CodeModel::Model CM = TM.getCodeModel();
3318 if (CM != CodeModel::Small && CM != CodeModel::Large)
3321 // Get opcode and regclass of the output for the given load instruction.
3323 const TargetRegisterClass *RC = nullptr;
3324 switch (VT.SimpleTy) {
3327 if (X86ScalarSSEf32) {
3328 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3329 RC = &X86::FR32RegClass;
3331 Opc = X86::LD_Fp32m;
3332 RC = &X86::RFP32RegClass;
3336 if (X86ScalarSSEf64) {
3337 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3338 RC = &X86::FR64RegClass;
3340 Opc = X86::LD_Fp64m;
3341 RC = &X86::RFP64RegClass;
3345 // No f80 support yet.
3349 // MachineConstantPool wants an explicit alignment.
3350 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3352 // Alignment of vector types. FIXME!
3353 Align = DL.getTypeAllocSize(CFP->getType());
3356 // x86-32 PIC requires a PIC base register for constant pools.
3357 unsigned PICBase = 0;
3358 unsigned char OpFlag = 0;
3359 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3360 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3361 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3362 } else if (Subtarget->isPICStyleGOT()) {
3363 OpFlag = X86II::MO_GOTOFF;
3364 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3365 } else if (Subtarget->isPICStyleRIPRel() &&
3366 TM.getCodeModel() == CodeModel::Small) {
3370 // Create the load from the constant pool.
3371 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3372 unsigned ResultReg = createResultReg(RC);
3374 if (CM == CodeModel::Large) {
3375 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3378 .addConstantPoolIndex(CPI, 0, OpFlag);
3379 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3380 TII.get(Opc), ResultReg);
3381 addDirectMem(MIB, AddrReg);
3382 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3383 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3384 TM.getDataLayout()->getPointerSize(), Align);
3385 MIB->addMemOperand(*FuncInfo.MF, MMO);
3389 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3390 TII.get(Opc), ResultReg),
3391 CPI, PICBase, OpFlag);
3395 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3396 // Can't handle alternate code models yet.
3397 if (TM.getCodeModel() != CodeModel::Small)
3400 // Materialize addresses with LEA/MOV instructions.
3402 if (X86SelectAddress(GV, AM)) {
3403 // If the expression is just a basereg, then we're done, otherwise we need
3405 if (AM.BaseType == X86AddressMode::RegBase &&
3406 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3409 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3410 if (TM.getRelocationModel() == Reloc::Static &&
3411 TLI.getPointerTy() == MVT::i64) {
3412 // The displacement code could be more than 32 bits away so we need to use
3413 // an instruction with a 64 bit immediate
3414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3416 .addGlobalAddress(GV);
3418 unsigned Opc = TLI.getPointerTy() == MVT::i32
3419 ? (Subtarget->isTarget64BitILP32()
3420 ? X86::LEA64_32r : X86::LEA32r)
3422 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3423 TII.get(Opc), ResultReg), AM);
3430 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3431 EVT CEVT = TLI.getValueType(C->getType(), true);
3433 // Only handle simple types.
3434 if (!CEVT.isSimple())
3436 MVT VT = CEVT.getSimpleVT();
3438 if (const auto *CI = dyn_cast<ConstantInt>(C))
3439 return X86MaterializeInt(CI, VT);
3440 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3441 return X86MaterializeFP(CFP, VT);
3442 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3443 return X86MaterializeGV(GV, VT);
3448 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3449 // Fail on dynamic allocas. At this point, getRegForValue has already
3450 // checked its CSE maps, so if we're here trying to handle a dynamic
3451 // alloca, we're not going to succeed. X86SelectAddress has a
3452 // check for dynamic allocas, because it's called directly from
3453 // various places, but targetMaterializeAlloca also needs a check
3454 // in order to avoid recursion between getRegForValue,
3455 // X86SelectAddrss, and targetMaterializeAlloca.
3456 if (!FuncInfo.StaticAllocaMap.count(C))
3458 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3461 if (!X86SelectAddress(C, AM))
3463 unsigned Opc = TLI.getPointerTy() == MVT::i32
3464 ? (Subtarget->isTarget64BitILP32()
3465 ? X86::LEA64_32r : X86::LEA32r)
3467 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3468 unsigned ResultReg = createResultReg(RC);
3469 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3470 TII.get(Opc), ResultReg), AM);
3474 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3476 if (!isTypeLegal(CF->getType(), VT))
3479 // Get opcode and regclass for the given zero.
3481 const TargetRegisterClass *RC = nullptr;
3482 switch (VT.SimpleTy) {
3485 if (X86ScalarSSEf32) {
3486 Opc = X86::FsFLD0SS;
3487 RC = &X86::FR32RegClass;
3489 Opc = X86::LD_Fp032;
3490 RC = &X86::RFP32RegClass;
3494 if (X86ScalarSSEf64) {
3495 Opc = X86::FsFLD0SD;
3496 RC = &X86::FR64RegClass;
3498 Opc = X86::LD_Fp064;
3499 RC = &X86::RFP64RegClass;
3503 // No f80 support yet.
3507 unsigned ResultReg = createResultReg(RC);
3508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3513 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3514 const LoadInst *LI) {
3515 const Value *Ptr = LI->getPointerOperand();
3517 if (!X86SelectAddress(Ptr, AM))
3520 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3522 unsigned Size = DL.getTypeAllocSize(LI->getType());
3523 unsigned Alignment = LI->getAlignment();
3525 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3526 Alignment = DL.getABITypeAlignment(LI->getType());
3528 SmallVector<MachineOperand, 8> AddrOps;
3529 AM.getFullAddress(AddrOps);
3531 MachineInstr *Result =
3532 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3533 Size, Alignment, /*AllowCommute=*/true);
3537 // The index register could be in the wrong register class. Unfortunately,
3538 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3539 // to just look at OpNo + the offset to the index reg. We actually need to
3540 // scan the instruction to find the index reg and see if its the correct reg
3542 for (MIOperands MO(Result); MO.isValid(); ++MO) {
3543 if (!MO->isReg() || MO->isDef() || MO->getReg() != AM.IndexReg)
3545 // Found the index reg, now try to rewrite it.
3546 unsigned OpNo = MO.getOperandNo();
3547 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3548 MO->getReg(), OpNo);
3549 if (IndexReg == MO->getReg())
3551 MO->setReg(IndexReg);
3554 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3555 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3556 MI->eraseFromParent();
3562 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3563 const TargetLibraryInfo *libInfo) {
3564 return new X86FastISel(funcInfo, libInfo);