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/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DebugInfo.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/MC/MCSymbol.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Target/TargetOptions.h"
48 class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
61 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62 const TargetLibraryInfo *libInfo)
63 : FastISel(funcInfo, libInfo) {
64 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
65 X86ScalarSSEf64 = Subtarget->hasSSE2();
66 X86ScalarSSEf32 = Subtarget->hasSSE1();
69 bool fastSelectInstruction(const Instruction *I) override;
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
82 #include "X86GenFastISel.inc"
85 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
88 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
89 unsigned &ResultReg, unsigned Alignment = 1);
91 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
92 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
95 MachineMemOperand *MMO = nullptr, bool Aligned = false);
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
103 bool X86SelectLoad(const Instruction *I);
105 bool X86SelectStore(const Instruction *I);
107 bool X86SelectRet(const Instruction *I);
109 bool X86SelectCmp(const Instruction *I);
111 bool X86SelectZExt(const Instruction *I);
113 bool X86SelectBranch(const Instruction *I);
115 bool X86SelectShift(const Instruction *I);
117 bool X86SelectDivRem(const Instruction *I);
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
125 bool X86SelectSelect(const Instruction *I);
127 bool X86SelectTrunc(const Instruction *I);
129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
134 bool X86SelectSIToFP(const Instruction *I);
136 const X86InstrInfo *getInstrInfo() const {
137 return Subtarget->getInstrInfo();
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148 unsigned fastMaterializeConstant(const Constant *C) override;
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
163 bool IsMemcpySmall(uint64_t Len);
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
175 } // end anonymous namespace.
177 static std::pair<X86::CondCode, bool>
178 getX86ConditionCode(CmpInst::Predicate Predicate) {
179 X86::CondCode CC = X86::COND_INVALID;
180 bool NeedSwap = false;
183 // Floating-point Predicates
184 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
185 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
186 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
187 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
188 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
189 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
190 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
191 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
192 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
193 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
194 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
195 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
196 case CmpInst::FCMP_OEQ: // fall-through
197 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
199 // Integer Predicates
200 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
201 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
202 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
203 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
204 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
205 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
206 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
207 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
208 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
209 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
212 return std::make_pair(CC, NeedSwap);
215 static std::pair<unsigned, bool>
216 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
218 bool NeedSwap = false;
220 // SSE Condition code mapping:
230 default: llvm_unreachable("Unexpected predicate");
231 case CmpInst::FCMP_OEQ: CC = 0; break;
232 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
233 case CmpInst::FCMP_OLT: CC = 1; break;
234 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
235 case CmpInst::FCMP_OLE: CC = 2; break;
236 case CmpInst::FCMP_UNO: CC = 3; break;
237 case CmpInst::FCMP_UNE: CC = 4; break;
238 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
239 case CmpInst::FCMP_UGE: CC = 5; break;
240 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
241 case CmpInst::FCMP_UGT: CC = 6; break;
242 case CmpInst::FCMP_ORD: CC = 7; break;
243 case CmpInst::FCMP_UEQ:
244 case CmpInst::FCMP_ONE: CC = 8; break;
247 return std::make_pair(CC, NeedSwap);
250 /// \brief Adds a complex addressing mode to the given machine instr builder.
251 /// Note, this will constrain the index register. If its not possible to
252 /// constrain the given index register, then a new one will be created. The
253 /// IndexReg field of the addressing mode will be updated to match in this case.
254 const MachineInstrBuilder &
255 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
256 X86AddressMode &AM) {
257 // First constrain the index register. It needs to be a GR64_NOSP.
258 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
259 MIB->getNumOperands() +
261 return ::addFullAddress(MIB, AM);
264 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
265 /// into the user. The condition code will only be updated on success.
266 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
268 if (!isa<ExtractValueInst>(Cond))
271 const auto *EV = cast<ExtractValueInst>(Cond);
272 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
275 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
277 const Function *Callee = II->getCalledFunction();
279 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
280 if (!isTypeLegal(RetTy, RetVT))
283 if (RetVT != MVT::i32 && RetVT != MVT::i64)
287 switch (II->getIntrinsicID()) {
288 default: return false;
289 case Intrinsic::sadd_with_overflow:
290 case Intrinsic::ssub_with_overflow:
291 case Intrinsic::smul_with_overflow:
292 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
293 case Intrinsic::uadd_with_overflow:
294 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
297 // Check if both instructions are in the same basic block.
298 if (II->getParent() != I->getParent())
301 // Make sure nothing is in the way
302 BasicBlock::const_iterator Start(I);
303 BasicBlock::const_iterator End(II);
304 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
305 // We only expect extractvalue instructions between the intrinsic and the
306 // instruction to be selected.
307 if (!isa<ExtractValueInst>(Itr))
310 // Check that the extractvalue operand comes from the intrinsic.
311 const auto *EVI = cast<ExtractValueInst>(Itr);
312 if (EVI->getAggregateOperand() != II)
320 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
321 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
322 if (evt == MVT::Other || !evt.isSimple())
323 // Unhandled type. Halt "fast" selection and bail.
326 VT = evt.getSimpleVT();
327 // For now, require SSE/SSE2 for performing floating-point operations,
328 // since x87 requires additional work.
329 if (VT == MVT::f64 && !X86ScalarSSEf64)
331 if (VT == MVT::f32 && !X86ScalarSSEf32)
333 // Similarly, no f80 support yet.
336 // We only handle legal types. For example, on x86-32 the instruction
337 // selector contains all of the 64-bit instructions from x86-64,
338 // under the assumption that i64 won't be used if the target doesn't
340 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
343 #include "X86GenCallingConv.inc"
345 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
346 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
347 /// Return true and the result register by reference if it is possible.
348 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
349 MachineMemOperand *MMO, unsigned &ResultReg,
350 unsigned Alignment) {
351 bool HasSSE41 = Subtarget->hasSSE41();
352 bool HasAVX = Subtarget->hasAVX();
353 bool HasAVX2 = Subtarget->hasAVX2();
354 bool IsNonTemporal = MMO && MMO->isNonTemporal();
356 // Get opcode and regclass of the output for the given load instruction.
358 const TargetRegisterClass *RC = nullptr;
359 switch (VT.getSimpleVT().SimpleTy) {
360 default: return false;
364 RC = &X86::GR8RegClass;
368 RC = &X86::GR16RegClass;
372 RC = &X86::GR32RegClass;
375 // Must be in x86-64 mode.
377 RC = &X86::GR64RegClass;
380 if (X86ScalarSSEf32) {
381 Opc = HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
382 RC = &X86::FR32RegClass;
385 RC = &X86::RFP32RegClass;
389 if (X86ScalarSSEf64) {
390 Opc = HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
391 RC = &X86::FR64RegClass;
394 RC = &X86::RFP64RegClass;
398 // No f80 support yet.
401 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
402 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
403 else if (Alignment >= 16)
404 Opc = HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
406 Opc = HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
407 RC = &X86::VR128RegClass;
410 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
411 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
412 else if (Alignment >= 16)
413 Opc = HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
415 Opc = HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
416 RC = &X86::VR128RegClass;
422 if (IsNonTemporal && Alignment >= 16)
423 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
424 else if (Alignment >= 16)
425 Opc = HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
427 Opc = HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
428 RC = &X86::VR128RegClass;
432 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
433 Opc = X86::VMOVNTDQAYrm;
435 Opc = (Alignment >= 32) ? X86::VMOVAPSYrm : X86::VMOVUPSYrm;
436 RC = &X86::VR256RegClass;
440 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
441 Opc = X86::VMOVNTDQAYrm;
443 Opc = (Alignment >= 32) ? X86::VMOVAPDYrm : X86::VMOVUPDYrm;
444 RC = &X86::VR256RegClass;
451 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
452 Opc = X86::VMOVNTDQAYrm;
454 Opc = (Alignment >= 32) ? X86::VMOVDQAYrm : X86::VMOVDQUYrm;
455 RC = &X86::VR256RegClass;
458 assert(Subtarget->hasAVX512());
459 if (IsNonTemporal && Alignment >= 64)
460 Opc = X86::VMOVNTDQAZrm;
462 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
463 RC = &X86::VR512RegClass;
466 assert(Subtarget->hasAVX512());
467 if (IsNonTemporal && Alignment >= 64)
468 Opc = X86::VMOVNTDQAZrm;
470 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
471 RC = &X86::VR512RegClass;
477 assert(Subtarget->hasAVX512());
478 // Note: There are a lot more choices based on type with AVX-512, but
479 // there's really no advantage when the load isn't masked.
480 if (IsNonTemporal && Alignment >= 64)
481 Opc = X86::VMOVNTDQAZrm;
483 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
484 RC = &X86::VR512RegClass;
488 ResultReg = createResultReg(RC);
489 MachineInstrBuilder MIB =
490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
491 addFullAddress(MIB, AM);
493 MIB->addMemOperand(*FuncInfo.MF, MMO);
497 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
498 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
499 /// and a displacement offset, or a GlobalAddress,
500 /// i.e. V. Return true if it is possible.
501 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
503 MachineMemOperand *MMO, bool Aligned) {
504 bool HasSSE2 = Subtarget->hasSSE2();
505 bool HasSSE4A = Subtarget->hasSSE4A();
506 bool HasAVX = Subtarget->hasAVX();
507 bool IsNonTemporal = MMO && MMO->isNonTemporal();
509 // Get opcode and regclass of the output for the given store instruction.
511 switch (VT.getSimpleVT().SimpleTy) {
512 case MVT::f80: // No f80 support yet.
513 default: return false;
515 // Mask out all but lowest bit.
516 unsigned AndResult = createResultReg(&X86::GR8RegClass);
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
518 TII.get(X86::AND8ri), AndResult)
519 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
522 // FALLTHROUGH, handling i1 as i8.
523 case MVT::i8: Opc = X86::MOV8mr; break;
524 case MVT::i16: Opc = X86::MOV16mr; break;
526 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
529 // Must be in x86-64 mode.
530 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
533 if (X86ScalarSSEf32) {
534 if (IsNonTemporal && HasSSE4A)
537 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
542 if (X86ScalarSSEf32) {
543 if (IsNonTemporal && HasSSE4A)
546 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
553 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
555 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
557 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
562 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
564 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
566 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
574 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
576 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
578 Opc = HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
583 Opc = IsNonTemporal ? X86::VMOVNTPSYmr : X86::VMOVAPSYmr;
585 Opc = X86::VMOVUPSYmr;
590 Opc = IsNonTemporal ? X86::VMOVNTPDYmr : X86::VMOVAPDYmr;
592 Opc = X86::VMOVUPDYmr;
600 Opc = IsNonTemporal ? X86::VMOVNTDQYmr : X86::VMOVDQAYmr;
602 Opc = X86::VMOVDQUYmr;
605 assert(Subtarget->hasAVX512());
607 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
609 Opc = X86::VMOVUPSZmr;
612 assert(Subtarget->hasAVX512());
614 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
616 Opc = X86::VMOVUPDZmr;
622 assert(Subtarget->hasAVX512());
623 // Note: There are a lot more choices based on type with AVX-512, but
624 // there's really no advantage when the store isn't masked.
626 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
628 Opc = X86::VMOVDQU64Zmr;
632 const MCInstrDesc &Desc = TII.get(Opc);
633 // Some of the instructions in the previous switch use FR128 instead
634 // of FR32 for ValReg. Make sure the register we feed the instruction
635 // matches its register class constraints.
636 // Note: This is fine to do a copy from FR32 to FR128, this is the
637 // same registers behind the scene and actually why it did not trigger
639 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
640 MachineInstrBuilder MIB =
641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
642 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
644 MIB->addMemOperand(*FuncInfo.MF, MMO);
649 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
651 MachineMemOperand *MMO, bool Aligned) {
652 // Handle 'null' like i32/i64 0.
653 if (isa<ConstantPointerNull>(Val))
654 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
656 // If this is a store of a simple constant, fold the constant into the store.
657 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
660 switch (VT.getSimpleVT().SimpleTy) {
662 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
663 case MVT::i8: Opc = X86::MOV8mi; break;
664 case MVT::i16: Opc = X86::MOV16mi; break;
665 case MVT::i32: Opc = X86::MOV32mi; break;
667 // Must be a 32-bit sign extended value.
668 if (isInt<32>(CI->getSExtValue()))
669 Opc = X86::MOV64mi32;
674 MachineInstrBuilder MIB =
675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
676 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
677 : CI->getZExtValue());
679 MIB->addMemOperand(*FuncInfo.MF, MMO);
684 unsigned ValReg = getRegForValue(Val);
688 bool ValKill = hasTrivialKill(Val);
689 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
692 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
693 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
694 /// ISD::SIGN_EXTEND).
695 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
696 unsigned Src, EVT SrcVT,
697 unsigned &ResultReg) {
698 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
699 Src, /*TODO: Kill=*/false);
707 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
708 // Handle constant address.
709 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
710 // Can't handle alternate code models yet.
711 if (TM.getCodeModel() != CodeModel::Small)
714 // Can't handle TLS yet.
715 if (GV->isThreadLocal())
718 // RIP-relative addresses can't have additional register operands, so if
719 // we've already folded stuff into the addressing mode, just force the
720 // global value into its own register, which we can use as the basereg.
721 if (!Subtarget->isPICStyleRIPRel() ||
722 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
723 // Okay, we've committed to selecting this global. Set up the address.
726 // Allow the subtarget to classify the global.
727 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
729 // If this reference is relative to the pic base, set it now.
730 if (isGlobalRelativeToPICBase(GVFlags)) {
731 // FIXME: How do we know Base.Reg is free??
732 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
735 // Unless the ABI requires an extra load, return a direct reference to
737 if (!isGlobalStubReference(GVFlags)) {
738 if (Subtarget->isPICStyleRIPRel()) {
739 // Use rip-relative addressing if we can. Above we verified that the
740 // base and index registers are unused.
741 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
742 AM.Base.Reg = X86::RIP;
744 AM.GVOpFlags = GVFlags;
748 // Ok, we need to do a load from a stub. If we've already loaded from
749 // this stub, reuse the loaded pointer, otherwise emit the load now.
750 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
752 if (I != LocalValueMap.end() && I->second != 0) {
755 // Issue load from stub.
757 const TargetRegisterClass *RC = nullptr;
758 X86AddressMode StubAM;
759 StubAM.Base.Reg = AM.Base.Reg;
761 StubAM.GVOpFlags = GVFlags;
763 // Prepare for inserting code in the local-value area.
764 SavePoint SaveInsertPt = enterLocalValueArea();
766 if (TLI.getPointerTy(DL) == MVT::i64) {
768 RC = &X86::GR64RegClass;
770 if (Subtarget->isPICStyleRIPRel())
771 StubAM.Base.Reg = X86::RIP;
774 RC = &X86::GR32RegClass;
777 LoadReg = createResultReg(RC);
778 MachineInstrBuilder LoadMI =
779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
780 addFullAddress(LoadMI, StubAM);
782 // Ok, back to normal mode.
783 leaveLocalValueArea(SaveInsertPt);
785 // Prevent loading GV stub multiple times in same MBB.
786 LocalValueMap[V] = LoadReg;
789 // Now construct the final address. Note that the Disp, Scale,
790 // and Index values may already be set here.
791 AM.Base.Reg = LoadReg;
797 // If all else fails, try to materialize the value in a register.
798 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
799 if (AM.Base.Reg == 0) {
800 AM.Base.Reg = getRegForValue(V);
801 return AM.Base.Reg != 0;
803 if (AM.IndexReg == 0) {
804 assert(AM.Scale == 1 && "Scale with no index!");
805 AM.IndexReg = getRegForValue(V);
806 return AM.IndexReg != 0;
813 /// X86SelectAddress - Attempt to fill in an address from the given value.
815 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
816 SmallVector<const Value *, 32> GEPs;
818 const User *U = nullptr;
819 unsigned Opcode = Instruction::UserOp1;
820 if (const Instruction *I = dyn_cast<Instruction>(V)) {
821 // Don't walk into other basic blocks; it's possible we haven't
822 // visited them yet, so the instructions may not yet be assigned
823 // virtual registers.
824 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
825 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
826 Opcode = I->getOpcode();
829 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
830 Opcode = C->getOpcode();
834 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
835 if (Ty->getAddressSpace() > 255)
836 // Fast instruction selection doesn't support the special
842 case Instruction::BitCast:
843 // Look past bitcasts.
844 return X86SelectAddress(U->getOperand(0), AM);
846 case Instruction::IntToPtr:
847 // Look past no-op inttoptrs.
848 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
849 TLI.getPointerTy(DL))
850 return X86SelectAddress(U->getOperand(0), AM);
853 case Instruction::PtrToInt:
854 // Look past no-op ptrtoints.
855 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
856 return X86SelectAddress(U->getOperand(0), AM);
859 case Instruction::Alloca: {
860 // Do static allocas.
861 const AllocaInst *A = cast<AllocaInst>(V);
862 DenseMap<const AllocaInst *, int>::iterator SI =
863 FuncInfo.StaticAllocaMap.find(A);
864 if (SI != FuncInfo.StaticAllocaMap.end()) {
865 AM.BaseType = X86AddressMode::FrameIndexBase;
866 AM.Base.FrameIndex = SI->second;
872 case Instruction::Add: {
873 // Adds of constants are common and easy enough.
874 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
875 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
876 // They have to fit in the 32-bit signed displacement field though.
877 if (isInt<32>(Disp)) {
878 AM.Disp = (uint32_t)Disp;
879 return X86SelectAddress(U->getOperand(0), AM);
885 case Instruction::GetElementPtr: {
886 X86AddressMode SavedAM = AM;
888 // Pattern-match simple GEPs.
889 uint64_t Disp = (int32_t)AM.Disp;
890 unsigned IndexReg = AM.IndexReg;
891 unsigned Scale = AM.Scale;
892 gep_type_iterator GTI = gep_type_begin(U);
893 // Iterate through the indices, folding what we can. Constants can be
894 // folded, and one dynamic index can be handled, if the scale is supported.
895 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
896 i != e; ++i, ++GTI) {
897 const Value *Op = *i;
898 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
899 const StructLayout *SL = DL.getStructLayout(STy);
900 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
904 // A array/variable index is always of the form i*S where S is the
905 // constant scale size. See if we can push the scale into immediates.
906 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
908 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
909 // Constant-offset addressing.
910 Disp += CI->getSExtValue() * S;
913 if (canFoldAddIntoGEP(U, Op)) {
914 // A compatible add with a constant operand. Fold the constant.
916 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
917 Disp += CI->getSExtValue() * S;
918 // Iterate on the other operand.
919 Op = cast<AddOperator>(Op)->getOperand(0);
923 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
924 (S == 1 || S == 2 || S == 4 || S == 8)) {
925 // Scaled-index addressing.
927 IndexReg = getRegForGEPIndex(Op).first;
933 goto unsupported_gep;
937 // Check for displacement overflow.
938 if (!isInt<32>(Disp))
941 AM.IndexReg = IndexReg;
943 AM.Disp = (uint32_t)Disp;
946 if (const GetElementPtrInst *GEP =
947 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
948 // Ok, the GEP indices were covered by constant-offset and scaled-index
949 // addressing. Update the address state and move on to examining the base.
952 } else if (X86SelectAddress(U->getOperand(0), AM)) {
956 // If we couldn't merge the gep value into this addr mode, revert back to
957 // our address and just match the value instead of completely failing.
960 for (const Value *I : reverse(GEPs))
961 if (handleConstantAddresses(I, AM))
966 // Ok, the GEP indices weren't all covered.
971 return handleConstantAddresses(V, AM);
974 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
976 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
977 const User *U = nullptr;
978 unsigned Opcode = Instruction::UserOp1;
979 const Instruction *I = dyn_cast<Instruction>(V);
980 // Record if the value is defined in the same basic block.
982 // This information is crucial to know whether or not folding an
984 // Indeed, FastISel generates or reuses a virtual register for all
985 // operands of all instructions it selects. Obviously, the definition and
986 // its uses must use the same virtual register otherwise the produced
987 // code is incorrect.
988 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
989 // registers for values that are alive across basic blocks. This ensures
990 // that the values are consistently set between across basic block, even
991 // if different instruction selection mechanisms are used (e.g., a mix of
992 // SDISel and FastISel).
993 // For values local to a basic block, the instruction selection process
994 // generates these virtual registers with whatever method is appropriate
995 // for its needs. In particular, FastISel and SDISel do not share the way
996 // local virtual registers are set.
997 // Therefore, this is impossible (or at least unsafe) to share values
998 // between basic blocks unless they use the same instruction selection
999 // method, which is not guarantee for X86.
1000 // Moreover, things like hasOneUse could not be used accurately, if we
1001 // allow to reference values across basic blocks whereas they are not
1002 // alive across basic blocks initially.
1005 Opcode = I->getOpcode();
1007 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1008 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1009 Opcode = C->getOpcode();
1015 case Instruction::BitCast:
1016 // Look past bitcasts if its operand is in the same BB.
1018 return X86SelectCallAddress(U->getOperand(0), AM);
1021 case Instruction::IntToPtr:
1022 // Look past no-op inttoptrs if its operand is in the same BB.
1024 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1025 TLI.getPointerTy(DL))
1026 return X86SelectCallAddress(U->getOperand(0), AM);
1029 case Instruction::PtrToInt:
1030 // Look past no-op ptrtoints if its operand is in the same BB.
1031 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1032 return X86SelectCallAddress(U->getOperand(0), AM);
1036 // Handle constant address.
1037 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1038 // Can't handle alternate code models yet.
1039 if (TM.getCodeModel() != CodeModel::Small)
1042 // RIP-relative addresses can't have additional register operands.
1043 if (Subtarget->isPICStyleRIPRel() &&
1044 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1047 // Can't handle DLL Import.
1048 if (GV->hasDLLImportStorageClass())
1051 // Can't handle TLS.
1052 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1053 if (GVar->isThreadLocal())
1056 // Okay, we've committed to selecting this global. Set up the basic address.
1059 // No ABI requires an extra load for anything other than DLLImport, which
1060 // we rejected above. Return a direct reference to the global.
1061 if (Subtarget->isPICStyleRIPRel()) {
1062 // Use rip-relative addressing if we can. Above we verified that the
1063 // base and index registers are unused.
1064 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1065 AM.Base.Reg = X86::RIP;
1067 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1073 // If all else fails, try to materialize the value in a register.
1074 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1075 if (AM.Base.Reg == 0) {
1076 AM.Base.Reg = getRegForValue(V);
1077 return AM.Base.Reg != 0;
1079 if (AM.IndexReg == 0) {
1080 assert(AM.Scale == 1 && "Scale with no index!");
1081 AM.IndexReg = getRegForValue(V);
1082 return AM.IndexReg != 0;
1090 /// X86SelectStore - Select and emit code to implement store instructions.
1091 bool X86FastISel::X86SelectStore(const Instruction *I) {
1092 // Atomic stores need special handling.
1093 const StoreInst *S = cast<StoreInst>(I);
1098 const Value *PtrV = I->getOperand(1);
1099 if (TLI.supportSwiftError()) {
1100 // Swifterror values can come from either a function parameter with
1101 // swifterror attribute or an alloca with swifterror attribute.
1102 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1103 if (Arg->hasSwiftErrorAttr())
1107 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1108 if (Alloca->isSwiftError())
1113 const Value *Val = S->getValueOperand();
1114 const Value *Ptr = S->getPointerOperand();
1117 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1120 unsigned Alignment = S->getAlignment();
1121 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1122 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1123 Alignment = ABIAlignment;
1124 bool Aligned = Alignment >= ABIAlignment;
1127 if (!X86SelectAddress(Ptr, AM))
1130 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1133 /// X86SelectRet - Select and emit code to implement ret instructions.
1134 bool X86FastISel::X86SelectRet(const Instruction *I) {
1135 const ReturnInst *Ret = cast<ReturnInst>(I);
1136 const Function &F = *I->getParent()->getParent();
1137 const X86MachineFunctionInfo *X86MFInfo =
1138 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1140 if (!FuncInfo.CanLowerReturn)
1143 if (TLI.supportSwiftError() &&
1144 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1147 if (TLI.supportSplitCSR(FuncInfo.MF))
1150 CallingConv::ID CC = F.getCallingConv();
1151 if (CC != CallingConv::C &&
1152 CC != CallingConv::Fast &&
1153 CC != CallingConv::X86_FastCall &&
1154 CC != CallingConv::X86_StdCall &&
1155 CC != CallingConv::X86_ThisCall &&
1156 CC != CallingConv::X86_64_SysV &&
1157 CC != CallingConv::X86_64_Win64)
1160 // Don't handle popping bytes if they don't fit the ret's immediate.
1161 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1164 // fastcc with -tailcallopt is intended to provide a guaranteed
1165 // tail call optimization. Fastisel doesn't know how to do that.
1166 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1169 // Let SDISel handle vararg functions.
1173 // Build a list of return value registers.
1174 SmallVector<unsigned, 4> RetRegs;
1176 if (Ret->getNumOperands() > 0) {
1177 SmallVector<ISD::OutputArg, 4> Outs;
1178 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1180 // Analyze operands of the call, assigning locations to each operand.
1181 SmallVector<CCValAssign, 16> ValLocs;
1182 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1183 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1185 const Value *RV = Ret->getOperand(0);
1186 unsigned Reg = getRegForValue(RV);
1190 // Only handle a single return value for now.
1191 if (ValLocs.size() != 1)
1194 CCValAssign &VA = ValLocs[0];
1196 // Don't bother handling odd stuff for now.
1197 if (VA.getLocInfo() != CCValAssign::Full)
1199 // Only handle register returns for now.
1203 // The calling-convention tables for x87 returns don't tell
1205 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1208 unsigned SrcReg = Reg + VA.getValNo();
1209 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1210 EVT DstVT = VA.getValVT();
1211 // Special handling for extended integers.
1212 if (SrcVT != DstVT) {
1213 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1216 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1219 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1221 if (SrcVT == MVT::i1) {
1222 if (Outs[0].Flags.isSExt())
1224 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1227 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1229 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1230 SrcReg, /*TODO: Kill=*/false);
1234 unsigned DstReg = VA.getLocReg();
1235 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1236 // Avoid a cross-class copy. This is very unlikely.
1237 if (!SrcRC->contains(DstReg))
1239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1240 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1242 // Add register to return instruction.
1243 RetRegs.push_back(VA.getLocReg());
1246 // Swift calling convention does not require we copy the sret argument
1247 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1249 // All x86 ABIs require that for returning structs by value we copy
1250 // the sret argument into %rax/%eax (depending on ABI) for the return.
1251 // We saved the argument into a virtual register in the entry block,
1252 // so now we copy the value out and into %rax/%eax.
1253 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
1254 unsigned Reg = X86MFInfo->getSRetReturnReg();
1256 "SRetReturnReg should have been set in LowerFormalArguments()!");
1257 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1259 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1260 RetRegs.push_back(RetReg);
1263 // Now emit the RET.
1264 MachineInstrBuilder MIB;
1265 if (X86MFInfo->getBytesToPopOnReturn()) {
1266 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1267 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1268 .addImm(X86MFInfo->getBytesToPopOnReturn());
1270 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1271 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1273 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1274 MIB.addReg(RetRegs[i], RegState::Implicit);
1278 /// X86SelectLoad - Select and emit code to implement load instructions.
1280 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1281 const LoadInst *LI = cast<LoadInst>(I);
1283 // Atomic loads need special handling.
1287 const Value *SV = I->getOperand(0);
1288 if (TLI.supportSwiftError()) {
1289 // Swifterror values can come from either a function parameter with
1290 // swifterror attribute or an alloca with swifterror attribute.
1291 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1292 if (Arg->hasSwiftErrorAttr())
1296 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1297 if (Alloca->isSwiftError())
1303 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1306 const Value *Ptr = LI->getPointerOperand();
1309 if (!X86SelectAddress(Ptr, AM))
1312 unsigned Alignment = LI->getAlignment();
1313 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1314 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1315 Alignment = ABIAlignment;
1317 unsigned ResultReg = 0;
1318 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1322 updateValueMap(I, ResultReg);
1326 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1327 bool HasAVX = Subtarget->hasAVX();
1328 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1329 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1331 switch (VT.getSimpleVT().SimpleTy) {
1333 case MVT::i8: return X86::CMP8rr;
1334 case MVT::i16: return X86::CMP16rr;
1335 case MVT::i32: return X86::CMP32rr;
1336 case MVT::i64: return X86::CMP64rr;
1338 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1340 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1344 /// If we have a comparison with RHS as the RHS of the comparison, return an
1345 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1346 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1347 int64_t Val = RHSC->getSExtValue();
1348 switch (VT.getSimpleVT().SimpleTy) {
1349 // Otherwise, we can't fold the immediate into this comparison.
1356 return X86::CMP16ri8;
1357 return X86::CMP16ri;
1360 return X86::CMP32ri8;
1361 return X86::CMP32ri;
1364 return X86::CMP64ri8;
1365 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1368 return X86::CMP64ri32;
1373 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1374 const DebugLoc &CurDbgLoc) {
1375 unsigned Op0Reg = getRegForValue(Op0);
1376 if (Op0Reg == 0) return false;
1378 // Handle 'null' like i32/i64 0.
1379 if (isa<ConstantPointerNull>(Op1))
1380 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1382 // We have two options: compare with register or immediate. If the RHS of
1383 // the compare is an immediate that we can fold into this compare, use
1384 // CMPri, otherwise use CMPrr.
1385 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1386 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1387 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1389 .addImm(Op1C->getSExtValue());
1394 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1395 if (CompareOpc == 0) return false;
1397 unsigned Op1Reg = getRegForValue(Op1);
1398 if (Op1Reg == 0) return false;
1399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1406 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1407 const CmpInst *CI = cast<CmpInst>(I);
1410 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1413 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1416 // Try to optimize or fold the cmp.
1417 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1418 unsigned ResultReg = 0;
1419 switch (Predicate) {
1421 case CmpInst::FCMP_FALSE: {
1422 ResultReg = createResultReg(&X86::GR32RegClass);
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1425 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1431 case CmpInst::FCMP_TRUE: {
1432 ResultReg = createResultReg(&X86::GR8RegClass);
1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1434 ResultReg).addImm(1);
1440 updateValueMap(I, ResultReg);
1444 const Value *LHS = CI->getOperand(0);
1445 const Value *RHS = CI->getOperand(1);
1447 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1448 // We don't have to materialize a zero constant for this case and can just use
1449 // %x again on the RHS.
1450 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1451 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1452 if (RHSC && RHSC->isNullValue())
1456 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1457 static unsigned SETFOpcTable[2][3] = {
1458 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1459 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1461 unsigned *SETFOpc = nullptr;
1462 switch (Predicate) {
1464 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1465 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1468 ResultReg = createResultReg(&X86::GR8RegClass);
1470 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1473 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1474 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1480 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1481 updateValueMap(I, ResultReg);
1487 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1488 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1489 unsigned Opc = X86::getSETFromCond(CC);
1492 std::swap(LHS, RHS);
1494 // Emit a compare of LHS/RHS.
1495 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1499 updateValueMap(I, ResultReg);
1503 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1504 EVT DstVT = TLI.getValueType(DL, I->getType());
1505 if (!TLI.isTypeLegal(DstVT))
1508 unsigned ResultReg = getRegForValue(I->getOperand(0));
1512 // Handle zero-extension from i1 to i8, which is common.
1513 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1514 if (SrcVT.SimpleTy == MVT::i1) {
1515 // Set the high bits to zero.
1516 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1523 if (DstVT == MVT::i64) {
1524 // Handle extension to 64-bits via sub-register shenanigans.
1527 switch (SrcVT.SimpleTy) {
1528 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1529 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1530 case MVT::i32: MovInst = X86::MOV32rr; break;
1531 default: llvm_unreachable("Unexpected zext to i64 source type");
1534 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1535 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1538 ResultReg = createResultReg(&X86::GR64RegClass);
1539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1541 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1542 } else if (DstVT != MVT::i8) {
1543 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1544 ResultReg, /*Kill=*/true);
1549 updateValueMap(I, ResultReg);
1553 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1554 // Unconditional branches are selected by tablegen-generated code.
1555 // Handle a conditional branch.
1556 const BranchInst *BI = cast<BranchInst>(I);
1557 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1558 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1560 // Fold the common case of a conditional branch with a comparison
1561 // in the same block (values defined on other blocks may not have
1562 // initialized registers).
1564 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1565 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1566 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1568 // Try to optimize or fold the cmp.
1569 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1570 switch (Predicate) {
1572 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1573 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1576 const Value *CmpLHS = CI->getOperand(0);
1577 const Value *CmpRHS = CI->getOperand(1);
1579 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1581 // We don't have to materialize a zero constant for this case and can just
1582 // use %x again on the RHS.
1583 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1584 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1585 if (CmpRHSC && CmpRHSC->isNullValue())
1589 // Try to take advantage of fallthrough opportunities.
1590 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1591 std::swap(TrueMBB, FalseMBB);
1592 Predicate = CmpInst::getInversePredicate(Predicate);
1595 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1596 // code check. Instead two branch instructions are required to check all
1597 // the flags. First we change the predicate to a supported condition code,
1598 // which will be the first branch. Later one we will emit the second
1600 bool NeedExtraBranch = false;
1601 switch (Predicate) {
1603 case CmpInst::FCMP_OEQ:
1604 std::swap(TrueMBB, FalseMBB); // fall-through
1605 case CmpInst::FCMP_UNE:
1606 NeedExtraBranch = true;
1607 Predicate = CmpInst::FCMP_ONE;
1613 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1614 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1616 BranchOpc = X86::GetCondBranchFromCond(CC);
1618 std::swap(CmpLHS, CmpRHS);
1620 // Emit a compare of the LHS and RHS, setting the flags.
1621 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1627 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1629 if (NeedExtraBranch) {
1630 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1634 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1637 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1638 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1639 // typically happen for _Bool and C++ bools.
1641 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1642 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1643 unsigned TestOpc = 0;
1644 switch (SourceVT.SimpleTy) {
1646 case MVT::i8: TestOpc = X86::TEST8ri; break;
1647 case MVT::i16: TestOpc = X86::TEST16ri; break;
1648 case MVT::i32: TestOpc = X86::TEST32ri; break;
1649 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1652 unsigned OpReg = getRegForValue(TI->getOperand(0));
1653 if (OpReg == 0) return false;
1654 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1655 .addReg(OpReg).addImm(1);
1657 unsigned JmpOpc = X86::JNE_1;
1658 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1659 std::swap(TrueMBB, FalseMBB);
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1666 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1670 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1671 // Fake request the condition, otherwise the intrinsic might be completely
1673 unsigned TmpReg = getRegForValue(BI->getCondition());
1677 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1681 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1685 // Otherwise do a clumsy setcc and re-test it.
1686 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1687 // in an explicit cast, so make sure to handle that correctly.
1688 unsigned OpReg = getRegForValue(BI->getCondition());
1689 if (OpReg == 0) return false;
1691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1692 .addReg(OpReg).addImm(1);
1693 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1695 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1699 bool X86FastISel::X86SelectShift(const Instruction *I) {
1700 unsigned CReg = 0, OpReg = 0;
1701 const TargetRegisterClass *RC = nullptr;
1702 if (I->getType()->isIntegerTy(8)) {
1704 RC = &X86::GR8RegClass;
1705 switch (I->getOpcode()) {
1706 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1707 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1708 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1709 default: return false;
1711 } else if (I->getType()->isIntegerTy(16)) {
1713 RC = &X86::GR16RegClass;
1714 switch (I->getOpcode()) {
1715 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1716 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1717 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1718 default: return false;
1720 } else if (I->getType()->isIntegerTy(32)) {
1722 RC = &X86::GR32RegClass;
1723 switch (I->getOpcode()) {
1724 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1725 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1726 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1727 default: return false;
1729 } else if (I->getType()->isIntegerTy(64)) {
1731 RC = &X86::GR64RegClass;
1732 switch (I->getOpcode()) {
1733 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1734 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1735 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1736 default: return false;
1743 if (!isTypeLegal(I->getType(), VT))
1746 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1747 if (Op0Reg == 0) return false;
1749 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1750 if (Op1Reg == 0) return false;
1751 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1752 CReg).addReg(Op1Reg);
1754 // The shift instruction uses X86::CL. If we defined a super-register
1755 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1756 if (CReg != X86::CL)
1757 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1758 TII.get(TargetOpcode::KILL), X86::CL)
1759 .addReg(CReg, RegState::Kill);
1761 unsigned ResultReg = createResultReg(RC);
1762 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1764 updateValueMap(I, ResultReg);
1768 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1769 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1770 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1771 const static bool S = true; // IsSigned
1772 const static bool U = false; // !IsSigned
1773 const static unsigned Copy = TargetOpcode::COPY;
1774 // For the X86 DIV/IDIV instruction, in most cases the dividend
1775 // (numerator) must be in a specific register pair highreg:lowreg,
1776 // producing the quotient in lowreg and the remainder in highreg.
1777 // For most data types, to set up the instruction, the dividend is
1778 // copied into lowreg, and lowreg is sign-extended or zero-extended
1779 // into highreg. The exception is i8, where the dividend is defined
1780 // as a single register rather than a register pair, and we
1781 // therefore directly sign-extend or zero-extend the dividend into
1782 // lowreg, instead of copying, and ignore the highreg.
1783 const static struct DivRemEntry {
1784 // The following portion depends only on the data type.
1785 const TargetRegisterClass *RC;
1786 unsigned LowInReg; // low part of the register pair
1787 unsigned HighInReg; // high part of the register pair
1788 // The following portion depends on both the data type and the operation.
1789 struct DivRemResult {
1790 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1791 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1792 // highreg, or copying a zero into highreg.
1793 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1794 // zero/sign-extending into lowreg for i8.
1795 unsigned DivRemResultReg; // Register containing the desired result.
1796 bool IsOpSigned; // Whether to use signed or unsigned form.
1797 } ResultTable[NumOps];
1798 } OpTable[NumTypes] = {
1799 { &X86::GR8RegClass, X86::AX, 0, {
1800 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1801 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1802 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1803 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1806 { &X86::GR16RegClass, X86::AX, X86::DX, {
1807 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1808 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1809 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1810 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1813 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1814 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1815 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1816 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1817 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1820 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1821 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1822 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1823 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1824 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1830 if (!isTypeLegal(I->getType(), VT))
1833 unsigned TypeIndex, OpIndex;
1834 switch (VT.SimpleTy) {
1835 default: return false;
1836 case MVT::i8: TypeIndex = 0; break;
1837 case MVT::i16: TypeIndex = 1; break;
1838 case MVT::i32: TypeIndex = 2; break;
1839 case MVT::i64: TypeIndex = 3;
1840 if (!Subtarget->is64Bit())
1845 switch (I->getOpcode()) {
1846 default: llvm_unreachable("Unexpected div/rem opcode");
1847 case Instruction::SDiv: OpIndex = 0; break;
1848 case Instruction::SRem: OpIndex = 1; break;
1849 case Instruction::UDiv: OpIndex = 2; break;
1850 case Instruction::URem: OpIndex = 3; break;
1853 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1854 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1855 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1858 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1862 // Move op0 into low-order input register.
1863 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1864 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1865 // Zero-extend or sign-extend into high-order input register.
1866 if (OpEntry.OpSignExtend) {
1867 if (OpEntry.IsOpSigned)
1868 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1869 TII.get(OpEntry.OpSignExtend));
1871 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1873 TII.get(X86::MOV32r0), Zero32);
1875 // Copy the zero into the appropriate sub/super/identical physical
1876 // register. Unfortunately the operations needed are not uniform enough
1877 // to fit neatly into the table above.
1878 if (VT.SimpleTy == MVT::i16) {
1879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1880 TII.get(Copy), TypeEntry.HighInReg)
1881 .addReg(Zero32, 0, X86::sub_16bit);
1882 } else if (VT.SimpleTy == MVT::i32) {
1883 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1884 TII.get(Copy), TypeEntry.HighInReg)
1886 } else if (VT.SimpleTy == MVT::i64) {
1887 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1888 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1889 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1893 // Generate the DIV/IDIV instruction.
1894 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1895 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1896 // For i8 remainder, we can't reference AH directly, as we'll end
1897 // up with bogus copies like %R9B = COPY %AH. Reference AX
1898 // instead to prevent AH references in a REX instruction.
1900 // The current assumption of the fast register allocator is that isel
1901 // won't generate explicit references to the GPR8_NOREX registers. If
1902 // the allocator and/or the backend get enhanced to be more robust in
1903 // that regard, this can be, and should be, removed.
1904 unsigned ResultReg = 0;
1905 if ((I->getOpcode() == Instruction::SRem ||
1906 I->getOpcode() == Instruction::URem) &&
1907 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1908 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1909 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1910 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1911 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1913 // Shift AX right by 8 bits instead of using AH.
1914 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1915 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1917 // Now reference the 8-bit subreg of the result.
1918 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1919 /*Kill=*/true, X86::sub_8bit);
1921 // Copy the result out of the physreg if we haven't already.
1923 ResultReg = createResultReg(TypeEntry.RC);
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1925 .addReg(OpEntry.DivRemResultReg);
1927 updateValueMap(I, ResultReg);
1932 /// \brief Emit a conditional move instruction (if the are supported) to lower
1934 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1935 // Check if the subtarget supports these instructions.
1936 if (!Subtarget->hasCMov())
1939 // FIXME: Add support for i8.
1940 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1943 const Value *Cond = I->getOperand(0);
1944 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1945 bool NeedTest = true;
1946 X86::CondCode CC = X86::COND_NE;
1948 // Optimize conditions coming from a compare if both instructions are in the
1949 // same basic block (values defined in other basic blocks may not have
1950 // initialized registers).
1951 const auto *CI = dyn_cast<CmpInst>(Cond);
1952 if (CI && (CI->getParent() == I->getParent())) {
1953 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1955 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1956 static unsigned SETFOpcTable[2][3] = {
1957 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1958 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1960 unsigned *SETFOpc = nullptr;
1961 switch (Predicate) {
1963 case CmpInst::FCMP_OEQ:
1964 SETFOpc = &SETFOpcTable[0][0];
1965 Predicate = CmpInst::ICMP_NE;
1967 case CmpInst::FCMP_UNE:
1968 SETFOpc = &SETFOpcTable[1][0];
1969 Predicate = CmpInst::ICMP_NE;
1974 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1975 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1977 const Value *CmpLHS = CI->getOperand(0);
1978 const Value *CmpRHS = CI->getOperand(1);
1980 std::swap(CmpLHS, CmpRHS);
1982 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
1983 // Emit a compare of the LHS and RHS, setting the flags.
1984 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1988 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1989 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1992 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1994 auto const &II = TII.get(SETFOpc[2]);
1995 if (II.getNumDefs()) {
1996 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1998 .addReg(FlagReg2).addReg(FlagReg1);
2000 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2001 .addReg(FlagReg2).addReg(FlagReg1);
2005 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2006 // Fake request the condition, otherwise the intrinsic might be completely
2008 unsigned TmpReg = getRegForValue(Cond);
2016 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2017 // garbage. Indeed, only the less significant bit is supposed to be
2018 // accurate. If we read more than the lsb, we may see non-zero values
2019 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2020 // the select. This is achieved by performing TEST against 1.
2021 unsigned CondReg = getRegForValue(Cond);
2024 bool CondIsKill = hasTrivialKill(Cond);
2026 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2027 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2030 const Value *LHS = I->getOperand(1);
2031 const Value *RHS = I->getOperand(2);
2033 unsigned RHSReg = getRegForValue(RHS);
2034 bool RHSIsKill = hasTrivialKill(RHS);
2036 unsigned LHSReg = getRegForValue(LHS);
2037 bool LHSIsKill = hasTrivialKill(LHS);
2039 if (!LHSReg || !RHSReg)
2042 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2043 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2045 updateValueMap(I, ResultReg);
2049 /// \brief Emit SSE or AVX instructions to lower the select.
2051 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2052 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2053 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2054 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2055 // Optimize conditions coming from a compare if both instructions are in the
2056 // same basic block (values defined in other basic blocks may not have
2057 // initialized registers).
2058 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2059 if (!CI || (CI->getParent() != I->getParent()))
2062 if (I->getType() != CI->getOperand(0)->getType() ||
2063 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2064 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2067 const Value *CmpLHS = CI->getOperand(0);
2068 const Value *CmpRHS = CI->getOperand(1);
2069 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2071 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2072 // We don't have to materialize a zero constant for this case and can just use
2073 // %x again on the RHS.
2074 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2075 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2076 if (CmpRHSC && CmpRHSC->isNullValue())
2082 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2087 std::swap(CmpLHS, CmpRHS);
2089 // Choose the SSE instruction sequence based on data type (float or double).
2090 static unsigned OpcTable[2][4] = {
2091 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2092 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
2095 unsigned *Opc = nullptr;
2096 switch (RetVT.SimpleTy) {
2097 default: return false;
2098 case MVT::f32: Opc = &OpcTable[0][0]; break;
2099 case MVT::f64: Opc = &OpcTable[1][0]; break;
2102 const Value *LHS = I->getOperand(1);
2103 const Value *RHS = I->getOperand(2);
2105 unsigned LHSReg = getRegForValue(LHS);
2106 bool LHSIsKill = hasTrivialKill(LHS);
2108 unsigned RHSReg = getRegForValue(RHS);
2109 bool RHSIsKill = hasTrivialKill(RHS);
2111 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2112 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2114 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2115 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2117 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2120 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2123 if (Subtarget->hasAVX()) {
2124 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2125 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2127 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2128 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2129 // uses XMM0 as the selection register. That may need just as many
2130 // instructions as the AND/ANDN/OR sequence due to register moves, so
2132 unsigned CmpOpcode =
2133 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2134 unsigned BlendOpcode =
2135 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2137 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
2138 CmpRHSReg, CmpRHSIsKill, CC);
2139 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2140 LHSReg, LHSIsKill, CmpReg, true);
2141 ResultReg = createResultReg(RC);
2142 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2143 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2145 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2146 CmpRHSReg, CmpRHSIsKill, CC);
2147 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2149 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2151 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2152 AndReg, /*IsKill=*/true);
2154 updateValueMap(I, ResultReg);
2158 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2159 // These are pseudo CMOV instructions and will be later expanded into control-
2162 switch (RetVT.SimpleTy) {
2163 default: return false;
2164 case MVT::i8: Opc = X86::CMOV_GR8; break;
2165 case MVT::i16: Opc = X86::CMOV_GR16; break;
2166 case MVT::i32: Opc = X86::CMOV_GR32; break;
2167 case MVT::f32: Opc = X86::CMOV_FR32; break;
2168 case MVT::f64: Opc = X86::CMOV_FR64; break;
2171 const Value *Cond = I->getOperand(0);
2172 X86::CondCode CC = X86::COND_NE;
2174 // Optimize conditions coming from a compare if both instructions are in the
2175 // same basic block (values defined in other basic blocks may not have
2176 // initialized registers).
2177 const auto *CI = dyn_cast<CmpInst>(Cond);
2178 if (CI && (CI->getParent() == I->getParent())) {
2180 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2181 if (CC > X86::LAST_VALID_COND)
2184 const Value *CmpLHS = CI->getOperand(0);
2185 const Value *CmpRHS = CI->getOperand(1);
2188 std::swap(CmpLHS, CmpRHS);
2190 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2191 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2194 unsigned CondReg = getRegForValue(Cond);
2197 bool CondIsKill = hasTrivialKill(Cond);
2198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2199 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2202 const Value *LHS = I->getOperand(1);
2203 const Value *RHS = I->getOperand(2);
2205 unsigned LHSReg = getRegForValue(LHS);
2206 bool LHSIsKill = hasTrivialKill(LHS);
2208 unsigned RHSReg = getRegForValue(RHS);
2209 bool RHSIsKill = hasTrivialKill(RHS);
2211 if (!LHSReg || !RHSReg)
2214 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2216 unsigned ResultReg =
2217 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2218 updateValueMap(I, ResultReg);
2222 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2224 if (!isTypeLegal(I->getType(), RetVT))
2227 // Check if we can fold the select.
2228 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2229 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2230 const Value *Opnd = nullptr;
2231 switch (Predicate) {
2233 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2234 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2236 // No need for a select anymore - this is an unconditional move.
2238 unsigned OpReg = getRegForValue(Opnd);
2241 bool OpIsKill = hasTrivialKill(Opnd);
2242 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2243 unsigned ResultReg = createResultReg(RC);
2244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2245 TII.get(TargetOpcode::COPY), ResultReg)
2246 .addReg(OpReg, getKillRegState(OpIsKill));
2247 updateValueMap(I, ResultReg);
2252 // First try to use real conditional move instructions.
2253 if (X86FastEmitCMoveSelect(RetVT, I))
2256 // Try to use a sequence of SSE instructions to simulate a conditional move.
2257 if (X86FastEmitSSESelect(RetVT, I))
2260 // Fall-back to pseudo conditional move instructions, which will be later
2261 // converted to control-flow.
2262 if (X86FastEmitPseudoSelect(RetVT, I))
2268 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2269 // The target-independent selection algorithm in FastISel already knows how
2270 // to select a SINT_TO_FP if the target is SSE but not AVX.
2271 // Early exit if the subtarget doesn't have AVX.
2272 if (!Subtarget->hasAVX())
2275 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2278 // Select integer to float/double conversion.
2279 unsigned OpReg = getRegForValue(I->getOperand(0));
2283 const TargetRegisterClass *RC = nullptr;
2286 if (I->getType()->isDoubleTy()) {
2287 // sitofp int -> double
2288 Opcode = X86::VCVTSI2SDrr;
2289 RC = &X86::FR64RegClass;
2290 } else if (I->getType()->isFloatTy()) {
2291 // sitofp int -> float
2292 Opcode = X86::VCVTSI2SSrr;
2293 RC = &X86::FR32RegClass;
2297 unsigned ImplicitDefReg = createResultReg(RC);
2298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2299 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2300 unsigned ResultReg =
2301 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2302 updateValueMap(I, ResultReg);
2306 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2307 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2309 const TargetRegisterClass *RC) {
2310 assert((I->getOpcode() == Instruction::FPExt ||
2311 I->getOpcode() == Instruction::FPTrunc) &&
2312 "Instruction must be an FPExt or FPTrunc!");
2314 unsigned OpReg = getRegForValue(I->getOperand(0));
2318 unsigned ResultReg = createResultReg(RC);
2319 MachineInstrBuilder MIB;
2320 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2322 if (Subtarget->hasAVX())
2325 updateValueMap(I, ResultReg);
2329 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2330 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2331 I->getOperand(0)->getType()->isFloatTy()) {
2332 // fpext from float to double.
2333 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2334 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2340 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2341 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2342 I->getOperand(0)->getType()->isDoubleTy()) {
2343 // fptrunc from double to float.
2344 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2345 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2351 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2352 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2353 EVT DstVT = TLI.getValueType(DL, I->getType());
2355 // This code only handles truncation to byte.
2356 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2358 if (!TLI.isTypeLegal(SrcVT))
2361 unsigned InputReg = getRegForValue(I->getOperand(0));
2363 // Unhandled operand. Halt "fast" selection and bail.
2366 if (SrcVT == MVT::i8) {
2367 // Truncate from i8 to i1; no code needed.
2368 updateValueMap(I, InputReg);
2372 bool KillInputReg = false;
2373 if (!Subtarget->is64Bit()) {
2374 // If we're on x86-32; we can't extract an i8 from a general register.
2375 // First issue a copy to GR16_ABCD or GR32_ABCD.
2376 const TargetRegisterClass *CopyRC =
2377 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2378 unsigned CopyReg = createResultReg(CopyRC);
2379 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2380 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2382 KillInputReg = true;
2385 // Issue an extract_subreg.
2386 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2387 InputReg, KillInputReg,
2392 updateValueMap(I, ResultReg);
2396 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2397 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2400 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2401 X86AddressMode SrcAM, uint64_t Len) {
2403 // Make sure we don't bloat code by inlining very large memcpy's.
2404 if (!IsMemcpySmall(Len))
2407 bool i64Legal = Subtarget->is64Bit();
2409 // We don't care about alignment here since we just emit integer accesses.
2412 if (Len >= 8 && i64Legal)
2422 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2423 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2424 assert(RV && "Failed to emit load or store??");
2426 unsigned Size = VT.getSizeInBits()/8;
2428 DestAM.Disp += Size;
2435 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2436 // FIXME: Handle more intrinsics.
2437 switch (II->getIntrinsicID()) {
2438 default: return false;
2439 case Intrinsic::convert_from_fp16:
2440 case Intrinsic::convert_to_fp16: {
2441 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2444 const Value *Op = II->getArgOperand(0);
2445 unsigned InputReg = getRegForValue(Op);
2449 // F16C only allows converting from float to half and from half to float.
2450 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2451 if (IsFloatToHalf) {
2452 if (!Op->getType()->isFloatTy())
2455 if (!II->getType()->isFloatTy())
2459 unsigned ResultReg = 0;
2460 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2461 if (IsFloatToHalf) {
2462 // 'InputReg' is implicitly promoted from register class FR32 to
2463 // register class VR128 by method 'constrainOperandRegClass' which is
2464 // directly called by 'fastEmitInst_ri'.
2465 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2466 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2467 // It's consistent with the other FP instructions, which are usually
2468 // controlled by MXCSR.
2469 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
2471 // Move the lower 32-bits of ResultReg to another register of class GR32.
2472 ResultReg = createResultReg(&X86::GR32RegClass);
2473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2474 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2475 .addReg(InputReg, RegState::Kill);
2477 // The result value is in the lower 16-bits of ResultReg.
2478 unsigned RegIdx = X86::sub_16bit;
2479 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2481 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2482 // Explicitly sign-extend the input to 32-bit.
2483 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2486 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2487 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2488 InputReg, /*Kill=*/true);
2490 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2492 // The result value is in the lower 32-bits of ResultReg.
2493 // Emit an explicit copy from register class VR128 to register class FR32.
2494 ResultReg = createResultReg(&X86::FR32RegClass);
2495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2496 TII.get(TargetOpcode::COPY), ResultReg)
2497 .addReg(InputReg, RegState::Kill);
2500 updateValueMap(II, ResultReg);
2503 case Intrinsic::frameaddress: {
2504 MachineFunction *MF = FuncInfo.MF;
2505 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2508 Type *RetTy = II->getCalledFunction()->getReturnType();
2511 if (!isTypeLegal(RetTy, VT))
2515 const TargetRegisterClass *RC = nullptr;
2517 switch (VT.SimpleTy) {
2518 default: llvm_unreachable("Invalid result type for frameaddress.");
2519 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2520 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2523 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2524 // we get the wrong frame register.
2525 MachineFrameInfo *MFI = MF->getFrameInfo();
2526 MFI->setFrameAddressIsTaken(true);
2528 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2529 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2530 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2531 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2532 "Invalid Frame Register!");
2534 // Always make a copy of the frame register to to a vreg first, so that we
2535 // never directly reference the frame register (the TwoAddressInstruction-
2536 // Pass doesn't like that).
2537 unsigned SrcReg = createResultReg(RC);
2538 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2539 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2541 // Now recursively load from the frame address.
2542 // movq (%rbp), %rax
2543 // movq (%rax), %rax
2544 // movq (%rax), %rax
2547 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2549 DestReg = createResultReg(RC);
2550 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2551 TII.get(Opc), DestReg), SrcReg);
2555 updateValueMap(II, SrcReg);
2558 case Intrinsic::memcpy: {
2559 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2560 // Don't handle volatile or variable length memcpys.
2561 if (MCI->isVolatile())
2564 if (isa<ConstantInt>(MCI->getLength())) {
2565 // Small memcpy's are common enough that we want to do them
2566 // without a call if possible.
2567 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2568 if (IsMemcpySmall(Len)) {
2569 X86AddressMode DestAM, SrcAM;
2570 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2571 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2573 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2578 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2579 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2582 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2585 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2587 case Intrinsic::memset: {
2588 const MemSetInst *MSI = cast<MemSetInst>(II);
2590 if (MSI->isVolatile())
2593 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2594 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2597 if (MSI->getDestAddressSpace() > 255)
2600 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2602 case Intrinsic::stackprotector: {
2603 // Emit code to store the stack guard onto the stack.
2604 EVT PtrTy = TLI.getPointerTy(DL);
2606 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2607 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2609 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2611 // Grab the frame index.
2613 if (!X86SelectAddress(Slot, AM)) return false;
2614 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2617 case Intrinsic::dbg_declare: {
2618 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2620 assert(DI->getAddress() && "Null address should be checked earlier!");
2621 if (!X86SelectAddress(DI->getAddress(), AM))
2623 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2624 // FIXME may need to add RegState::Debug to any registers produced,
2625 // although ESP/EBP should be the only ones at the moment.
2626 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2627 "Expected inlined-at fields to agree");
2628 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2630 .addMetadata(DI->getVariable())
2631 .addMetadata(DI->getExpression());
2634 case Intrinsic::trap: {
2635 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2638 case Intrinsic::sqrt: {
2639 if (!Subtarget->hasSSE1())
2642 Type *RetTy = II->getCalledFunction()->getReturnType();
2645 if (!isTypeLegal(RetTy, VT))
2648 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2649 // is not generated by FastISel yet.
2650 // FIXME: Update this code once tablegen can handle it.
2651 static const uint16_t SqrtOpc[2][2] = {
2652 {X86::SQRTSSr, X86::VSQRTSSr},
2653 {X86::SQRTSDr, X86::VSQRTSDr}
2655 bool HasAVX = Subtarget->hasAVX();
2657 const TargetRegisterClass *RC;
2658 switch (VT.SimpleTy) {
2659 default: return false;
2660 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2661 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2664 const Value *SrcVal = II->getArgOperand(0);
2665 unsigned SrcReg = getRegForValue(SrcVal);
2670 unsigned ImplicitDefReg = 0;
2672 ImplicitDefReg = createResultReg(RC);
2673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2674 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2677 unsigned ResultReg = createResultReg(RC);
2678 MachineInstrBuilder MIB;
2679 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2683 MIB.addReg(ImplicitDefReg);
2687 updateValueMap(II, ResultReg);
2690 case Intrinsic::sadd_with_overflow:
2691 case Intrinsic::uadd_with_overflow:
2692 case Intrinsic::ssub_with_overflow:
2693 case Intrinsic::usub_with_overflow:
2694 case Intrinsic::smul_with_overflow:
2695 case Intrinsic::umul_with_overflow: {
2696 // This implements the basic lowering of the xalu with overflow intrinsics
2697 // into add/sub/mul followed by either seto or setb.
2698 const Function *Callee = II->getCalledFunction();
2699 auto *Ty = cast<StructType>(Callee->getReturnType());
2700 Type *RetTy = Ty->getTypeAtIndex(0U);
2701 Type *CondTy = Ty->getTypeAtIndex(1);
2704 if (!isTypeLegal(RetTy, VT))
2707 if (VT < MVT::i8 || VT > MVT::i64)
2710 const Value *LHS = II->getArgOperand(0);
2711 const Value *RHS = II->getArgOperand(1);
2713 // Canonicalize immediate to the RHS.
2714 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2715 isCommutativeIntrinsic(II))
2716 std::swap(LHS, RHS);
2718 bool UseIncDec = false;
2719 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2722 unsigned BaseOpc, CondOpc;
2723 switch (II->getIntrinsicID()) {
2724 default: llvm_unreachable("Unexpected intrinsic!");
2725 case Intrinsic::sadd_with_overflow:
2726 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2727 CondOpc = X86::SETOr;
2729 case Intrinsic::uadd_with_overflow:
2730 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2731 case Intrinsic::ssub_with_overflow:
2732 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2733 CondOpc = X86::SETOr;
2735 case Intrinsic::usub_with_overflow:
2736 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2737 case Intrinsic::smul_with_overflow:
2738 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2739 case Intrinsic::umul_with_overflow:
2740 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2743 unsigned LHSReg = getRegForValue(LHS);
2746 bool LHSIsKill = hasTrivialKill(LHS);
2748 unsigned ResultReg = 0;
2749 // Check if we have an immediate version.
2750 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2751 static const uint16_t Opc[2][4] = {
2752 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2753 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2756 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2757 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2758 bool IsDec = BaseOpc == X86ISD::DEC;
2759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2760 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2761 .addReg(LHSReg, getKillRegState(LHSIsKill));
2763 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2764 CI->getZExtValue());
2770 RHSReg = getRegForValue(RHS);
2773 RHSIsKill = hasTrivialKill(RHS);
2774 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2778 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2780 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2781 static const uint16_t MULOpc[] =
2782 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2783 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2784 // First copy the first operand into RAX, which is an implicit input to
2785 // the X86::MUL*r instruction.
2786 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2787 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2788 .addReg(LHSReg, getKillRegState(LHSIsKill));
2789 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2790 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2791 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2792 static const uint16_t MULOpc[] =
2793 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2794 if (VT == MVT::i8) {
2795 // Copy the first operand into AL, which is an implicit input to the
2796 // X86::IMUL8r instruction.
2797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2798 TII.get(TargetOpcode::COPY), X86::AL)
2799 .addReg(LHSReg, getKillRegState(LHSIsKill));
2800 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2803 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2804 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2811 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2812 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2813 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2816 updateValueMap(II, ResultReg, 2);
2819 case Intrinsic::x86_sse_cvttss2si:
2820 case Intrinsic::x86_sse_cvttss2si64:
2821 case Intrinsic::x86_sse2_cvttsd2si:
2822 case Intrinsic::x86_sse2_cvttsd2si64: {
2824 switch (II->getIntrinsicID()) {
2825 default: llvm_unreachable("Unexpected intrinsic.");
2826 case Intrinsic::x86_sse_cvttss2si:
2827 case Intrinsic::x86_sse_cvttss2si64:
2828 if (!Subtarget->hasSSE1())
2830 IsInputDouble = false;
2832 case Intrinsic::x86_sse2_cvttsd2si:
2833 case Intrinsic::x86_sse2_cvttsd2si64:
2834 if (!Subtarget->hasSSE2())
2836 IsInputDouble = true;
2840 Type *RetTy = II->getCalledFunction()->getReturnType();
2842 if (!isTypeLegal(RetTy, VT))
2845 static const uint16_t CvtOpc[2][2][2] = {
2846 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2847 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2848 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2849 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2851 bool HasAVX = Subtarget->hasAVX();
2853 switch (VT.SimpleTy) {
2854 default: llvm_unreachable("Unexpected result type.");
2855 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2856 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2859 // Check if we can fold insertelement instructions into the convert.
2860 const Value *Op = II->getArgOperand(0);
2861 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2862 const Value *Index = IE->getOperand(2);
2863 if (!isa<ConstantInt>(Index))
2865 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2868 Op = IE->getOperand(1);
2871 Op = IE->getOperand(0);
2874 unsigned Reg = getRegForValue(Op);
2878 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2882 updateValueMap(II, ResultReg);
2888 bool X86FastISel::fastLowerArguments() {
2889 if (!FuncInfo.CanLowerReturn)
2892 const Function *F = FuncInfo.Fn;
2896 CallingConv::ID CC = F->getCallingConv();
2897 if (CC != CallingConv::C)
2900 if (Subtarget->isCallingConvWin64(CC))
2903 if (!Subtarget->is64Bit())
2906 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2907 unsigned GPRCnt = 0;
2908 unsigned FPRCnt = 0;
2910 for (auto const &Arg : F->args()) {
2911 // The first argument is at index 1.
2913 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2914 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2915 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2916 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
2917 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
2918 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2921 Type *ArgTy = Arg.getType();
2922 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2925 EVT ArgVT = TLI.getValueType(DL, ArgTy);
2926 if (!ArgVT.isSimple()) return false;
2927 switch (ArgVT.getSimpleVT().SimpleTy) {
2928 default: return false;
2935 if (!Subtarget->hasSSE1())
2948 static const MCPhysReg GPR32ArgRegs[] = {
2949 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2951 static const MCPhysReg GPR64ArgRegs[] = {
2952 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2954 static const MCPhysReg XMMArgRegs[] = {
2955 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2956 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2959 unsigned GPRIdx = 0;
2960 unsigned FPRIdx = 0;
2961 for (auto const &Arg : F->args()) {
2962 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
2963 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2965 switch (VT.SimpleTy) {
2966 default: llvm_unreachable("Unexpected value type.");
2967 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2968 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2969 case MVT::f32: // fall-through
2970 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2972 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2973 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2974 // Without this, EmitLiveInCopies may eliminate the livein if its only
2975 // use is a bitcast (which isn't turned into an instruction).
2976 unsigned ResultReg = createResultReg(RC);
2977 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2978 TII.get(TargetOpcode::COPY), ResultReg)
2979 .addReg(DstReg, getKillRegState(true));
2980 updateValueMap(&Arg, ResultReg);
2985 static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
2987 ImmutableCallSite *CS) {
2988 if (Subtarget->is64Bit())
2990 if (Subtarget->getTargetTriple().isOSMSVCRT())
2992 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2993 CC == CallingConv::HiPE)
2997 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
2998 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
3004 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3005 auto &OutVals = CLI.OutVals;
3006 auto &OutFlags = CLI.OutFlags;
3007 auto &OutRegs = CLI.OutRegs;
3008 auto &Ins = CLI.Ins;
3009 auto &InRegs = CLI.InRegs;
3010 CallingConv::ID CC = CLI.CallConv;
3011 bool &IsTailCall = CLI.IsTailCall;
3012 bool IsVarArg = CLI.IsVarArg;
3013 const Value *Callee = CLI.Callee;
3014 MCSymbol *Symbol = CLI.Symbol;
3016 bool Is64Bit = Subtarget->is64Bit();
3017 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3019 // Handle only C, fastcc, and webkit_js calling conventions for now.
3021 default: return false;
3022 case CallingConv::C:
3023 case CallingConv::Fast:
3024 case CallingConv::WebKit_JS:
3025 case CallingConv::Swift:
3026 case CallingConv::X86_FastCall:
3027 case CallingConv::X86_StdCall:
3028 case CallingConv::X86_ThisCall:
3029 case CallingConv::X86_64_Win64:
3030 case CallingConv::X86_64_SysV:
3034 // Allow SelectionDAG isel to handle tail calls.
3038 // fastcc with -tailcallopt is intended to provide a guaranteed
3039 // tail call optimization. Fastisel doesn't know how to do that.
3040 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3043 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3044 // x86-32. Special handling for x86-64 is implemented.
3045 if (IsVarArg && IsWin64)
3048 // Don't know about inalloca yet.
3049 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3052 for (auto Flag : CLI.OutFlags)
3053 if (Flag.isSwiftError())
3056 SmallVector<MVT, 16> OutVTs;
3057 SmallVector<unsigned, 16> ArgRegs;
3059 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3060 // instruction. This is safe because it is common to all FastISel supported
3061 // calling conventions on x86.
3062 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3063 Value *&Val = OutVals[i];
3064 ISD::ArgFlagsTy Flags = OutFlags[i];
3065 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3066 if (CI->getBitWidth() < 32) {
3068 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3070 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3074 // Passing bools around ends up doing a trunc to i1 and passing it.
3075 // Codegen this as an argument + "and 1".
3077 auto *TI = dyn_cast<TruncInst>(Val);
3079 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3080 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3082 Value *PrevVal = TI->getOperand(0);
3083 ResultReg = getRegForValue(PrevVal);
3088 if (!isTypeLegal(PrevVal->getType(), VT))
3092 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3094 if (!isTypeLegal(Val->getType(), VT))
3096 ResultReg = getRegForValue(Val);
3102 ArgRegs.push_back(ResultReg);
3103 OutVTs.push_back(VT);
3106 // Analyze operands of the call, assigning locations to each operand.
3107 SmallVector<CCValAssign, 16> ArgLocs;
3108 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3110 // Allocate shadow area for Win64
3112 CCInfo.AllocateStack(32, 8);
3114 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3116 // Get a count of how many bytes are to be pushed on the stack.
3117 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3119 // Issue CALLSEQ_START
3120 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3121 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3122 .addImm(NumBytes).addImm(0);
3124 // Walk the register/memloc assignments, inserting copies/loads.
3125 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3126 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3127 CCValAssign const &VA = ArgLocs[i];
3128 const Value *ArgVal = OutVals[VA.getValNo()];
3129 MVT ArgVT = OutVTs[VA.getValNo()];
3131 if (ArgVT == MVT::x86mmx)
3134 unsigned ArgReg = ArgRegs[VA.getValNo()];
3136 // Promote the value if needed.
3137 switch (VA.getLocInfo()) {
3138 case CCValAssign::Full: break;
3139 case CCValAssign::SExt: {
3140 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3141 "Unexpected extend");
3143 if (ArgVT.SimpleTy == MVT::i1)
3146 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3148 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3149 ArgVT = VA.getLocVT();
3152 case CCValAssign::ZExt: {
3153 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3154 "Unexpected extend");
3156 // Handle zero-extension from i1 to i8, which is common.
3157 if (ArgVT.SimpleTy == MVT::i1) {
3158 // Set the high bits to zero.
3159 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3166 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3168 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3169 ArgVT = VA.getLocVT();
3172 case CCValAssign::AExt: {
3173 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3174 "Unexpected extend");
3175 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3178 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3181 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3184 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3185 ArgVT = VA.getLocVT();
3188 case CCValAssign::BCvt: {
3189 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3190 /*TODO: Kill=*/false);
3191 assert(ArgReg && "Failed to emit a bitcast!");
3192 ArgVT = VA.getLocVT();
3195 case CCValAssign::VExt:
3196 // VExt has not been implemented, so this should be impossible to reach
3197 // for now. However, fallback to Selection DAG isel once implemented.
3199 case CCValAssign::AExtUpper:
3200 case CCValAssign::SExtUpper:
3201 case CCValAssign::ZExtUpper:
3202 case CCValAssign::FPExt:
3203 llvm_unreachable("Unexpected loc info!");
3204 case CCValAssign::Indirect:
3205 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3210 if (VA.isRegLoc()) {
3211 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3212 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3213 OutRegs.push_back(VA.getLocReg());
3215 assert(VA.isMemLoc());
3217 // Don't emit stores for undef values.
3218 if (isa<UndefValue>(ArgVal))
3221 unsigned LocMemOffset = VA.getLocMemOffset();
3223 AM.Base.Reg = RegInfo->getStackRegister();
3224 AM.Disp = LocMemOffset;
3225 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3226 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3227 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3228 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3229 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3230 if (Flags.isByVal()) {
3231 X86AddressMode SrcAM;
3232 SrcAM.Base.Reg = ArgReg;
3233 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3235 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3236 // If this is a really simple value, emit this with the Value* version
3237 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3238 // as it can cause us to reevaluate the argument.
3239 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3242 bool ValIsKill = hasTrivialKill(ArgVal);
3243 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3249 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3251 if (Subtarget->isPICStyleGOT()) {
3252 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3254 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3257 if (Is64Bit && IsVarArg && !IsWin64) {
3258 // From AMD64 ABI document:
3259 // For calls that may call functions that use varargs or stdargs
3260 // (prototype-less calls or calls to functions containing ellipsis (...) in
3261 // the declaration) %al is used as hidden argument to specify the number
3262 // of SSE registers used. The contents of %al do not need to match exactly
3263 // the number of registers, but must be an ubound on the number of SSE
3264 // registers used and is in the range 0 - 8 inclusive.
3266 // Count the number of XMM registers allocated.
3267 static const MCPhysReg XMMArgRegs[] = {
3268 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3269 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3271 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3272 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3273 && "SSE registers cannot be used when SSE is disabled");
3274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3275 X86::AL).addImm(NumXMMRegs);
3278 // Materialize callee address in a register. FIXME: GV address can be
3279 // handled with a CALLpcrel32 instead.
3280 X86AddressMode CalleeAM;
3281 if (!X86SelectCallAddress(Callee, CalleeAM))
3284 unsigned CalleeOp = 0;
3285 const GlobalValue *GV = nullptr;
3286 if (CalleeAM.GV != nullptr) {
3288 } else if (CalleeAM.Base.Reg != 0) {
3289 CalleeOp = CalleeAM.Base.Reg;
3294 MachineInstrBuilder MIB;
3296 // Register-indirect call.
3297 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3298 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3302 assert(GV && "Not a direct call");
3303 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3305 // See if we need any target-specific flags on the GV operand.
3306 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3307 // Ignore NonLazyBind attribute in FastISel
3308 if (OpFlags == X86II::MO_GOTPCREL)
3311 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3313 MIB.addSym(Symbol, OpFlags);
3315 MIB.addGlobalAddress(GV, 0, OpFlags);
3318 // Add a register mask operand representing the call-preserved registers.
3319 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3320 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3322 // Add an implicit use GOT pointer in EBX.
3323 if (Subtarget->isPICStyleGOT())
3324 MIB.addReg(X86::EBX, RegState::Implicit);
3326 if (Is64Bit && IsVarArg && !IsWin64)
3327 MIB.addReg(X86::AL, RegState::Implicit);
3329 // Add implicit physical register uses to the call.
3330 for (auto Reg : OutRegs)
3331 MIB.addReg(Reg, RegState::Implicit);
3333 // Issue CALLSEQ_END
3334 unsigned NumBytesForCalleeToPop =
3335 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3336 TM.Options.GuaranteedTailCallOpt)
3337 ? NumBytes // Callee pops everything.
3338 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
3339 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3341 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3343 // Now handle call return values.
3344 SmallVector<CCValAssign, 16> RVLocs;
3345 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3346 CLI.RetTy->getContext());
3347 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3349 // Copy all of the result registers out of their specified physreg.
3350 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3351 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3352 CCValAssign &VA = RVLocs[i];
3353 EVT CopyVT = VA.getValVT();
3354 unsigned CopyReg = ResultReg + i;
3356 // If this is x86-64, and we disabled SSE, we can't return FP values
3357 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3358 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3359 report_fatal_error("SSE register return with SSE disabled");
3362 // If we prefer to use the value in xmm registers, copy it out as f80 and
3363 // use a truncate to move it from fp stack reg to xmm reg.
3364 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3365 isScalarFPTypeInSSEReg(VA.getValVT())) {
3367 CopyReg = createResultReg(&X86::RFP80RegClass);
3370 // Copy out the result.
3371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3372 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3373 InRegs.push_back(VA.getLocReg());
3375 // Round the f80 to the right size, which also moves it to the appropriate
3376 // xmm register. This is accomplished by storing the f80 value in memory
3377 // and then loading it back.
3378 if (CopyVT != VA.getValVT()) {
3379 EVT ResVT = VA.getValVT();
3380 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3381 unsigned MemSize = ResVT.getSizeInBits()/8;
3382 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3383 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3386 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3387 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3388 TII.get(Opc), ResultReg + i), FI);
3392 CLI.ResultReg = ResultReg;
3393 CLI.NumResultRegs = RVLocs.size();
3400 X86FastISel::fastSelectInstruction(const Instruction *I) {
3401 switch (I->getOpcode()) {
3403 case Instruction::Load:
3404 return X86SelectLoad(I);
3405 case Instruction::Store:
3406 return X86SelectStore(I);
3407 case Instruction::Ret:
3408 return X86SelectRet(I);
3409 case Instruction::ICmp:
3410 case Instruction::FCmp:
3411 return X86SelectCmp(I);
3412 case Instruction::ZExt:
3413 return X86SelectZExt(I);
3414 case Instruction::Br:
3415 return X86SelectBranch(I);
3416 case Instruction::LShr:
3417 case Instruction::AShr:
3418 case Instruction::Shl:
3419 return X86SelectShift(I);
3420 case Instruction::SDiv:
3421 case Instruction::UDiv:
3422 case Instruction::SRem:
3423 case Instruction::URem:
3424 return X86SelectDivRem(I);
3425 case Instruction::Select:
3426 return X86SelectSelect(I);
3427 case Instruction::Trunc:
3428 return X86SelectTrunc(I);
3429 case Instruction::FPExt:
3430 return X86SelectFPExt(I);
3431 case Instruction::FPTrunc:
3432 return X86SelectFPTrunc(I);
3433 case Instruction::SIToFP:
3434 return X86SelectSIToFP(I);
3435 case Instruction::IntToPtr: // Deliberate fall-through.
3436 case Instruction::PtrToInt: {
3437 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3438 EVT DstVT = TLI.getValueType(DL, I->getType());
3439 if (DstVT.bitsGT(SrcVT))
3440 return X86SelectZExt(I);
3441 if (DstVT.bitsLT(SrcVT))
3442 return X86SelectTrunc(I);
3443 unsigned Reg = getRegForValue(I->getOperand(0));
3444 if (Reg == 0) return false;
3445 updateValueMap(I, Reg);
3448 case Instruction::BitCast: {
3449 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3450 if (!Subtarget->hasSSE2())
3453 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3454 EVT DstVT = TLI.getValueType(DL, I->getType());
3456 if (!SrcVT.isSimple() || !DstVT.isSimple())
3459 if (!SrcVT.is128BitVector() &&
3460 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3463 unsigned Reg = getRegForValue(I->getOperand(0));
3467 // No instruction is needed for conversion. Reuse the register used by
3468 // the fist operand.
3469 updateValueMap(I, Reg);
3477 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3481 uint64_t Imm = CI->getZExtValue();
3483 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3484 switch (VT.SimpleTy) {
3485 default: llvm_unreachable("Unexpected value type");
3488 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3491 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3496 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3498 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3499 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3506 switch (VT.SimpleTy) {
3507 default: llvm_unreachable("Unexpected value type");
3508 case MVT::i1: VT = MVT::i8; // fall-through
3509 case MVT::i8: Opc = X86::MOV8ri; break;
3510 case MVT::i16: Opc = X86::MOV16ri; break;
3511 case MVT::i32: Opc = X86::MOV32ri; break;
3513 if (isUInt<32>(Imm))
3515 else if (isInt<32>(Imm))
3516 Opc = X86::MOV64ri32;
3522 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3523 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3524 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3526 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3527 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3530 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3533 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3534 if (CFP->isNullValue())
3535 return fastMaterializeFloatZero(CFP);
3537 // Can't handle alternate code models yet.
3538 CodeModel::Model CM = TM.getCodeModel();
3539 if (CM != CodeModel::Small && CM != CodeModel::Large)
3542 // Get opcode and regclass of the output for the given load instruction.
3544 const TargetRegisterClass *RC = nullptr;
3545 switch (VT.SimpleTy) {
3548 if (X86ScalarSSEf32) {
3549 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3550 RC = &X86::FR32RegClass;
3552 Opc = X86::LD_Fp32m;
3553 RC = &X86::RFP32RegClass;
3557 if (X86ScalarSSEf64) {
3558 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3559 RC = &X86::FR64RegClass;
3561 Opc = X86::LD_Fp64m;
3562 RC = &X86::RFP64RegClass;
3566 // No f80 support yet.
3570 // MachineConstantPool wants an explicit alignment.
3571 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3573 // Alignment of vector types. FIXME!
3574 Align = DL.getTypeAllocSize(CFP->getType());
3577 // x86-32 PIC requires a PIC base register for constant pools.
3578 unsigned PICBase = 0;
3579 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3580 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3581 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3582 else if (OpFlag == X86II::MO_GOTOFF)
3583 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3584 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
3587 // Create the load from the constant pool.
3588 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3589 unsigned ResultReg = createResultReg(RC);
3591 if (CM == CodeModel::Large) {
3592 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3595 .addConstantPoolIndex(CPI, 0, OpFlag);
3596 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3597 TII.get(Opc), ResultReg);
3598 addDirectMem(MIB, AddrReg);
3599 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3600 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3601 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3602 MIB->addMemOperand(*FuncInfo.MF, MMO);
3606 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3607 TII.get(Opc), ResultReg),
3608 CPI, PICBase, OpFlag);
3612 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3613 // Can't handle alternate code models yet.
3614 if (TM.getCodeModel() != CodeModel::Small)
3617 // Materialize addresses with LEA/MOV instructions.
3619 if (X86SelectAddress(GV, AM)) {
3620 // If the expression is just a basereg, then we're done, otherwise we need
3622 if (AM.BaseType == X86AddressMode::RegBase &&
3623 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3626 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3627 if (TM.getRelocationModel() == Reloc::Static &&
3628 TLI.getPointerTy(DL) == MVT::i64) {
3629 // The displacement code could be more than 32 bits away so we need to use
3630 // an instruction with a 64 bit immediate
3631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3633 .addGlobalAddress(GV);
3636 TLI.getPointerTy(DL) == MVT::i32
3637 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3639 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3640 TII.get(Opc), ResultReg), AM);
3647 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3648 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3650 // Only handle simple types.
3651 if (!CEVT.isSimple())
3653 MVT VT = CEVT.getSimpleVT();
3655 if (const auto *CI = dyn_cast<ConstantInt>(C))
3656 return X86MaterializeInt(CI, VT);
3657 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3658 return X86MaterializeFP(CFP, VT);
3659 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3660 return X86MaterializeGV(GV, VT);
3665 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3666 // Fail on dynamic allocas. At this point, getRegForValue has already
3667 // checked its CSE maps, so if we're here trying to handle a dynamic
3668 // alloca, we're not going to succeed. X86SelectAddress has a
3669 // check for dynamic allocas, because it's called directly from
3670 // various places, but targetMaterializeAlloca also needs a check
3671 // in order to avoid recursion between getRegForValue,
3672 // X86SelectAddrss, and targetMaterializeAlloca.
3673 if (!FuncInfo.StaticAllocaMap.count(C))
3675 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3678 if (!X86SelectAddress(C, AM))
3681 TLI.getPointerTy(DL) == MVT::i32
3682 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3684 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3685 unsigned ResultReg = createResultReg(RC);
3686 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3687 TII.get(Opc), ResultReg), AM);
3691 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3693 if (!isTypeLegal(CF->getType(), VT))
3696 // Get opcode and regclass for the given zero.
3698 const TargetRegisterClass *RC = nullptr;
3699 switch (VT.SimpleTy) {
3702 if (X86ScalarSSEf32) {
3703 Opc = X86::FsFLD0SS;
3704 RC = &X86::FR32RegClass;
3706 Opc = X86::LD_Fp032;
3707 RC = &X86::RFP32RegClass;
3711 if (X86ScalarSSEf64) {
3712 Opc = X86::FsFLD0SD;
3713 RC = &X86::FR64RegClass;
3715 Opc = X86::LD_Fp064;
3716 RC = &X86::RFP64RegClass;
3720 // No f80 support yet.
3724 unsigned ResultReg = createResultReg(RC);
3725 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3730 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3731 const LoadInst *LI) {
3732 const Value *Ptr = LI->getPointerOperand();
3734 if (!X86SelectAddress(Ptr, AM))
3737 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3739 unsigned Size = DL.getTypeAllocSize(LI->getType());
3740 unsigned Alignment = LI->getAlignment();
3742 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3743 Alignment = DL.getABITypeAlignment(LI->getType());
3745 SmallVector<MachineOperand, 8> AddrOps;
3746 AM.getFullAddress(AddrOps);
3748 MachineInstr *Result = XII.foldMemoryOperandImpl(
3749 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3750 /*AllowCommute=*/true);
3754 // The index register could be in the wrong register class. Unfortunately,
3755 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3756 // to just look at OpNo + the offset to the index reg. We actually need to
3757 // scan the instruction to find the index reg and see if its the correct reg
3759 unsigned OperandNo = 0;
3760 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3761 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3762 MachineOperand &MO = *I;
3763 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3765 // Found the index reg, now try to rewrite it.
3766 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3767 MO.getReg(), OperandNo);
3768 if (IndexReg == MO.getReg())
3770 MO.setReg(IndexReg);
3773 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3774 MI->eraseFromParent();
3780 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3781 const TargetLibraryInfo *libInfo) {
3782 return new X86FastISel(funcInfo, libInfo);