1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
46 class X86FastISel final : public FastISel {
47 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
48 /// make the right decision when generating code for different targets.
49 const X86Subtarget *Subtarget;
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
60 const TargetLibraryInfo *libInfo)
61 : FastISel(funcInfo, libInfo) {
62 Subtarget = &TM.getSubtarget<X86Subtarget>();
63 X86ScalarSSEf64 = Subtarget->hasSSE2();
64 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 bool TargetSelectInstruction(const Instruction *I) override;
69 /// \brief The specified machine instr operand is a vreg, and that
70 /// vreg is being provided by the specified load instruction. If possible,
71 /// try to fold the load as an operand to the instruction, returning true if
73 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74 const LoadInst *LI) override;
76 bool FastLowerArguments() override;
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
86 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
87 MachineMemOperand *MMO = nullptr, bool Aligned = false);
88 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
89 const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
95 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
96 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
98 bool X86SelectLoad(const Instruction *I);
100 bool X86SelectStore(const Instruction *I);
102 bool X86SelectRet(const Instruction *I);
104 bool X86SelectCmp(const Instruction *I);
106 bool X86SelectZExt(const Instruction *I);
108 bool X86SelectBranch(const Instruction *I);
110 bool X86SelectShift(const Instruction *I);
112 bool X86SelectDivRem(const Instruction *I);
114 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
116 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
118 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
120 bool X86SelectSelect(const Instruction *I);
122 bool X86SelectTrunc(const Instruction *I);
124 bool X86SelectFPExt(const Instruction *I);
125 bool X86SelectFPTrunc(const Instruction *I);
127 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
128 bool X86SelectCall(const Instruction *I);
130 bool DoSelectCall(const Instruction *I, const char *MemIntName);
132 const X86InstrInfo *getInstrInfo() const {
133 return getTargetMachine()->getInstrInfo();
135 const X86TargetMachine *getTargetMachine() const {
136 return static_cast<const X86TargetMachine *>(&TM);
139 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
141 unsigned TargetMaterializeConstant(const Constant *C) override;
143 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
145 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
147 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
148 /// computed in an SSE register, not on the X87 floating point stack.
149 bool isScalarFPTypeInSSEReg(EVT VT) const {
150 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
151 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
154 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
156 bool IsMemcpySmall(uint64_t Len);
158 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
159 X86AddressMode SrcAM, uint64_t Len);
161 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
165 } // end anonymous namespace.
167 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
168 // If both operands are the same, then try to optimize or fold the cmp.
169 CmpInst::Predicate Predicate = CI->getPredicate();
170 if (CI->getOperand(0) != CI->getOperand(1))
174 default: llvm_unreachable("Invalid predicate!");
175 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
176 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
177 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
178 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
179 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
180 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
181 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
182 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
183 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
184 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
185 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
186 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
187 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
188 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
189 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
190 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
192 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
194 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
195 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
196 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
197 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
198 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
199 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
200 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
201 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
207 static std::pair<X86::CondCode, bool>
208 getX86ConditionCode(CmpInst::Predicate Predicate) {
209 X86::CondCode CC = X86::COND_INVALID;
210 bool NeedSwap = false;
213 // Floating-point Predicates
214 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
215 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
216 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
217 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
218 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
219 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
220 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
221 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
222 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
223 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
224 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
225 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
226 case CmpInst::FCMP_OEQ: // fall-through
227 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
229 // Integer Predicates
230 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
231 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
232 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
233 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
234 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
235 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
236 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
237 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
238 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
239 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
242 return std::make_pair(CC, NeedSwap);
245 static std::pair<unsigned, bool>
246 getX86SSECondtionCode(CmpInst::Predicate Predicate) {
248 bool NeedSwap = false;
250 // SSE Condition code mapping:
260 default: llvm_unreachable("Unexpected predicate");
261 case CmpInst::FCMP_OEQ: CC = 0; break;
262 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
263 case CmpInst::FCMP_OLT: CC = 1; break;
264 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
265 case CmpInst::FCMP_OLE: CC = 2; break;
266 case CmpInst::FCMP_UNO: CC = 3; break;
267 case CmpInst::FCMP_UNE: CC = 4; break;
268 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
269 case CmpInst::FCMP_UGE: CC = 5; break;
270 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
271 case CmpInst::FCMP_UGT: CC = 6; break;
272 case CmpInst::FCMP_ORD: CC = 7; break;
273 case CmpInst::FCMP_UEQ:
274 case CmpInst::FCMP_ONE: CC = 8; break;
277 return std::make_pair(CC, NeedSwap);
280 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
281 /// into the user. The condition code will only be updated on success.
282 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
284 if (!isa<ExtractValueInst>(Cond))
287 const auto *EV = cast<ExtractValueInst>(Cond);
288 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
291 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
293 const Function *Callee = II->getCalledFunction();
295 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
296 if (!isTypeLegal(RetTy, RetVT))
299 if (RetVT != MVT::i32 && RetVT != MVT::i64)
303 switch (II->getIntrinsicID()) {
304 default: return false;
305 case Intrinsic::sadd_with_overflow:
306 case Intrinsic::ssub_with_overflow:
307 case Intrinsic::smul_with_overflow:
308 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
309 case Intrinsic::uadd_with_overflow:
310 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
313 // Check if both instructions are in the same basic block.
314 if (II->getParent() != I->getParent())
317 // Make sure nothing is in the way
318 BasicBlock::const_iterator Start = I;
319 BasicBlock::const_iterator End = II;
320 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
321 // We only expect extractvalue instructions between the intrinsic and the
322 // instruction to be selected.
323 if (!isa<ExtractValueInst>(Itr))
326 // Check that the extractvalue operand comes from the intrinsic.
327 const auto *EVI = cast<ExtractValueInst>(Itr);
328 if (EVI->getAggregateOperand() != II)
336 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
337 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
338 if (evt == MVT::Other || !evt.isSimple())
339 // Unhandled type. Halt "fast" selection and bail.
342 VT = evt.getSimpleVT();
343 // For now, require SSE/SSE2 for performing floating-point operations,
344 // since x87 requires additional work.
345 if (VT == MVT::f64 && !X86ScalarSSEf64)
347 if (VT == MVT::f32 && !X86ScalarSSEf32)
349 // Similarly, no f80 support yet.
352 // We only handle legal types. For example, on x86-32 the instruction
353 // selector contains all of the 64-bit instructions from x86-64,
354 // under the assumption that i64 won't be used if the target doesn't
356 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
359 #include "X86GenCallingConv.inc"
361 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
362 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
363 /// Return true and the result register by reference if it is possible.
364 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
365 MachineMemOperand *MMO, unsigned &ResultReg) {
366 // Get opcode and regclass of the output for the given load instruction.
368 const TargetRegisterClass *RC = nullptr;
369 switch (VT.getSimpleVT().SimpleTy) {
370 default: return false;
374 RC = &X86::GR8RegClass;
378 RC = &X86::GR16RegClass;
382 RC = &X86::GR32RegClass;
385 // Must be in x86-64 mode.
387 RC = &X86::GR64RegClass;
390 if (X86ScalarSSEf32) {
391 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
392 RC = &X86::FR32RegClass;
395 RC = &X86::RFP32RegClass;
399 if (X86ScalarSSEf64) {
400 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
401 RC = &X86::FR64RegClass;
404 RC = &X86::RFP64RegClass;
408 // No f80 support yet.
412 ResultReg = createResultReg(RC);
413 MachineInstrBuilder MIB =
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
415 addFullAddress(MIB, AM);
417 MIB->addMemOperand(*FuncInfo.MF, MMO);
421 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
422 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
423 /// and a displacement offset, or a GlobalAddress,
424 /// i.e. V. Return true if it is possible.
425 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
426 const X86AddressMode &AM,
427 MachineMemOperand *MMO, bool Aligned) {
428 // Get opcode and regclass of the output for the given store instruction.
430 switch (VT.getSimpleVT().SimpleTy) {
431 case MVT::f80: // No f80 support yet.
432 default: return false;
434 // Mask out all but lowest bit.
435 unsigned AndResult = createResultReg(&X86::GR8RegClass);
436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
437 TII.get(X86::AND8ri), AndResult)
438 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
441 // FALLTHROUGH, handling i1 as i8.
442 case MVT::i8: Opc = X86::MOV8mr; break;
443 case MVT::i16: Opc = X86::MOV16mr; break;
444 case MVT::i32: Opc = X86::MOV32mr; break;
445 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
447 Opc = X86ScalarSSEf32 ?
448 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
451 Opc = X86ScalarSSEf64 ?
452 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
456 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
458 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
462 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
464 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
471 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
473 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
477 MachineInstrBuilder MIB =
478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
479 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
481 MIB->addMemOperand(*FuncInfo.MF, MMO);
486 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
487 const X86AddressMode &AM,
488 MachineMemOperand *MMO, bool Aligned) {
489 // Handle 'null' like i32/i64 0.
490 if (isa<ConstantPointerNull>(Val))
491 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
493 // If this is a store of a simple constant, fold the constant into the store.
494 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
497 switch (VT.getSimpleVT().SimpleTy) {
499 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
500 case MVT::i8: Opc = X86::MOV8mi; break;
501 case MVT::i16: Opc = X86::MOV16mi; break;
502 case MVT::i32: Opc = X86::MOV32mi; break;
504 // Must be a 32-bit sign extended value.
505 if (isInt<32>(CI->getSExtValue()))
506 Opc = X86::MOV64mi32;
511 MachineInstrBuilder MIB =
512 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
513 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
514 : CI->getZExtValue());
516 MIB->addMemOperand(*FuncInfo.MF, MMO);
521 unsigned ValReg = getRegForValue(Val);
525 bool ValKill = hasTrivialKill(Val);
526 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
529 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
530 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
531 /// ISD::SIGN_EXTEND).
532 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
533 unsigned Src, EVT SrcVT,
534 unsigned &ResultReg) {
535 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
536 Src, /*TODO: Kill=*/false);
544 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
545 // Handle constant address.
546 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
547 // Can't handle alternate code models yet.
548 if (TM.getCodeModel() != CodeModel::Small)
551 // Can't handle TLS yet.
552 if (GV->isThreadLocal())
555 // RIP-relative addresses can't have additional register operands, so if
556 // we've already folded stuff into the addressing mode, just force the
557 // global value into its own register, which we can use as the basereg.
558 if (!Subtarget->isPICStyleRIPRel() ||
559 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
560 // Okay, we've committed to selecting this global. Set up the address.
563 // Allow the subtarget to classify the global.
564 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
566 // If this reference is relative to the pic base, set it now.
567 if (isGlobalRelativeToPICBase(GVFlags)) {
568 // FIXME: How do we know Base.Reg is free??
569 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
572 // Unless the ABI requires an extra load, return a direct reference to
574 if (!isGlobalStubReference(GVFlags)) {
575 if (Subtarget->isPICStyleRIPRel()) {
576 // Use rip-relative addressing if we can. Above we verified that the
577 // base and index registers are unused.
578 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
579 AM.Base.Reg = X86::RIP;
581 AM.GVOpFlags = GVFlags;
585 // Ok, we need to do a load from a stub. If we've already loaded from
586 // this stub, reuse the loaded pointer, otherwise emit the load now.
587 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
589 if (I != LocalValueMap.end() && I->second != 0) {
592 // Issue load from stub.
594 const TargetRegisterClass *RC = nullptr;
595 X86AddressMode StubAM;
596 StubAM.Base.Reg = AM.Base.Reg;
598 StubAM.GVOpFlags = GVFlags;
600 // Prepare for inserting code in the local-value area.
601 SavePoint SaveInsertPt = enterLocalValueArea();
603 if (TLI.getPointerTy() == MVT::i64) {
605 RC = &X86::GR64RegClass;
607 if (Subtarget->isPICStyleRIPRel())
608 StubAM.Base.Reg = X86::RIP;
611 RC = &X86::GR32RegClass;
614 LoadReg = createResultReg(RC);
615 MachineInstrBuilder LoadMI =
616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
617 addFullAddress(LoadMI, StubAM);
619 // Ok, back to normal mode.
620 leaveLocalValueArea(SaveInsertPt);
622 // Prevent loading GV stub multiple times in same MBB.
623 LocalValueMap[V] = LoadReg;
626 // Now construct the final address. Note that the Disp, Scale,
627 // and Index values may already be set here.
628 AM.Base.Reg = LoadReg;
634 // If all else fails, try to materialize the value in a register.
635 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
636 if (AM.Base.Reg == 0) {
637 AM.Base.Reg = getRegForValue(V);
638 return AM.Base.Reg != 0;
640 if (AM.IndexReg == 0) {
641 assert(AM.Scale == 1 && "Scale with no index!");
642 AM.IndexReg = getRegForValue(V);
643 return AM.IndexReg != 0;
650 /// X86SelectAddress - Attempt to fill in an address from the given value.
652 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
653 SmallVector<const Value *, 32> GEPs;
655 const User *U = nullptr;
656 unsigned Opcode = Instruction::UserOp1;
657 if (const Instruction *I = dyn_cast<Instruction>(V)) {
658 // Don't walk into other basic blocks; it's possible we haven't
659 // visited them yet, so the instructions may not yet be assigned
660 // virtual registers.
661 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
662 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
663 Opcode = I->getOpcode();
666 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
667 Opcode = C->getOpcode();
671 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
672 if (Ty->getAddressSpace() > 255)
673 // Fast instruction selection doesn't support the special
679 case Instruction::BitCast:
680 // Look past bitcasts.
681 return X86SelectAddress(U->getOperand(0), AM);
683 case Instruction::IntToPtr:
684 // Look past no-op inttoptrs.
685 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
686 return X86SelectAddress(U->getOperand(0), AM);
689 case Instruction::PtrToInt:
690 // Look past no-op ptrtoints.
691 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
692 return X86SelectAddress(U->getOperand(0), AM);
695 case Instruction::Alloca: {
696 // Do static allocas.
697 const AllocaInst *A = cast<AllocaInst>(V);
698 DenseMap<const AllocaInst*, int>::iterator SI =
699 FuncInfo.StaticAllocaMap.find(A);
700 if (SI != FuncInfo.StaticAllocaMap.end()) {
701 AM.BaseType = X86AddressMode::FrameIndexBase;
702 AM.Base.FrameIndex = SI->second;
708 case Instruction::Add: {
709 // Adds of constants are common and easy enough.
710 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
711 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
712 // They have to fit in the 32-bit signed displacement field though.
713 if (isInt<32>(Disp)) {
714 AM.Disp = (uint32_t)Disp;
715 return X86SelectAddress(U->getOperand(0), AM);
721 case Instruction::GetElementPtr: {
722 X86AddressMode SavedAM = AM;
724 // Pattern-match simple GEPs.
725 uint64_t Disp = (int32_t)AM.Disp;
726 unsigned IndexReg = AM.IndexReg;
727 unsigned Scale = AM.Scale;
728 gep_type_iterator GTI = gep_type_begin(U);
729 // Iterate through the indices, folding what we can. Constants can be
730 // folded, and one dynamic index can be handled, if the scale is supported.
731 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
732 i != e; ++i, ++GTI) {
733 const Value *Op = *i;
734 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
735 const StructLayout *SL = DL.getStructLayout(STy);
736 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
740 // A array/variable index is always of the form i*S where S is the
741 // constant scale size. See if we can push the scale into immediates.
742 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
744 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
745 // Constant-offset addressing.
746 Disp += CI->getSExtValue() * S;
749 if (canFoldAddIntoGEP(U, Op)) {
750 // A compatible add with a constant operand. Fold the constant.
752 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
753 Disp += CI->getSExtValue() * S;
754 // Iterate on the other operand.
755 Op = cast<AddOperator>(Op)->getOperand(0);
759 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
760 (S == 1 || S == 2 || S == 4 || S == 8)) {
761 // Scaled-index addressing.
763 IndexReg = getRegForGEPIndex(Op).first;
769 goto unsupported_gep;
773 // Check for displacement overflow.
774 if (!isInt<32>(Disp))
777 AM.IndexReg = IndexReg;
779 AM.Disp = (uint32_t)Disp;
782 if (const GetElementPtrInst *GEP =
783 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
784 // Ok, the GEP indices were covered by constant-offset and scaled-index
785 // addressing. Update the address state and move on to examining the base.
788 } else if (X86SelectAddress(U->getOperand(0), AM)) {
792 // If we couldn't merge the gep value into this addr mode, revert back to
793 // our address and just match the value instead of completely failing.
796 for (SmallVectorImpl<const Value *>::reverse_iterator
797 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
798 if (handleConstantAddresses(*I, AM))
803 // Ok, the GEP indices weren't all covered.
808 return handleConstantAddresses(V, AM);
811 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
813 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
814 const User *U = nullptr;
815 unsigned Opcode = Instruction::UserOp1;
816 const Instruction *I = dyn_cast<Instruction>(V);
817 // Record if the value is defined in the same basic block.
819 // This information is crucial to know whether or not folding an
821 // Indeed, FastISel generates or reuses a virtual register for all
822 // operands of all instructions it selects. Obviously, the definition and
823 // its uses must use the same virtual register otherwise the produced
824 // code is incorrect.
825 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
826 // registers for values that are alive across basic blocks. This ensures
827 // that the values are consistently set between across basic block, even
828 // if different instruction selection mechanisms are used (e.g., a mix of
829 // SDISel and FastISel).
830 // For values local to a basic block, the instruction selection process
831 // generates these virtual registers with whatever method is appropriate
832 // for its needs. In particular, FastISel and SDISel do not share the way
833 // local virtual registers are set.
834 // Therefore, this is impossible (or at least unsafe) to share values
835 // between basic blocks unless they use the same instruction selection
836 // method, which is not guarantee for X86.
837 // Moreover, things like hasOneUse could not be used accurately, if we
838 // allow to reference values across basic blocks whereas they are not
839 // alive across basic blocks initially.
842 Opcode = I->getOpcode();
844 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
845 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
846 Opcode = C->getOpcode();
852 case Instruction::BitCast:
853 // Look past bitcasts if its operand is in the same BB.
855 return X86SelectCallAddress(U->getOperand(0), AM);
858 case Instruction::IntToPtr:
859 // Look past no-op inttoptrs if its operand is in the same BB.
861 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
862 return X86SelectCallAddress(U->getOperand(0), AM);
865 case Instruction::PtrToInt:
866 // Look past no-op ptrtoints if its operand is in the same BB.
868 TLI.getValueType(U->getType()) == TLI.getPointerTy())
869 return X86SelectCallAddress(U->getOperand(0), AM);
873 // Handle constant address.
874 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
875 // Can't handle alternate code models yet.
876 if (TM.getCodeModel() != CodeModel::Small)
879 // RIP-relative addresses can't have additional register operands.
880 if (Subtarget->isPICStyleRIPRel() &&
881 (AM.Base.Reg != 0 || AM.IndexReg != 0))
884 // Can't handle DbgLocLImport.
885 if (GV->hasDLLImportStorageClass())
889 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
890 if (GVar->isThreadLocal())
893 // Okay, we've committed to selecting this global. Set up the basic address.
896 // No ABI requires an extra load for anything other than DLLImport, which
897 // we rejected above. Return a direct reference to the global.
898 if (Subtarget->isPICStyleRIPRel()) {
899 // Use rip-relative addressing if we can. Above we verified that the
900 // base and index registers are unused.
901 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
902 AM.Base.Reg = X86::RIP;
903 } else if (Subtarget->isPICStyleStubPIC()) {
904 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
905 } else if (Subtarget->isPICStyleGOT()) {
906 AM.GVOpFlags = X86II::MO_GOTOFF;
912 // If all else fails, try to materialize the value in a register.
913 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
914 if (AM.Base.Reg == 0) {
915 AM.Base.Reg = getRegForValue(V);
916 return AM.Base.Reg != 0;
918 if (AM.IndexReg == 0) {
919 assert(AM.Scale == 1 && "Scale with no index!");
920 AM.IndexReg = getRegForValue(V);
921 return AM.IndexReg != 0;
929 /// X86SelectStore - Select and emit code to implement store instructions.
930 bool X86FastISel::X86SelectStore(const Instruction *I) {
931 // Atomic stores need special handling.
932 const StoreInst *S = cast<StoreInst>(I);
937 const Value *Val = S->getValueOperand();
938 const Value *Ptr = S->getPointerOperand();
941 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
944 unsigned Alignment = S->getAlignment();
945 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
946 if (Alignment == 0) // Ensure that codegen never sees alignment 0
947 Alignment = ABIAlignment;
948 bool Aligned = Alignment >= ABIAlignment;
951 if (!X86SelectAddress(Ptr, AM))
954 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
957 /// X86SelectRet - Select and emit code to implement ret instructions.
958 bool X86FastISel::X86SelectRet(const Instruction *I) {
959 const ReturnInst *Ret = cast<ReturnInst>(I);
960 const Function &F = *I->getParent()->getParent();
961 const X86MachineFunctionInfo *X86MFInfo =
962 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
964 if (!FuncInfo.CanLowerReturn)
967 CallingConv::ID CC = F.getCallingConv();
968 if (CC != CallingConv::C &&
969 CC != CallingConv::Fast &&
970 CC != CallingConv::X86_FastCall &&
971 CC != CallingConv::X86_64_SysV)
974 if (Subtarget->isCallingConvWin64(CC))
977 // Don't handle popping bytes on return for now.
978 if (X86MFInfo->getBytesToPopOnReturn() != 0)
981 // fastcc with -tailcallopt is intended to provide a guaranteed
982 // tail call optimization. Fastisel doesn't know how to do that.
983 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
986 // Let SDISel handle vararg functions.
990 // Build a list of return value registers.
991 SmallVector<unsigned, 4> RetRegs;
993 if (Ret->getNumOperands() > 0) {
994 SmallVector<ISD::OutputArg, 4> Outs;
995 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
997 // Analyze operands of the call, assigning locations to each operand.
998 SmallVector<CCValAssign, 16> ValLocs;
999 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1001 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1003 const Value *RV = Ret->getOperand(0);
1004 unsigned Reg = getRegForValue(RV);
1008 // Only handle a single return value for now.
1009 if (ValLocs.size() != 1)
1012 CCValAssign &VA = ValLocs[0];
1014 // Don't bother handling odd stuff for now.
1015 if (VA.getLocInfo() != CCValAssign::Full)
1017 // Only handle register returns for now.
1021 // The calling-convention tables for x87 returns don't tell
1023 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
1026 unsigned SrcReg = Reg + VA.getValNo();
1027 EVT SrcVT = TLI.getValueType(RV->getType());
1028 EVT DstVT = VA.getValVT();
1029 // Special handling for extended integers.
1030 if (SrcVT != DstVT) {
1031 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1034 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1037 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1039 if (SrcVT == MVT::i1) {
1040 if (Outs[0].Flags.isSExt())
1042 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1045 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1047 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1048 SrcReg, /*TODO: Kill=*/false);
1052 unsigned DstReg = VA.getLocReg();
1053 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1054 // Avoid a cross-class copy. This is very unlikely.
1055 if (!SrcRC->contains(DstReg))
1057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1058 DstReg).addReg(SrcReg);
1060 // Add register to return instruction.
1061 RetRegs.push_back(VA.getLocReg());
1064 // The x86-64 ABI for returning structs by value requires that we copy
1065 // the sret argument into %rax for the return. We saved the argument into
1066 // a virtual register in the entry block, so now we copy the value out
1067 // and into %rax. We also do the same with %eax for Win32.
1068 if (F.hasStructRetAttr() &&
1069 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1070 unsigned Reg = X86MFInfo->getSRetReturnReg();
1072 "SRetReturnReg should have been set in LowerFormalArguments()!");
1073 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1075 RetReg).addReg(Reg);
1076 RetRegs.push_back(RetReg);
1079 // Now emit the RET.
1080 MachineInstrBuilder MIB =
1081 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1082 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1083 MIB.addReg(RetRegs[i], RegState::Implicit);
1087 /// X86SelectLoad - Select and emit code to implement load instructions.
1089 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1090 const LoadInst *LI = cast<LoadInst>(I);
1092 // Atomic loads need special handling.
1097 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1100 const Value *Ptr = LI->getPointerOperand();
1103 if (!X86SelectAddress(Ptr, AM))
1106 unsigned ResultReg = 0;
1107 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1110 UpdateValueMap(I, ResultReg);
1114 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1115 bool HasAVX = Subtarget->hasAVX();
1116 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1117 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1119 switch (VT.getSimpleVT().SimpleTy) {
1121 case MVT::i8: return X86::CMP8rr;
1122 case MVT::i16: return X86::CMP16rr;
1123 case MVT::i32: return X86::CMP32rr;
1124 case MVT::i64: return X86::CMP64rr;
1126 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1128 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1132 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1133 /// of the comparison, return an opcode that works for the compare (e.g.
1134 /// CMP32ri) otherwise return 0.
1135 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1136 switch (VT.getSimpleVT().SimpleTy) {
1137 // Otherwise, we can't fold the immediate into this comparison.
1139 case MVT::i8: return X86::CMP8ri;
1140 case MVT::i16: return X86::CMP16ri;
1141 case MVT::i32: return X86::CMP32ri;
1143 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1145 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1146 return X86::CMP64ri32;
1151 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1153 unsigned Op0Reg = getRegForValue(Op0);
1154 if (Op0Reg == 0) return false;
1156 // Handle 'null' like i32/i64 0.
1157 if (isa<ConstantPointerNull>(Op1))
1158 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1160 // We have two options: compare with register or immediate. If the RHS of
1161 // the compare is an immediate that we can fold into this compare, use
1162 // CMPri, otherwise use CMPrr.
1163 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1164 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1165 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1167 .addImm(Op1C->getSExtValue());
1172 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1173 if (CompareOpc == 0) return false;
1175 unsigned Op1Reg = getRegForValue(Op1);
1176 if (Op1Reg == 0) return false;
1177 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1184 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1185 const CmpInst *CI = cast<CmpInst>(I);
1188 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1191 // Try to optimize or fold the cmp.
1192 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1193 unsigned ResultReg = 0;
1194 switch (Predicate) {
1196 case CmpInst::FCMP_FALSE: {
1197 ResultReg = createResultReg(&X86::GR32RegClass);
1198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1200 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1206 case CmpInst::FCMP_TRUE: {
1207 ResultReg = createResultReg(&X86::GR8RegClass);
1208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1209 ResultReg).addImm(1);
1215 UpdateValueMap(I, ResultReg);
1219 const Value *LHS = CI->getOperand(0);
1220 const Value *RHS = CI->getOperand(1);
1222 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1223 // We don't have to materialize a zero constant for this case and can just use
1224 // %x again on the RHS.
1225 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1226 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1227 if (RHSC && RHSC->isNullValue())
1231 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1232 static unsigned SETFOpcTable[2][3] = {
1233 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1234 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1236 unsigned *SETFOpc = nullptr;
1237 switch (Predicate) {
1239 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1240 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1243 ResultReg = createResultReg(&X86::GR8RegClass);
1245 if (!X86FastEmitCompare(LHS, RHS, VT))
1248 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1249 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1252 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1255 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1256 UpdateValueMap(I, ResultReg);
1262 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1263 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1264 unsigned Opc = X86::getSETFromCond(CC);
1267 std::swap(LHS, RHS);
1269 // Emit a compare of LHS/RHS.
1270 if (!X86FastEmitCompare(LHS, RHS, VT))
1273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1274 UpdateValueMap(I, ResultReg);
1278 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1279 EVT DstVT = TLI.getValueType(I->getType());
1280 if (!TLI.isTypeLegal(DstVT))
1283 unsigned ResultReg = getRegForValue(I->getOperand(0));
1287 // Handle zero-extension from i1 to i8, which is common.
1288 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1289 if (SrcVT.SimpleTy == MVT::i1) {
1290 // Set the high bits to zero.
1291 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1298 if (DstVT == MVT::i64) {
1299 // Handle extension to 64-bits via sub-register shenanigans.
1302 switch (SrcVT.SimpleTy) {
1303 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1304 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1305 case MVT::i32: MovInst = X86::MOV32rr; break;
1306 default: llvm_unreachable("Unexpected zext to i64 source type");
1309 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1313 ResultReg = createResultReg(&X86::GR64RegClass);
1314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1316 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1317 } else if (DstVT != MVT::i8) {
1318 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1319 ResultReg, /*Kill=*/true);
1324 UpdateValueMap(I, ResultReg);
1329 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1330 // Unconditional branches are selected by tablegen-generated code.
1331 // Handle a conditional branch.
1332 const BranchInst *BI = cast<BranchInst>(I);
1333 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1334 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1336 // Fold the common case of a conditional branch with a comparison
1337 // in the same block (values defined on other blocks may not have
1338 // initialized registers).
1340 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1341 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1342 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1344 // Try to optimize or fold the cmp.
1345 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1346 switch (Predicate) {
1348 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1349 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1352 const Value *CmpLHS = CI->getOperand(0);
1353 const Value *CmpRHS = CI->getOperand(1);
1355 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1357 // We don't have to materialize a zero constant for this case and can just
1358 // use %x again on the RHS.
1359 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1360 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1361 if (CmpRHSC && CmpRHSC->isNullValue())
1365 // Try to take advantage of fallthrough opportunities.
1366 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1367 std::swap(TrueMBB, FalseMBB);
1368 Predicate = CmpInst::getInversePredicate(Predicate);
1371 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1372 // code check. Instead two branch instructions are required to check all
1373 // the flags. First we change the predicate to a supported conditon code,
1374 // which will be the first branch. Later one we will emit the second
1376 bool NeedExtraBranch = false;
1377 switch (Predicate) {
1379 case CmpInst::FCMP_OEQ:
1380 std::swap(TrueMBB, FalseMBB); // fall-through
1381 case CmpInst::FCMP_UNE:
1382 NeedExtraBranch = true;
1383 Predicate = CmpInst::FCMP_ONE;
1389 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1390 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1392 BranchOpc = X86::GetCondBranchFromCond(CC);
1394 std::swap(CmpLHS, CmpRHS);
1396 // Emit a compare of the LHS and RHS, setting the flags.
1397 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1403 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1405 if (NeedExtraBranch) {
1406 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1410 // Obtain the branch weight and add the TrueBB to the successor list.
1411 uint32_t BranchWeight = 0;
1413 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1414 TrueMBB->getBasicBlock());
1415 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1417 // Emits an unconditional branch to the FalseBB, obtains the branch
1418 // weight, and adds it to the successor list.
1419 FastEmitBranch(FalseMBB, DbgLoc);
1423 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1424 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1425 // typically happen for _Bool and C++ bools.
1427 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1428 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1429 unsigned TestOpc = 0;
1430 switch (SourceVT.SimpleTy) {
1432 case MVT::i8: TestOpc = X86::TEST8ri; break;
1433 case MVT::i16: TestOpc = X86::TEST16ri; break;
1434 case MVT::i32: TestOpc = X86::TEST32ri; break;
1435 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1438 unsigned OpReg = getRegForValue(TI->getOperand(0));
1439 if (OpReg == 0) return false;
1440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1441 .addReg(OpReg).addImm(1);
1443 unsigned JmpOpc = X86::JNE_4;
1444 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1445 std::swap(TrueMBB, FalseMBB);
1449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1451 FastEmitBranch(FalseMBB, DbgLoc);
1452 uint32_t BranchWeight = 0;
1454 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1455 TrueMBB->getBasicBlock());
1456 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1460 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1461 // Fake request the condition, otherwise the intrinsic might be completely
1463 unsigned TmpReg = getRegForValue(BI->getCondition());
1467 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1469 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1471 FastEmitBranch(FalseMBB, DbgLoc);
1472 uint32_t BranchWeight = 0;
1474 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1475 TrueMBB->getBasicBlock());
1476 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1480 // Otherwise do a clumsy setcc and re-test it.
1481 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1482 // in an explicit cast, so make sure to handle that correctly.
1483 unsigned OpReg = getRegForValue(BI->getCondition());
1484 if (OpReg == 0) return false;
1486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1487 .addReg(OpReg).addImm(1);
1488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1490 FastEmitBranch(FalseMBB, DbgLoc);
1491 uint32_t BranchWeight = 0;
1493 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1494 TrueMBB->getBasicBlock());
1495 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1499 bool X86FastISel::X86SelectShift(const Instruction *I) {
1500 unsigned CReg = 0, OpReg = 0;
1501 const TargetRegisterClass *RC = nullptr;
1502 if (I->getType()->isIntegerTy(8)) {
1504 RC = &X86::GR8RegClass;
1505 switch (I->getOpcode()) {
1506 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1507 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1508 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1509 default: return false;
1511 } else if (I->getType()->isIntegerTy(16)) {
1513 RC = &X86::GR16RegClass;
1514 switch (I->getOpcode()) {
1515 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1516 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1517 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1518 default: return false;
1520 } else if (I->getType()->isIntegerTy(32)) {
1522 RC = &X86::GR32RegClass;
1523 switch (I->getOpcode()) {
1524 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1525 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1526 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1527 default: return false;
1529 } else if (I->getType()->isIntegerTy(64)) {
1531 RC = &X86::GR64RegClass;
1532 switch (I->getOpcode()) {
1533 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1534 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1535 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1536 default: return false;
1543 if (!isTypeLegal(I->getType(), VT))
1546 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1547 if (Op0Reg == 0) return false;
1549 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1550 if (Op1Reg == 0) return false;
1551 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1552 CReg).addReg(Op1Reg);
1554 // The shift instruction uses X86::CL. If we defined a super-register
1555 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1556 if (CReg != X86::CL)
1557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1558 TII.get(TargetOpcode::KILL), X86::CL)
1559 .addReg(CReg, RegState::Kill);
1561 unsigned ResultReg = createResultReg(RC);
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1564 UpdateValueMap(I, ResultReg);
1568 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1569 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1570 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1571 const static bool S = true; // IsSigned
1572 const static bool U = false; // !IsSigned
1573 const static unsigned Copy = TargetOpcode::COPY;
1574 // For the X86 DIV/IDIV instruction, in most cases the dividend
1575 // (numerator) must be in a specific register pair highreg:lowreg,
1576 // producing the quotient in lowreg and the remainder in highreg.
1577 // For most data types, to set up the instruction, the dividend is
1578 // copied into lowreg, and lowreg is sign-extended or zero-extended
1579 // into highreg. The exception is i8, where the dividend is defined
1580 // as a single register rather than a register pair, and we
1581 // therefore directly sign-extend or zero-extend the dividend into
1582 // lowreg, instead of copying, and ignore the highreg.
1583 const static struct DivRemEntry {
1584 // The following portion depends only on the data type.
1585 const TargetRegisterClass *RC;
1586 unsigned LowInReg; // low part of the register pair
1587 unsigned HighInReg; // high part of the register pair
1588 // The following portion depends on both the data type and the operation.
1589 struct DivRemResult {
1590 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1591 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1592 // highreg, or copying a zero into highreg.
1593 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1594 // zero/sign-extending into lowreg for i8.
1595 unsigned DivRemResultReg; // Register containing the desired result.
1596 bool IsOpSigned; // Whether to use signed or unsigned form.
1597 } ResultTable[NumOps];
1598 } OpTable[NumTypes] = {
1599 { &X86::GR8RegClass, X86::AX, 0, {
1600 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1601 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1602 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1603 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1606 { &X86::GR16RegClass, X86::AX, X86::DX, {
1607 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1608 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1609 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1610 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1613 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1614 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1615 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1616 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1617 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1620 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1621 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1622 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1623 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1624 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1630 if (!isTypeLegal(I->getType(), VT))
1633 unsigned TypeIndex, OpIndex;
1634 switch (VT.SimpleTy) {
1635 default: return false;
1636 case MVT::i8: TypeIndex = 0; break;
1637 case MVT::i16: TypeIndex = 1; break;
1638 case MVT::i32: TypeIndex = 2; break;
1639 case MVT::i64: TypeIndex = 3;
1640 if (!Subtarget->is64Bit())
1645 switch (I->getOpcode()) {
1646 default: llvm_unreachable("Unexpected div/rem opcode");
1647 case Instruction::SDiv: OpIndex = 0; break;
1648 case Instruction::SRem: OpIndex = 1; break;
1649 case Instruction::UDiv: OpIndex = 2; break;
1650 case Instruction::URem: OpIndex = 3; break;
1653 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1654 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1655 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1658 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1662 // Move op0 into low-order input register.
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1664 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1665 // Zero-extend or sign-extend into high-order input register.
1666 if (OpEntry.OpSignExtend) {
1667 if (OpEntry.IsOpSigned)
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1669 TII.get(OpEntry.OpSignExtend));
1671 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1673 TII.get(X86::MOV32r0), Zero32);
1675 // Copy the zero into the appropriate sub/super/identical physical
1676 // register. Unfortunately the operations needed are not uniform enough to
1677 // fit neatly into the table above.
1678 if (VT.SimpleTy == MVT::i16) {
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1680 TII.get(Copy), TypeEntry.HighInReg)
1681 .addReg(Zero32, 0, X86::sub_16bit);
1682 } else if (VT.SimpleTy == MVT::i32) {
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1684 TII.get(Copy), TypeEntry.HighInReg)
1686 } else if (VT.SimpleTy == MVT::i64) {
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1688 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1689 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1693 // Generate the DIV/IDIV instruction.
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1695 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1696 // For i8 remainder, we can't reference AH directly, as we'll end
1697 // up with bogus copies like %R9B = COPY %AH. Reference AX
1698 // instead to prevent AH references in a REX instruction.
1700 // The current assumption of the fast register allocator is that isel
1701 // won't generate explicit references to the GPR8_NOREX registers. If
1702 // the allocator and/or the backend get enhanced to be more robust in
1703 // that regard, this can be, and should be, removed.
1704 unsigned ResultReg = 0;
1705 if ((I->getOpcode() == Instruction::SRem ||
1706 I->getOpcode() == Instruction::URem) &&
1707 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1708 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1709 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1711 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1713 // Shift AX right by 8 bits instead of using AH.
1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1715 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1717 // Now reference the 8-bit subreg of the result.
1718 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1719 /*Kill=*/true, X86::sub_8bit);
1721 // Copy the result out of the physreg if we haven't already.
1723 ResultReg = createResultReg(TypeEntry.RC);
1724 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1725 .addReg(OpEntry.DivRemResultReg);
1727 UpdateValueMap(I, ResultReg);
1732 /// \brief Emit a conditional move instruction (if the are supported) to lower
1734 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1735 // Check if the subtarget supports these instructions.
1736 if (!Subtarget->hasCMov())
1739 // FIXME: Add support for i8.
1740 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1743 const Value *Cond = I->getOperand(0);
1744 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1745 bool NeedTest = true;
1746 X86::CondCode CC = X86::COND_NE;
1748 // Optimize conditons coming from a compare if both instructions are in the
1749 // same basic block (values defined in other basic blocks may not have
1750 // initialized registers).
1751 const auto *CI = dyn_cast<CmpInst>(Cond);
1752 if (CI && (CI->getParent() == I->getParent())) {
1753 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1755 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1756 static unsigned SETFOpcTable[2][3] = {
1757 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1758 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1760 unsigned *SETFOpc = nullptr;
1761 switch (Predicate) {
1763 case CmpInst::FCMP_OEQ:
1764 SETFOpc = &SETFOpcTable[0][0];
1765 Predicate = CmpInst::ICMP_NE;
1767 case CmpInst::FCMP_UNE:
1768 SETFOpc = &SETFOpcTable[1][0];
1769 Predicate = CmpInst::ICMP_NE;
1774 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1775 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1777 const Value *CmpLHS = CI->getOperand(0);
1778 const Value *CmpRHS = CI->getOperand(1);
1780 std::swap(CmpLHS, CmpRHS);
1782 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1783 // Emit a compare of the LHS and RHS, setting the flags.
1784 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1788 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1789 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1794 auto const &II = TII.get(SETFOpc[2]);
1795 if (II.getNumDefs()) {
1796 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1798 .addReg(FlagReg2).addReg(FlagReg1);
1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1801 .addReg(FlagReg2).addReg(FlagReg1);
1805 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1806 // Fake request the condition, otherwise the intrinsic might be completely
1808 unsigned TmpReg = getRegForValue(Cond);
1816 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1817 // garbage. Indeed, only the less significant bit is supposed to be
1818 // accurate. If we read more than the lsb, we may see non-zero values
1819 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1820 // the select. This is achieved by performing TEST against 1.
1821 unsigned CondReg = getRegForValue(Cond);
1824 bool CondIsKill = hasTrivialKill(Cond);
1826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1827 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1830 const Value *LHS = I->getOperand(1);
1831 const Value *RHS = I->getOperand(2);
1833 unsigned RHSReg = getRegForValue(RHS);
1834 bool RHSIsKill = hasTrivialKill(RHS);
1836 unsigned LHSReg = getRegForValue(LHS);
1837 bool LHSIsKill = hasTrivialKill(LHS);
1839 if (!LHSReg || !RHSReg)
1842 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1843 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1845 UpdateValueMap(I, ResultReg);
1849 /// \brief Emit SSE instructions to lower the select.
1851 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1852 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1853 /// SSE instructions are available.
1854 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1855 // Optimize conditons coming from a compare if both instructions are in the
1856 // same basic block (values defined in other basic blocks may not have
1857 // initialized registers).
1858 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1859 if (!CI || (CI->getParent() != I->getParent()))
1862 if (I->getType() != CI->getOperand(0)->getType() ||
1863 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1864 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1867 const Value *CmpLHS = CI->getOperand(0);
1868 const Value *CmpRHS = CI->getOperand(1);
1869 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1871 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1872 // We don't have to materialize a zero constant for this case and can just use
1873 // %x again on the RHS.
1874 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1875 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1876 if (CmpRHSC && CmpRHSC->isNullValue())
1882 std::tie(CC, NeedSwap) = getX86SSECondtionCode(Predicate);
1887 std::swap(CmpLHS, CmpRHS);
1889 static unsigned OpcTable[2][2][4] = {
1890 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1891 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1892 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1893 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1896 bool HasAVX = Subtarget->hasAVX();
1897 unsigned *Opc = nullptr;
1898 switch (RetVT.SimpleTy) {
1899 default: return false;
1900 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1901 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1904 const Value *LHS = I->getOperand(1);
1905 const Value *RHS = I->getOperand(2);
1907 unsigned LHSReg = getRegForValue(LHS);
1908 bool LHSIsKill = hasTrivialKill(LHS);
1910 unsigned RHSReg = getRegForValue(RHS);
1911 bool RHSIsKill = hasTrivialKill(RHS);
1913 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1914 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1916 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1917 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1919 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1922 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1923 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1924 CmpRHSReg, CmpRHSIsKill, CC);
1925 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1927 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1929 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1930 AndReg, /*IsKill=*/true);
1931 UpdateValueMap(I, ResultReg);
1935 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1936 // These are pseudo CMOV instructions and will be later expanded into control-
1939 switch (RetVT.SimpleTy) {
1940 default: return false;
1941 case MVT::i8: Opc = X86::CMOV_GR8; break;
1942 case MVT::i16: Opc = X86::CMOV_GR16; break;
1943 case MVT::i32: Opc = X86::CMOV_GR32; break;
1944 case MVT::f32: Opc = X86::CMOV_FR32; break;
1945 case MVT::f64: Opc = X86::CMOV_FR64; break;
1948 const Value *Cond = I->getOperand(0);
1949 X86::CondCode CC = X86::COND_NE;
1951 // Optimize conditons coming from a compare if both instructions are in the
1952 // same basic block (values defined in other basic blocks may not have
1953 // initialized registers).
1954 const auto *CI = dyn_cast<CmpInst>(Cond);
1955 if (CI && (CI->getParent() == I->getParent())) {
1957 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1958 if (CC > X86::LAST_VALID_COND)
1961 const Value *CmpLHS = CI->getOperand(0);
1962 const Value *CmpRHS = CI->getOperand(1);
1965 std::swap(CmpLHS, CmpRHS);
1967 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1968 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1971 unsigned CondReg = getRegForValue(Cond);
1974 bool CondIsKill = hasTrivialKill(Cond);
1975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1976 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1979 const Value *LHS = I->getOperand(1);
1980 const Value *RHS = I->getOperand(2);
1982 unsigned LHSReg = getRegForValue(LHS);
1983 bool LHSIsKill = hasTrivialKill(LHS);
1985 unsigned RHSReg = getRegForValue(RHS);
1986 bool RHSIsKill = hasTrivialKill(RHS);
1988 if (!LHSReg || !RHSReg)
1991 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1993 unsigned ResultReg =
1994 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
1995 UpdateValueMap(I, ResultReg);
1999 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2001 if (!isTypeLegal(I->getType(), RetVT))
2004 // Check if we can fold the select.
2005 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2006 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2007 const Value *Opnd = nullptr;
2008 switch (Predicate) {
2010 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2011 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2013 // No need for a select anymore - this is an unconditional move.
2015 unsigned OpReg = getRegForValue(Opnd);
2018 bool OpIsKill = hasTrivialKill(Opnd);
2019 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2020 unsigned ResultReg = createResultReg(RC);
2021 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2022 TII.get(TargetOpcode::COPY), ResultReg)
2023 .addReg(OpReg, getKillRegState(OpIsKill));
2024 UpdateValueMap(I, ResultReg);
2029 // First try to use real conditional move instructions.
2030 if (X86FastEmitCMoveSelect(RetVT, I))
2033 // Try to use a sequence of SSE instructions to simulate a conditonal move.
2034 if (X86FastEmitSSESelect(RetVT, I))
2037 // Fall-back to pseudo conditional move instructions, which will be later
2038 // converted to control-flow.
2039 if (X86FastEmitPseudoSelect(RetVT, I))
2045 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2046 // fpext from float to double.
2047 if (X86ScalarSSEf64 &&
2048 I->getType()->isDoubleTy()) {
2049 const Value *V = I->getOperand(0);
2050 if (V->getType()->isFloatTy()) {
2051 unsigned OpReg = getRegForValue(V);
2052 if (OpReg == 0) return false;
2053 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
2054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2055 TII.get(X86::CVTSS2SDrr), ResultReg)
2057 UpdateValueMap(I, ResultReg);
2065 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2066 if (X86ScalarSSEf64) {
2067 if (I->getType()->isFloatTy()) {
2068 const Value *V = I->getOperand(0);
2069 if (V->getType()->isDoubleTy()) {
2070 unsigned OpReg = getRegForValue(V);
2071 if (OpReg == 0) return false;
2072 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
2073 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2074 TII.get(X86::CVTSD2SSrr), ResultReg)
2076 UpdateValueMap(I, ResultReg);
2085 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2086 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2087 EVT DstVT = TLI.getValueType(I->getType());
2089 // This code only handles truncation to byte.
2090 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2092 if (!TLI.isTypeLegal(SrcVT))
2095 unsigned InputReg = getRegForValue(I->getOperand(0));
2097 // Unhandled operand. Halt "fast" selection and bail.
2100 if (SrcVT == MVT::i8) {
2101 // Truncate from i8 to i1; no code needed.
2102 UpdateValueMap(I, InputReg);
2106 if (!Subtarget->is64Bit()) {
2107 // If we're on x86-32; we can't extract an i8 from a general register.
2108 // First issue a copy to GR16_ABCD or GR32_ABCD.
2109 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
2110 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
2111 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
2112 unsigned CopyReg = createResultReg(CopyRC);
2113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2114 CopyReg).addReg(InputReg);
2118 // Issue an extract_subreg.
2119 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
2120 InputReg, /*Kill=*/true,
2125 UpdateValueMap(I, ResultReg);
2129 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2130 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2133 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2134 X86AddressMode SrcAM, uint64_t Len) {
2136 // Make sure we don't bloat code by inlining very large memcpy's.
2137 if (!IsMemcpySmall(Len))
2140 bool i64Legal = Subtarget->is64Bit();
2142 // We don't care about alignment here since we just emit integer accesses.
2145 if (Len >= 8 && i64Legal)
2156 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2157 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2158 assert(RV && "Failed to emit load or store??");
2160 unsigned Size = VT.getSizeInBits()/8;
2162 DestAM.Disp += Size;
2169 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
2170 switch (I.getIntrinsicID()) {
2171 case Intrinsic::sadd_with_overflow:
2172 case Intrinsic::uadd_with_overflow:
2173 case Intrinsic::smul_with_overflow:
2174 case Intrinsic::umul_with_overflow:
2181 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
2182 // FIXME: Handle more intrinsics.
2183 switch (I.getIntrinsicID()) {
2184 default: return false;
2185 case Intrinsic::frameaddress: {
2186 Type *RetTy = I.getCalledFunction()->getReturnType();
2189 if (!isTypeLegal(RetTy, VT))
2193 const TargetRegisterClass *RC = nullptr;
2195 switch (VT.SimpleTy) {
2196 default: llvm_unreachable("Invalid result type for frameaddress.");
2197 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2198 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2201 // This needs to be set before we call getFrameRegister, otherwise we get
2202 // the wrong frame register.
2203 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2204 MFI->setFrameAddressIsTaken(true);
2206 const X86RegisterInfo *RegInfo =
2207 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2208 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2209 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2210 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2211 "Invalid Frame Register!");
2213 // Always make a copy of the frame register to to a vreg first, so that we
2214 // never directly reference the frame register (the TwoAddressInstruction-
2215 // Pass doesn't like that).
2216 unsigned SrcReg = createResultReg(RC);
2217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2218 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2220 // Now recursively load from the frame address.
2221 // movq (%rbp), %rax
2222 // movq (%rax), %rax
2223 // movq (%rax), %rax
2226 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2228 DestReg = createResultReg(RC);
2229 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2230 TII.get(Opc), DestReg), SrcReg);
2234 UpdateValueMap(&I, SrcReg);
2237 case Intrinsic::memcpy: {
2238 const MemCpyInst &MCI = cast<MemCpyInst>(I);
2239 // Don't handle volatile or variable length memcpys.
2240 if (MCI.isVolatile())
2243 if (isa<ConstantInt>(MCI.getLength())) {
2244 // Small memcpy's are common enough that we want to do them
2245 // without a call if possible.
2246 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
2247 if (IsMemcpySmall(Len)) {
2248 X86AddressMode DestAM, SrcAM;
2249 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
2250 !X86SelectAddress(MCI.getRawSource(), SrcAM))
2252 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2257 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2258 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
2261 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
2264 return DoSelectCall(&I, "memcpy");
2266 case Intrinsic::memset: {
2267 const MemSetInst &MSI = cast<MemSetInst>(I);
2269 if (MSI.isVolatile())
2272 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2273 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
2276 if (MSI.getDestAddressSpace() > 255)
2279 return DoSelectCall(&I, "memset");
2281 case Intrinsic::stackprotector: {
2282 // Emit code to store the stack guard onto the stack.
2283 EVT PtrTy = TLI.getPointerTy();
2285 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2286 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2288 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2290 // Grab the frame index.
2292 if (!X86SelectAddress(Slot, AM)) return false;
2293 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2296 case Intrinsic::dbg_declare: {
2297 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2299 assert(DI->getAddress() && "Null address should be checked earlier!");
2300 if (!X86SelectAddress(DI->getAddress(), AM))
2302 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2303 // FIXME may need to add RegState::Debug to any registers produced,
2304 // although ESP/EBP should be the only ones at the moment.
2305 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2306 addImm(0).addMetadata(DI->getVariable());
2309 case Intrinsic::trap: {
2310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2313 case Intrinsic::sqrt: {
2314 if (!Subtarget->hasSSE1())
2317 Type *RetTy = I.getCalledFunction()->getReturnType();
2320 if (!isTypeLegal(RetTy, VT))
2323 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
2324 // is not generated by FastISel yet.
2325 // FIXME: Update this code once tablegen can handle it.
2326 static const unsigned SqrtOpc[2][2] = {
2327 {X86::SQRTSSr, X86::VSQRTSSr},
2328 {X86::SQRTSDr, X86::VSQRTSDr}
2330 bool HasAVX = Subtarget->hasAVX();
2332 const TargetRegisterClass *RC;
2333 switch (VT.SimpleTy) {
2334 default: return false;
2335 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2336 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2339 const Value *SrcVal = I.getArgOperand(0);
2340 unsigned SrcReg = getRegForValue(SrcVal);
2345 unsigned ImplicitDefReg = 0;
2347 ImplicitDefReg = createResultReg(RC);
2348 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2349 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2352 unsigned ResultReg = createResultReg(RC);
2353 MachineInstrBuilder MIB;
2354 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2358 MIB.addReg(ImplicitDefReg);
2362 UpdateValueMap(&I, ResultReg);
2365 case Intrinsic::sadd_with_overflow:
2366 case Intrinsic::uadd_with_overflow:
2367 case Intrinsic::ssub_with_overflow:
2368 case Intrinsic::usub_with_overflow:
2369 case Intrinsic::smul_with_overflow:
2370 case Intrinsic::umul_with_overflow: {
2371 // This implements the basic lowering of the xalu with overflow intrinsics
2372 // into add/sub/mul folowed by either seto or setb.
2373 const Function *Callee = I.getCalledFunction();
2374 auto *Ty = cast<StructType>(Callee->getReturnType());
2375 Type *RetTy = Ty->getTypeAtIndex(0U);
2376 Type *CondTy = Ty->getTypeAtIndex(1);
2379 if (!isTypeLegal(RetTy, VT))
2382 if (VT < MVT::i8 || VT > MVT::i64)
2385 const Value *LHS = I.getArgOperand(0);
2386 const Value *RHS = I.getArgOperand(1);
2388 // Canonicalize immediates to the RHS.
2389 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2390 isCommutativeIntrinsic(I))
2391 std::swap(LHS, RHS);
2393 unsigned BaseOpc, CondOpc;
2394 switch (I.getIntrinsicID()) {
2395 default: llvm_unreachable("Unexpected intrinsic!");
2396 case Intrinsic::sadd_with_overflow:
2397 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2398 case Intrinsic::uadd_with_overflow:
2399 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2400 case Intrinsic::ssub_with_overflow:
2401 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2402 case Intrinsic::usub_with_overflow:
2403 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2404 case Intrinsic::smul_with_overflow:
2405 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2406 case Intrinsic::umul_with_overflow:
2407 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2410 unsigned LHSReg = getRegForValue(LHS);
2413 bool LHSIsKill = hasTrivialKill(LHS);
2415 unsigned ResultReg = 0;
2416 // Check if we have an immediate version.
2417 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2418 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2425 RHSReg = getRegForValue(RHS);
2428 RHSIsKill = hasTrivialKill(RHS);
2429 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2433 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2434 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2435 static const unsigned MULOpc[] =
2436 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2437 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2438 // First copy the first operand into RAX, which is an implicit input to
2439 // the X86::MUL*r instruction.
2440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2441 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2442 .addReg(LHSReg, getKillRegState(LHSIsKill));
2443 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2444 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2450 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2451 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2455 UpdateValueMap(&I, ResultReg, 2);
2458 case Intrinsic::x86_sse_cvttss2si:
2459 case Intrinsic::x86_sse_cvttss2si64:
2460 case Intrinsic::x86_sse2_cvttsd2si:
2461 case Intrinsic::x86_sse2_cvttsd2si64: {
2463 switch (I.getIntrinsicID()) {
2464 default: llvm_unreachable("Unexpected intrinsic.");
2465 case Intrinsic::x86_sse_cvttss2si:
2466 case Intrinsic::x86_sse_cvttss2si64:
2467 if (!Subtarget->hasSSE1())
2469 IsInputDouble = false;
2471 case Intrinsic::x86_sse2_cvttsd2si:
2472 case Intrinsic::x86_sse2_cvttsd2si64:
2473 if (!Subtarget->hasSSE2())
2475 IsInputDouble = true;
2479 Type *RetTy = I.getCalledFunction()->getReturnType();
2481 if (!isTypeLegal(RetTy, VT))
2484 static const unsigned CvtOpc[2][2][2] = {
2485 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2486 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2487 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2488 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2490 bool HasAVX = Subtarget->hasAVX();
2492 switch (VT.SimpleTy) {
2493 default: llvm_unreachable("Unexpected result type.");
2494 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2495 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2498 // Check if we can fold insertelement instructions into the convert.
2499 const Value *Op = I.getArgOperand(0);
2500 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2501 const Value *Index = IE->getOperand(2);
2502 if (!isa<ConstantInt>(Index))
2504 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2507 Op = IE->getOperand(1);
2510 Op = IE->getOperand(0);
2513 unsigned Reg = getRegForValue(Op);
2517 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2521 UpdateValueMap(&I, ResultReg);
2527 bool X86FastISel::FastLowerArguments() {
2528 if (!FuncInfo.CanLowerReturn)
2531 const Function *F = FuncInfo.Fn;
2535 CallingConv::ID CC = F->getCallingConv();
2536 if (CC != CallingConv::C)
2539 if (Subtarget->isCallingConvWin64(CC))
2542 if (!Subtarget->is64Bit())
2545 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2546 unsigned GPRCnt = 0;
2547 unsigned FPRCnt = 0;
2549 for (auto const &Arg : F->args()) {
2550 // The first argument is at index 1.
2552 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2553 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2554 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2555 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2558 Type *ArgTy = Arg.getType();
2559 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2562 EVT ArgVT = TLI.getValueType(ArgTy);
2563 if (!ArgVT.isSimple()) return false;
2564 switch (ArgVT.getSimpleVT().SimpleTy) {
2565 default: return false;
2572 if (!Subtarget->hasSSE1())
2585 static const MCPhysReg GPR32ArgRegs[] = {
2586 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2588 static const MCPhysReg GPR64ArgRegs[] = {
2589 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2591 static const MCPhysReg XMMArgRegs[] = {
2592 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2593 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2596 unsigned GPRIdx = 0;
2597 unsigned FPRIdx = 0;
2598 for (auto const &Arg : F->args()) {
2599 MVT VT = TLI.getSimpleValueType(Arg.getType());
2600 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2602 switch (VT.SimpleTy) {
2603 default: llvm_unreachable("Unexpected value type.");
2604 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2605 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2606 case MVT::f32: // fall-through
2607 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2609 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2610 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2611 // Without this, EmitLiveInCopies may eliminate the livein if its only
2612 // use is a bitcast (which isn't turned into an instruction).
2613 unsigned ResultReg = createResultReg(RC);
2614 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2615 TII.get(TargetOpcode::COPY), ResultReg)
2616 .addReg(DstReg, getKillRegState(true));
2617 UpdateValueMap(&Arg, ResultReg);
2622 bool X86FastISel::X86SelectCall(const Instruction *I) {
2623 const CallInst *CI = cast<CallInst>(I);
2624 const Value *Callee = CI->getCalledValue();
2626 // Can't handle inline asm yet.
2627 if (isa<InlineAsm>(Callee))
2630 // Handle intrinsic calls.
2631 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2632 return X86VisitIntrinsicCall(*II);
2634 // Allow SelectionDAG isel to handle tail calls.
2635 if (cast<CallInst>(I)->isTailCall())
2638 return DoSelectCall(I, nullptr);
2641 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2642 const ImmutableCallSite &CS) {
2643 if (Subtarget.is64Bit())
2645 if (Subtarget.getTargetTriple().isOSMSVCRT())
2647 CallingConv::ID CC = CS.getCallingConv();
2648 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2650 if (!CS.paramHasAttr(1, Attribute::StructRet))
2652 if (CS.paramHasAttr(1, Attribute::InReg))
2657 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2658 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2659 const CallInst *CI = cast<CallInst>(I);
2660 const Value *Callee = CI->getCalledValue();
2662 // Handle only C and fastcc calling conventions for now.
2663 ImmutableCallSite CS(CI);
2664 CallingConv::ID CC = CS.getCallingConv();
2665 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2666 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2667 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2668 CC != CallingConv::X86_64_SysV)
2671 // fastcc with -tailcallopt is intended to provide a guaranteed
2672 // tail call optimization. Fastisel doesn't know how to do that.
2673 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2676 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2677 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2678 bool isVarArg = FTy->isVarArg();
2680 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2681 // x86-32. Special handling for x86-64 is implemented.
2682 if (isVarArg && isWin64)
2685 // Don't know about inalloca yet.
2686 if (CS.hasInAllocaArgument())
2689 // Fast-isel doesn't know about callee-pop yet.
2690 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2691 TM.Options.GuaranteedTailCallOpt))
2694 // Check whether the function can return without sret-demotion.
2695 SmallVector<ISD::OutputArg, 4> Outs;
2696 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2697 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2698 *FuncInfo.MF, FTy->isVarArg(),
2699 Outs, FTy->getContext());
2700 if (!CanLowerReturn)
2703 // Materialize callee address in a register. FIXME: GV address can be
2704 // handled with a CALLpcrel32 instead.
2705 X86AddressMode CalleeAM;
2706 if (!X86SelectCallAddress(Callee, CalleeAM))
2708 unsigned CalleeOp = 0;
2709 const GlobalValue *GV = nullptr;
2710 if (CalleeAM.GV != nullptr) {
2712 } else if (CalleeAM.Base.Reg != 0) {
2713 CalleeOp = CalleeAM.Base.Reg;
2717 // Deal with call operands first.
2718 SmallVector<const Value *, 8> ArgVals;
2719 SmallVector<unsigned, 8> Args;
2720 SmallVector<MVT, 8> ArgVTs;
2721 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2722 unsigned arg_size = CS.arg_size();
2723 Args.reserve(arg_size);
2724 ArgVals.reserve(arg_size);
2725 ArgVTs.reserve(arg_size);
2726 ArgFlags.reserve(arg_size);
2727 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2729 // If we're lowering a mem intrinsic instead of a regular call, skip the
2730 // last two arguments, which should not passed to the underlying functions.
2731 if (MemIntName && e-i <= 2)
2734 ISD::ArgFlagsTy Flags;
2735 unsigned AttrInd = i - CS.arg_begin() + 1;
2736 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2738 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2741 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2742 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2743 Type *ElementTy = Ty->getElementType();
2744 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2745 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2747 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2749 Flags.setByValSize(FrameSize);
2750 Flags.setByValAlign(FrameAlign);
2751 if (!IsMemcpySmall(FrameSize))
2755 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2757 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2760 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2761 // instruction. This is safe because it is common to all fastisel supported
2762 // calling conventions on x86.
2763 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2764 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2765 CI->getBitWidth() == 16) {
2767 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2769 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2775 // Passing bools around ends up doing a trunc to i1 and passing it.
2776 // Codegen this as an argument + "and 1".
2777 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2778 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2779 ArgVal->hasOneUse()) {
2780 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2781 ArgReg = getRegForValue(ArgVal);
2782 if (ArgReg == 0) return false;
2785 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2787 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2788 ArgVal->hasOneUse(), 1);
2790 ArgReg = getRegForValue(ArgVal);
2793 if (ArgReg == 0) return false;
2795 Type *ArgTy = ArgVal->getType();
2797 if (!isTypeLegal(ArgTy, ArgVT))
2799 if (ArgVT == MVT::x86mmx)
2801 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2802 Flags.setOrigAlign(OriginalAlignment);
2804 Args.push_back(ArgReg);
2805 ArgVals.push_back(ArgVal);
2806 ArgVTs.push_back(ArgVT);
2807 ArgFlags.push_back(Flags);
2810 // Analyze operands of the call, assigning locations to each operand.
2811 SmallVector<CCValAssign, 16> ArgLocs;
2812 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2813 I->getParent()->getContext());
2815 // Allocate shadow area for Win64
2817 CCInfo.AllocateStack(32, 8);
2819 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2821 // Get a count of how many bytes are to be pushed on the stack.
2822 unsigned NumBytes = CCInfo.getNextStackOffset();
2824 // Issue CALLSEQ_START
2825 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2829 // Process argument: walk the register/memloc assignments, inserting
2831 SmallVector<unsigned, 4> RegArgs;
2832 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2833 CCValAssign &VA = ArgLocs[i];
2834 unsigned Arg = Args[VA.getValNo()];
2835 EVT ArgVT = ArgVTs[VA.getValNo()];
2837 // Promote the value if needed.
2838 switch (VA.getLocInfo()) {
2839 case CCValAssign::Full: break;
2840 case CCValAssign::SExt: {
2841 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2842 "Unexpected extend");
2843 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2845 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2846 ArgVT = VA.getLocVT();
2849 case CCValAssign::ZExt: {
2850 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2851 "Unexpected extend");
2852 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2854 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2855 ArgVT = VA.getLocVT();
2858 case CCValAssign::AExt: {
2859 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2860 "Unexpected extend");
2861 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2864 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2867 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2870 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2871 ArgVT = VA.getLocVT();
2874 case CCValAssign::BCvt: {
2875 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2876 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2877 assert(BC != 0 && "Failed to emit a bitcast!");
2879 ArgVT = VA.getLocVT();
2882 case CCValAssign::VExt:
2883 // VExt has not been implemented, so this should be impossible to reach
2884 // for now. However, fallback to Selection DAG isel once implemented.
2886 case CCValAssign::Indirect:
2887 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2890 case CCValAssign::FPExt:
2891 llvm_unreachable("Unexpected loc info!");
2894 if (VA.isRegLoc()) {
2895 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2896 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2897 RegArgs.push_back(VA.getLocReg());
2899 unsigned LocMemOffset = VA.getLocMemOffset();
2901 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2902 getTargetMachine()->getRegisterInfo());
2903 AM.Base.Reg = RegInfo->getStackRegister();
2904 AM.Disp = LocMemOffset;
2905 const Value *ArgVal = ArgVals[VA.getValNo()];
2906 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2908 if (Flags.isByVal()) {
2909 X86AddressMode SrcAM;
2910 SrcAM.Base.Reg = Arg;
2911 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2912 assert(Res && "memcpy length already checked!"); (void)Res;
2913 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2914 // If this is a really simple value, emit this with the Value* version
2915 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2916 // as it can cause us to reevaluate the argument.
2917 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2920 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2926 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2928 if (Subtarget->isPICStyleGOT()) {
2929 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2930 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2931 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2934 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2935 // Count the number of XMM registers allocated.
2936 static const MCPhysReg XMMArgRegs[] = {
2937 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2938 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2940 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2942 X86::AL).addImm(NumXMMRegs);
2946 MachineInstrBuilder MIB;
2948 // Register-indirect call.
2950 if (Subtarget->is64Bit())
2951 CallOpc = X86::CALL64r;
2953 CallOpc = X86::CALL32r;
2954 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2959 assert(GV && "Not a direct call");
2961 if (Subtarget->is64Bit())
2962 CallOpc = X86::CALL64pcrel32;
2964 CallOpc = X86::CALLpcrel32;
2966 // See if we need any target-specific flags on the GV operand.
2967 unsigned char OpFlags = 0;
2969 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2970 // external symbols most go through the PLT in PIC mode. If the symbol
2971 // has hidden or protected visibility, or if it is static or local, then
2972 // we don't need to use the PLT - we can directly call it.
2973 if (Subtarget->isTargetELF() &&
2974 TM.getRelocationModel() == Reloc::PIC_ &&
2975 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2976 OpFlags = X86II::MO_PLT;
2977 } else if (Subtarget->isPICStyleStubAny() &&
2978 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2979 (!Subtarget->getTargetTriple().isMacOSX() ||
2980 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2981 // PC-relative references to external symbols should go through $stub,
2982 // unless we're building with the leopard linker or later, which
2983 // automatically synthesizes these stubs.
2984 OpFlags = X86II::MO_DARWIN_STUB;
2988 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2990 MIB.addExternalSymbol(MemIntName, OpFlags);
2992 MIB.addGlobalAddress(GV, 0, OpFlags);
2995 // Add a register mask with the call-preserved registers.
2996 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2997 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2999 // Add an implicit use GOT pointer in EBX.
3000 if (Subtarget->isPICStyleGOT())
3001 MIB.addReg(X86::EBX, RegState::Implicit);
3003 if (Subtarget->is64Bit() && isVarArg && !isWin64)
3004 MIB.addReg(X86::AL, RegState::Implicit);
3006 // Add implicit physical register uses to the call.
3007 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
3008 MIB.addReg(RegArgs[i], RegState::Implicit);
3010 // Issue CALLSEQ_END
3011 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3012 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
3013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3014 .addImm(NumBytes).addImm(NumBytesCallee);
3016 // Build info for return calling conv lowering code.
3017 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
3018 SmallVector<ISD::InputArg, 32> Ins;
3019 SmallVector<EVT, 4> RetTys;
3020 ComputeValueVTs(TLI, I->getType(), RetTys);
3021 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
3023 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
3024 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
3025 for (unsigned j = 0; j != NumRegs; ++j) {
3026 ISD::InputArg MyFlags;
3027 MyFlags.VT = RegisterVT;
3028 MyFlags.Used = !CS.getInstruction()->use_empty();
3029 if (CS.paramHasAttr(0, Attribute::SExt))
3030 MyFlags.Flags.setSExt();
3031 if (CS.paramHasAttr(0, Attribute::ZExt))
3032 MyFlags.Flags.setZExt();
3033 if (CS.paramHasAttr(0, Attribute::InReg))
3034 MyFlags.Flags.setInReg();
3035 Ins.push_back(MyFlags);
3039 // Now handle call return values.
3040 SmallVector<unsigned, 4> UsedRegs;
3041 SmallVector<CCValAssign, 16> RVLocs;
3042 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
3043 I->getParent()->getContext());
3044 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
3045 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3046 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3047 EVT CopyVT = RVLocs[i].getValVT();
3048 unsigned CopyReg = ResultReg + i;
3050 // If this is a call to a function that returns an fp value on the x87 fp
3051 // stack, but where we prefer to use the value in xmm registers, copy it
3052 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
3053 if ((RVLocs[i].getLocReg() == X86::ST0 ||
3054 RVLocs[i].getLocReg() == X86::ST1)) {
3055 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
3057 CopyReg = createResultReg(&X86::RFP80RegClass);
3059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3060 TII.get(X86::FpPOP_RETVAL), CopyReg);
3062 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3063 TII.get(TargetOpcode::COPY),
3064 CopyReg).addReg(RVLocs[i].getLocReg());
3065 UsedRegs.push_back(RVLocs[i].getLocReg());
3068 if (CopyVT != RVLocs[i].getValVT()) {
3069 // Round the F80 the right size, which also moves to the appropriate xmm
3070 // register. This is accomplished by storing the F80 value in memory and
3071 // then loading it back. Ewww...
3072 EVT ResVT = RVLocs[i].getValVT();
3073 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3074 unsigned MemSize = ResVT.getSizeInBits()/8;
3075 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3076 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3079 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3080 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3081 TII.get(Opc), ResultReg + i), FI);
3086 UpdateValueMap(I, ResultReg, RVLocs.size());
3088 // Set all unused physreg defs as dead.
3089 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
3096 X86FastISel::TargetSelectInstruction(const Instruction *I) {
3097 switch (I->getOpcode()) {
3099 case Instruction::Load:
3100 return X86SelectLoad(I);
3101 case Instruction::Store:
3102 return X86SelectStore(I);
3103 case Instruction::Ret:
3104 return X86SelectRet(I);
3105 case Instruction::ICmp:
3106 case Instruction::FCmp:
3107 return X86SelectCmp(I);
3108 case Instruction::ZExt:
3109 return X86SelectZExt(I);
3110 case Instruction::Br:
3111 return X86SelectBranch(I);
3112 case Instruction::Call:
3113 return X86SelectCall(I);
3114 case Instruction::LShr:
3115 case Instruction::AShr:
3116 case Instruction::Shl:
3117 return X86SelectShift(I);
3118 case Instruction::SDiv:
3119 case Instruction::UDiv:
3120 case Instruction::SRem:
3121 case Instruction::URem:
3122 return X86SelectDivRem(I);
3123 case Instruction::Select:
3124 return X86SelectSelect(I);
3125 case Instruction::Trunc:
3126 return X86SelectTrunc(I);
3127 case Instruction::FPExt:
3128 return X86SelectFPExt(I);
3129 case Instruction::FPTrunc:
3130 return X86SelectFPTrunc(I);
3131 case Instruction::IntToPtr: // Deliberate fall-through.
3132 case Instruction::PtrToInt: {
3133 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3134 EVT DstVT = TLI.getValueType(I->getType());
3135 if (DstVT.bitsGT(SrcVT))
3136 return X86SelectZExt(I);
3137 if (DstVT.bitsLT(SrcVT))
3138 return X86SelectTrunc(I);
3139 unsigned Reg = getRegForValue(I->getOperand(0));
3140 if (Reg == 0) return false;
3141 UpdateValueMap(I, Reg);
3149 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3151 if (!isTypeLegal(C->getType(), VT))
3154 // Can't handle alternate code models yet.
3155 if (TM.getCodeModel() != CodeModel::Small)
3158 // Get opcode and regclass of the output for the given load instruction.
3160 const TargetRegisterClass *RC = nullptr;
3161 switch (VT.SimpleTy) {
3165 RC = &X86::GR8RegClass;
3169 RC = &X86::GR16RegClass;
3173 RC = &X86::GR32RegClass;
3176 // Must be in x86-64 mode.
3178 RC = &X86::GR64RegClass;
3181 if (X86ScalarSSEf32) {
3182 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3183 RC = &X86::FR32RegClass;
3185 Opc = X86::LD_Fp32m;
3186 RC = &X86::RFP32RegClass;
3190 if (X86ScalarSSEf64) {
3191 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3192 RC = &X86::FR64RegClass;
3194 Opc = X86::LD_Fp64m;
3195 RC = &X86::RFP64RegClass;
3199 // No f80 support yet.
3203 // Materialize addresses with LEA/MOV instructions.
3204 if (isa<GlobalValue>(C)) {
3206 if (X86SelectAddress(C, AM)) {
3207 // If the expression is just a basereg, then we're done, otherwise we need
3209 if (AM.BaseType == X86AddressMode::RegBase &&
3210 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3213 unsigned ResultReg = createResultReg(RC);
3214 if (TM.getRelocationModel() == Reloc::Static &&
3215 TLI.getPointerTy() == MVT::i64) {
3216 // The displacement code be more than 32 bits away so we need to use
3217 // an instruction with a 64 bit immediate
3219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3220 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
3222 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3223 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3224 TII.get(Opc), ResultReg), AM);
3231 // MachineConstantPool wants an explicit alignment.
3232 unsigned Align = DL.getPrefTypeAlignment(C->getType());
3234 // Alignment of vector types. FIXME!
3235 Align = DL.getTypeAllocSize(C->getType());
3238 // x86-32 PIC requires a PIC base register for constant pools.
3239 unsigned PICBase = 0;
3240 unsigned char OpFlag = 0;
3241 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3242 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3243 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3244 } else if (Subtarget->isPICStyleGOT()) {
3245 OpFlag = X86II::MO_GOTOFF;
3246 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3247 } else if (Subtarget->isPICStyleRIPRel() &&
3248 TM.getCodeModel() == CodeModel::Small) {
3252 // Create the load from the constant pool.
3253 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
3254 unsigned ResultReg = createResultReg(RC);
3255 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3256 TII.get(Opc), ResultReg),
3257 MCPOffset, PICBase, OpFlag);
3262 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3263 // Fail on dynamic allocas. At this point, getRegForValue has already
3264 // checked its CSE maps, so if we're here trying to handle a dynamic
3265 // alloca, we're not going to succeed. X86SelectAddress has a
3266 // check for dynamic allocas, because it's called directly from
3267 // various places, but TargetMaterializeAlloca also needs a check
3268 // in order to avoid recursion between getRegForValue,
3269 // X86SelectAddrss, and TargetMaterializeAlloca.
3270 if (!FuncInfo.StaticAllocaMap.count(C))
3272 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3275 if (!X86SelectAddress(C, AM))
3277 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3278 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3279 unsigned ResultReg = createResultReg(RC);
3280 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3281 TII.get(Opc), ResultReg), AM);
3285 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3287 if (!isTypeLegal(CF->getType(), VT))
3290 // Get opcode and regclass for the given zero.
3292 const TargetRegisterClass *RC = nullptr;
3293 switch (VT.SimpleTy) {
3296 if (X86ScalarSSEf32) {
3297 Opc = X86::FsFLD0SS;
3298 RC = &X86::FR32RegClass;
3300 Opc = X86::LD_Fp032;
3301 RC = &X86::RFP32RegClass;
3305 if (X86ScalarSSEf64) {
3306 Opc = X86::FsFLD0SD;
3307 RC = &X86::FR64RegClass;
3309 Opc = X86::LD_Fp064;
3310 RC = &X86::RFP64RegClass;
3314 // No f80 support yet.
3318 unsigned ResultReg = createResultReg(RC);
3319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3324 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3325 const LoadInst *LI) {
3326 const Value *Ptr = LI->getPointerOperand();
3328 if (!X86SelectAddress(Ptr, AM))
3331 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3333 unsigned Size = DL.getTypeAllocSize(LI->getType());
3334 unsigned Alignment = LI->getAlignment();
3336 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3337 Alignment = DL.getABITypeAlignment(LI->getType());
3339 SmallVector<MachineOperand, 8> AddrOps;
3340 AM.getFullAddress(AddrOps);
3342 MachineInstr *Result =
3343 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3347 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3348 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3349 MI->eraseFromParent();
3355 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3356 const TargetLibraryInfo *libInfo) {
3357 return new X86FastISel(funcInfo, libInfo);