1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
46 class X86FastISel final : public FastISel {
47 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
48 /// make the right decision when generating code for different targets.
49 const X86Subtarget *Subtarget;
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
60 const TargetLibraryInfo *libInfo)
61 : FastISel(funcInfo, libInfo) {
62 Subtarget = &TM.getSubtarget<X86Subtarget>();
63 X86ScalarSSEf64 = Subtarget->hasSSE2();
64 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 bool TargetSelectInstruction(const Instruction *I) override;
69 /// \brief The specified machine instr operand is a vreg, and that
70 /// vreg is being provided by the specified load instruction. If possible,
71 /// try to fold the load as an operand to the instruction, returning true if
73 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74 const LoadInst *LI) override;
76 bool FastLowerArguments() override;
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
86 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
87 MachineMemOperand *MMO = nullptr, bool Aligned = false);
88 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
89 const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
95 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
96 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
98 bool X86SelectLoad(const Instruction *I);
100 bool X86SelectStore(const Instruction *I);
102 bool X86SelectRet(const Instruction *I);
104 bool X86SelectCmp(const Instruction *I);
106 bool X86SelectZExt(const Instruction *I);
108 bool X86SelectBranch(const Instruction *I);
110 bool X86SelectShift(const Instruction *I);
112 bool X86SelectDivRem(const Instruction *I);
114 bool X86FastEmitCMoveSelect(const Instruction *I);
116 bool X86SelectSelect(const Instruction *I);
118 bool X86SelectTrunc(const Instruction *I);
120 bool X86SelectFPExt(const Instruction *I);
121 bool X86SelectFPTrunc(const Instruction *I);
123 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
124 bool X86SelectCall(const Instruction *I);
126 bool DoSelectCall(const Instruction *I, const char *MemIntName);
128 const X86InstrInfo *getInstrInfo() const {
129 return getTargetMachine()->getInstrInfo();
131 const X86TargetMachine *getTargetMachine() const {
132 return static_cast<const X86TargetMachine *>(&TM);
135 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
137 unsigned TargetMaterializeConstant(const Constant *C) override;
139 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
141 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
143 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
144 /// computed in an SSE register, not on the X87 floating point stack.
145 bool isScalarFPTypeInSSEReg(EVT VT) const {
146 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
147 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
150 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
152 bool IsMemcpySmall(uint64_t Len);
154 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
155 X86AddressMode SrcAM, uint64_t Len);
158 } // end anonymous namespace.
160 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
161 // If both operands are the same, then try to optimize or fold the cmp.
162 CmpInst::Predicate Predicate = CI->getPredicate();
163 if (CI->getOperand(0) != CI->getOperand(1))
167 default: llvm_unreachable("Invalid predicate!");
168 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
169 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
170 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
171 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
172 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
173 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
174 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
175 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
176 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
177 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
178 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
179 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
180 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
181 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
182 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
183 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
185 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
186 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
187 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
188 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
189 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
190 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
191 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
192 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
194 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
200 static std::pair<X86::CondCode, bool>
201 getX86ConditonCode(CmpInst::Predicate Predicate) {
202 X86::CondCode CC = X86::COND_INVALID;
203 bool NeedSwap = false;
206 // Floating-point Predicates
207 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
208 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
209 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
210 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
211 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
212 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
213 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
214 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
215 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
216 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
217 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
218 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
219 case CmpInst::FCMP_OEQ: // fall-through
220 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
222 // Integer Predicates
223 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
224 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
225 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
226 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
227 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
228 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
229 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
230 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
231 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
232 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
235 return std::make_pair(CC, NeedSwap);
238 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
239 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
240 if (evt == MVT::Other || !evt.isSimple())
241 // Unhandled type. Halt "fast" selection and bail.
244 VT = evt.getSimpleVT();
245 // For now, require SSE/SSE2 for performing floating-point operations,
246 // since x87 requires additional work.
247 if (VT == MVT::f64 && !X86ScalarSSEf64)
249 if (VT == MVT::f32 && !X86ScalarSSEf32)
251 // Similarly, no f80 support yet.
254 // We only handle legal types. For example, on x86-32 the instruction
255 // selector contains all of the 64-bit instructions from x86-64,
256 // under the assumption that i64 won't be used if the target doesn't
258 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
261 #include "X86GenCallingConv.inc"
263 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
264 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
265 /// Return true and the result register by reference if it is possible.
266 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
267 MachineMemOperand *MMO, unsigned &ResultReg) {
268 // Get opcode and regclass of the output for the given load instruction.
270 const TargetRegisterClass *RC = nullptr;
271 switch (VT.getSimpleVT().SimpleTy) {
272 default: return false;
276 RC = &X86::GR8RegClass;
280 RC = &X86::GR16RegClass;
284 RC = &X86::GR32RegClass;
287 // Must be in x86-64 mode.
289 RC = &X86::GR64RegClass;
292 if (X86ScalarSSEf32) {
293 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
294 RC = &X86::FR32RegClass;
297 RC = &X86::RFP32RegClass;
301 if (X86ScalarSSEf64) {
302 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
303 RC = &X86::FR64RegClass;
306 RC = &X86::RFP64RegClass;
310 // No f80 support yet.
314 ResultReg = createResultReg(RC);
315 MachineInstrBuilder MIB =
316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
317 addFullAddress(MIB, AM);
319 MIB->addMemOperand(*FuncInfo.MF, MMO);
323 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
324 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
325 /// and a displacement offset, or a GlobalAddress,
326 /// i.e. V. Return true if it is possible.
327 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
328 const X86AddressMode &AM,
329 MachineMemOperand *MMO, bool Aligned) {
330 // Get opcode and regclass of the output for the given store instruction.
332 switch (VT.getSimpleVT().SimpleTy) {
333 case MVT::f80: // No f80 support yet.
334 default: return false;
336 // Mask out all but lowest bit.
337 unsigned AndResult = createResultReg(&X86::GR8RegClass);
338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
339 TII.get(X86::AND8ri), AndResult)
340 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
343 // FALLTHROUGH, handling i1 as i8.
344 case MVT::i8: Opc = X86::MOV8mr; break;
345 case MVT::i16: Opc = X86::MOV16mr; break;
346 case MVT::i32: Opc = X86::MOV32mr; break;
347 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
349 Opc = X86ScalarSSEf32 ?
350 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
353 Opc = X86ScalarSSEf64 ?
354 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
358 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
360 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
364 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
366 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
373 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
375 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
379 MachineInstrBuilder MIB =
380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
381 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
383 MIB->addMemOperand(*FuncInfo.MF, MMO);
388 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
389 const X86AddressMode &AM,
390 MachineMemOperand *MMO, bool Aligned) {
391 // Handle 'null' like i32/i64 0.
392 if (isa<ConstantPointerNull>(Val))
393 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
395 // If this is a store of a simple constant, fold the constant into the store.
396 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
399 switch (VT.getSimpleVT().SimpleTy) {
401 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
402 case MVT::i8: Opc = X86::MOV8mi; break;
403 case MVT::i16: Opc = X86::MOV16mi; break;
404 case MVT::i32: Opc = X86::MOV32mi; break;
406 // Must be a 32-bit sign extended value.
407 if (isInt<32>(CI->getSExtValue()))
408 Opc = X86::MOV64mi32;
413 MachineInstrBuilder MIB =
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
415 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
416 : CI->getZExtValue());
418 MIB->addMemOperand(*FuncInfo.MF, MMO);
423 unsigned ValReg = getRegForValue(Val);
427 bool ValKill = hasTrivialKill(Val);
428 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
431 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
432 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
433 /// ISD::SIGN_EXTEND).
434 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
435 unsigned Src, EVT SrcVT,
436 unsigned &ResultReg) {
437 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
438 Src, /*TODO: Kill=*/false);
446 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
447 // Handle constant address.
448 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
449 // Can't handle alternate code models yet.
450 if (TM.getCodeModel() != CodeModel::Small)
453 // Can't handle TLS yet.
454 if (GV->isThreadLocal())
457 // RIP-relative addresses can't have additional register operands, so if
458 // we've already folded stuff into the addressing mode, just force the
459 // global value into its own register, which we can use as the basereg.
460 if (!Subtarget->isPICStyleRIPRel() ||
461 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
462 // Okay, we've committed to selecting this global. Set up the address.
465 // Allow the subtarget to classify the global.
466 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
468 // If this reference is relative to the pic base, set it now.
469 if (isGlobalRelativeToPICBase(GVFlags)) {
470 // FIXME: How do we know Base.Reg is free??
471 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
474 // Unless the ABI requires an extra load, return a direct reference to
476 if (!isGlobalStubReference(GVFlags)) {
477 if (Subtarget->isPICStyleRIPRel()) {
478 // Use rip-relative addressing if we can. Above we verified that the
479 // base and index registers are unused.
480 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
481 AM.Base.Reg = X86::RIP;
483 AM.GVOpFlags = GVFlags;
487 // Ok, we need to do a load from a stub. If we've already loaded from
488 // this stub, reuse the loaded pointer, otherwise emit the load now.
489 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
491 if (I != LocalValueMap.end() && I->second != 0) {
494 // Issue load from stub.
496 const TargetRegisterClass *RC = nullptr;
497 X86AddressMode StubAM;
498 StubAM.Base.Reg = AM.Base.Reg;
500 StubAM.GVOpFlags = GVFlags;
502 // Prepare for inserting code in the local-value area.
503 SavePoint SaveInsertPt = enterLocalValueArea();
505 if (TLI.getPointerTy() == MVT::i64) {
507 RC = &X86::GR64RegClass;
509 if (Subtarget->isPICStyleRIPRel())
510 StubAM.Base.Reg = X86::RIP;
513 RC = &X86::GR32RegClass;
516 LoadReg = createResultReg(RC);
517 MachineInstrBuilder LoadMI =
518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
519 addFullAddress(LoadMI, StubAM);
521 // Ok, back to normal mode.
522 leaveLocalValueArea(SaveInsertPt);
524 // Prevent loading GV stub multiple times in same MBB.
525 LocalValueMap[V] = LoadReg;
528 // Now construct the final address. Note that the Disp, Scale,
529 // and Index values may already be set here.
530 AM.Base.Reg = LoadReg;
536 // If all else fails, try to materialize the value in a register.
537 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
538 if (AM.Base.Reg == 0) {
539 AM.Base.Reg = getRegForValue(V);
540 return AM.Base.Reg != 0;
542 if (AM.IndexReg == 0) {
543 assert(AM.Scale == 1 && "Scale with no index!");
544 AM.IndexReg = getRegForValue(V);
545 return AM.IndexReg != 0;
552 /// X86SelectAddress - Attempt to fill in an address from the given value.
554 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
555 SmallVector<const Value *, 32> GEPs;
557 const User *U = nullptr;
558 unsigned Opcode = Instruction::UserOp1;
559 if (const Instruction *I = dyn_cast<Instruction>(V)) {
560 // Don't walk into other basic blocks; it's possible we haven't
561 // visited them yet, so the instructions may not yet be assigned
562 // virtual registers.
563 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
564 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
565 Opcode = I->getOpcode();
568 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
569 Opcode = C->getOpcode();
573 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
574 if (Ty->getAddressSpace() > 255)
575 // Fast instruction selection doesn't support the special
581 case Instruction::BitCast:
582 // Look past bitcasts.
583 return X86SelectAddress(U->getOperand(0), AM);
585 case Instruction::IntToPtr:
586 // Look past no-op inttoptrs.
587 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
588 return X86SelectAddress(U->getOperand(0), AM);
591 case Instruction::PtrToInt:
592 // Look past no-op ptrtoints.
593 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
594 return X86SelectAddress(U->getOperand(0), AM);
597 case Instruction::Alloca: {
598 // Do static allocas.
599 const AllocaInst *A = cast<AllocaInst>(V);
600 DenseMap<const AllocaInst*, int>::iterator SI =
601 FuncInfo.StaticAllocaMap.find(A);
602 if (SI != FuncInfo.StaticAllocaMap.end()) {
603 AM.BaseType = X86AddressMode::FrameIndexBase;
604 AM.Base.FrameIndex = SI->second;
610 case Instruction::Add: {
611 // Adds of constants are common and easy enough.
612 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
613 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
614 // They have to fit in the 32-bit signed displacement field though.
615 if (isInt<32>(Disp)) {
616 AM.Disp = (uint32_t)Disp;
617 return X86SelectAddress(U->getOperand(0), AM);
623 case Instruction::GetElementPtr: {
624 X86AddressMode SavedAM = AM;
626 // Pattern-match simple GEPs.
627 uint64_t Disp = (int32_t)AM.Disp;
628 unsigned IndexReg = AM.IndexReg;
629 unsigned Scale = AM.Scale;
630 gep_type_iterator GTI = gep_type_begin(U);
631 // Iterate through the indices, folding what we can. Constants can be
632 // folded, and one dynamic index can be handled, if the scale is supported.
633 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
634 i != e; ++i, ++GTI) {
635 const Value *Op = *i;
636 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
637 const StructLayout *SL = DL.getStructLayout(STy);
638 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
642 // A array/variable index is always of the form i*S where S is the
643 // constant scale size. See if we can push the scale into immediates.
644 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
646 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
647 // Constant-offset addressing.
648 Disp += CI->getSExtValue() * S;
651 if (canFoldAddIntoGEP(U, Op)) {
652 // A compatible add with a constant operand. Fold the constant.
654 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
655 Disp += CI->getSExtValue() * S;
656 // Iterate on the other operand.
657 Op = cast<AddOperator>(Op)->getOperand(0);
661 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
662 (S == 1 || S == 2 || S == 4 || S == 8)) {
663 // Scaled-index addressing.
665 IndexReg = getRegForGEPIndex(Op).first;
671 goto unsupported_gep;
675 // Check for displacement overflow.
676 if (!isInt<32>(Disp))
679 AM.IndexReg = IndexReg;
681 AM.Disp = (uint32_t)Disp;
684 if (const GetElementPtrInst *GEP =
685 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
686 // Ok, the GEP indices were covered by constant-offset and scaled-index
687 // addressing. Update the address state and move on to examining the base.
690 } else if (X86SelectAddress(U->getOperand(0), AM)) {
694 // If we couldn't merge the gep value into this addr mode, revert back to
695 // our address and just match the value instead of completely failing.
698 for (SmallVectorImpl<const Value *>::reverse_iterator
699 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
700 if (handleConstantAddresses(*I, AM))
705 // Ok, the GEP indices weren't all covered.
710 return handleConstantAddresses(V, AM);
713 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
715 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
716 const User *U = nullptr;
717 unsigned Opcode = Instruction::UserOp1;
718 const Instruction *I = dyn_cast<Instruction>(V);
719 // Record if the value is defined in the same basic block.
721 // This information is crucial to know whether or not folding an
723 // Indeed, FastISel generates or reuses a virtual register for all
724 // operands of all instructions it selects. Obviously, the definition and
725 // its uses must use the same virtual register otherwise the produced
726 // code is incorrect.
727 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
728 // registers for values that are alive across basic blocks. This ensures
729 // that the values are consistently set between across basic block, even
730 // if different instruction selection mechanisms are used (e.g., a mix of
731 // SDISel and FastISel).
732 // For values local to a basic block, the instruction selection process
733 // generates these virtual registers with whatever method is appropriate
734 // for its needs. In particular, FastISel and SDISel do not share the way
735 // local virtual registers are set.
736 // Therefore, this is impossible (or at least unsafe) to share values
737 // between basic blocks unless they use the same instruction selection
738 // method, which is not guarantee for X86.
739 // Moreover, things like hasOneUse could not be used accurately, if we
740 // allow to reference values across basic blocks whereas they are not
741 // alive across basic blocks initially.
744 Opcode = I->getOpcode();
746 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
747 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
748 Opcode = C->getOpcode();
754 case Instruction::BitCast:
755 // Look past bitcasts if its operand is in the same BB.
757 return X86SelectCallAddress(U->getOperand(0), AM);
760 case Instruction::IntToPtr:
761 // Look past no-op inttoptrs if its operand is in the same BB.
763 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
764 return X86SelectCallAddress(U->getOperand(0), AM);
767 case Instruction::PtrToInt:
768 // Look past no-op ptrtoints if its operand is in the same BB.
770 TLI.getValueType(U->getType()) == TLI.getPointerTy())
771 return X86SelectCallAddress(U->getOperand(0), AM);
775 // Handle constant address.
776 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
777 // Can't handle alternate code models yet.
778 if (TM.getCodeModel() != CodeModel::Small)
781 // RIP-relative addresses can't have additional register operands.
782 if (Subtarget->isPICStyleRIPRel() &&
783 (AM.Base.Reg != 0 || AM.IndexReg != 0))
786 // Can't handle DbgLocLImport.
787 if (GV->hasDLLImportStorageClass())
791 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
792 if (GVar->isThreadLocal())
795 // Okay, we've committed to selecting this global. Set up the basic address.
798 // No ABI requires an extra load for anything other than DLLImport, which
799 // we rejected above. Return a direct reference to the global.
800 if (Subtarget->isPICStyleRIPRel()) {
801 // Use rip-relative addressing if we can. Above we verified that the
802 // base and index registers are unused.
803 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
804 AM.Base.Reg = X86::RIP;
805 } else if (Subtarget->isPICStyleStubPIC()) {
806 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
807 } else if (Subtarget->isPICStyleGOT()) {
808 AM.GVOpFlags = X86II::MO_GOTOFF;
814 // If all else fails, try to materialize the value in a register.
815 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
816 if (AM.Base.Reg == 0) {
817 AM.Base.Reg = getRegForValue(V);
818 return AM.Base.Reg != 0;
820 if (AM.IndexReg == 0) {
821 assert(AM.Scale == 1 && "Scale with no index!");
822 AM.IndexReg = getRegForValue(V);
823 return AM.IndexReg != 0;
831 /// X86SelectStore - Select and emit code to implement store instructions.
832 bool X86FastISel::X86SelectStore(const Instruction *I) {
833 // Atomic stores need special handling.
834 const StoreInst *S = cast<StoreInst>(I);
839 const Value *Val = S->getValueOperand();
840 const Value *Ptr = S->getPointerOperand();
843 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
846 unsigned Alignment = S->getAlignment();
847 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
848 if (Alignment == 0) // Ensure that codegen never sees alignment 0
849 Alignment = ABIAlignment;
850 bool Aligned = Alignment >= ABIAlignment;
853 if (!X86SelectAddress(Ptr, AM))
856 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
859 /// X86SelectRet - Select and emit code to implement ret instructions.
860 bool X86FastISel::X86SelectRet(const Instruction *I) {
861 const ReturnInst *Ret = cast<ReturnInst>(I);
862 const Function &F = *I->getParent()->getParent();
863 const X86MachineFunctionInfo *X86MFInfo =
864 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
866 if (!FuncInfo.CanLowerReturn)
869 CallingConv::ID CC = F.getCallingConv();
870 if (CC != CallingConv::C &&
871 CC != CallingConv::Fast &&
872 CC != CallingConv::X86_FastCall &&
873 CC != CallingConv::X86_64_SysV)
876 if (Subtarget->isCallingConvWin64(CC))
879 // Don't handle popping bytes on return for now.
880 if (X86MFInfo->getBytesToPopOnReturn() != 0)
883 // fastcc with -tailcallopt is intended to provide a guaranteed
884 // tail call optimization. Fastisel doesn't know how to do that.
885 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
888 // Let SDISel handle vararg functions.
892 // Build a list of return value registers.
893 SmallVector<unsigned, 4> RetRegs;
895 if (Ret->getNumOperands() > 0) {
896 SmallVector<ISD::OutputArg, 4> Outs;
897 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
899 // Analyze operands of the call, assigning locations to each operand.
900 SmallVector<CCValAssign, 16> ValLocs;
901 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
903 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
905 const Value *RV = Ret->getOperand(0);
906 unsigned Reg = getRegForValue(RV);
910 // Only handle a single return value for now.
911 if (ValLocs.size() != 1)
914 CCValAssign &VA = ValLocs[0];
916 // Don't bother handling odd stuff for now.
917 if (VA.getLocInfo() != CCValAssign::Full)
919 // Only handle register returns for now.
923 // The calling-convention tables for x87 returns don't tell
925 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
928 unsigned SrcReg = Reg + VA.getValNo();
929 EVT SrcVT = TLI.getValueType(RV->getType());
930 EVT DstVT = VA.getValVT();
931 // Special handling for extended integers.
932 if (SrcVT != DstVT) {
933 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
936 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
939 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
941 if (SrcVT == MVT::i1) {
942 if (Outs[0].Flags.isSExt())
944 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
947 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
949 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
950 SrcReg, /*TODO: Kill=*/false);
954 unsigned DstReg = VA.getLocReg();
955 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
956 // Avoid a cross-class copy. This is very unlikely.
957 if (!SrcRC->contains(DstReg))
959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
960 DstReg).addReg(SrcReg);
962 // Add register to return instruction.
963 RetRegs.push_back(VA.getLocReg());
966 // The x86-64 ABI for returning structs by value requires that we copy
967 // the sret argument into %rax for the return. We saved the argument into
968 // a virtual register in the entry block, so now we copy the value out
969 // and into %rax. We also do the same with %eax for Win32.
970 if (F.hasStructRetAttr() &&
971 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
972 unsigned Reg = X86MFInfo->getSRetReturnReg();
974 "SRetReturnReg should have been set in LowerFormalArguments()!");
975 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
978 RetRegs.push_back(RetReg);
982 MachineInstrBuilder MIB =
983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
984 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
985 MIB.addReg(RetRegs[i], RegState::Implicit);
989 /// X86SelectLoad - Select and emit code to implement load instructions.
991 bool X86FastISel::X86SelectLoad(const Instruction *I) {
992 const LoadInst *LI = cast<LoadInst>(I);
994 // Atomic loads need special handling.
999 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1002 const Value *Ptr = LI->getPointerOperand();
1005 if (!X86SelectAddress(Ptr, AM))
1008 unsigned ResultReg = 0;
1009 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1012 UpdateValueMap(I, ResultReg);
1016 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1017 bool HasAVX = Subtarget->hasAVX();
1018 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1019 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1021 switch (VT.getSimpleVT().SimpleTy) {
1023 case MVT::i8: return X86::CMP8rr;
1024 case MVT::i16: return X86::CMP16rr;
1025 case MVT::i32: return X86::CMP32rr;
1026 case MVT::i64: return X86::CMP64rr;
1028 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1030 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1034 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1035 /// of the comparison, return an opcode that works for the compare (e.g.
1036 /// CMP32ri) otherwise return 0.
1037 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1038 switch (VT.getSimpleVT().SimpleTy) {
1039 // Otherwise, we can't fold the immediate into this comparison.
1041 case MVT::i8: return X86::CMP8ri;
1042 case MVT::i16: return X86::CMP16ri;
1043 case MVT::i32: return X86::CMP32ri;
1045 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1047 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1048 return X86::CMP64ri32;
1053 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1055 unsigned Op0Reg = getRegForValue(Op0);
1056 if (Op0Reg == 0) return false;
1058 // Handle 'null' like i32/i64 0.
1059 if (isa<ConstantPointerNull>(Op1))
1060 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1062 // We have two options: compare with register or immediate. If the RHS of
1063 // the compare is an immediate that we can fold into this compare, use
1064 // CMPri, otherwise use CMPrr.
1065 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1066 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1069 .addImm(Op1C->getSExtValue());
1074 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1075 if (CompareOpc == 0) return false;
1077 unsigned Op1Reg = getRegForValue(Op1);
1078 if (Op1Reg == 0) return false;
1079 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1086 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1087 const CmpInst *CI = cast<CmpInst>(I);
1090 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1093 // Try to optimize or fold the cmp.
1094 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1095 unsigned ResultReg = 0;
1096 switch (Predicate) {
1098 case CmpInst::FCMP_FALSE: {
1099 ResultReg = createResultReg(&X86::GR32RegClass);
1100 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1102 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1108 case CmpInst::FCMP_TRUE: {
1109 ResultReg = createResultReg(&X86::GR8RegClass);
1110 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1111 ResultReg).addImm(1);
1117 UpdateValueMap(I, ResultReg);
1121 const Value *LHS = CI->getOperand(0);
1122 const Value *RHS = CI->getOperand(1);
1124 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1125 // We don't have to materialize a zero constant for this case and can just use
1126 // %x again on the RHS.
1127 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1128 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1129 if (RHSC && RHSC->isNullValue())
1133 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1134 static unsigned SETFOpcTable[2][3] = {
1135 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1136 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1138 unsigned *SETFOpc = nullptr;
1139 switch (Predicate) {
1141 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1142 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1145 ResultReg = createResultReg(&X86::GR8RegClass);
1147 if (!X86FastEmitCompare(LHS, RHS, VT))
1150 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1151 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1152 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1154 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1156 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1157 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1158 UpdateValueMap(I, ResultReg);
1164 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1165 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1166 unsigned Opc = X86::getSETFromCond(CC);
1169 std::swap(LHS, RHS);
1171 // Emit a compare of LHS/RHS.
1172 if (!X86FastEmitCompare(LHS, RHS, VT))
1175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1176 UpdateValueMap(I, ResultReg);
1180 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1181 EVT DstVT = TLI.getValueType(I->getType());
1182 if (!TLI.isTypeLegal(DstVT))
1185 unsigned ResultReg = getRegForValue(I->getOperand(0));
1189 // Handle zero-extension from i1 to i8, which is common.
1190 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1191 if (SrcVT.SimpleTy == MVT::i1) {
1192 // Set the high bits to zero.
1193 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1200 if (DstVT == MVT::i64) {
1201 // Handle extension to 64-bits via sub-register shenanigans.
1204 switch (SrcVT.SimpleTy) {
1205 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1206 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1207 case MVT::i32: MovInst = X86::MOV32rr; break;
1208 default: llvm_unreachable("Unexpected zext to i64 source type");
1211 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1215 ResultReg = createResultReg(&X86::GR64RegClass);
1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1218 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1219 } else if (DstVT != MVT::i8) {
1220 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1221 ResultReg, /*Kill=*/true);
1226 UpdateValueMap(I, ResultReg);
1231 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1232 // Unconditional branches are selected by tablegen-generated code.
1233 // Handle a conditional branch.
1234 const BranchInst *BI = cast<BranchInst>(I);
1235 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1236 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1238 // Fold the common case of a conditional branch with a comparison
1239 // in the same block (values defined on other blocks may not have
1240 // initialized registers).
1241 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1242 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1243 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1245 // Try to optimize or fold the cmp.
1246 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1247 switch (Predicate) {
1249 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1250 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1253 const Value *CmpLHS = CI->getOperand(0);
1254 const Value *CmpRHS = CI->getOperand(1);
1256 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1258 // We don't have to materialize a zero constant for this case and can just
1259 // use %x again on the RHS.
1260 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1261 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1262 if (CmpRHSC && CmpRHSC->isNullValue())
1266 // Try to take advantage of fallthrough opportunities.
1267 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1268 std::swap(TrueMBB, FalseMBB);
1269 Predicate = CmpInst::getInversePredicate(Predicate);
1272 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1273 // code check. Instead two branch instructions are required to check all
1274 // the flags. First we change the predicate to a supported conditon code,
1275 // which will be the first branch. Later one we will emit the second
1277 bool NeedExtraBranch = false;
1278 switch (Predicate) {
1280 case CmpInst::FCMP_OEQ:
1281 std::swap(TrueMBB, FalseMBB); // fall-through
1282 case CmpInst::FCMP_UNE:
1283 NeedExtraBranch = true;
1284 Predicate = CmpInst::FCMP_ONE;
1291 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1292 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1294 BranchOpc = X86::GetCondBranchFromCond(CC);
1296 std::swap(CmpLHS, CmpRHS);
1298 // Emit a compare of the LHS and RHS, setting the flags.
1299 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1305 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1307 if (NeedExtraBranch) {
1308 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1312 // Obtain the branch weight and add the TrueBB to the successor list.
1313 uint32_t BranchWeight = 0;
1315 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1316 TrueMBB->getBasicBlock());
1317 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1319 // Emits an unconditional branch to the FalseBB, obtains the branch
1320 // weight, and adds it to the successor list.
1321 FastEmitBranch(FalseMBB, DbgLoc);
1325 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1326 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1327 // typically happen for _Bool and C++ bools.
1329 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1330 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1331 unsigned TestOpc = 0;
1332 switch (SourceVT.SimpleTy) {
1334 case MVT::i8: TestOpc = X86::TEST8ri; break;
1335 case MVT::i16: TestOpc = X86::TEST16ri; break;
1336 case MVT::i32: TestOpc = X86::TEST32ri; break;
1337 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1340 unsigned OpReg = getRegForValue(TI->getOperand(0));
1341 if (OpReg == 0) return false;
1342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1343 .addReg(OpReg).addImm(1);
1345 unsigned JmpOpc = X86::JNE_4;
1346 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1347 std::swap(TrueMBB, FalseMBB);
1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1353 FastEmitBranch(FalseMBB, DbgLoc);
1354 uint32_t BranchWeight = 0;
1356 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1357 TrueMBB->getBasicBlock());
1358 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1364 // Otherwise do a clumsy setcc and re-test it.
1365 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1366 // in an explicit cast, so make sure to handle that correctly.
1367 unsigned OpReg = getRegForValue(BI->getCondition());
1368 if (OpReg == 0) return false;
1370 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1371 .addReg(OpReg).addImm(1);
1372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1374 FastEmitBranch(FalseMBB, DbgLoc);
1375 uint32_t BranchWeight = 0;
1377 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1378 TrueMBB->getBasicBlock());
1379 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1383 bool X86FastISel::X86SelectShift(const Instruction *I) {
1384 unsigned CReg = 0, OpReg = 0;
1385 const TargetRegisterClass *RC = nullptr;
1386 if (I->getType()->isIntegerTy(8)) {
1388 RC = &X86::GR8RegClass;
1389 switch (I->getOpcode()) {
1390 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1391 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1392 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1393 default: return false;
1395 } else if (I->getType()->isIntegerTy(16)) {
1397 RC = &X86::GR16RegClass;
1398 switch (I->getOpcode()) {
1399 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1400 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1401 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1402 default: return false;
1404 } else if (I->getType()->isIntegerTy(32)) {
1406 RC = &X86::GR32RegClass;
1407 switch (I->getOpcode()) {
1408 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1409 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1410 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1411 default: return false;
1413 } else if (I->getType()->isIntegerTy(64)) {
1415 RC = &X86::GR64RegClass;
1416 switch (I->getOpcode()) {
1417 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1418 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1419 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1420 default: return false;
1427 if (!isTypeLegal(I->getType(), VT))
1430 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1431 if (Op0Reg == 0) return false;
1433 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1434 if (Op1Reg == 0) return false;
1435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1436 CReg).addReg(Op1Reg);
1438 // The shift instruction uses X86::CL. If we defined a super-register
1439 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1440 if (CReg != X86::CL)
1441 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1442 TII.get(TargetOpcode::KILL), X86::CL)
1443 .addReg(CReg, RegState::Kill);
1445 unsigned ResultReg = createResultReg(RC);
1446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1448 UpdateValueMap(I, ResultReg);
1452 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1453 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1454 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1455 const static bool S = true; // IsSigned
1456 const static bool U = false; // !IsSigned
1457 const static unsigned Copy = TargetOpcode::COPY;
1458 // For the X86 DIV/IDIV instruction, in most cases the dividend
1459 // (numerator) must be in a specific register pair highreg:lowreg,
1460 // producing the quotient in lowreg and the remainder in highreg.
1461 // For most data types, to set up the instruction, the dividend is
1462 // copied into lowreg, and lowreg is sign-extended or zero-extended
1463 // into highreg. The exception is i8, where the dividend is defined
1464 // as a single register rather than a register pair, and we
1465 // therefore directly sign-extend or zero-extend the dividend into
1466 // lowreg, instead of copying, and ignore the highreg.
1467 const static struct DivRemEntry {
1468 // The following portion depends only on the data type.
1469 const TargetRegisterClass *RC;
1470 unsigned LowInReg; // low part of the register pair
1471 unsigned HighInReg; // high part of the register pair
1472 // The following portion depends on both the data type and the operation.
1473 struct DivRemResult {
1474 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1475 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1476 // highreg, or copying a zero into highreg.
1477 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1478 // zero/sign-extending into lowreg for i8.
1479 unsigned DivRemResultReg; // Register containing the desired result.
1480 bool IsOpSigned; // Whether to use signed or unsigned form.
1481 } ResultTable[NumOps];
1482 } OpTable[NumTypes] = {
1483 { &X86::GR8RegClass, X86::AX, 0, {
1484 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1485 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1486 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1487 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1490 { &X86::GR16RegClass, X86::AX, X86::DX, {
1491 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1492 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1493 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1494 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1497 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1498 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1499 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1500 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1501 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1504 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1505 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1506 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1507 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1508 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1514 if (!isTypeLegal(I->getType(), VT))
1517 unsigned TypeIndex, OpIndex;
1518 switch (VT.SimpleTy) {
1519 default: return false;
1520 case MVT::i8: TypeIndex = 0; break;
1521 case MVT::i16: TypeIndex = 1; break;
1522 case MVT::i32: TypeIndex = 2; break;
1523 case MVT::i64: TypeIndex = 3;
1524 if (!Subtarget->is64Bit())
1529 switch (I->getOpcode()) {
1530 default: llvm_unreachable("Unexpected div/rem opcode");
1531 case Instruction::SDiv: OpIndex = 0; break;
1532 case Instruction::SRem: OpIndex = 1; break;
1533 case Instruction::UDiv: OpIndex = 2; break;
1534 case Instruction::URem: OpIndex = 3; break;
1537 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1538 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1539 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1542 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1546 // Move op0 into low-order input register.
1547 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1548 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1549 // Zero-extend or sign-extend into high-order input register.
1550 if (OpEntry.OpSignExtend) {
1551 if (OpEntry.IsOpSigned)
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1553 TII.get(OpEntry.OpSignExtend));
1555 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1557 TII.get(X86::MOV32r0), Zero32);
1559 // Copy the zero into the appropriate sub/super/identical physical
1560 // register. Unfortunately the operations needed are not uniform enough to
1561 // fit neatly into the table above.
1562 if (VT.SimpleTy == MVT::i16) {
1563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1564 TII.get(Copy), TypeEntry.HighInReg)
1565 .addReg(Zero32, 0, X86::sub_16bit);
1566 } else if (VT.SimpleTy == MVT::i32) {
1567 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1568 TII.get(Copy), TypeEntry.HighInReg)
1570 } else if (VT.SimpleTy == MVT::i64) {
1571 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1572 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1573 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1577 // Generate the DIV/IDIV instruction.
1578 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1579 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1580 // For i8 remainder, we can't reference AH directly, as we'll end
1581 // up with bogus copies like %R9B = COPY %AH. Reference AX
1582 // instead to prevent AH references in a REX instruction.
1584 // The current assumption of the fast register allocator is that isel
1585 // won't generate explicit references to the GPR8_NOREX registers. If
1586 // the allocator and/or the backend get enhanced to be more robust in
1587 // that regard, this can be, and should be, removed.
1588 unsigned ResultReg = 0;
1589 if ((I->getOpcode() == Instruction::SRem ||
1590 I->getOpcode() == Instruction::URem) &&
1591 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1592 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1593 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1595 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1597 // Shift AX right by 8 bits instead of using AH.
1598 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1599 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1601 // Now reference the 8-bit subreg of the result.
1602 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1603 /*Kill=*/true, X86::sub_8bit);
1605 // Copy the result out of the physreg if we haven't already.
1607 ResultReg = createResultReg(TypeEntry.RC);
1608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1609 .addReg(OpEntry.DivRemResultReg);
1611 UpdateValueMap(I, ResultReg);
1616 /// \brief Emit a conditional move instruction (if the are supported) to lower
1618 bool X86FastISel::X86FastEmitCMoveSelect(const Instruction *I) {
1620 if (!isTypeLegal(I->getType(), RetVT))
1623 // Check if the subtarget supports these instructions.
1624 if (!Subtarget->hasCMov())
1627 // FIXME: Add support for i8.
1629 switch (RetVT.SimpleTy) {
1630 default: return false;
1631 case MVT::i16: Opc = X86::CMOVNE16rr; break;
1632 case MVT::i32: Opc = X86::CMOVNE32rr; break;
1633 case MVT::i64: Opc = X86::CMOVNE64rr; break;
1636 const Value *Cond = I->getOperand(0);
1637 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1638 bool NeedTest = true;
1640 // Optimize conditons coming from a compare.
1641 if (const auto *CI = dyn_cast<CmpInst>(Cond)) {
1642 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1644 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1645 static unsigned SETFOpcTable[2][3] = {
1646 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1647 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1649 unsigned *SETFOpc = nullptr;
1650 switch (Predicate) {
1652 case CmpInst::FCMP_OEQ:
1653 SETFOpc = &SETFOpcTable[0][0];
1654 Predicate = CmpInst::ICMP_NE;
1656 case CmpInst::FCMP_UNE:
1657 SETFOpc = &SETFOpcTable[1][0];
1658 Predicate = CmpInst::ICMP_NE;
1664 std::tie(CC, NeedSwap) = getX86ConditonCode(Predicate);
1665 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1666 Opc = X86::getCMovFromCond(CC, RC->getSize());
1668 const Value *CmpLHS = CI->getOperand(0);
1669 const Value *CmpRHS = CI->getOperand(1);
1671 std::swap(CmpLHS, CmpRHS);
1673 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1674 // Emit a compare of the LHS and RHS, setting the flags.
1675 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1679 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1680 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1685 auto const &II = TII.get(SETFOpc[2]);
1686 if (II.getNumDefs()) {
1687 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1689 .addReg(FlagReg2).addReg(FlagReg1);
1691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1692 .addReg(FlagReg2).addReg(FlagReg1);
1699 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1700 // garbage. Indeed, only the less significant bit is supposed to be
1701 // accurate. If we read more than the lsb, we may see non-zero values
1702 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1703 // the select. This is achieved by performing TEST against 1.
1704 unsigned CondReg = getRegForValue(Cond);
1707 bool CondIsKill = hasTrivialKill(Cond);
1709 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1710 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1713 const Value *LHS = I->getOperand(1);
1714 const Value *RHS = I->getOperand(2);
1716 unsigned RHSReg = getRegForValue(RHS);
1717 bool RHSIsKill = hasTrivialKill(RHS);
1719 unsigned LHSReg = getRegForValue(LHS);
1720 bool LHSIsKill = hasTrivialKill(LHS);
1722 if (!LHSReg || !RHSReg)
1725 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1727 UpdateValueMap(I, ResultReg);
1731 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1733 if (!isTypeLegal(I->getType(), RetVT))
1736 // Check if we can fold the select.
1737 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
1738 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1739 const Value *Opnd = nullptr;
1740 switch (Predicate) {
1742 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
1743 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
1745 // No need for a select anymore - this is an unconditional move.
1747 unsigned OpReg = getRegForValue(Opnd);
1750 bool OpIsKill = hasTrivialKill(Opnd);
1751 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1752 unsigned ResultReg = createResultReg(RC);
1753 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1754 TII.get(TargetOpcode::COPY), ResultReg)
1755 .addReg(OpReg, getKillRegState(OpIsKill));
1756 UpdateValueMap(I, ResultReg);
1761 // First try to use real conditional move instructions.
1762 if (X86FastEmitCMoveSelect(I))
1768 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1769 // fpext from float to double.
1770 if (X86ScalarSSEf64 &&
1771 I->getType()->isDoubleTy()) {
1772 const Value *V = I->getOperand(0);
1773 if (V->getType()->isFloatTy()) {
1774 unsigned OpReg = getRegForValue(V);
1775 if (OpReg == 0) return false;
1776 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1777 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1778 TII.get(X86::CVTSS2SDrr), ResultReg)
1780 UpdateValueMap(I, ResultReg);
1788 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1789 if (X86ScalarSSEf64) {
1790 if (I->getType()->isFloatTy()) {
1791 const Value *V = I->getOperand(0);
1792 if (V->getType()->isDoubleTy()) {
1793 unsigned OpReg = getRegForValue(V);
1794 if (OpReg == 0) return false;
1795 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1796 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1797 TII.get(X86::CVTSD2SSrr), ResultReg)
1799 UpdateValueMap(I, ResultReg);
1808 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1809 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1810 EVT DstVT = TLI.getValueType(I->getType());
1812 // This code only handles truncation to byte.
1813 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1815 if (!TLI.isTypeLegal(SrcVT))
1818 unsigned InputReg = getRegForValue(I->getOperand(0));
1820 // Unhandled operand. Halt "fast" selection and bail.
1823 if (SrcVT == MVT::i8) {
1824 // Truncate from i8 to i1; no code needed.
1825 UpdateValueMap(I, InputReg);
1829 if (!Subtarget->is64Bit()) {
1830 // If we're on x86-32; we can't extract an i8 from a general register.
1831 // First issue a copy to GR16_ABCD or GR32_ABCD.
1832 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1833 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1834 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1835 unsigned CopyReg = createResultReg(CopyRC);
1836 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1837 CopyReg).addReg(InputReg);
1841 // Issue an extract_subreg.
1842 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1843 InputReg, /*Kill=*/true,
1848 UpdateValueMap(I, ResultReg);
1852 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1853 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1856 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1857 X86AddressMode SrcAM, uint64_t Len) {
1859 // Make sure we don't bloat code by inlining very large memcpy's.
1860 if (!IsMemcpySmall(Len))
1863 bool i64Legal = Subtarget->is64Bit();
1865 // We don't care about alignment here since we just emit integer accesses.
1868 if (Len >= 8 && i64Legal)
1879 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
1880 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
1881 assert(RV && "Failed to emit load or store??");
1883 unsigned Size = VT.getSizeInBits()/8;
1885 DestAM.Disp += Size;
1892 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
1893 switch (I.getIntrinsicID()) {
1894 case Intrinsic::sadd_with_overflow:
1895 case Intrinsic::uadd_with_overflow:
1896 case Intrinsic::smul_with_overflow:
1897 case Intrinsic::umul_with_overflow:
1904 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1905 // FIXME: Handle more intrinsics.
1906 switch (I.getIntrinsicID()) {
1907 default: return false;
1908 case Intrinsic::frameaddress: {
1909 Type *RetTy = I.getCalledFunction()->getReturnType();
1912 if (!isTypeLegal(RetTy, VT))
1916 const TargetRegisterClass *RC = nullptr;
1918 switch (VT.SimpleTy) {
1919 default: llvm_unreachable("Invalid result type for frameaddress.");
1920 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
1921 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
1924 // This needs to be set before we call getFrameRegister, otherwise we get
1925 // the wrong frame register.
1926 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1927 MFI->setFrameAddressIsTaken(true);
1929 const X86RegisterInfo *RegInfo =
1930 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
1931 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
1932 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
1933 (FrameReg == X86::EBP && VT == MVT::i32)) &&
1934 "Invalid Frame Register!");
1936 // Always make a copy of the frame register to to a vreg first, so that we
1937 // never directly reference the frame register (the TwoAddressInstruction-
1938 // Pass doesn't like that).
1939 unsigned SrcReg = createResultReg(RC);
1940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1941 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
1943 // Now recursively load from the frame address.
1944 // movq (%rbp), %rax
1945 // movq (%rax), %rax
1946 // movq (%rax), %rax
1949 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
1951 DestReg = createResultReg(RC);
1952 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1953 TII.get(Opc), DestReg), SrcReg);
1957 UpdateValueMap(&I, SrcReg);
1960 case Intrinsic::memcpy: {
1961 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1962 // Don't handle volatile or variable length memcpys.
1963 if (MCI.isVolatile())
1966 if (isa<ConstantInt>(MCI.getLength())) {
1967 // Small memcpy's are common enough that we want to do them
1968 // without a call if possible.
1969 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1970 if (IsMemcpySmall(Len)) {
1971 X86AddressMode DestAM, SrcAM;
1972 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1973 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1975 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1980 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1981 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1984 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1987 return DoSelectCall(&I, "memcpy");
1989 case Intrinsic::memset: {
1990 const MemSetInst &MSI = cast<MemSetInst>(I);
1992 if (MSI.isVolatile())
1995 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1996 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1999 if (MSI.getDestAddressSpace() > 255)
2002 return DoSelectCall(&I, "memset");
2004 case Intrinsic::stackprotector: {
2005 // Emit code to store the stack guard onto the stack.
2006 EVT PtrTy = TLI.getPointerTy();
2008 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2009 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2011 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2013 // Grab the frame index.
2015 if (!X86SelectAddress(Slot, AM)) return false;
2016 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2019 case Intrinsic::dbg_declare: {
2020 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2022 assert(DI->getAddress() && "Null address should be checked earlier!");
2023 if (!X86SelectAddress(DI->getAddress(), AM))
2025 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2026 // FIXME may need to add RegState::Debug to any registers produced,
2027 // although ESP/EBP should be the only ones at the moment.
2028 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2029 addImm(0).addMetadata(DI->getVariable());
2032 case Intrinsic::trap: {
2033 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2036 case Intrinsic::sqrt: {
2037 if (!Subtarget->hasSSE1())
2040 Type *RetTy = I.getCalledFunction()->getReturnType();
2043 if (!isTypeLegal(RetTy, VT))
2046 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
2047 // is not generated by FastISel yet.
2048 // FIXME: Update this code once tablegen can handle it.
2049 static const unsigned SqrtOpc[2][2] = {
2050 {X86::SQRTSSr, X86::VSQRTSSr},
2051 {X86::SQRTSDr, X86::VSQRTSDr}
2053 bool HasAVX = Subtarget->hasAVX();
2055 const TargetRegisterClass *RC;
2056 switch (VT.SimpleTy) {
2057 default: return false;
2058 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2059 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2062 const Value *SrcVal = I.getArgOperand(0);
2063 unsigned SrcReg = getRegForValue(SrcVal);
2068 unsigned ImplicitDefReg = 0;
2070 ImplicitDefReg = createResultReg(RC);
2071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2072 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2075 unsigned ResultReg = createResultReg(RC);
2076 MachineInstrBuilder MIB;
2077 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2081 MIB.addReg(ImplicitDefReg);
2085 UpdateValueMap(&I, ResultReg);
2088 case Intrinsic::sadd_with_overflow:
2089 case Intrinsic::uadd_with_overflow:
2090 case Intrinsic::ssub_with_overflow:
2091 case Intrinsic::usub_with_overflow:
2092 case Intrinsic::smul_with_overflow:
2093 case Intrinsic::umul_with_overflow: {
2094 // This implements the basic lowering of the xalu with overflow intrinsics
2095 // into add/sub/mul folowed by either seto or setb.
2096 const Function *Callee = I.getCalledFunction();
2097 auto *Ty = cast<StructType>(Callee->getReturnType());
2098 Type *RetTy = Ty->getTypeAtIndex(0U);
2099 Type *CondTy = Ty->getTypeAtIndex(1);
2102 if (!isTypeLegal(RetTy, VT))
2105 if (VT < MVT::i8 || VT > MVT::i64)
2108 const Value *LHS = I.getArgOperand(0);
2109 const Value *RHS = I.getArgOperand(1);
2111 // Canonicalize immediates to the RHS.
2112 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2113 isCommutativeIntrinsic(I))
2114 std::swap(LHS, RHS);
2116 unsigned BaseOpc, CondOpc;
2117 switch (I.getIntrinsicID()) {
2118 default: llvm_unreachable("Unexpected intrinsic!");
2119 case Intrinsic::sadd_with_overflow:
2120 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2121 case Intrinsic::uadd_with_overflow:
2122 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2123 case Intrinsic::ssub_with_overflow:
2124 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2125 case Intrinsic::usub_with_overflow:
2126 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2127 case Intrinsic::smul_with_overflow:
2128 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2129 case Intrinsic::umul_with_overflow:
2130 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2133 unsigned LHSReg = getRegForValue(LHS);
2136 bool LHSIsKill = hasTrivialKill(LHS);
2138 unsigned ResultReg = 0;
2139 // Check if we have an immediate version.
2140 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2141 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2148 RHSReg = getRegForValue(RHS);
2151 RHSIsKill = hasTrivialKill(RHS);
2152 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2156 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2157 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2158 static const unsigned MULOpc[] =
2159 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2160 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2161 // First copy the first operand into RAX, which is an implicit input to
2162 // the X86::MUL*r instruction.
2163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2164 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2165 .addReg(LHSReg, getKillRegState(LHSIsKill));
2166 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2167 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2173 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2174 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2178 UpdateValueMap(&I, ResultReg, 2);
2181 case Intrinsic::x86_sse_cvttss2si:
2182 case Intrinsic::x86_sse_cvttss2si64:
2183 case Intrinsic::x86_sse2_cvttsd2si:
2184 case Intrinsic::x86_sse2_cvttsd2si64: {
2186 switch (I.getIntrinsicID()) {
2187 default: llvm_unreachable("Unexpected intrinsic.");
2188 case Intrinsic::x86_sse_cvttss2si:
2189 case Intrinsic::x86_sse_cvttss2si64:
2190 if (!Subtarget->hasSSE1())
2192 IsInputDouble = false;
2194 case Intrinsic::x86_sse2_cvttsd2si:
2195 case Intrinsic::x86_sse2_cvttsd2si64:
2196 if (!Subtarget->hasSSE2())
2198 IsInputDouble = true;
2202 Type *RetTy = I.getCalledFunction()->getReturnType();
2204 if (!isTypeLegal(RetTy, VT))
2207 static const unsigned CvtOpc[2][2][2] = {
2208 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2209 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2210 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2211 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2213 bool HasAVX = Subtarget->hasAVX();
2215 switch (VT.SimpleTy) {
2216 default: llvm_unreachable("Unexpected result type.");
2217 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2218 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2221 // Check if we can fold insertelement instructions into the convert.
2222 const Value *Op = I.getArgOperand(0);
2223 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2224 const Value *Index = IE->getOperand(2);
2225 if (!isa<ConstantInt>(Index))
2227 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2230 Op = IE->getOperand(1);
2233 Op = IE->getOperand(0);
2236 unsigned Reg = getRegForValue(Op);
2240 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2244 UpdateValueMap(&I, ResultReg);
2250 bool X86FastISel::FastLowerArguments() {
2251 if (!FuncInfo.CanLowerReturn)
2254 const Function *F = FuncInfo.Fn;
2258 CallingConv::ID CC = F->getCallingConv();
2259 if (CC != CallingConv::C)
2262 if (Subtarget->isCallingConvWin64(CC))
2265 if (!Subtarget->is64Bit())
2268 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2269 unsigned GPRCnt = 0;
2270 unsigned FPRCnt = 0;
2272 for (auto const &Arg : F->args()) {
2273 // The first argument is at index 1.
2275 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2276 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2277 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2278 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2281 Type *ArgTy = Arg.getType();
2282 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2285 EVT ArgVT = TLI.getValueType(ArgTy);
2286 if (!ArgVT.isSimple()) return false;
2287 switch (ArgVT.getSimpleVT().SimpleTy) {
2288 default: return false;
2295 if (!Subtarget->hasSSE1())
2308 static const MCPhysReg GPR32ArgRegs[] = {
2309 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2311 static const MCPhysReg GPR64ArgRegs[] = {
2312 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2314 static const MCPhysReg XMMArgRegs[] = {
2315 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2316 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2319 unsigned GPRIdx = 0;
2320 unsigned FPRIdx = 0;
2321 for (auto const &Arg : F->args()) {
2322 MVT VT = TLI.getSimpleValueType(Arg.getType());
2323 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2325 switch (VT.SimpleTy) {
2326 default: llvm_unreachable("Unexpected value type.");
2327 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2328 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2329 case MVT::f32: // fall-through
2330 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2332 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2333 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2334 // Without this, EmitLiveInCopies may eliminate the livein if its only
2335 // use is a bitcast (which isn't turned into an instruction).
2336 unsigned ResultReg = createResultReg(RC);
2337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2338 TII.get(TargetOpcode::COPY), ResultReg)
2339 .addReg(DstReg, getKillRegState(true));
2340 UpdateValueMap(&Arg, ResultReg);
2345 bool X86FastISel::X86SelectCall(const Instruction *I) {
2346 const CallInst *CI = cast<CallInst>(I);
2347 const Value *Callee = CI->getCalledValue();
2349 // Can't handle inline asm yet.
2350 if (isa<InlineAsm>(Callee))
2353 // Handle intrinsic calls.
2354 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2355 return X86VisitIntrinsicCall(*II);
2357 // Allow SelectionDAG isel to handle tail calls.
2358 if (cast<CallInst>(I)->isTailCall())
2361 return DoSelectCall(I, nullptr);
2364 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2365 const ImmutableCallSite &CS) {
2366 if (Subtarget.is64Bit())
2368 if (Subtarget.getTargetTriple().isOSMSVCRT())
2370 CallingConv::ID CC = CS.getCallingConv();
2371 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2373 if (!CS.paramHasAttr(1, Attribute::StructRet))
2375 if (CS.paramHasAttr(1, Attribute::InReg))
2380 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2381 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2382 const CallInst *CI = cast<CallInst>(I);
2383 const Value *Callee = CI->getCalledValue();
2385 // Handle only C and fastcc calling conventions for now.
2386 ImmutableCallSite CS(CI);
2387 CallingConv::ID CC = CS.getCallingConv();
2388 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2389 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2390 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2391 CC != CallingConv::X86_64_SysV)
2394 // fastcc with -tailcallopt is intended to provide a guaranteed
2395 // tail call optimization. Fastisel doesn't know how to do that.
2396 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2399 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2400 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2401 bool isVarArg = FTy->isVarArg();
2403 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2404 // x86-32. Special handling for x86-64 is implemented.
2405 if (isVarArg && isWin64)
2408 // Don't know about inalloca yet.
2409 if (CS.hasInAllocaArgument())
2412 // Fast-isel doesn't know about callee-pop yet.
2413 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2414 TM.Options.GuaranteedTailCallOpt))
2417 // Check whether the function can return without sret-demotion.
2418 SmallVector<ISD::OutputArg, 4> Outs;
2419 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2420 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2421 *FuncInfo.MF, FTy->isVarArg(),
2422 Outs, FTy->getContext());
2423 if (!CanLowerReturn)
2426 // Materialize callee address in a register. FIXME: GV address can be
2427 // handled with a CALLpcrel32 instead.
2428 X86AddressMode CalleeAM;
2429 if (!X86SelectCallAddress(Callee, CalleeAM))
2431 unsigned CalleeOp = 0;
2432 const GlobalValue *GV = nullptr;
2433 if (CalleeAM.GV != nullptr) {
2435 } else if (CalleeAM.Base.Reg != 0) {
2436 CalleeOp = CalleeAM.Base.Reg;
2440 // Deal with call operands first.
2441 SmallVector<const Value *, 8> ArgVals;
2442 SmallVector<unsigned, 8> Args;
2443 SmallVector<MVT, 8> ArgVTs;
2444 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2445 unsigned arg_size = CS.arg_size();
2446 Args.reserve(arg_size);
2447 ArgVals.reserve(arg_size);
2448 ArgVTs.reserve(arg_size);
2449 ArgFlags.reserve(arg_size);
2450 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2452 // If we're lowering a mem intrinsic instead of a regular call, skip the
2453 // last two arguments, which should not passed to the underlying functions.
2454 if (MemIntName && e-i <= 2)
2457 ISD::ArgFlagsTy Flags;
2458 unsigned AttrInd = i - CS.arg_begin() + 1;
2459 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2461 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2464 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2465 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2466 Type *ElementTy = Ty->getElementType();
2467 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2468 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2470 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2472 Flags.setByValSize(FrameSize);
2473 Flags.setByValAlign(FrameAlign);
2474 if (!IsMemcpySmall(FrameSize))
2478 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2480 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2483 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2484 // instruction. This is safe because it is common to all fastisel supported
2485 // calling conventions on x86.
2486 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2487 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2488 CI->getBitWidth() == 16) {
2490 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2492 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2498 // Passing bools around ends up doing a trunc to i1 and passing it.
2499 // Codegen this as an argument + "and 1".
2500 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2501 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2502 ArgVal->hasOneUse()) {
2503 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2504 ArgReg = getRegForValue(ArgVal);
2505 if (ArgReg == 0) return false;
2508 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2510 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2511 ArgVal->hasOneUse(), 1);
2513 ArgReg = getRegForValue(ArgVal);
2516 if (ArgReg == 0) return false;
2518 Type *ArgTy = ArgVal->getType();
2520 if (!isTypeLegal(ArgTy, ArgVT))
2522 if (ArgVT == MVT::x86mmx)
2524 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2525 Flags.setOrigAlign(OriginalAlignment);
2527 Args.push_back(ArgReg);
2528 ArgVals.push_back(ArgVal);
2529 ArgVTs.push_back(ArgVT);
2530 ArgFlags.push_back(Flags);
2533 // Analyze operands of the call, assigning locations to each operand.
2534 SmallVector<CCValAssign, 16> ArgLocs;
2535 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2536 I->getParent()->getContext());
2538 // Allocate shadow area for Win64
2540 CCInfo.AllocateStack(32, 8);
2542 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2544 // Get a count of how many bytes are to be pushed on the stack.
2545 unsigned NumBytes = CCInfo.getNextStackOffset();
2547 // Issue CALLSEQ_START
2548 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2549 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2552 // Process argument: walk the register/memloc assignments, inserting
2554 SmallVector<unsigned, 4> RegArgs;
2555 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2556 CCValAssign &VA = ArgLocs[i];
2557 unsigned Arg = Args[VA.getValNo()];
2558 EVT ArgVT = ArgVTs[VA.getValNo()];
2560 // Promote the value if needed.
2561 switch (VA.getLocInfo()) {
2562 case CCValAssign::Full: break;
2563 case CCValAssign::SExt: {
2564 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2565 "Unexpected extend");
2566 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2568 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2569 ArgVT = VA.getLocVT();
2572 case CCValAssign::ZExt: {
2573 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2574 "Unexpected extend");
2575 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2577 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2578 ArgVT = VA.getLocVT();
2581 case CCValAssign::AExt: {
2582 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2583 "Unexpected extend");
2584 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2587 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2590 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2593 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2594 ArgVT = VA.getLocVT();
2597 case CCValAssign::BCvt: {
2598 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2599 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2600 assert(BC != 0 && "Failed to emit a bitcast!");
2602 ArgVT = VA.getLocVT();
2605 case CCValAssign::VExt:
2606 // VExt has not been implemented, so this should be impossible to reach
2607 // for now. However, fallback to Selection DAG isel once implemented.
2609 case CCValAssign::Indirect:
2610 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2613 case CCValAssign::FPExt:
2614 llvm_unreachable("Unexpected loc info!");
2617 if (VA.isRegLoc()) {
2618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2619 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2620 RegArgs.push_back(VA.getLocReg());
2622 unsigned LocMemOffset = VA.getLocMemOffset();
2624 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2625 getTargetMachine()->getRegisterInfo());
2626 AM.Base.Reg = RegInfo->getStackRegister();
2627 AM.Disp = LocMemOffset;
2628 const Value *ArgVal = ArgVals[VA.getValNo()];
2629 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2631 if (Flags.isByVal()) {
2632 X86AddressMode SrcAM;
2633 SrcAM.Base.Reg = Arg;
2634 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2635 assert(Res && "memcpy length already checked!"); (void)Res;
2636 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2637 // If this is a really simple value, emit this with the Value* version
2638 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2639 // as it can cause us to reevaluate the argument.
2640 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2643 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2649 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2651 if (Subtarget->isPICStyleGOT()) {
2652 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2654 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2657 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2658 // Count the number of XMM registers allocated.
2659 static const MCPhysReg XMMArgRegs[] = {
2660 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2661 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2663 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2665 X86::AL).addImm(NumXMMRegs);
2669 MachineInstrBuilder MIB;
2671 // Register-indirect call.
2673 if (Subtarget->is64Bit())
2674 CallOpc = X86::CALL64r;
2676 CallOpc = X86::CALL32r;
2677 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2682 assert(GV && "Not a direct call");
2684 if (Subtarget->is64Bit())
2685 CallOpc = X86::CALL64pcrel32;
2687 CallOpc = X86::CALLpcrel32;
2689 // See if we need any target-specific flags on the GV operand.
2690 unsigned char OpFlags = 0;
2692 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2693 // external symbols most go through the PLT in PIC mode. If the symbol
2694 // has hidden or protected visibility, or if it is static or local, then
2695 // we don't need to use the PLT - we can directly call it.
2696 if (Subtarget->isTargetELF() &&
2697 TM.getRelocationModel() == Reloc::PIC_ &&
2698 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2699 OpFlags = X86II::MO_PLT;
2700 } else if (Subtarget->isPICStyleStubAny() &&
2701 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2702 (!Subtarget->getTargetTriple().isMacOSX() ||
2703 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2704 // PC-relative references to external symbols should go through $stub,
2705 // unless we're building with the leopard linker or later, which
2706 // automatically synthesizes these stubs.
2707 OpFlags = X86II::MO_DARWIN_STUB;
2711 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2713 MIB.addExternalSymbol(MemIntName, OpFlags);
2715 MIB.addGlobalAddress(GV, 0, OpFlags);
2718 // Add a register mask with the call-preserved registers.
2719 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2720 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2722 // Add an implicit use GOT pointer in EBX.
2723 if (Subtarget->isPICStyleGOT())
2724 MIB.addReg(X86::EBX, RegState::Implicit);
2726 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2727 MIB.addReg(X86::AL, RegState::Implicit);
2729 // Add implicit physical register uses to the call.
2730 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2731 MIB.addReg(RegArgs[i], RegState::Implicit);
2733 // Issue CALLSEQ_END
2734 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2735 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2737 .addImm(NumBytes).addImm(NumBytesCallee);
2739 // Build info for return calling conv lowering code.
2740 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2741 SmallVector<ISD::InputArg, 32> Ins;
2742 SmallVector<EVT, 4> RetTys;
2743 ComputeValueVTs(TLI, I->getType(), RetTys);
2744 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2746 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2747 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2748 for (unsigned j = 0; j != NumRegs; ++j) {
2749 ISD::InputArg MyFlags;
2750 MyFlags.VT = RegisterVT;
2751 MyFlags.Used = !CS.getInstruction()->use_empty();
2752 if (CS.paramHasAttr(0, Attribute::SExt))
2753 MyFlags.Flags.setSExt();
2754 if (CS.paramHasAttr(0, Attribute::ZExt))
2755 MyFlags.Flags.setZExt();
2756 if (CS.paramHasAttr(0, Attribute::InReg))
2757 MyFlags.Flags.setInReg();
2758 Ins.push_back(MyFlags);
2762 // Now handle call return values.
2763 SmallVector<unsigned, 4> UsedRegs;
2764 SmallVector<CCValAssign, 16> RVLocs;
2765 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2766 I->getParent()->getContext());
2767 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2768 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2769 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2770 EVT CopyVT = RVLocs[i].getValVT();
2771 unsigned CopyReg = ResultReg + i;
2773 // If this is a call to a function that returns an fp value on the x87 fp
2774 // stack, but where we prefer to use the value in xmm registers, copy it
2775 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2776 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2777 RVLocs[i].getLocReg() == X86::ST1)) {
2778 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2780 CopyReg = createResultReg(&X86::RFP80RegClass);
2782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2783 TII.get(X86::FpPOP_RETVAL), CopyReg);
2785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2786 TII.get(TargetOpcode::COPY),
2787 CopyReg).addReg(RVLocs[i].getLocReg());
2788 UsedRegs.push_back(RVLocs[i].getLocReg());
2791 if (CopyVT != RVLocs[i].getValVT()) {
2792 // Round the F80 the right size, which also moves to the appropriate xmm
2793 // register. This is accomplished by storing the F80 value in memory and
2794 // then loading it back. Ewww...
2795 EVT ResVT = RVLocs[i].getValVT();
2796 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2797 unsigned MemSize = ResVT.getSizeInBits()/8;
2798 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2799 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2802 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2803 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2804 TII.get(Opc), ResultReg + i), FI);
2809 UpdateValueMap(I, ResultReg, RVLocs.size());
2811 // Set all unused physreg defs as dead.
2812 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2819 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2820 switch (I->getOpcode()) {
2822 case Instruction::Load:
2823 return X86SelectLoad(I);
2824 case Instruction::Store:
2825 return X86SelectStore(I);
2826 case Instruction::Ret:
2827 return X86SelectRet(I);
2828 case Instruction::ICmp:
2829 case Instruction::FCmp:
2830 return X86SelectCmp(I);
2831 case Instruction::ZExt:
2832 return X86SelectZExt(I);
2833 case Instruction::Br:
2834 return X86SelectBranch(I);
2835 case Instruction::Call:
2836 return X86SelectCall(I);
2837 case Instruction::LShr:
2838 case Instruction::AShr:
2839 case Instruction::Shl:
2840 return X86SelectShift(I);
2841 case Instruction::SDiv:
2842 case Instruction::UDiv:
2843 case Instruction::SRem:
2844 case Instruction::URem:
2845 return X86SelectDivRem(I);
2846 case Instruction::Select:
2847 return X86SelectSelect(I);
2848 case Instruction::Trunc:
2849 return X86SelectTrunc(I);
2850 case Instruction::FPExt:
2851 return X86SelectFPExt(I);
2852 case Instruction::FPTrunc:
2853 return X86SelectFPTrunc(I);
2854 case Instruction::IntToPtr: // Deliberate fall-through.
2855 case Instruction::PtrToInt: {
2856 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2857 EVT DstVT = TLI.getValueType(I->getType());
2858 if (DstVT.bitsGT(SrcVT))
2859 return X86SelectZExt(I);
2860 if (DstVT.bitsLT(SrcVT))
2861 return X86SelectTrunc(I);
2862 unsigned Reg = getRegForValue(I->getOperand(0));
2863 if (Reg == 0) return false;
2864 UpdateValueMap(I, Reg);
2872 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2874 if (!isTypeLegal(C->getType(), VT))
2877 // Can't handle alternate code models yet.
2878 if (TM.getCodeModel() != CodeModel::Small)
2881 // Get opcode and regclass of the output for the given load instruction.
2883 const TargetRegisterClass *RC = nullptr;
2884 switch (VT.SimpleTy) {
2888 RC = &X86::GR8RegClass;
2892 RC = &X86::GR16RegClass;
2896 RC = &X86::GR32RegClass;
2899 // Must be in x86-64 mode.
2901 RC = &X86::GR64RegClass;
2904 if (X86ScalarSSEf32) {
2905 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2906 RC = &X86::FR32RegClass;
2908 Opc = X86::LD_Fp32m;
2909 RC = &X86::RFP32RegClass;
2913 if (X86ScalarSSEf64) {
2914 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2915 RC = &X86::FR64RegClass;
2917 Opc = X86::LD_Fp64m;
2918 RC = &X86::RFP64RegClass;
2922 // No f80 support yet.
2926 // Materialize addresses with LEA/MOV instructions.
2927 if (isa<GlobalValue>(C)) {
2929 if (X86SelectAddress(C, AM)) {
2930 // If the expression is just a basereg, then we're done, otherwise we need
2932 if (AM.BaseType == X86AddressMode::RegBase &&
2933 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
2936 unsigned ResultReg = createResultReg(RC);
2937 if (TM.getRelocationModel() == Reloc::Static &&
2938 TLI.getPointerTy() == MVT::i64) {
2939 // The displacement code be more than 32 bits away so we need to use
2940 // an instruction with a 64 bit immediate
2942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2943 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
2945 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2946 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2947 TII.get(Opc), ResultReg), AM);
2954 // MachineConstantPool wants an explicit alignment.
2955 unsigned Align = DL.getPrefTypeAlignment(C->getType());
2957 // Alignment of vector types. FIXME!
2958 Align = DL.getTypeAllocSize(C->getType());
2961 // x86-32 PIC requires a PIC base register for constant pools.
2962 unsigned PICBase = 0;
2963 unsigned char OpFlag = 0;
2964 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2965 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2966 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2967 } else if (Subtarget->isPICStyleGOT()) {
2968 OpFlag = X86II::MO_GOTOFF;
2969 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2970 } else if (Subtarget->isPICStyleRIPRel() &&
2971 TM.getCodeModel() == CodeModel::Small) {
2975 // Create the load from the constant pool.
2976 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2977 unsigned ResultReg = createResultReg(RC);
2978 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2979 TII.get(Opc), ResultReg),
2980 MCPOffset, PICBase, OpFlag);
2985 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2986 // Fail on dynamic allocas. At this point, getRegForValue has already
2987 // checked its CSE maps, so if we're here trying to handle a dynamic
2988 // alloca, we're not going to succeed. X86SelectAddress has a
2989 // check for dynamic allocas, because it's called directly from
2990 // various places, but TargetMaterializeAlloca also needs a check
2991 // in order to avoid recursion between getRegForValue,
2992 // X86SelectAddrss, and TargetMaterializeAlloca.
2993 if (!FuncInfo.StaticAllocaMap.count(C))
2995 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2998 if (!X86SelectAddress(C, AM))
3000 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3001 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3002 unsigned ResultReg = createResultReg(RC);
3003 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3004 TII.get(Opc), ResultReg), AM);
3008 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3010 if (!isTypeLegal(CF->getType(), VT))
3013 // Get opcode and regclass for the given zero.
3015 const TargetRegisterClass *RC = nullptr;
3016 switch (VT.SimpleTy) {
3019 if (X86ScalarSSEf32) {
3020 Opc = X86::FsFLD0SS;
3021 RC = &X86::FR32RegClass;
3023 Opc = X86::LD_Fp032;
3024 RC = &X86::RFP32RegClass;
3028 if (X86ScalarSSEf64) {
3029 Opc = X86::FsFLD0SD;
3030 RC = &X86::FR64RegClass;
3032 Opc = X86::LD_Fp064;
3033 RC = &X86::RFP64RegClass;
3037 // No f80 support yet.
3041 unsigned ResultReg = createResultReg(RC);
3042 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3047 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3048 const LoadInst *LI) {
3049 const Value *Ptr = LI->getPointerOperand();
3051 if (!X86SelectAddress(Ptr, AM))
3054 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3056 unsigned Size = DL.getTypeAllocSize(LI->getType());
3057 unsigned Alignment = LI->getAlignment();
3059 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3060 Alignment = DL.getABITypeAlignment(LI->getType());
3062 SmallVector<MachineOperand, 8> AddrOps;
3063 AM.getFullAddress(AddrOps);
3065 MachineInstr *Result =
3066 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3070 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3071 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3072 MI->eraseFromParent();
3078 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3079 const TargetLibraryInfo *libInfo) {
3080 return new X86FastISel(funcInfo, libInfo);