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;
77 bool FastLowerCall(CallLoweringInfo &CLI) override;
79 #include "X86GenFastISel.inc"
82 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
84 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
87 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
88 MachineMemOperand *MMO = nullptr, bool Aligned = false);
89 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
90 const X86AddressMode &AM,
91 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
96 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
97 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
99 bool X86SelectLoad(const Instruction *I);
101 bool X86SelectStore(const Instruction *I);
103 bool X86SelectRet(const Instruction *I);
105 bool X86SelectCmp(const Instruction *I);
107 bool X86SelectZExt(const Instruction *I);
109 bool X86SelectBranch(const Instruction *I);
111 bool X86SelectShift(const Instruction *I);
113 bool X86SelectDivRem(const Instruction *I);
115 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
117 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
119 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
121 bool X86SelectSelect(const Instruction *I);
123 bool X86SelectTrunc(const Instruction *I);
125 bool X86SelectFPExt(const Instruction *I);
126 bool X86SelectFPTrunc(const Instruction *I);
128 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
129 bool X86SelectCall(const Instruction *I);
131 bool DoSelectCall(const Instruction *I, const char *MemIntName);
133 const X86InstrInfo *getInstrInfo() const {
134 return getTargetMachine()->getInstrInfo();
136 const X86TargetMachine *getTargetMachine() const {
137 return static_cast<const X86TargetMachine *>(&TM);
140 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
142 unsigned TargetMaterializeConstant(const Constant *C) override;
144 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
146 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
148 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
149 /// computed in an SSE register, not on the X87 floating point stack.
150 bool isScalarFPTypeInSSEReg(EVT VT) const {
151 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
152 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
155 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
157 bool IsMemcpySmall(uint64_t Len);
159 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
160 X86AddressMode SrcAM, uint64_t Len);
162 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
166 } // end anonymous namespace.
168 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
169 // If both operands are the same, then try to optimize or fold the cmp.
170 CmpInst::Predicate Predicate = CI->getPredicate();
171 if (CI->getOperand(0) != CI->getOperand(1))
175 default: llvm_unreachable("Invalid predicate!");
176 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
177 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
178 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
179 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
180 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
181 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
182 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
183 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
184 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
185 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
186 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
187 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
188 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
189 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
190 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
191 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
194 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
195 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
196 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
197 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
198 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
199 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
200 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
201 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
202 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
208 static std::pair<X86::CondCode, bool>
209 getX86ConditionCode(CmpInst::Predicate Predicate) {
210 X86::CondCode CC = X86::COND_INVALID;
211 bool NeedSwap = false;
214 // Floating-point Predicates
215 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
216 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
217 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
218 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
219 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
220 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
221 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
222 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
223 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
224 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
225 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
226 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
227 case CmpInst::FCMP_OEQ: // fall-through
228 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
230 // Integer Predicates
231 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
232 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
233 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
234 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
235 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
236 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
237 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
238 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
239 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
240 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
243 return std::make_pair(CC, NeedSwap);
246 static std::pair<unsigned, bool>
247 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
249 bool NeedSwap = false;
251 // SSE Condition code mapping:
261 default: llvm_unreachable("Unexpected predicate");
262 case CmpInst::FCMP_OEQ: CC = 0; break;
263 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
264 case CmpInst::FCMP_OLT: CC = 1; break;
265 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
266 case CmpInst::FCMP_OLE: CC = 2; break;
267 case CmpInst::FCMP_UNO: CC = 3; break;
268 case CmpInst::FCMP_UNE: CC = 4; break;
269 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
270 case CmpInst::FCMP_UGE: CC = 5; break;
271 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
272 case CmpInst::FCMP_UGT: CC = 6; break;
273 case CmpInst::FCMP_ORD: CC = 7; break;
274 case CmpInst::FCMP_UEQ:
275 case CmpInst::FCMP_ONE: CC = 8; break;
278 return std::make_pair(CC, NeedSwap);
281 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
282 /// into the user. The condition code will only be updated on success.
283 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
285 if (!isa<ExtractValueInst>(Cond))
288 const auto *EV = cast<ExtractValueInst>(Cond);
289 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
292 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
294 const Function *Callee = II->getCalledFunction();
296 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
297 if (!isTypeLegal(RetTy, RetVT))
300 if (RetVT != MVT::i32 && RetVT != MVT::i64)
304 switch (II->getIntrinsicID()) {
305 default: return false;
306 case Intrinsic::sadd_with_overflow:
307 case Intrinsic::ssub_with_overflow:
308 case Intrinsic::smul_with_overflow:
309 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
310 case Intrinsic::uadd_with_overflow:
311 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
314 // Check if both instructions are in the same basic block.
315 if (II->getParent() != I->getParent())
318 // Make sure nothing is in the way
319 BasicBlock::const_iterator Start = I;
320 BasicBlock::const_iterator End = II;
321 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
322 // We only expect extractvalue instructions between the intrinsic and the
323 // instruction to be selected.
324 if (!isa<ExtractValueInst>(Itr))
327 // Check that the extractvalue operand comes from the intrinsic.
328 const auto *EVI = cast<ExtractValueInst>(Itr);
329 if (EVI->getAggregateOperand() != II)
337 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
338 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
339 if (evt == MVT::Other || !evt.isSimple())
340 // Unhandled type. Halt "fast" selection and bail.
343 VT = evt.getSimpleVT();
344 // For now, require SSE/SSE2 for performing floating-point operations,
345 // since x87 requires additional work.
346 if (VT == MVT::f64 && !X86ScalarSSEf64)
348 if (VT == MVT::f32 && !X86ScalarSSEf32)
350 // Similarly, no f80 support yet.
353 // We only handle legal types. For example, on x86-32 the instruction
354 // selector contains all of the 64-bit instructions from x86-64,
355 // under the assumption that i64 won't be used if the target doesn't
357 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
360 #include "X86GenCallingConv.inc"
362 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
363 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
364 /// Return true and the result register by reference if it is possible.
365 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
366 MachineMemOperand *MMO, unsigned &ResultReg) {
367 // Get opcode and regclass of the output for the given load instruction.
369 const TargetRegisterClass *RC = nullptr;
370 switch (VT.getSimpleVT().SimpleTy) {
371 default: return false;
375 RC = &X86::GR8RegClass;
379 RC = &X86::GR16RegClass;
383 RC = &X86::GR32RegClass;
386 // Must be in x86-64 mode.
388 RC = &X86::GR64RegClass;
391 if (X86ScalarSSEf32) {
392 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
393 RC = &X86::FR32RegClass;
396 RC = &X86::RFP32RegClass;
400 if (X86ScalarSSEf64) {
401 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
402 RC = &X86::FR64RegClass;
405 RC = &X86::RFP64RegClass;
409 // No f80 support yet.
413 ResultReg = createResultReg(RC);
414 MachineInstrBuilder MIB =
415 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
416 addFullAddress(MIB, AM);
418 MIB->addMemOperand(*FuncInfo.MF, MMO);
422 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
423 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
424 /// and a displacement offset, or a GlobalAddress,
425 /// i.e. V. Return true if it is possible.
426 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
427 const X86AddressMode &AM,
428 MachineMemOperand *MMO, bool Aligned) {
429 // Get opcode and regclass of the output for the given store instruction.
431 switch (VT.getSimpleVT().SimpleTy) {
432 case MVT::f80: // No f80 support yet.
433 default: return false;
435 // Mask out all but lowest bit.
436 unsigned AndResult = createResultReg(&X86::GR8RegClass);
437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
438 TII.get(X86::AND8ri), AndResult)
439 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
442 // FALLTHROUGH, handling i1 as i8.
443 case MVT::i8: Opc = X86::MOV8mr; break;
444 case MVT::i16: Opc = X86::MOV16mr; break;
445 case MVT::i32: Opc = X86::MOV32mr; break;
446 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
448 Opc = X86ScalarSSEf32 ?
449 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
452 Opc = X86ScalarSSEf64 ?
453 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
457 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
459 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
463 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
465 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
472 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
474 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
478 MachineInstrBuilder MIB =
479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
480 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
482 MIB->addMemOperand(*FuncInfo.MF, MMO);
487 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
488 const X86AddressMode &AM,
489 MachineMemOperand *MMO, bool Aligned) {
490 // Handle 'null' like i32/i64 0.
491 if (isa<ConstantPointerNull>(Val))
492 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
494 // If this is a store of a simple constant, fold the constant into the store.
495 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
498 switch (VT.getSimpleVT().SimpleTy) {
500 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
501 case MVT::i8: Opc = X86::MOV8mi; break;
502 case MVT::i16: Opc = X86::MOV16mi; break;
503 case MVT::i32: Opc = X86::MOV32mi; break;
505 // Must be a 32-bit sign extended value.
506 if (isInt<32>(CI->getSExtValue()))
507 Opc = X86::MOV64mi32;
512 MachineInstrBuilder MIB =
513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
514 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
515 : CI->getZExtValue());
517 MIB->addMemOperand(*FuncInfo.MF, MMO);
522 unsigned ValReg = getRegForValue(Val);
526 bool ValKill = hasTrivialKill(Val);
527 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
530 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
531 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
532 /// ISD::SIGN_EXTEND).
533 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
534 unsigned Src, EVT SrcVT,
535 unsigned &ResultReg) {
536 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
537 Src, /*TODO: Kill=*/false);
545 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
546 // Handle constant address.
547 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
548 // Can't handle alternate code models yet.
549 if (TM.getCodeModel() != CodeModel::Small)
552 // Can't handle TLS yet.
553 if (GV->isThreadLocal())
556 // RIP-relative addresses can't have additional register operands, so if
557 // we've already folded stuff into the addressing mode, just force the
558 // global value into its own register, which we can use as the basereg.
559 if (!Subtarget->isPICStyleRIPRel() ||
560 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
561 // Okay, we've committed to selecting this global. Set up the address.
564 // Allow the subtarget to classify the global.
565 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
567 // If this reference is relative to the pic base, set it now.
568 if (isGlobalRelativeToPICBase(GVFlags)) {
569 // FIXME: How do we know Base.Reg is free??
570 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
573 // Unless the ABI requires an extra load, return a direct reference to
575 if (!isGlobalStubReference(GVFlags)) {
576 if (Subtarget->isPICStyleRIPRel()) {
577 // Use rip-relative addressing if we can. Above we verified that the
578 // base and index registers are unused.
579 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
580 AM.Base.Reg = X86::RIP;
582 AM.GVOpFlags = GVFlags;
586 // Ok, we need to do a load from a stub. If we've already loaded from
587 // this stub, reuse the loaded pointer, otherwise emit the load now.
588 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
590 if (I != LocalValueMap.end() && I->second != 0) {
593 // Issue load from stub.
595 const TargetRegisterClass *RC = nullptr;
596 X86AddressMode StubAM;
597 StubAM.Base.Reg = AM.Base.Reg;
599 StubAM.GVOpFlags = GVFlags;
601 // Prepare for inserting code in the local-value area.
602 SavePoint SaveInsertPt = enterLocalValueArea();
604 if (TLI.getPointerTy() == MVT::i64) {
606 RC = &X86::GR64RegClass;
608 if (Subtarget->isPICStyleRIPRel())
609 StubAM.Base.Reg = X86::RIP;
612 RC = &X86::GR32RegClass;
615 LoadReg = createResultReg(RC);
616 MachineInstrBuilder LoadMI =
617 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
618 addFullAddress(LoadMI, StubAM);
620 // Ok, back to normal mode.
621 leaveLocalValueArea(SaveInsertPt);
623 // Prevent loading GV stub multiple times in same MBB.
624 LocalValueMap[V] = LoadReg;
627 // Now construct the final address. Note that the Disp, Scale,
628 // and Index values may already be set here.
629 AM.Base.Reg = LoadReg;
635 // If all else fails, try to materialize the value in a register.
636 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
637 if (AM.Base.Reg == 0) {
638 AM.Base.Reg = getRegForValue(V);
639 return AM.Base.Reg != 0;
641 if (AM.IndexReg == 0) {
642 assert(AM.Scale == 1 && "Scale with no index!");
643 AM.IndexReg = getRegForValue(V);
644 return AM.IndexReg != 0;
651 /// X86SelectAddress - Attempt to fill in an address from the given value.
653 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
654 SmallVector<const Value *, 32> GEPs;
656 const User *U = nullptr;
657 unsigned Opcode = Instruction::UserOp1;
658 if (const Instruction *I = dyn_cast<Instruction>(V)) {
659 // Don't walk into other basic blocks; it's possible we haven't
660 // visited them yet, so the instructions may not yet be assigned
661 // virtual registers.
662 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
663 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
664 Opcode = I->getOpcode();
667 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
668 Opcode = C->getOpcode();
672 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
673 if (Ty->getAddressSpace() > 255)
674 // Fast instruction selection doesn't support the special
680 case Instruction::BitCast:
681 // Look past bitcasts.
682 return X86SelectAddress(U->getOperand(0), AM);
684 case Instruction::IntToPtr:
685 // Look past no-op inttoptrs.
686 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
687 return X86SelectAddress(U->getOperand(0), AM);
690 case Instruction::PtrToInt:
691 // Look past no-op ptrtoints.
692 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
693 return X86SelectAddress(U->getOperand(0), AM);
696 case Instruction::Alloca: {
697 // Do static allocas.
698 const AllocaInst *A = cast<AllocaInst>(V);
699 DenseMap<const AllocaInst*, int>::iterator SI =
700 FuncInfo.StaticAllocaMap.find(A);
701 if (SI != FuncInfo.StaticAllocaMap.end()) {
702 AM.BaseType = X86AddressMode::FrameIndexBase;
703 AM.Base.FrameIndex = SI->second;
709 case Instruction::Add: {
710 // Adds of constants are common and easy enough.
711 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
712 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
713 // They have to fit in the 32-bit signed displacement field though.
714 if (isInt<32>(Disp)) {
715 AM.Disp = (uint32_t)Disp;
716 return X86SelectAddress(U->getOperand(0), AM);
722 case Instruction::GetElementPtr: {
723 X86AddressMode SavedAM = AM;
725 // Pattern-match simple GEPs.
726 uint64_t Disp = (int32_t)AM.Disp;
727 unsigned IndexReg = AM.IndexReg;
728 unsigned Scale = AM.Scale;
729 gep_type_iterator GTI = gep_type_begin(U);
730 // Iterate through the indices, folding what we can. Constants can be
731 // folded, and one dynamic index can be handled, if the scale is supported.
732 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
733 i != e; ++i, ++GTI) {
734 const Value *Op = *i;
735 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
736 const StructLayout *SL = DL.getStructLayout(STy);
737 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
741 // A array/variable index is always of the form i*S where S is the
742 // constant scale size. See if we can push the scale into immediates.
743 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
745 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
746 // Constant-offset addressing.
747 Disp += CI->getSExtValue() * S;
750 if (canFoldAddIntoGEP(U, Op)) {
751 // A compatible add with a constant operand. Fold the constant.
753 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
754 Disp += CI->getSExtValue() * S;
755 // Iterate on the other operand.
756 Op = cast<AddOperator>(Op)->getOperand(0);
760 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
761 (S == 1 || S == 2 || S == 4 || S == 8)) {
762 // Scaled-index addressing.
764 IndexReg = getRegForGEPIndex(Op).first;
770 goto unsupported_gep;
774 // Check for displacement overflow.
775 if (!isInt<32>(Disp))
778 AM.IndexReg = IndexReg;
780 AM.Disp = (uint32_t)Disp;
783 if (const GetElementPtrInst *GEP =
784 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
785 // Ok, the GEP indices were covered by constant-offset and scaled-index
786 // addressing. Update the address state and move on to examining the base.
789 } else if (X86SelectAddress(U->getOperand(0), AM)) {
793 // If we couldn't merge the gep value into this addr mode, revert back to
794 // our address and just match the value instead of completely failing.
797 for (SmallVectorImpl<const Value *>::reverse_iterator
798 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
799 if (handleConstantAddresses(*I, AM))
804 // Ok, the GEP indices weren't all covered.
809 return handleConstantAddresses(V, AM);
812 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
814 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
815 const User *U = nullptr;
816 unsigned Opcode = Instruction::UserOp1;
817 const Instruction *I = dyn_cast<Instruction>(V);
818 // Record if the value is defined in the same basic block.
820 // This information is crucial to know whether or not folding an
822 // Indeed, FastISel generates or reuses a virtual register for all
823 // operands of all instructions it selects. Obviously, the definition and
824 // its uses must use the same virtual register otherwise the produced
825 // code is incorrect.
826 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
827 // registers for values that are alive across basic blocks. This ensures
828 // that the values are consistently set between across basic block, even
829 // if different instruction selection mechanisms are used (e.g., a mix of
830 // SDISel and FastISel).
831 // For values local to a basic block, the instruction selection process
832 // generates these virtual registers with whatever method is appropriate
833 // for its needs. In particular, FastISel and SDISel do not share the way
834 // local virtual registers are set.
835 // Therefore, this is impossible (or at least unsafe) to share values
836 // between basic blocks unless they use the same instruction selection
837 // method, which is not guarantee for X86.
838 // Moreover, things like hasOneUse could not be used accurately, if we
839 // allow to reference values across basic blocks whereas they are not
840 // alive across basic blocks initially.
843 Opcode = I->getOpcode();
845 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
846 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
847 Opcode = C->getOpcode();
853 case Instruction::BitCast:
854 // Look past bitcasts if its operand is in the same BB.
856 return X86SelectCallAddress(U->getOperand(0), AM);
859 case Instruction::IntToPtr:
860 // Look past no-op inttoptrs if its operand is in the same BB.
862 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
863 return X86SelectCallAddress(U->getOperand(0), AM);
866 case Instruction::PtrToInt:
867 // Look past no-op ptrtoints if its operand is in the same BB.
869 TLI.getValueType(U->getType()) == TLI.getPointerTy())
870 return X86SelectCallAddress(U->getOperand(0), AM);
874 // Handle constant address.
875 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
876 // Can't handle alternate code models yet.
877 if (TM.getCodeModel() != CodeModel::Small)
880 // RIP-relative addresses can't have additional register operands.
881 if (Subtarget->isPICStyleRIPRel() &&
882 (AM.Base.Reg != 0 || AM.IndexReg != 0))
885 // Can't handle DLL Import.
886 if (GV->hasDLLImportStorageClass())
890 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
891 if (GVar->isThreadLocal())
894 // Okay, we've committed to selecting this global. Set up the basic address.
897 // No ABI requires an extra load for anything other than DLLImport, which
898 // we rejected above. Return a direct reference to the global.
899 if (Subtarget->isPICStyleRIPRel()) {
900 // Use rip-relative addressing if we can. Above we verified that the
901 // base and index registers are unused.
902 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
903 AM.Base.Reg = X86::RIP;
904 } else if (Subtarget->isPICStyleStubPIC()) {
905 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
906 } else if (Subtarget->isPICStyleGOT()) {
907 AM.GVOpFlags = X86II::MO_GOTOFF;
913 // If all else fails, try to materialize the value in a register.
914 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
915 if (AM.Base.Reg == 0) {
916 AM.Base.Reg = getRegForValue(V);
917 return AM.Base.Reg != 0;
919 if (AM.IndexReg == 0) {
920 assert(AM.Scale == 1 && "Scale with no index!");
921 AM.IndexReg = getRegForValue(V);
922 return AM.IndexReg != 0;
930 /// X86SelectStore - Select and emit code to implement store instructions.
931 bool X86FastISel::X86SelectStore(const Instruction *I) {
932 // Atomic stores need special handling.
933 const StoreInst *S = cast<StoreInst>(I);
938 const Value *Val = S->getValueOperand();
939 const Value *Ptr = S->getPointerOperand();
942 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
945 unsigned Alignment = S->getAlignment();
946 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
947 if (Alignment == 0) // Ensure that codegen never sees alignment 0
948 Alignment = ABIAlignment;
949 bool Aligned = Alignment >= ABIAlignment;
952 if (!X86SelectAddress(Ptr, AM))
955 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
958 /// X86SelectRet - Select and emit code to implement ret instructions.
959 bool X86FastISel::X86SelectRet(const Instruction *I) {
960 const ReturnInst *Ret = cast<ReturnInst>(I);
961 const Function &F = *I->getParent()->getParent();
962 const X86MachineFunctionInfo *X86MFInfo =
963 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
965 if (!FuncInfo.CanLowerReturn)
968 CallingConv::ID CC = F.getCallingConv();
969 if (CC != CallingConv::C &&
970 CC != CallingConv::Fast &&
971 CC != CallingConv::X86_FastCall &&
972 CC != CallingConv::X86_64_SysV)
975 if (Subtarget->isCallingConvWin64(CC))
978 // Don't handle popping bytes on return for now.
979 if (X86MFInfo->getBytesToPopOnReturn() != 0)
982 // fastcc with -tailcallopt is intended to provide a guaranteed
983 // tail call optimization. Fastisel doesn't know how to do that.
984 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
987 // Let SDISel handle vararg functions.
991 // Build a list of return value registers.
992 SmallVector<unsigned, 4> RetRegs;
994 if (Ret->getNumOperands() > 0) {
995 SmallVector<ISD::OutputArg, 4> Outs;
996 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
998 // Analyze operands of the call, assigning locations to each operand.
999 SmallVector<CCValAssign, 16> ValLocs;
1000 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1002 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1004 const Value *RV = Ret->getOperand(0);
1005 unsigned Reg = getRegForValue(RV);
1009 // Only handle a single return value for now.
1010 if (ValLocs.size() != 1)
1013 CCValAssign &VA = ValLocs[0];
1015 // Don't bother handling odd stuff for now.
1016 if (VA.getLocInfo() != CCValAssign::Full)
1018 // Only handle register returns for now.
1022 // The calling-convention tables for x87 returns don't tell
1024 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
1027 unsigned SrcReg = Reg + VA.getValNo();
1028 EVT SrcVT = TLI.getValueType(RV->getType());
1029 EVT DstVT = VA.getValVT();
1030 // Special handling for extended integers.
1031 if (SrcVT != DstVT) {
1032 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1035 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1038 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1040 if (SrcVT == MVT::i1) {
1041 if (Outs[0].Flags.isSExt())
1043 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1046 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1048 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1049 SrcReg, /*TODO: Kill=*/false);
1053 unsigned DstReg = VA.getLocReg();
1054 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1055 // Avoid a cross-class copy. This is very unlikely.
1056 if (!SrcRC->contains(DstReg))
1058 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1059 DstReg).addReg(SrcReg);
1061 // Add register to return instruction.
1062 RetRegs.push_back(VA.getLocReg());
1065 // The x86-64 ABI for returning structs by value requires that we copy
1066 // the sret argument into %rax for the return. We saved the argument into
1067 // a virtual register in the entry block, so now we copy the value out
1068 // and into %rax. We also do the same with %eax for Win32.
1069 if (F.hasStructRetAttr() &&
1070 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1071 unsigned Reg = X86MFInfo->getSRetReturnReg();
1073 "SRetReturnReg should have been set in LowerFormalArguments()!");
1074 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1075 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1076 RetReg).addReg(Reg);
1077 RetRegs.push_back(RetReg);
1080 // Now emit the RET.
1081 MachineInstrBuilder MIB =
1082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1083 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1084 MIB.addReg(RetRegs[i], RegState::Implicit);
1088 /// X86SelectLoad - Select and emit code to implement load instructions.
1090 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1091 const LoadInst *LI = cast<LoadInst>(I);
1093 // Atomic loads need special handling.
1098 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1101 const Value *Ptr = LI->getPointerOperand();
1104 if (!X86SelectAddress(Ptr, AM))
1107 unsigned ResultReg = 0;
1108 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1111 UpdateValueMap(I, ResultReg);
1115 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1116 bool HasAVX = Subtarget->hasAVX();
1117 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1118 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1120 switch (VT.getSimpleVT().SimpleTy) {
1122 case MVT::i8: return X86::CMP8rr;
1123 case MVT::i16: return X86::CMP16rr;
1124 case MVT::i32: return X86::CMP32rr;
1125 case MVT::i64: return X86::CMP64rr;
1127 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1129 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1133 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1134 /// of the comparison, return an opcode that works for the compare (e.g.
1135 /// CMP32ri) otherwise return 0.
1136 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1137 switch (VT.getSimpleVT().SimpleTy) {
1138 // Otherwise, we can't fold the immediate into this comparison.
1140 case MVT::i8: return X86::CMP8ri;
1141 case MVT::i16: return X86::CMP16ri;
1142 case MVT::i32: return X86::CMP32ri;
1144 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1146 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1147 return X86::CMP64ri32;
1152 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1154 unsigned Op0Reg = getRegForValue(Op0);
1155 if (Op0Reg == 0) return false;
1157 // Handle 'null' like i32/i64 0.
1158 if (isa<ConstantPointerNull>(Op1))
1159 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1161 // We have two options: compare with register or immediate. If the RHS of
1162 // the compare is an immediate that we can fold into this compare, use
1163 // CMPri, otherwise use CMPrr.
1164 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1165 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1166 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1168 .addImm(Op1C->getSExtValue());
1173 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1174 if (CompareOpc == 0) return false;
1176 unsigned Op1Reg = getRegForValue(Op1);
1177 if (Op1Reg == 0) return false;
1178 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1185 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1186 const CmpInst *CI = cast<CmpInst>(I);
1189 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1192 // Try to optimize or fold the cmp.
1193 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1194 unsigned ResultReg = 0;
1195 switch (Predicate) {
1197 case CmpInst::FCMP_FALSE: {
1198 ResultReg = createResultReg(&X86::GR32RegClass);
1199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1201 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1207 case CmpInst::FCMP_TRUE: {
1208 ResultReg = createResultReg(&X86::GR8RegClass);
1209 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1210 ResultReg).addImm(1);
1216 UpdateValueMap(I, ResultReg);
1220 const Value *LHS = CI->getOperand(0);
1221 const Value *RHS = CI->getOperand(1);
1223 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1224 // We don't have to materialize a zero constant for this case and can just use
1225 // %x again on the RHS.
1226 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1227 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1228 if (RHSC && RHSC->isNullValue())
1232 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1233 static unsigned SETFOpcTable[2][3] = {
1234 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1235 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1237 unsigned *SETFOpc = nullptr;
1238 switch (Predicate) {
1240 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1241 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1244 ResultReg = createResultReg(&X86::GR8RegClass);
1246 if (!X86FastEmitCompare(LHS, RHS, VT))
1249 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1250 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1256 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1257 UpdateValueMap(I, ResultReg);
1263 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1264 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1265 unsigned Opc = X86::getSETFromCond(CC);
1268 std::swap(LHS, RHS);
1270 // Emit a compare of LHS/RHS.
1271 if (!X86FastEmitCompare(LHS, RHS, VT))
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1275 UpdateValueMap(I, ResultReg);
1279 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1280 EVT DstVT = TLI.getValueType(I->getType());
1281 if (!TLI.isTypeLegal(DstVT))
1284 unsigned ResultReg = getRegForValue(I->getOperand(0));
1288 // Handle zero-extension from i1 to i8, which is common.
1289 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1290 if (SrcVT.SimpleTy == MVT::i1) {
1291 // Set the high bits to zero.
1292 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1299 if (DstVT == MVT::i64) {
1300 // Handle extension to 64-bits via sub-register shenanigans.
1303 switch (SrcVT.SimpleTy) {
1304 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1305 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1306 case MVT::i32: MovInst = X86::MOV32rr; break;
1307 default: llvm_unreachable("Unexpected zext to i64 source type");
1310 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1314 ResultReg = createResultReg(&X86::GR64RegClass);
1315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1317 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1318 } else if (DstVT != MVT::i8) {
1319 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1320 ResultReg, /*Kill=*/true);
1325 UpdateValueMap(I, ResultReg);
1330 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1331 // Unconditional branches are selected by tablegen-generated code.
1332 // Handle a conditional branch.
1333 const BranchInst *BI = cast<BranchInst>(I);
1334 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1335 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1337 // Fold the common case of a conditional branch with a comparison
1338 // in the same block (values defined on other blocks may not have
1339 // initialized registers).
1341 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1342 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1343 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1345 // Try to optimize or fold the cmp.
1346 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1347 switch (Predicate) {
1349 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1350 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1353 const Value *CmpLHS = CI->getOperand(0);
1354 const Value *CmpRHS = CI->getOperand(1);
1356 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1358 // We don't have to materialize a zero constant for this case and can just
1359 // use %x again on the RHS.
1360 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1361 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1362 if (CmpRHSC && CmpRHSC->isNullValue())
1366 // Try to take advantage of fallthrough opportunities.
1367 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1368 std::swap(TrueMBB, FalseMBB);
1369 Predicate = CmpInst::getInversePredicate(Predicate);
1372 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1373 // code check. Instead two branch instructions are required to check all
1374 // the flags. First we change the predicate to a supported condition code,
1375 // which will be the first branch. Later one we will emit the second
1377 bool NeedExtraBranch = false;
1378 switch (Predicate) {
1380 case CmpInst::FCMP_OEQ:
1381 std::swap(TrueMBB, FalseMBB); // fall-through
1382 case CmpInst::FCMP_UNE:
1383 NeedExtraBranch = true;
1384 Predicate = CmpInst::FCMP_ONE;
1390 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1391 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1393 BranchOpc = X86::GetCondBranchFromCond(CC);
1395 std::swap(CmpLHS, CmpRHS);
1397 // Emit a compare of the LHS and RHS, setting the flags.
1398 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1404 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1406 if (NeedExtraBranch) {
1407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1411 // Obtain the branch weight and add the TrueBB to the successor list.
1412 uint32_t BranchWeight = 0;
1414 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1415 TrueMBB->getBasicBlock());
1416 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1418 // Emits an unconditional branch to the FalseBB, obtains the branch
1419 // weight, and adds it to the successor list.
1420 FastEmitBranch(FalseMBB, DbgLoc);
1424 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1425 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1426 // typically happen for _Bool and C++ bools.
1428 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1429 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1430 unsigned TestOpc = 0;
1431 switch (SourceVT.SimpleTy) {
1433 case MVT::i8: TestOpc = X86::TEST8ri; break;
1434 case MVT::i16: TestOpc = X86::TEST16ri; break;
1435 case MVT::i32: TestOpc = X86::TEST32ri; break;
1436 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1439 unsigned OpReg = getRegForValue(TI->getOperand(0));
1440 if (OpReg == 0) return false;
1441 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1442 .addReg(OpReg).addImm(1);
1444 unsigned JmpOpc = X86::JNE_4;
1445 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1446 std::swap(TrueMBB, FalseMBB);
1450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1452 FastEmitBranch(FalseMBB, DbgLoc);
1453 uint32_t BranchWeight = 0;
1455 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1456 TrueMBB->getBasicBlock());
1457 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1461 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1462 // Fake request the condition, otherwise the intrinsic might be completely
1464 unsigned TmpReg = getRegForValue(BI->getCondition());
1468 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1472 FastEmitBranch(FalseMBB, DbgLoc);
1473 uint32_t BranchWeight = 0;
1475 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1476 TrueMBB->getBasicBlock());
1477 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1481 // Otherwise do a clumsy setcc and re-test it.
1482 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1483 // in an explicit cast, so make sure to handle that correctly.
1484 unsigned OpReg = getRegForValue(BI->getCondition());
1485 if (OpReg == 0) return false;
1487 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1488 .addReg(OpReg).addImm(1);
1489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1491 FastEmitBranch(FalseMBB, DbgLoc);
1492 uint32_t BranchWeight = 0;
1494 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1495 TrueMBB->getBasicBlock());
1496 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1500 bool X86FastISel::X86SelectShift(const Instruction *I) {
1501 unsigned CReg = 0, OpReg = 0;
1502 const TargetRegisterClass *RC = nullptr;
1503 if (I->getType()->isIntegerTy(8)) {
1505 RC = &X86::GR8RegClass;
1506 switch (I->getOpcode()) {
1507 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1508 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1509 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1510 default: return false;
1512 } else if (I->getType()->isIntegerTy(16)) {
1514 RC = &X86::GR16RegClass;
1515 switch (I->getOpcode()) {
1516 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1517 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1518 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1519 default: return false;
1521 } else if (I->getType()->isIntegerTy(32)) {
1523 RC = &X86::GR32RegClass;
1524 switch (I->getOpcode()) {
1525 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1526 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1527 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1528 default: return false;
1530 } else if (I->getType()->isIntegerTy(64)) {
1532 RC = &X86::GR64RegClass;
1533 switch (I->getOpcode()) {
1534 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1535 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1536 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1537 default: return false;
1544 if (!isTypeLegal(I->getType(), VT))
1547 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1548 if (Op0Reg == 0) return false;
1550 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1551 if (Op1Reg == 0) return false;
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1553 CReg).addReg(Op1Reg);
1555 // The shift instruction uses X86::CL. If we defined a super-register
1556 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1557 if (CReg != X86::CL)
1558 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1559 TII.get(TargetOpcode::KILL), X86::CL)
1560 .addReg(CReg, RegState::Kill);
1562 unsigned ResultReg = createResultReg(RC);
1563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1565 UpdateValueMap(I, ResultReg);
1569 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1570 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1571 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1572 const static bool S = true; // IsSigned
1573 const static bool U = false; // !IsSigned
1574 const static unsigned Copy = TargetOpcode::COPY;
1575 // For the X86 DIV/IDIV instruction, in most cases the dividend
1576 // (numerator) must be in a specific register pair highreg:lowreg,
1577 // producing the quotient in lowreg and the remainder in highreg.
1578 // For most data types, to set up the instruction, the dividend is
1579 // copied into lowreg, and lowreg is sign-extended or zero-extended
1580 // into highreg. The exception is i8, where the dividend is defined
1581 // as a single register rather than a register pair, and we
1582 // therefore directly sign-extend or zero-extend the dividend into
1583 // lowreg, instead of copying, and ignore the highreg.
1584 const static struct DivRemEntry {
1585 // The following portion depends only on the data type.
1586 const TargetRegisterClass *RC;
1587 unsigned LowInReg; // low part of the register pair
1588 unsigned HighInReg; // high part of the register pair
1589 // The following portion depends on both the data type and the operation.
1590 struct DivRemResult {
1591 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1592 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1593 // highreg, or copying a zero into highreg.
1594 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1595 // zero/sign-extending into lowreg for i8.
1596 unsigned DivRemResultReg; // Register containing the desired result.
1597 bool IsOpSigned; // Whether to use signed or unsigned form.
1598 } ResultTable[NumOps];
1599 } OpTable[NumTypes] = {
1600 { &X86::GR8RegClass, X86::AX, 0, {
1601 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1602 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1603 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1604 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1607 { &X86::GR16RegClass, X86::AX, X86::DX, {
1608 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1609 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1610 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1611 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1614 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1615 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1616 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1617 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1618 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1621 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1622 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1623 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1624 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1625 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1631 if (!isTypeLegal(I->getType(), VT))
1634 unsigned TypeIndex, OpIndex;
1635 switch (VT.SimpleTy) {
1636 default: return false;
1637 case MVT::i8: TypeIndex = 0; break;
1638 case MVT::i16: TypeIndex = 1; break;
1639 case MVT::i32: TypeIndex = 2; break;
1640 case MVT::i64: TypeIndex = 3;
1641 if (!Subtarget->is64Bit())
1646 switch (I->getOpcode()) {
1647 default: llvm_unreachable("Unexpected div/rem opcode");
1648 case Instruction::SDiv: OpIndex = 0; break;
1649 case Instruction::SRem: OpIndex = 1; break;
1650 case Instruction::UDiv: OpIndex = 2; break;
1651 case Instruction::URem: OpIndex = 3; break;
1654 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1655 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1656 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1659 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1663 // Move op0 into low-order input register.
1664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1665 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1666 // Zero-extend or sign-extend into high-order input register.
1667 if (OpEntry.OpSignExtend) {
1668 if (OpEntry.IsOpSigned)
1669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1670 TII.get(OpEntry.OpSignExtend));
1672 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1674 TII.get(X86::MOV32r0), Zero32);
1676 // Copy the zero into the appropriate sub/super/identical physical
1677 // register. Unfortunately the operations needed are not uniform enough to
1678 // fit neatly into the table above.
1679 if (VT.SimpleTy == MVT::i16) {
1680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1681 TII.get(Copy), TypeEntry.HighInReg)
1682 .addReg(Zero32, 0, X86::sub_16bit);
1683 } else if (VT.SimpleTy == MVT::i32) {
1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1685 TII.get(Copy), TypeEntry.HighInReg)
1687 } else if (VT.SimpleTy == MVT::i64) {
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1689 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1690 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1694 // Generate the DIV/IDIV instruction.
1695 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1696 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1697 // For i8 remainder, we can't reference AH directly, as we'll end
1698 // up with bogus copies like %R9B = COPY %AH. Reference AX
1699 // instead to prevent AH references in a REX instruction.
1701 // The current assumption of the fast register allocator is that isel
1702 // won't generate explicit references to the GPR8_NOREX registers. If
1703 // the allocator and/or the backend get enhanced to be more robust in
1704 // that regard, this can be, and should be, removed.
1705 unsigned ResultReg = 0;
1706 if ((I->getOpcode() == Instruction::SRem ||
1707 I->getOpcode() == Instruction::URem) &&
1708 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1709 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1710 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1712 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1714 // Shift AX right by 8 bits instead of using AH.
1715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1716 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1718 // Now reference the 8-bit subreg of the result.
1719 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1720 /*Kill=*/true, X86::sub_8bit);
1722 // Copy the result out of the physreg if we haven't already.
1724 ResultReg = createResultReg(TypeEntry.RC);
1725 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1726 .addReg(OpEntry.DivRemResultReg);
1728 UpdateValueMap(I, ResultReg);
1733 /// \brief Emit a conditional move instruction (if the are supported) to lower
1735 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1736 // Check if the subtarget supports these instructions.
1737 if (!Subtarget->hasCMov())
1740 // FIXME: Add support for i8.
1741 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1744 const Value *Cond = I->getOperand(0);
1745 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1746 bool NeedTest = true;
1747 X86::CondCode CC = X86::COND_NE;
1749 // Optimize conditions coming from a compare if both instructions are in the
1750 // same basic block (values defined in other basic blocks may not have
1751 // initialized registers).
1752 const auto *CI = dyn_cast<CmpInst>(Cond);
1753 if (CI && (CI->getParent() == I->getParent())) {
1754 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1756 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1757 static unsigned SETFOpcTable[2][3] = {
1758 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1759 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1761 unsigned *SETFOpc = nullptr;
1762 switch (Predicate) {
1764 case CmpInst::FCMP_OEQ:
1765 SETFOpc = &SETFOpcTable[0][0];
1766 Predicate = CmpInst::ICMP_NE;
1768 case CmpInst::FCMP_UNE:
1769 SETFOpc = &SETFOpcTable[1][0];
1770 Predicate = CmpInst::ICMP_NE;
1775 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1776 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1778 const Value *CmpLHS = CI->getOperand(0);
1779 const Value *CmpRHS = CI->getOperand(1);
1781 std::swap(CmpLHS, CmpRHS);
1783 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1784 // Emit a compare of the LHS and RHS, setting the flags.
1785 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1789 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1790 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1791 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1793 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1795 auto const &II = TII.get(SETFOpc[2]);
1796 if (II.getNumDefs()) {
1797 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1798 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1799 .addReg(FlagReg2).addReg(FlagReg1);
1801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1802 .addReg(FlagReg2).addReg(FlagReg1);
1806 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1807 // Fake request the condition, otherwise the intrinsic might be completely
1809 unsigned TmpReg = getRegForValue(Cond);
1817 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1818 // garbage. Indeed, only the less significant bit is supposed to be
1819 // accurate. If we read more than the lsb, we may see non-zero values
1820 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1821 // the select. This is achieved by performing TEST against 1.
1822 unsigned CondReg = getRegForValue(Cond);
1825 bool CondIsKill = hasTrivialKill(Cond);
1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1828 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1831 const Value *LHS = I->getOperand(1);
1832 const Value *RHS = I->getOperand(2);
1834 unsigned RHSReg = getRegForValue(RHS);
1835 bool RHSIsKill = hasTrivialKill(RHS);
1837 unsigned LHSReg = getRegForValue(LHS);
1838 bool LHSIsKill = hasTrivialKill(LHS);
1840 if (!LHSReg || !RHSReg)
1843 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1844 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1846 UpdateValueMap(I, ResultReg);
1850 /// \brief Emit SSE instructions to lower the select.
1852 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1853 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1854 /// SSE instructions are available.
1855 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1856 // Optimize conditions coming from a compare if both instructions are in the
1857 // same basic block (values defined in other basic blocks may not have
1858 // initialized registers).
1859 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1860 if (!CI || (CI->getParent() != I->getParent()))
1863 if (I->getType() != CI->getOperand(0)->getType() ||
1864 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1865 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1868 const Value *CmpLHS = CI->getOperand(0);
1869 const Value *CmpRHS = CI->getOperand(1);
1870 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1872 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1873 // We don't have to materialize a zero constant for this case and can just use
1874 // %x again on the RHS.
1875 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1876 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1877 if (CmpRHSC && CmpRHSC->isNullValue())
1883 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1888 std::swap(CmpLHS, CmpRHS);
1890 static unsigned OpcTable[2][2][4] = {
1891 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1892 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1893 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1894 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1897 bool HasAVX = Subtarget->hasAVX();
1898 unsigned *Opc = nullptr;
1899 switch (RetVT.SimpleTy) {
1900 default: return false;
1901 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1902 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1905 const Value *LHS = I->getOperand(1);
1906 const Value *RHS = I->getOperand(2);
1908 unsigned LHSReg = getRegForValue(LHS);
1909 bool LHSIsKill = hasTrivialKill(LHS);
1911 unsigned RHSReg = getRegForValue(RHS);
1912 bool RHSIsKill = hasTrivialKill(RHS);
1914 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1915 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1917 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1918 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1920 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1923 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1924 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1925 CmpRHSReg, CmpRHSIsKill, CC);
1926 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1928 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1930 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1931 AndReg, /*IsKill=*/true);
1932 UpdateValueMap(I, ResultReg);
1936 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1937 // These are pseudo CMOV instructions and will be later expanded into control-
1940 switch (RetVT.SimpleTy) {
1941 default: return false;
1942 case MVT::i8: Opc = X86::CMOV_GR8; break;
1943 case MVT::i16: Opc = X86::CMOV_GR16; break;
1944 case MVT::i32: Opc = X86::CMOV_GR32; break;
1945 case MVT::f32: Opc = X86::CMOV_FR32; break;
1946 case MVT::f64: Opc = X86::CMOV_FR64; break;
1949 const Value *Cond = I->getOperand(0);
1950 X86::CondCode CC = X86::COND_NE;
1952 // Optimize conditions coming from a compare if both instructions are in the
1953 // same basic block (values defined in other basic blocks may not have
1954 // initialized registers).
1955 const auto *CI = dyn_cast<CmpInst>(Cond);
1956 if (CI && (CI->getParent() == I->getParent())) {
1958 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1959 if (CC > X86::LAST_VALID_COND)
1962 const Value *CmpLHS = CI->getOperand(0);
1963 const Value *CmpRHS = CI->getOperand(1);
1966 std::swap(CmpLHS, CmpRHS);
1968 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1969 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1972 unsigned CondReg = getRegForValue(Cond);
1975 bool CondIsKill = hasTrivialKill(Cond);
1976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1977 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1980 const Value *LHS = I->getOperand(1);
1981 const Value *RHS = I->getOperand(2);
1983 unsigned LHSReg = getRegForValue(LHS);
1984 bool LHSIsKill = hasTrivialKill(LHS);
1986 unsigned RHSReg = getRegForValue(RHS);
1987 bool RHSIsKill = hasTrivialKill(RHS);
1989 if (!LHSReg || !RHSReg)
1992 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1994 unsigned ResultReg =
1995 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
1996 UpdateValueMap(I, ResultReg);
2000 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2002 if (!isTypeLegal(I->getType(), RetVT))
2005 // Check if we can fold the select.
2006 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2007 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2008 const Value *Opnd = nullptr;
2009 switch (Predicate) {
2011 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2012 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2014 // No need for a select anymore - this is an unconditional move.
2016 unsigned OpReg = getRegForValue(Opnd);
2019 bool OpIsKill = hasTrivialKill(Opnd);
2020 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2021 unsigned ResultReg = createResultReg(RC);
2022 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2023 TII.get(TargetOpcode::COPY), ResultReg)
2024 .addReg(OpReg, getKillRegState(OpIsKill));
2025 UpdateValueMap(I, ResultReg);
2030 // First try to use real conditional move instructions.
2031 if (X86FastEmitCMoveSelect(RetVT, I))
2034 // Try to use a sequence of SSE instructions to simulate a conditional move.
2035 if (X86FastEmitSSESelect(RetVT, I))
2038 // Fall-back to pseudo conditional move instructions, which will be later
2039 // converted to control-flow.
2040 if (X86FastEmitPseudoSelect(RetVT, I))
2046 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2047 // fpext from float to double.
2048 if (X86ScalarSSEf64 &&
2049 I->getType()->isDoubleTy()) {
2050 const Value *V = I->getOperand(0);
2051 if (V->getType()->isFloatTy()) {
2052 unsigned OpReg = getRegForValue(V);
2053 if (OpReg == 0) return false;
2054 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
2055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2056 TII.get(X86::CVTSS2SDrr), ResultReg)
2058 UpdateValueMap(I, ResultReg);
2066 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2067 if (X86ScalarSSEf64) {
2068 if (I->getType()->isFloatTy()) {
2069 const Value *V = I->getOperand(0);
2070 if (V->getType()->isDoubleTy()) {
2071 unsigned OpReg = getRegForValue(V);
2072 if (OpReg == 0) return false;
2073 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
2074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2075 TII.get(X86::CVTSD2SSrr), ResultReg)
2077 UpdateValueMap(I, ResultReg);
2086 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2087 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2088 EVT DstVT = TLI.getValueType(I->getType());
2090 // This code only handles truncation to byte.
2091 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2093 if (!TLI.isTypeLegal(SrcVT))
2096 unsigned InputReg = getRegForValue(I->getOperand(0));
2098 // Unhandled operand. Halt "fast" selection and bail.
2101 if (SrcVT == MVT::i8) {
2102 // Truncate from i8 to i1; no code needed.
2103 UpdateValueMap(I, InputReg);
2107 if (!Subtarget->is64Bit()) {
2108 // If we're on x86-32; we can't extract an i8 from a general register.
2109 // First issue a copy to GR16_ABCD or GR32_ABCD.
2110 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
2111 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
2112 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
2113 unsigned CopyReg = createResultReg(CopyRC);
2114 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2115 CopyReg).addReg(InputReg);
2119 // Issue an extract_subreg.
2120 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
2121 InputReg, /*Kill=*/true,
2126 UpdateValueMap(I, ResultReg);
2130 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2131 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2134 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2135 X86AddressMode SrcAM, uint64_t Len) {
2137 // Make sure we don't bloat code by inlining very large memcpy's.
2138 if (!IsMemcpySmall(Len))
2141 bool i64Legal = Subtarget->is64Bit();
2143 // We don't care about alignment here since we just emit integer accesses.
2146 if (Len >= 8 && i64Legal)
2157 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2158 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2159 assert(RV && "Failed to emit load or store??");
2161 unsigned Size = VT.getSizeInBits()/8;
2163 DestAM.Disp += Size;
2170 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
2171 switch (I.getIntrinsicID()) {
2172 case Intrinsic::sadd_with_overflow:
2173 case Intrinsic::uadd_with_overflow:
2174 case Intrinsic::smul_with_overflow:
2175 case Intrinsic::umul_with_overflow:
2182 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
2183 // FIXME: Handle more intrinsics.
2184 switch (I.getIntrinsicID()) {
2185 default: return false;
2186 case Intrinsic::frameaddress: {
2187 Type *RetTy = I.getCalledFunction()->getReturnType();
2190 if (!isTypeLegal(RetTy, VT))
2194 const TargetRegisterClass *RC = nullptr;
2196 switch (VT.SimpleTy) {
2197 default: llvm_unreachable("Invalid result type for frameaddress.");
2198 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2199 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2202 // This needs to be set before we call getFrameRegister, otherwise we get
2203 // the wrong frame register.
2204 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2205 MFI->setFrameAddressIsTaken(true);
2207 const X86RegisterInfo *RegInfo =
2208 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2209 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2210 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2211 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2212 "Invalid Frame Register!");
2214 // Always make a copy of the frame register to to a vreg first, so that we
2215 // never directly reference the frame register (the TwoAddressInstruction-
2216 // Pass doesn't like that).
2217 unsigned SrcReg = createResultReg(RC);
2218 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2219 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2221 // Now recursively load from the frame address.
2222 // movq (%rbp), %rax
2223 // movq (%rax), %rax
2224 // movq (%rax), %rax
2227 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2229 DestReg = createResultReg(RC);
2230 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2231 TII.get(Opc), DestReg), SrcReg);
2235 UpdateValueMap(&I, SrcReg);
2238 case Intrinsic::memcpy: {
2239 const MemCpyInst &MCI = cast<MemCpyInst>(I);
2240 // Don't handle volatile or variable length memcpys.
2241 if (MCI.isVolatile())
2244 if (isa<ConstantInt>(MCI.getLength())) {
2245 // Small memcpy's are common enough that we want to do them
2246 // without a call if possible.
2247 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
2248 if (IsMemcpySmall(Len)) {
2249 X86AddressMode DestAM, SrcAM;
2250 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
2251 !X86SelectAddress(MCI.getRawSource(), SrcAM))
2253 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2258 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2259 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
2262 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
2265 return DoSelectCall(&I, "memcpy");
2267 case Intrinsic::memset: {
2268 const MemSetInst &MSI = cast<MemSetInst>(I);
2270 if (MSI.isVolatile())
2273 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2274 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
2277 if (MSI.getDestAddressSpace() > 255)
2280 return DoSelectCall(&I, "memset");
2282 case Intrinsic::stackprotector: {
2283 // Emit code to store the stack guard onto the stack.
2284 EVT PtrTy = TLI.getPointerTy();
2286 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2287 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2289 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2291 // Grab the frame index.
2293 if (!X86SelectAddress(Slot, AM)) return false;
2294 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2297 case Intrinsic::dbg_declare: {
2298 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2300 assert(DI->getAddress() && "Null address should be checked earlier!");
2301 if (!X86SelectAddress(DI->getAddress(), AM))
2303 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2304 // FIXME may need to add RegState::Debug to any registers produced,
2305 // although ESP/EBP should be the only ones at the moment.
2306 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2307 addImm(0).addMetadata(DI->getVariable());
2310 case Intrinsic::trap: {
2311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2314 case Intrinsic::sqrt: {
2315 if (!Subtarget->hasSSE1())
2318 Type *RetTy = I.getCalledFunction()->getReturnType();
2321 if (!isTypeLegal(RetTy, VT))
2324 // Unfortunately we can't use FastEmit_r, because the AVX version of FSQRT
2325 // is not generated by FastISel yet.
2326 // FIXME: Update this code once tablegen can handle it.
2327 static const unsigned SqrtOpc[2][2] = {
2328 {X86::SQRTSSr, X86::VSQRTSSr},
2329 {X86::SQRTSDr, X86::VSQRTSDr}
2331 bool HasAVX = Subtarget->hasAVX();
2333 const TargetRegisterClass *RC;
2334 switch (VT.SimpleTy) {
2335 default: return false;
2336 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2337 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2340 const Value *SrcVal = I.getArgOperand(0);
2341 unsigned SrcReg = getRegForValue(SrcVal);
2346 unsigned ImplicitDefReg = 0;
2348 ImplicitDefReg = createResultReg(RC);
2349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2350 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2353 unsigned ResultReg = createResultReg(RC);
2354 MachineInstrBuilder MIB;
2355 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2359 MIB.addReg(ImplicitDefReg);
2363 UpdateValueMap(&I, ResultReg);
2366 case Intrinsic::sadd_with_overflow:
2367 case Intrinsic::uadd_with_overflow:
2368 case Intrinsic::ssub_with_overflow:
2369 case Intrinsic::usub_with_overflow:
2370 case Intrinsic::smul_with_overflow:
2371 case Intrinsic::umul_with_overflow: {
2372 // This implements the basic lowering of the xalu with overflow intrinsics
2373 // into add/sub/mul followed by either seto or setb.
2374 const Function *Callee = I.getCalledFunction();
2375 auto *Ty = cast<StructType>(Callee->getReturnType());
2376 Type *RetTy = Ty->getTypeAtIndex(0U);
2377 Type *CondTy = Ty->getTypeAtIndex(1);
2380 if (!isTypeLegal(RetTy, VT))
2383 if (VT < MVT::i8 || VT > MVT::i64)
2386 const Value *LHS = I.getArgOperand(0);
2387 const Value *RHS = I.getArgOperand(1);
2389 // Canonicalize immediate to the RHS.
2390 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2391 isCommutativeIntrinsic(I))
2392 std::swap(LHS, RHS);
2394 unsigned BaseOpc, CondOpc;
2395 switch (I.getIntrinsicID()) {
2396 default: llvm_unreachable("Unexpected intrinsic!");
2397 case Intrinsic::sadd_with_overflow:
2398 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2399 case Intrinsic::uadd_with_overflow:
2400 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2401 case Intrinsic::ssub_with_overflow:
2402 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2403 case Intrinsic::usub_with_overflow:
2404 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2405 case Intrinsic::smul_with_overflow:
2406 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2407 case Intrinsic::umul_with_overflow:
2408 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2411 unsigned LHSReg = getRegForValue(LHS);
2414 bool LHSIsKill = hasTrivialKill(LHS);
2416 unsigned ResultReg = 0;
2417 // Check if we have an immediate version.
2418 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2419 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2426 RHSReg = getRegForValue(RHS);
2429 RHSIsKill = hasTrivialKill(RHS);
2430 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2434 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2436 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2437 static const unsigned MULOpc[] =
2438 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2439 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2440 // First copy the first operand into RAX, which is an implicit input to
2441 // the X86::MUL*r instruction.
2442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2443 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2444 .addReg(LHSReg, getKillRegState(LHSIsKill));
2445 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2446 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2447 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2448 static const unsigned MULOpc[] =
2449 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2450 if (VT == MVT::i8) {
2451 // Copy the first operand into AL, which is an implicit input to the
2452 // X86::IMUL8r instruction.
2453 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2454 TII.get(TargetOpcode::COPY), X86::AL)
2455 .addReg(LHSReg, getKillRegState(LHSIsKill));
2456 ResultReg = FastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2459 ResultReg = FastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2460 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2467 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2468 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2469 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2472 UpdateValueMap(&I, ResultReg, 2);
2475 case Intrinsic::x86_sse_cvttss2si:
2476 case Intrinsic::x86_sse_cvttss2si64:
2477 case Intrinsic::x86_sse2_cvttsd2si:
2478 case Intrinsic::x86_sse2_cvttsd2si64: {
2480 switch (I.getIntrinsicID()) {
2481 default: llvm_unreachable("Unexpected intrinsic.");
2482 case Intrinsic::x86_sse_cvttss2si:
2483 case Intrinsic::x86_sse_cvttss2si64:
2484 if (!Subtarget->hasSSE1())
2486 IsInputDouble = false;
2488 case Intrinsic::x86_sse2_cvttsd2si:
2489 case Intrinsic::x86_sse2_cvttsd2si64:
2490 if (!Subtarget->hasSSE2())
2492 IsInputDouble = true;
2496 Type *RetTy = I.getCalledFunction()->getReturnType();
2498 if (!isTypeLegal(RetTy, VT))
2501 static const unsigned CvtOpc[2][2][2] = {
2502 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2503 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2504 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2505 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2507 bool HasAVX = Subtarget->hasAVX();
2509 switch (VT.SimpleTy) {
2510 default: llvm_unreachable("Unexpected result type.");
2511 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2512 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2515 // Check if we can fold insertelement instructions into the convert.
2516 const Value *Op = I.getArgOperand(0);
2517 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2518 const Value *Index = IE->getOperand(2);
2519 if (!isa<ConstantInt>(Index))
2521 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2524 Op = IE->getOperand(1);
2527 Op = IE->getOperand(0);
2530 unsigned Reg = getRegForValue(Op);
2534 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2535 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2538 UpdateValueMap(&I, ResultReg);
2544 bool X86FastISel::FastLowerArguments() {
2545 if (!FuncInfo.CanLowerReturn)
2548 const Function *F = FuncInfo.Fn;
2552 CallingConv::ID CC = F->getCallingConv();
2553 if (CC != CallingConv::C)
2556 if (Subtarget->isCallingConvWin64(CC))
2559 if (!Subtarget->is64Bit())
2562 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2563 unsigned GPRCnt = 0;
2564 unsigned FPRCnt = 0;
2566 for (auto const &Arg : F->args()) {
2567 // The first argument is at index 1.
2569 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2570 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2571 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2572 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2575 Type *ArgTy = Arg.getType();
2576 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2579 EVT ArgVT = TLI.getValueType(ArgTy);
2580 if (!ArgVT.isSimple()) return false;
2581 switch (ArgVT.getSimpleVT().SimpleTy) {
2582 default: return false;
2589 if (!Subtarget->hasSSE1())
2602 static const MCPhysReg GPR32ArgRegs[] = {
2603 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2605 static const MCPhysReg GPR64ArgRegs[] = {
2606 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2608 static const MCPhysReg XMMArgRegs[] = {
2609 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2610 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2613 unsigned GPRIdx = 0;
2614 unsigned FPRIdx = 0;
2615 for (auto const &Arg : F->args()) {
2616 MVT VT = TLI.getSimpleValueType(Arg.getType());
2617 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2619 switch (VT.SimpleTy) {
2620 default: llvm_unreachable("Unexpected value type.");
2621 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2622 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2623 case MVT::f32: // fall-through
2624 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2626 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2627 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2628 // Without this, EmitLiveInCopies may eliminate the livein if its only
2629 // use is a bitcast (which isn't turned into an instruction).
2630 unsigned ResultReg = createResultReg(RC);
2631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2632 TII.get(TargetOpcode::COPY), ResultReg)
2633 .addReg(DstReg, getKillRegState(true));
2634 UpdateValueMap(&Arg, ResultReg);
2639 bool X86FastISel::X86SelectCall(const Instruction *I) {
2640 const CallInst *CI = cast<CallInst>(I);
2641 const Value *Callee = CI->getCalledValue();
2643 // Can't handle inline asm yet.
2644 if (isa<InlineAsm>(Callee))
2647 // Handle intrinsic calls.
2648 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2649 return X86VisitIntrinsicCall(*II);
2651 // Allow SelectionDAG isel to handle tail calls.
2652 if (cast<CallInst>(I)->isTailCall())
2655 return DoSelectCall(I, nullptr);
2658 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2660 ImmutableCallSite *CS) {
2661 if (Subtarget->is64Bit())
2663 if (Subtarget->getTargetTriple().isOSMSVCRT())
2665 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2666 CC == CallingConv::HiPE)
2668 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2670 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2675 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2676 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2677 const CallInst *CI = cast<CallInst>(I);
2678 const Value *Callee = CI->getCalledValue();
2680 // Handle only C and fastcc calling conventions for now.
2681 ImmutableCallSite CS(CI);
2682 CallingConv::ID CC = CS.getCallingConv();
2683 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2684 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2685 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2686 CC != CallingConv::X86_64_SysV)
2689 // fastcc with -tailcallopt is intended to provide a guaranteed
2690 // tail call optimization. Fastisel doesn't know how to do that.
2691 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2694 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2695 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2696 bool isVarArg = FTy->isVarArg();
2698 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2699 // x86-32. Special handling for x86-64 is implemented.
2700 if (isVarArg && isWin64)
2703 // Don't know about inalloca yet.
2704 if (CS.hasInAllocaArgument())
2707 // Fast-isel doesn't know about callee-pop yet.
2708 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2709 TM.Options.GuaranteedTailCallOpt))
2712 // Check whether the function can return without sret-demotion.
2713 SmallVector<ISD::OutputArg, 4> Outs;
2714 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2715 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2716 *FuncInfo.MF, FTy->isVarArg(),
2717 Outs, FTy->getContext());
2718 if (!CanLowerReturn)
2721 // Materialize callee address in a register. FIXME: GV address can be
2722 // handled with a CALLpcrel32 instead.
2723 X86AddressMode CalleeAM;
2724 if (!X86SelectCallAddress(Callee, CalleeAM))
2726 unsigned CalleeOp = 0;
2727 const GlobalValue *GV = nullptr;
2728 if (CalleeAM.GV != nullptr) {
2730 } else if (CalleeAM.Base.Reg != 0) {
2731 CalleeOp = CalleeAM.Base.Reg;
2735 // Deal with call operands first.
2736 SmallVector<const Value *, 8> ArgVals;
2737 SmallVector<unsigned, 8> Args;
2738 SmallVector<MVT, 8> ArgVTs;
2739 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2740 unsigned arg_size = CS.arg_size();
2741 Args.reserve(arg_size);
2742 ArgVals.reserve(arg_size);
2743 ArgVTs.reserve(arg_size);
2744 ArgFlags.reserve(arg_size);
2745 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2747 // If we're lowering a mem intrinsic instead of a regular call, skip the
2748 // last two arguments, which should not passed to the underlying functions.
2749 if (MemIntName && e-i <= 2)
2752 ISD::ArgFlagsTy Flags;
2753 unsigned AttrInd = i - CS.arg_begin() + 1;
2754 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2756 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2759 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2760 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2761 Type *ElementTy = Ty->getElementType();
2762 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2763 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2765 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2767 Flags.setByValSize(FrameSize);
2768 Flags.setByValAlign(FrameAlign);
2769 if (!IsMemcpySmall(FrameSize))
2773 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2775 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2778 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2779 // instruction. This is safe because it is common to all fastisel supported
2780 // calling conventions on x86.
2781 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2782 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2783 CI->getBitWidth() == 16) {
2785 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2787 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2793 // Passing bools around ends up doing a trunc to i1 and passing it.
2794 // Codegen this as an argument + "and 1".
2795 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2796 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2797 ArgVal->hasOneUse()) {
2798 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2799 ArgReg = getRegForValue(ArgVal);
2800 if (ArgReg == 0) return false;
2803 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2805 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2806 ArgVal->hasOneUse(), 1);
2808 ArgReg = getRegForValue(ArgVal);
2811 if (ArgReg == 0) return false;
2813 Type *ArgTy = ArgVal->getType();
2815 if (!isTypeLegal(ArgTy, ArgVT))
2817 if (ArgVT == MVT::x86mmx)
2819 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2820 Flags.setOrigAlign(OriginalAlignment);
2822 Args.push_back(ArgReg);
2823 ArgVals.push_back(ArgVal);
2824 ArgVTs.push_back(ArgVT);
2825 ArgFlags.push_back(Flags);
2828 // Analyze operands of the call, assigning locations to each operand.
2829 SmallVector<CCValAssign, 16> ArgLocs;
2830 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2831 I->getParent()->getContext());
2833 // Allocate shadow area for Win64
2835 CCInfo.AllocateStack(32, 8);
2837 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2839 // Get a count of how many bytes are to be pushed on the stack.
2840 unsigned NumBytes = CCInfo.getNextStackOffset();
2842 // Issue CALLSEQ_START
2843 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2847 // Process argument: walk the register/memloc assignments, inserting
2849 SmallVector<unsigned, 4> RegArgs;
2850 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851 CCValAssign &VA = ArgLocs[i];
2852 unsigned Arg = Args[VA.getValNo()];
2853 EVT ArgVT = ArgVTs[VA.getValNo()];
2855 // Promote the value if needed.
2856 switch (VA.getLocInfo()) {
2857 case CCValAssign::Full: break;
2858 case CCValAssign::SExt: {
2859 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2860 "Unexpected extend");
2861 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2863 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2864 ArgVT = VA.getLocVT();
2867 case CCValAssign::ZExt: {
2868 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2869 "Unexpected extend");
2870 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2872 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2873 ArgVT = VA.getLocVT();
2876 case CCValAssign::AExt: {
2877 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2878 "Unexpected extend");
2879 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2882 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2885 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2888 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2889 ArgVT = VA.getLocVT();
2892 case CCValAssign::BCvt: {
2893 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2894 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2895 assert(BC != 0 && "Failed to emit a bitcast!");
2897 ArgVT = VA.getLocVT();
2900 case CCValAssign::VExt:
2901 // VExt has not been implemented, so this should be impossible to reach
2902 // for now. However, fallback to Selection DAG isel once implemented.
2904 case CCValAssign::Indirect:
2905 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2908 case CCValAssign::FPExt:
2909 llvm_unreachable("Unexpected loc info!");
2912 if (VA.isRegLoc()) {
2913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2914 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2915 RegArgs.push_back(VA.getLocReg());
2917 unsigned LocMemOffset = VA.getLocMemOffset();
2919 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2920 getTargetMachine()->getRegisterInfo());
2921 AM.Base.Reg = RegInfo->getStackRegister();
2922 AM.Disp = LocMemOffset;
2923 const Value *ArgVal = ArgVals[VA.getValNo()];
2924 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2926 if (Flags.isByVal()) {
2927 X86AddressMode SrcAM;
2928 SrcAM.Base.Reg = Arg;
2929 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2930 assert(Res && "memcpy length already checked!"); (void)Res;
2931 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2932 // If this is a really simple value, emit this with the Value* version
2933 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2934 // as it can cause us to reevaluate the argument.
2935 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2938 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2944 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2946 if (Subtarget->isPICStyleGOT()) {
2947 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2948 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2949 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2952 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2953 // Count the number of XMM registers allocated.
2954 static const MCPhysReg XMMArgRegs[] = {
2955 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2956 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2958 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2960 X86::AL).addImm(NumXMMRegs);
2964 MachineInstrBuilder MIB;
2966 // Register-indirect call.
2968 if (Subtarget->is64Bit())
2969 CallOpc = X86::CALL64r;
2971 CallOpc = X86::CALL32r;
2972 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2977 assert(GV && "Not a direct call");
2979 if (Subtarget->is64Bit())
2980 CallOpc = X86::CALL64pcrel32;
2982 CallOpc = X86::CALLpcrel32;
2984 // See if we need any target-specific flags on the GV operand.
2985 unsigned char OpFlags = 0;
2987 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2988 // external symbols most go through the PLT in PIC mode. If the symbol
2989 // has hidden or protected visibility, or if it is static or local, then
2990 // we don't need to use the PLT - we can directly call it.
2991 if (Subtarget->isTargetELF() &&
2992 TM.getRelocationModel() == Reloc::PIC_ &&
2993 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2994 OpFlags = X86II::MO_PLT;
2995 } else if (Subtarget->isPICStyleStubAny() &&
2996 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2997 (!Subtarget->getTargetTriple().isMacOSX() ||
2998 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2999 // PC-relative references to external symbols should go through $stub,
3000 // unless we're building with the leopard linker or later, which
3001 // automatically synthesizes these stubs.
3002 OpFlags = X86II::MO_DARWIN_STUB;
3006 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3008 MIB.addExternalSymbol(MemIntName, OpFlags);
3010 MIB.addGlobalAddress(GV, 0, OpFlags);
3013 // Add a register mask with the call-preserved registers.
3014 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3015 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
3017 // Add an implicit use GOT pointer in EBX.
3018 if (Subtarget->isPICStyleGOT())
3019 MIB.addReg(X86::EBX, RegState::Implicit);
3021 if (Subtarget->is64Bit() && isVarArg && !isWin64)
3022 MIB.addReg(X86::AL, RegState::Implicit);
3024 // Add implicit physical register uses to the call.
3025 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
3026 MIB.addReg(RegArgs[i], RegState::Implicit);
3028 // Issue CALLSEQ_END
3029 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3030 unsigned NumBytesCallee = computeBytesPoppedByCallee(Subtarget, CC, &CS);
3031 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3032 .addImm(NumBytes).addImm(NumBytesCallee);
3034 // Build info for return calling conv lowering code.
3035 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
3036 SmallVector<ISD::InputArg, 32> Ins;
3037 SmallVector<EVT, 4> RetTys;
3038 ComputeValueVTs(TLI, I->getType(), RetTys);
3039 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
3041 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
3042 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
3043 for (unsigned j = 0; j != NumRegs; ++j) {
3044 ISD::InputArg MyFlags;
3045 MyFlags.VT = RegisterVT;
3046 MyFlags.Used = !CS.getInstruction()->use_empty();
3047 if (CS.paramHasAttr(0, Attribute::SExt))
3048 MyFlags.Flags.setSExt();
3049 if (CS.paramHasAttr(0, Attribute::ZExt))
3050 MyFlags.Flags.setZExt();
3051 if (CS.paramHasAttr(0, Attribute::InReg))
3052 MyFlags.Flags.setInReg();
3053 Ins.push_back(MyFlags);
3057 // Now handle call return values.
3058 SmallVector<unsigned, 4> UsedRegs;
3059 SmallVector<CCValAssign, 16> RVLocs;
3060 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
3061 I->getParent()->getContext());
3062 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
3063 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3064 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3065 EVT CopyVT = RVLocs[i].getValVT();
3066 unsigned CopyReg = ResultReg + i;
3068 // If this is a call to a function that returns an fp value on the x87 fp
3069 // stack, but where we prefer to use the value in xmm registers, copy it
3070 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
3071 if ((RVLocs[i].getLocReg() == X86::ST0 ||
3072 RVLocs[i].getLocReg() == X86::ST1)) {
3073 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
3075 CopyReg = createResultReg(&X86::RFP80RegClass);
3077 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3078 TII.get(X86::FpPOP_RETVAL), CopyReg);
3080 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3081 TII.get(TargetOpcode::COPY),
3082 CopyReg).addReg(RVLocs[i].getLocReg());
3083 UsedRegs.push_back(RVLocs[i].getLocReg());
3086 if (CopyVT != RVLocs[i].getValVT()) {
3087 // Round the F80 the right size, which also moves to the appropriate xmm
3088 // register. This is accomplished by storing the F80 value in memory and
3089 // then loading it back. Ewww...
3090 EVT ResVT = RVLocs[i].getValVT();
3091 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3092 unsigned MemSize = ResVT.getSizeInBits()/8;
3093 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3094 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3097 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3098 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3099 TII.get(Opc), ResultReg + i), FI);
3104 UpdateValueMap(I, ResultReg, RVLocs.size());
3106 // Set all unused physreg defs as dead.
3107 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
3112 bool X86FastISel::FastLowerCall(CallLoweringInfo &CLI) {
3113 auto &OutVals = CLI.OutVals;
3114 auto &OutFlags = CLI.OutFlags;
3115 auto &OutRegs = CLI.OutRegs;
3116 auto &Ins = CLI.Ins;
3117 auto &InRegs = CLI.InRegs;
3118 CallingConv::ID CC = CLI.CallConv;
3119 bool &IsTailCall = CLI.IsTailCall;
3120 bool IsVarArg = CLI.IsVarArg;
3121 const Value *Callee = CLI.Callee;
3122 const char *SymName = CLI.SymName;
3124 bool Is64Bit = Subtarget->is64Bit();
3125 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3127 // Handle only C, fastcc, and webkit_js calling conventions for now.
3129 default: return false;
3130 case CallingConv::C:
3131 case CallingConv::Fast:
3132 case CallingConv::WebKit_JS:
3133 case CallingConv::X86_FastCall:
3134 case CallingConv::X86_64_Win64:
3135 case CallingConv::X86_64_SysV:
3139 // Allow SelectionDAG isel to handle tail calls.
3143 // fastcc with -tailcallopt is intended to provide a guaranteed
3144 // tail call optimization. Fastisel doesn't know how to do that.
3145 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3148 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3149 // x86-32. Special handling for x86-64 is implemented.
3150 if (IsVarArg && IsWin64)
3153 // Don't know about inalloca yet.
3154 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3157 // Fast-isel doesn't know about callee-pop yet.
3158 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3159 TM.Options.GuaranteedTailCallOpt))
3162 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3163 // instruction. This is safe because it is common to all FastISel supported
3164 // calling conventions on x86.
3165 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3166 Value *&Val = OutVals[i];
3167 ISD::ArgFlagsTy Flags = OutFlags[i];
3168 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3169 if (CI->getBitWidth() < 32) {
3171 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3173 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3177 // Passing bools around ends up doing a trunc to i1 and passing it.
3178 // Codegen this as an argument + "and 1".
3179 if (auto *TI = dyn_cast<TruncInst>(Val)) {
3180 if (TI->getType()->isIntegerTy(1) && CLI.CS &&
3181 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3183 Val = cast<TruncInst>(Val)->getOperand(0);
3184 unsigned ResultReg = getRegForValue(Val);
3190 if (!isTypeLegal(Val->getType(), ArgVT))
3194 FastEmit_ri(ArgVT, ArgVT, ISD::AND, ResultReg, Val->hasOneUse(), 1);
3198 UpdateValueMap(Val, ResultReg);
3203 // Analyze operands of the call, assigning locations to each operand.
3204 SmallVector<CCValAssign, 16> ArgLocs;
3205 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs,
3206 CLI.RetTy->getContext());
3208 // Allocate shadow area for Win64
3210 CCInfo.AllocateStack(32, 8);
3212 SmallVector<MVT, 16> OutVTs;
3213 for (auto *Val : OutVals) {
3215 if (!isTypeLegal(Val->getType(), VT, true))
3217 OutVTs.push_back(VT);
3219 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3221 // Get a count of how many bytes are to be pushed on the stack.
3222 unsigned NumBytes = CCInfo.getNextStackOffset();
3224 // Issue CALLSEQ_START
3225 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3226 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3229 // Walk the register/memloc assignments, inserting copies/loads.
3230 const X86RegisterInfo *RegInfo =
3231 static_cast<const X86RegisterInfo *>(TM.getRegisterInfo());
3232 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3233 CCValAssign const &VA = ArgLocs[i];
3234 const Value *ArgVal = OutVals[VA.getValNo()];
3235 MVT ArgVT = OutVTs[VA.getValNo()];
3237 if (ArgVT == MVT::x86mmx)
3240 unsigned ArgReg = getRegForValue(ArgVal);
3244 // Promote the value if needed.
3245 switch (VA.getLocInfo()) {
3246 case CCValAssign::Full: break;
3247 case CCValAssign::SExt: {
3248 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3249 "Unexpected extend");
3250 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3252 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3253 ArgVT = VA.getLocVT();
3256 case CCValAssign::ZExt: {
3257 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3258 "Unexpected extend");
3259 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3261 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3262 ArgVT = VA.getLocVT();
3265 case CCValAssign::AExt: {
3266 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3267 "Unexpected extend");
3268 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3271 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3274 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3277 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3278 ArgVT = VA.getLocVT();
3281 case CCValAssign::BCvt: {
3282 ArgReg = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3283 /*TODO: Kill=*/false);
3284 assert(ArgReg && "Failed to emit a bitcast!");
3285 ArgVT = VA.getLocVT();
3288 case CCValAssign::VExt:
3289 // VExt has not been implemented, so this should be impossible to reach
3290 // for now. However, fallback to Selection DAG isel once implemented.
3292 case CCValAssign::FPExt:
3293 llvm_unreachable("Unexpected loc info!");
3294 case CCValAssign::Indirect:
3295 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3300 if (VA.isRegLoc()) {
3301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3302 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3303 OutRegs.push_back(VA.getLocReg());
3305 assert(VA.isMemLoc());
3306 unsigned LocMemOffset = VA.getLocMemOffset();
3308 AM.Base.Reg = RegInfo->getStackRegister();
3309 AM.Disp = LocMemOffset;
3310 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3311 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3312 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3313 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3314 ArgVT.getStoreSize(), Alignment);
3315 if (Flags.isByVal()) {
3316 X86AddressMode SrcAM;
3317 SrcAM.Base.Reg = ArgReg;
3318 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3320 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3321 // If this is a really simple value, emit this with the Value* version
3322 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3323 // as it can cause us to reevaluate the argument.
3324 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3327 bool ValIsKill = hasTrivialKill(ArgVal);
3328 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3334 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3336 if (Subtarget->isPICStyleGOT()) {
3337 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3339 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3342 if (Is64Bit && IsVarArg && !IsWin64) {
3343 // From AMD64 ABI document:
3344 // For calls that may call functions that use varargs or stdargs
3345 // (prototype-less calls or calls to functions containing ellipsis (...) in
3346 // the declaration) %al is used as hidden argument to specify the number
3347 // of SSE registers used. The contents of %al do not need to match exactly
3348 // the number of registers, but must be an ubound on the number of SSE
3349 // registers used and is in the range 0 - 8 inclusive.
3351 // Count the number of XMM registers allocated.
3352 static const MCPhysReg XMMArgRegs[] = {
3353 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3354 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3356 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
3357 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3358 && "SSE registers cannot be used when SSE is disabled");
3359 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3360 X86::AL).addImm(NumXMMRegs);
3363 // Materialize callee address in a register. FIXME: GV address can be
3364 // handled with a CALLpcrel32 instead.
3365 X86AddressMode CalleeAM;
3366 if (!X86SelectCallAddress(Callee, CalleeAM))
3369 unsigned CalleeOp = 0;
3370 const GlobalValue *GV = nullptr;
3371 if (CalleeAM.GV != nullptr) {
3373 } else if (CalleeAM.Base.Reg != 0) {
3374 CalleeOp = CalleeAM.Base.Reg;
3379 MachineInstrBuilder MIB;
3381 // Register-indirect call.
3382 unsigned CallOpc = Is64Bit ? X86::CALL64r : CallOpc = X86::CALL32r;
3383 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3387 assert(GV && "Not a direct call");
3388 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3390 // See if we need any target-specific flags on the GV operand.
3391 unsigned char OpFlags = 0;
3393 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3394 // external symbols most go through the PLT in PIC mode. If the symbol
3395 // has hidden or protected visibility, or if it is static or local, then
3396 // we don't need to use the PLT - we can directly call it.
3397 if (Subtarget->isTargetELF() &&
3398 TM.getRelocationModel() == Reloc::PIC_ &&
3399 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3400 OpFlags = X86II::MO_PLT;
3401 } else if (Subtarget->isPICStyleStubAny() &&
3402 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3403 (!Subtarget->getTargetTriple().isMacOSX() ||
3404 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3405 // PC-relative references to external symbols should go through $stub,
3406 // unless we're building with the leopard linker or later, which
3407 // automatically synthesizes these stubs.
3408 OpFlags = X86II::MO_DARWIN_STUB;
3411 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3413 MIB.addExternalSymbol(SymName, OpFlags);
3415 MIB.addGlobalAddress(GV, 0, OpFlags);
3418 // Add a register mask operand representing the call-preserved registers.
3419 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3420 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3422 // Add an implicit use GOT pointer in EBX.
3423 if (Subtarget->isPICStyleGOT())
3424 MIB.addReg(X86::EBX, RegState::Implicit);
3426 if (Is64Bit && IsVarArg && !IsWin64)
3427 MIB.addReg(X86::AL, RegState::Implicit);
3429 // Add implicit physical register uses to the call.
3430 for (auto Reg : OutRegs)
3431 MIB.addReg(Reg, RegState::Implicit);
3433 // Issue CALLSEQ_END
3434 unsigned NumBytesForCalleeToPop =
3435 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3436 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3438 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3440 // Now handle call return values.
3441 SmallVector<CCValAssign, 16> RVLocs;
3442 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs,
3443 CLI.RetTy->getContext());
3444 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3446 // Copy all of the result registers out of their specified physreg.
3447 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3448 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3449 CCValAssign &VA = RVLocs[i];
3450 EVT CopyVT = VA.getValVT();
3451 unsigned CopyReg = ResultReg + i;
3453 // If this is x86-64, and we disabled SSE, we can't return FP values
3454 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3455 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3456 report_fatal_error("SSE register return with SSE disabled");
3459 // If this is a call to a function that returns an fp value on the floating
3460 // point stack, we must guarantee the value is popped from the stack, so
3461 // a COPY is not good enough - the copy instruction may be eliminated if the
3462 // return value is not used. We use the FpPOP_RETVAL instruction instead.
3463 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
3464 // If we prefer to use the value in xmm registers, copy it out as f80 and
3465 // use a truncate to move it from fp stack reg to xmm reg.
3466 if (isScalarFPTypeInSSEReg(VA.getValVT())) {
3468 CopyReg = createResultReg(&X86::RFP80RegClass);
3470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3471 TII.get(X86::FpPOP_RETVAL), CopyReg);
3473 // Round the f80 to the right size, which also moves it to the appropriate
3474 // xmm register. This is accomplished by storing the f80 value in memory
3475 // and then loading it back.
3476 if (CopyVT != VA.getValVT()) {
3477 EVT ResVT = VA.getValVT();
3478 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3479 unsigned MemSize = ResVT.getSizeInBits()/8;
3480 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3481 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3484 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3485 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3486 TII.get(Opc), ResultReg + i), FI);
3489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3490 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3491 InRegs.push_back(VA.getLocReg());
3495 CLI.ResultReg = ResultReg;
3496 CLI.NumResultRegs = RVLocs.size();
3503 X86FastISel::TargetSelectInstruction(const Instruction *I) {
3504 switch (I->getOpcode()) {
3506 case Instruction::Load:
3507 return X86SelectLoad(I);
3508 case Instruction::Store:
3509 return X86SelectStore(I);
3510 case Instruction::Ret:
3511 return X86SelectRet(I);
3512 case Instruction::ICmp:
3513 case Instruction::FCmp:
3514 return X86SelectCmp(I);
3515 case Instruction::ZExt:
3516 return X86SelectZExt(I);
3517 case Instruction::Br:
3518 return X86SelectBranch(I);
3519 case Instruction::Call:
3520 return X86SelectCall(I);
3521 case Instruction::LShr:
3522 case Instruction::AShr:
3523 case Instruction::Shl:
3524 return X86SelectShift(I);
3525 case Instruction::SDiv:
3526 case Instruction::UDiv:
3527 case Instruction::SRem:
3528 case Instruction::URem:
3529 return X86SelectDivRem(I);
3530 case Instruction::Select:
3531 return X86SelectSelect(I);
3532 case Instruction::Trunc:
3533 return X86SelectTrunc(I);
3534 case Instruction::FPExt:
3535 return X86SelectFPExt(I);
3536 case Instruction::FPTrunc:
3537 return X86SelectFPTrunc(I);
3538 case Instruction::IntToPtr: // Deliberate fall-through.
3539 case Instruction::PtrToInt: {
3540 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3541 EVT DstVT = TLI.getValueType(I->getType());
3542 if (DstVT.bitsGT(SrcVT))
3543 return X86SelectZExt(I);
3544 if (DstVT.bitsLT(SrcVT))
3545 return X86SelectTrunc(I);
3546 unsigned Reg = getRegForValue(I->getOperand(0));
3547 if (Reg == 0) return false;
3548 UpdateValueMap(I, Reg);
3556 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3558 if (!isTypeLegal(C->getType(), VT))
3561 // Can't handle alternate code models yet.
3562 if (TM.getCodeModel() != CodeModel::Small)
3565 // Get opcode and regclass of the output for the given load instruction.
3567 const TargetRegisterClass *RC = nullptr;
3568 switch (VT.SimpleTy) {
3572 RC = &X86::GR8RegClass;
3576 RC = &X86::GR16RegClass;
3580 RC = &X86::GR32RegClass;
3583 // Must be in x86-64 mode.
3585 RC = &X86::GR64RegClass;
3588 if (X86ScalarSSEf32) {
3589 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3590 RC = &X86::FR32RegClass;
3592 Opc = X86::LD_Fp32m;
3593 RC = &X86::RFP32RegClass;
3597 if (X86ScalarSSEf64) {
3598 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3599 RC = &X86::FR64RegClass;
3601 Opc = X86::LD_Fp64m;
3602 RC = &X86::RFP64RegClass;
3606 // No f80 support yet.
3610 // Materialize addresses with LEA/MOV instructions.
3611 if (isa<GlobalValue>(C)) {
3613 if (X86SelectAddress(C, AM)) {
3614 // If the expression is just a basereg, then we're done, otherwise we need
3616 if (AM.BaseType == X86AddressMode::RegBase &&
3617 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3620 unsigned ResultReg = createResultReg(RC);
3621 if (TM.getRelocationModel() == Reloc::Static &&
3622 TLI.getPointerTy() == MVT::i64) {
3623 // The displacement code be more than 32 bits away so we need to use
3624 // an instruction with a 64 bit immediate
3626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3627 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
3629 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3630 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3631 TII.get(Opc), ResultReg), AM);
3638 // MachineConstantPool wants an explicit alignment.
3639 unsigned Align = DL.getPrefTypeAlignment(C->getType());
3641 // Alignment of vector types. FIXME!
3642 Align = DL.getTypeAllocSize(C->getType());
3645 // x86-32 PIC requires a PIC base register for constant pools.
3646 unsigned PICBase = 0;
3647 unsigned char OpFlag = 0;
3648 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3649 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3650 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3651 } else if (Subtarget->isPICStyleGOT()) {
3652 OpFlag = X86II::MO_GOTOFF;
3653 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3654 } else if (Subtarget->isPICStyleRIPRel() &&
3655 TM.getCodeModel() == CodeModel::Small) {
3659 // Create the load from the constant pool.
3660 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
3661 unsigned ResultReg = createResultReg(RC);
3662 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3663 TII.get(Opc), ResultReg),
3664 MCPOffset, PICBase, OpFlag);
3669 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3670 // Fail on dynamic allocas. At this point, getRegForValue has already
3671 // checked its CSE maps, so if we're here trying to handle a dynamic
3672 // alloca, we're not going to succeed. X86SelectAddress has a
3673 // check for dynamic allocas, because it's called directly from
3674 // various places, but TargetMaterializeAlloca also needs a check
3675 // in order to avoid recursion between getRegForValue,
3676 // X86SelectAddrss, and TargetMaterializeAlloca.
3677 if (!FuncInfo.StaticAllocaMap.count(C))
3679 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3682 if (!X86SelectAddress(C, AM))
3684 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3685 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3686 unsigned ResultReg = createResultReg(RC);
3687 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3688 TII.get(Opc), ResultReg), AM);
3692 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3694 if (!isTypeLegal(CF->getType(), VT))
3697 // Get opcode and regclass for the given zero.
3699 const TargetRegisterClass *RC = nullptr;
3700 switch (VT.SimpleTy) {
3703 if (X86ScalarSSEf32) {
3704 Opc = X86::FsFLD0SS;
3705 RC = &X86::FR32RegClass;
3707 Opc = X86::LD_Fp032;
3708 RC = &X86::RFP32RegClass;
3712 if (X86ScalarSSEf64) {
3713 Opc = X86::FsFLD0SD;
3714 RC = &X86::FR64RegClass;
3716 Opc = X86::LD_Fp064;
3717 RC = &X86::RFP64RegClass;
3721 // No f80 support yet.
3725 unsigned ResultReg = createResultReg(RC);
3726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3731 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3732 const LoadInst *LI) {
3733 const Value *Ptr = LI->getPointerOperand();
3735 if (!X86SelectAddress(Ptr, AM))
3738 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3740 unsigned Size = DL.getTypeAllocSize(LI->getType());
3741 unsigned Alignment = LI->getAlignment();
3743 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3744 Alignment = DL.getABITypeAlignment(LI->getType());
3746 SmallVector<MachineOperand, 8> AddrOps;
3747 AM.getFullAddress(AddrOps);
3749 MachineInstr *Result =
3750 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3754 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3755 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3756 MI->eraseFromParent();
3762 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3763 const TargetLibraryInfo *libInfo) {
3764 return new X86FastISel(funcInfo, libInfo);