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 X86FastEmitSSESelect(const Instruction *I);
118 bool X86SelectSelect(const Instruction *I);
120 bool X86SelectTrunc(const Instruction *I);
122 bool X86SelectFPExt(const Instruction *I);
123 bool X86SelectFPTrunc(const Instruction *I);
125 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
126 bool X86SelectCall(const Instruction *I);
128 bool DoSelectCall(const Instruction *I, const char *MemIntName);
130 const X86InstrInfo *getInstrInfo() const {
131 return getTargetMachine()->getInstrInfo();
133 const X86TargetMachine *getTargetMachine() const {
134 return static_cast<const X86TargetMachine *>(&TM);
137 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
139 unsigned TargetMaterializeConstant(const Constant *C) override;
141 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
143 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
145 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
146 /// computed in an SSE register, not on the X87 floating point stack.
147 bool isScalarFPTypeInSSEReg(EVT VT) const {
148 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
149 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
152 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
154 bool IsMemcpySmall(uint64_t Len);
156 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
157 X86AddressMode SrcAM, uint64_t Len);
160 } // end anonymous namespace.
162 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
163 // If both operands are the same, then try to optimize or fold the cmp.
164 CmpInst::Predicate Predicate = CI->getPredicate();
165 if (CI->getOperand(0) != CI->getOperand(1))
169 default: llvm_unreachable("Invalid predicate!");
170 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
171 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
172 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
173 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
174 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
175 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
176 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
177 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
178 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
179 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
180 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
181 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
182 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
183 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
184 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
185 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
187 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
188 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
189 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
190 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
191 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
192 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
194 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
195 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
196 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
202 static std::pair<X86::CondCode, bool>
203 getX86ConditonCode(CmpInst::Predicate Predicate) {
204 X86::CondCode CC = X86::COND_INVALID;
205 bool NeedSwap = false;
208 // Floating-point Predicates
209 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
210 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
211 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
212 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
213 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
214 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
215 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
216 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
217 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
218 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
219 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
220 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
221 case CmpInst::FCMP_OEQ: // fall-through
222 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
224 // Integer Predicates
225 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
226 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
227 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
228 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
229 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
230 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
231 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
232 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
233 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
234 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
237 return std::make_pair(CC, NeedSwap);
240 static std::pair<unsigned, bool>
241 getX86SSECondtionCode(CmpInst::Predicate Predicate) {
243 bool NeedSwap = false;
245 // SSE Condition code mapping:
255 default: llvm_unreachable("Unexpected predicate");
256 case CmpInst::FCMP_OEQ: CC = 0; break;
257 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
258 case CmpInst::FCMP_OLT: CC = 1; break;
259 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
260 case CmpInst::FCMP_OLE: CC = 2; break;
261 case CmpInst::FCMP_UNO: CC = 3; break;
262 case CmpInst::FCMP_UNE: CC = 4; break;
263 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
264 case CmpInst::FCMP_UGE: CC = 5; break;
265 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
266 case CmpInst::FCMP_UGT: CC = 6; break;
267 case CmpInst::FCMP_ORD: CC = 7; break;
268 case CmpInst::FCMP_UEQ:
269 case CmpInst::FCMP_ONE: CC = 8; break;
272 return std::make_pair(CC, NeedSwap);
275 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
276 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
277 if (evt == MVT::Other || !evt.isSimple())
278 // Unhandled type. Halt "fast" selection and bail.
281 VT = evt.getSimpleVT();
282 // For now, require SSE/SSE2 for performing floating-point operations,
283 // since x87 requires additional work.
284 if (VT == MVT::f64 && !X86ScalarSSEf64)
286 if (VT == MVT::f32 && !X86ScalarSSEf32)
288 // Similarly, no f80 support yet.
291 // We only handle legal types. For example, on x86-32 the instruction
292 // selector contains all of the 64-bit instructions from x86-64,
293 // under the assumption that i64 won't be used if the target doesn't
295 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
298 #include "X86GenCallingConv.inc"
300 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
301 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
302 /// Return true and the result register by reference if it is possible.
303 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
304 MachineMemOperand *MMO, unsigned &ResultReg) {
305 // Get opcode and regclass of the output for the given load instruction.
307 const TargetRegisterClass *RC = nullptr;
308 switch (VT.getSimpleVT().SimpleTy) {
309 default: return false;
313 RC = &X86::GR8RegClass;
317 RC = &X86::GR16RegClass;
321 RC = &X86::GR32RegClass;
324 // Must be in x86-64 mode.
326 RC = &X86::GR64RegClass;
329 if (X86ScalarSSEf32) {
330 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
331 RC = &X86::FR32RegClass;
334 RC = &X86::RFP32RegClass;
338 if (X86ScalarSSEf64) {
339 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
340 RC = &X86::FR64RegClass;
343 RC = &X86::RFP64RegClass;
347 // No f80 support yet.
351 ResultReg = createResultReg(RC);
352 MachineInstrBuilder MIB =
353 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
354 addFullAddress(MIB, AM);
356 MIB->addMemOperand(*FuncInfo.MF, MMO);
360 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
361 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
362 /// and a displacement offset, or a GlobalAddress,
363 /// i.e. V. Return true if it is possible.
364 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
365 const X86AddressMode &AM,
366 MachineMemOperand *MMO, bool Aligned) {
367 // Get opcode and regclass of the output for the given store instruction.
369 switch (VT.getSimpleVT().SimpleTy) {
370 case MVT::f80: // No f80 support yet.
371 default: return false;
373 // Mask out all but lowest bit.
374 unsigned AndResult = createResultReg(&X86::GR8RegClass);
375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
376 TII.get(X86::AND8ri), AndResult)
377 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
380 // FALLTHROUGH, handling i1 as i8.
381 case MVT::i8: Opc = X86::MOV8mr; break;
382 case MVT::i16: Opc = X86::MOV16mr; break;
383 case MVT::i32: Opc = X86::MOV32mr; break;
384 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
386 Opc = X86ScalarSSEf32 ?
387 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
390 Opc = X86ScalarSSEf64 ?
391 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
395 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
397 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
401 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
403 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
410 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
412 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
416 MachineInstrBuilder MIB =
417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
418 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
420 MIB->addMemOperand(*FuncInfo.MF, MMO);
425 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
426 const X86AddressMode &AM,
427 MachineMemOperand *MMO, bool Aligned) {
428 // Handle 'null' like i32/i64 0.
429 if (isa<ConstantPointerNull>(Val))
430 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
432 // If this is a store of a simple constant, fold the constant into the store.
433 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
436 switch (VT.getSimpleVT().SimpleTy) {
438 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
439 case MVT::i8: Opc = X86::MOV8mi; break;
440 case MVT::i16: Opc = X86::MOV16mi; break;
441 case MVT::i32: Opc = X86::MOV32mi; break;
443 // Must be a 32-bit sign extended value.
444 if (isInt<32>(CI->getSExtValue()))
445 Opc = X86::MOV64mi32;
450 MachineInstrBuilder MIB =
451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
452 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
453 : CI->getZExtValue());
455 MIB->addMemOperand(*FuncInfo.MF, MMO);
460 unsigned ValReg = getRegForValue(Val);
464 bool ValKill = hasTrivialKill(Val);
465 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
468 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
469 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
470 /// ISD::SIGN_EXTEND).
471 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
472 unsigned Src, EVT SrcVT,
473 unsigned &ResultReg) {
474 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
475 Src, /*TODO: Kill=*/false);
483 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
484 // Handle constant address.
485 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
486 // Can't handle alternate code models yet.
487 if (TM.getCodeModel() != CodeModel::Small)
490 // Can't handle TLS yet.
491 if (GV->isThreadLocal())
494 // RIP-relative addresses can't have additional register operands, so if
495 // we've already folded stuff into the addressing mode, just force the
496 // global value into its own register, which we can use as the basereg.
497 if (!Subtarget->isPICStyleRIPRel() ||
498 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
499 // Okay, we've committed to selecting this global. Set up the address.
502 // Allow the subtarget to classify the global.
503 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
505 // If this reference is relative to the pic base, set it now.
506 if (isGlobalRelativeToPICBase(GVFlags)) {
507 // FIXME: How do we know Base.Reg is free??
508 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
511 // Unless the ABI requires an extra load, return a direct reference to
513 if (!isGlobalStubReference(GVFlags)) {
514 if (Subtarget->isPICStyleRIPRel()) {
515 // Use rip-relative addressing if we can. Above we verified that the
516 // base and index registers are unused.
517 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
518 AM.Base.Reg = X86::RIP;
520 AM.GVOpFlags = GVFlags;
524 // Ok, we need to do a load from a stub. If we've already loaded from
525 // this stub, reuse the loaded pointer, otherwise emit the load now.
526 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
528 if (I != LocalValueMap.end() && I->second != 0) {
531 // Issue load from stub.
533 const TargetRegisterClass *RC = nullptr;
534 X86AddressMode StubAM;
535 StubAM.Base.Reg = AM.Base.Reg;
537 StubAM.GVOpFlags = GVFlags;
539 // Prepare for inserting code in the local-value area.
540 SavePoint SaveInsertPt = enterLocalValueArea();
542 if (TLI.getPointerTy() == MVT::i64) {
544 RC = &X86::GR64RegClass;
546 if (Subtarget->isPICStyleRIPRel())
547 StubAM.Base.Reg = X86::RIP;
550 RC = &X86::GR32RegClass;
553 LoadReg = createResultReg(RC);
554 MachineInstrBuilder LoadMI =
555 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
556 addFullAddress(LoadMI, StubAM);
558 // Ok, back to normal mode.
559 leaveLocalValueArea(SaveInsertPt);
561 // Prevent loading GV stub multiple times in same MBB.
562 LocalValueMap[V] = LoadReg;
565 // Now construct the final address. Note that the Disp, Scale,
566 // and Index values may already be set here.
567 AM.Base.Reg = LoadReg;
573 // If all else fails, try to materialize the value in a register.
574 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
575 if (AM.Base.Reg == 0) {
576 AM.Base.Reg = getRegForValue(V);
577 return AM.Base.Reg != 0;
579 if (AM.IndexReg == 0) {
580 assert(AM.Scale == 1 && "Scale with no index!");
581 AM.IndexReg = getRegForValue(V);
582 return AM.IndexReg != 0;
589 /// X86SelectAddress - Attempt to fill in an address from the given value.
591 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
592 SmallVector<const Value *, 32> GEPs;
594 const User *U = nullptr;
595 unsigned Opcode = Instruction::UserOp1;
596 if (const Instruction *I = dyn_cast<Instruction>(V)) {
597 // Don't walk into other basic blocks; it's possible we haven't
598 // visited them yet, so the instructions may not yet be assigned
599 // virtual registers.
600 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
601 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
602 Opcode = I->getOpcode();
605 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
606 Opcode = C->getOpcode();
610 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
611 if (Ty->getAddressSpace() > 255)
612 // Fast instruction selection doesn't support the special
618 case Instruction::BitCast:
619 // Look past bitcasts.
620 return X86SelectAddress(U->getOperand(0), AM);
622 case Instruction::IntToPtr:
623 // Look past no-op inttoptrs.
624 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
625 return X86SelectAddress(U->getOperand(0), AM);
628 case Instruction::PtrToInt:
629 // Look past no-op ptrtoints.
630 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
631 return X86SelectAddress(U->getOperand(0), AM);
634 case Instruction::Alloca: {
635 // Do static allocas.
636 const AllocaInst *A = cast<AllocaInst>(V);
637 DenseMap<const AllocaInst*, int>::iterator SI =
638 FuncInfo.StaticAllocaMap.find(A);
639 if (SI != FuncInfo.StaticAllocaMap.end()) {
640 AM.BaseType = X86AddressMode::FrameIndexBase;
641 AM.Base.FrameIndex = SI->second;
647 case Instruction::Add: {
648 // Adds of constants are common and easy enough.
649 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
650 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
651 // They have to fit in the 32-bit signed displacement field though.
652 if (isInt<32>(Disp)) {
653 AM.Disp = (uint32_t)Disp;
654 return X86SelectAddress(U->getOperand(0), AM);
660 case Instruction::GetElementPtr: {
661 X86AddressMode SavedAM = AM;
663 // Pattern-match simple GEPs.
664 uint64_t Disp = (int32_t)AM.Disp;
665 unsigned IndexReg = AM.IndexReg;
666 unsigned Scale = AM.Scale;
667 gep_type_iterator GTI = gep_type_begin(U);
668 // Iterate through the indices, folding what we can. Constants can be
669 // folded, and one dynamic index can be handled, if the scale is supported.
670 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
671 i != e; ++i, ++GTI) {
672 const Value *Op = *i;
673 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
674 const StructLayout *SL = DL.getStructLayout(STy);
675 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
679 // A array/variable index is always of the form i*S where S is the
680 // constant scale size. See if we can push the scale into immediates.
681 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
683 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
684 // Constant-offset addressing.
685 Disp += CI->getSExtValue() * S;
688 if (canFoldAddIntoGEP(U, Op)) {
689 // A compatible add with a constant operand. Fold the constant.
691 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
692 Disp += CI->getSExtValue() * S;
693 // Iterate on the other operand.
694 Op = cast<AddOperator>(Op)->getOperand(0);
698 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
699 (S == 1 || S == 2 || S == 4 || S == 8)) {
700 // Scaled-index addressing.
702 IndexReg = getRegForGEPIndex(Op).first;
708 goto unsupported_gep;
712 // Check for displacement overflow.
713 if (!isInt<32>(Disp))
716 AM.IndexReg = IndexReg;
718 AM.Disp = (uint32_t)Disp;
721 if (const GetElementPtrInst *GEP =
722 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
723 // Ok, the GEP indices were covered by constant-offset and scaled-index
724 // addressing. Update the address state and move on to examining the base.
727 } else if (X86SelectAddress(U->getOperand(0), AM)) {
731 // If we couldn't merge the gep value into this addr mode, revert back to
732 // our address and just match the value instead of completely failing.
735 for (SmallVectorImpl<const Value *>::reverse_iterator
736 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
737 if (handleConstantAddresses(*I, AM))
742 // Ok, the GEP indices weren't all covered.
747 return handleConstantAddresses(V, AM);
750 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
752 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
753 const User *U = nullptr;
754 unsigned Opcode = Instruction::UserOp1;
755 const Instruction *I = dyn_cast<Instruction>(V);
756 // Record if the value is defined in the same basic block.
758 // This information is crucial to know whether or not folding an
760 // Indeed, FastISel generates or reuses a virtual register for all
761 // operands of all instructions it selects. Obviously, the definition and
762 // its uses must use the same virtual register otherwise the produced
763 // code is incorrect.
764 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
765 // registers for values that are alive across basic blocks. This ensures
766 // that the values are consistently set between across basic block, even
767 // if different instruction selection mechanisms are used (e.g., a mix of
768 // SDISel and FastISel).
769 // For values local to a basic block, the instruction selection process
770 // generates these virtual registers with whatever method is appropriate
771 // for its needs. In particular, FastISel and SDISel do not share the way
772 // local virtual registers are set.
773 // Therefore, this is impossible (or at least unsafe) to share values
774 // between basic blocks unless they use the same instruction selection
775 // method, which is not guarantee for X86.
776 // Moreover, things like hasOneUse could not be used accurately, if we
777 // allow to reference values across basic blocks whereas they are not
778 // alive across basic blocks initially.
781 Opcode = I->getOpcode();
783 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
784 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
785 Opcode = C->getOpcode();
791 case Instruction::BitCast:
792 // Look past bitcasts if its operand is in the same BB.
794 return X86SelectCallAddress(U->getOperand(0), AM);
797 case Instruction::IntToPtr:
798 // Look past no-op inttoptrs if its operand is in the same BB.
800 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
801 return X86SelectCallAddress(U->getOperand(0), AM);
804 case Instruction::PtrToInt:
805 // Look past no-op ptrtoints if its operand is in the same BB.
807 TLI.getValueType(U->getType()) == TLI.getPointerTy())
808 return X86SelectCallAddress(U->getOperand(0), AM);
812 // Handle constant address.
813 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
814 // Can't handle alternate code models yet.
815 if (TM.getCodeModel() != CodeModel::Small)
818 // RIP-relative addresses can't have additional register operands.
819 if (Subtarget->isPICStyleRIPRel() &&
820 (AM.Base.Reg != 0 || AM.IndexReg != 0))
823 // Can't handle DbgLocLImport.
824 if (GV->hasDLLImportStorageClass())
828 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
829 if (GVar->isThreadLocal())
832 // Okay, we've committed to selecting this global. Set up the basic address.
835 // No ABI requires an extra load for anything other than DLLImport, which
836 // we rejected above. Return a direct reference to the global.
837 if (Subtarget->isPICStyleRIPRel()) {
838 // Use rip-relative addressing if we can. Above we verified that the
839 // base and index registers are unused.
840 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
841 AM.Base.Reg = X86::RIP;
842 } else if (Subtarget->isPICStyleStubPIC()) {
843 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
844 } else if (Subtarget->isPICStyleGOT()) {
845 AM.GVOpFlags = X86II::MO_GOTOFF;
851 // If all else fails, try to materialize the value in a register.
852 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
853 if (AM.Base.Reg == 0) {
854 AM.Base.Reg = getRegForValue(V);
855 return AM.Base.Reg != 0;
857 if (AM.IndexReg == 0) {
858 assert(AM.Scale == 1 && "Scale with no index!");
859 AM.IndexReg = getRegForValue(V);
860 return AM.IndexReg != 0;
868 /// X86SelectStore - Select and emit code to implement store instructions.
869 bool X86FastISel::X86SelectStore(const Instruction *I) {
870 // Atomic stores need special handling.
871 const StoreInst *S = cast<StoreInst>(I);
876 const Value *Val = S->getValueOperand();
877 const Value *Ptr = S->getPointerOperand();
880 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
883 unsigned Alignment = S->getAlignment();
884 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
885 if (Alignment == 0) // Ensure that codegen never sees alignment 0
886 Alignment = ABIAlignment;
887 bool Aligned = Alignment >= ABIAlignment;
890 if (!X86SelectAddress(Ptr, AM))
893 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
896 /// X86SelectRet - Select and emit code to implement ret instructions.
897 bool X86FastISel::X86SelectRet(const Instruction *I) {
898 const ReturnInst *Ret = cast<ReturnInst>(I);
899 const Function &F = *I->getParent()->getParent();
900 const X86MachineFunctionInfo *X86MFInfo =
901 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
903 if (!FuncInfo.CanLowerReturn)
906 CallingConv::ID CC = F.getCallingConv();
907 if (CC != CallingConv::C &&
908 CC != CallingConv::Fast &&
909 CC != CallingConv::X86_FastCall &&
910 CC != CallingConv::X86_64_SysV)
913 if (Subtarget->isCallingConvWin64(CC))
916 // Don't handle popping bytes on return for now.
917 if (X86MFInfo->getBytesToPopOnReturn() != 0)
920 // fastcc with -tailcallopt is intended to provide a guaranteed
921 // tail call optimization. Fastisel doesn't know how to do that.
922 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
925 // Let SDISel handle vararg functions.
929 // Build a list of return value registers.
930 SmallVector<unsigned, 4> RetRegs;
932 if (Ret->getNumOperands() > 0) {
933 SmallVector<ISD::OutputArg, 4> Outs;
934 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
936 // Analyze operands of the call, assigning locations to each operand.
937 SmallVector<CCValAssign, 16> ValLocs;
938 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
940 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
942 const Value *RV = Ret->getOperand(0);
943 unsigned Reg = getRegForValue(RV);
947 // Only handle a single return value for now.
948 if (ValLocs.size() != 1)
951 CCValAssign &VA = ValLocs[0];
953 // Don't bother handling odd stuff for now.
954 if (VA.getLocInfo() != CCValAssign::Full)
956 // Only handle register returns for now.
960 // The calling-convention tables for x87 returns don't tell
962 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
965 unsigned SrcReg = Reg + VA.getValNo();
966 EVT SrcVT = TLI.getValueType(RV->getType());
967 EVT DstVT = VA.getValVT();
968 // Special handling for extended integers.
969 if (SrcVT != DstVT) {
970 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
973 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
976 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
978 if (SrcVT == MVT::i1) {
979 if (Outs[0].Flags.isSExt())
981 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
984 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
986 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
987 SrcReg, /*TODO: Kill=*/false);
991 unsigned DstReg = VA.getLocReg();
992 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
993 // Avoid a cross-class copy. This is very unlikely.
994 if (!SrcRC->contains(DstReg))
996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
997 DstReg).addReg(SrcReg);
999 // Add register to return instruction.
1000 RetRegs.push_back(VA.getLocReg());
1003 // The x86-64 ABI for returning structs by value requires that we copy
1004 // the sret argument into %rax for the return. We saved the argument into
1005 // a virtual register in the entry block, so now we copy the value out
1006 // and into %rax. We also do the same with %eax for Win32.
1007 if (F.hasStructRetAttr() &&
1008 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1009 unsigned Reg = X86MFInfo->getSRetReturnReg();
1011 "SRetReturnReg should have been set in LowerFormalArguments()!");
1012 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1014 RetReg).addReg(Reg);
1015 RetRegs.push_back(RetReg);
1018 // Now emit the RET.
1019 MachineInstrBuilder MIB =
1020 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1021 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1022 MIB.addReg(RetRegs[i], RegState::Implicit);
1026 /// X86SelectLoad - Select and emit code to implement load instructions.
1028 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1029 const LoadInst *LI = cast<LoadInst>(I);
1031 // Atomic loads need special handling.
1036 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1039 const Value *Ptr = LI->getPointerOperand();
1042 if (!X86SelectAddress(Ptr, AM))
1045 unsigned ResultReg = 0;
1046 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1049 UpdateValueMap(I, ResultReg);
1053 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1054 bool HasAVX = Subtarget->hasAVX();
1055 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1056 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1058 switch (VT.getSimpleVT().SimpleTy) {
1060 case MVT::i8: return X86::CMP8rr;
1061 case MVT::i16: return X86::CMP16rr;
1062 case MVT::i32: return X86::CMP32rr;
1063 case MVT::i64: return X86::CMP64rr;
1065 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1067 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1071 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1072 /// of the comparison, return an opcode that works for the compare (e.g.
1073 /// CMP32ri) otherwise return 0.
1074 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1075 switch (VT.getSimpleVT().SimpleTy) {
1076 // Otherwise, we can't fold the immediate into this comparison.
1078 case MVT::i8: return X86::CMP8ri;
1079 case MVT::i16: return X86::CMP16ri;
1080 case MVT::i32: return X86::CMP32ri;
1082 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1084 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1085 return X86::CMP64ri32;
1090 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1092 unsigned Op0Reg = getRegForValue(Op0);
1093 if (Op0Reg == 0) return false;
1095 // Handle 'null' like i32/i64 0.
1096 if (isa<ConstantPointerNull>(Op1))
1097 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1099 // We have two options: compare with register or immediate. If the RHS of
1100 // the compare is an immediate that we can fold into this compare, use
1101 // CMPri, otherwise use CMPrr.
1102 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1103 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1106 .addImm(Op1C->getSExtValue());
1111 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1112 if (CompareOpc == 0) return false;
1114 unsigned Op1Reg = getRegForValue(Op1);
1115 if (Op1Reg == 0) return false;
1116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1123 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1124 const CmpInst *CI = cast<CmpInst>(I);
1127 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1130 // Try to optimize or fold the cmp.
1131 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1132 unsigned ResultReg = 0;
1133 switch (Predicate) {
1135 case CmpInst::FCMP_FALSE: {
1136 ResultReg = createResultReg(&X86::GR32RegClass);
1137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1139 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1145 case CmpInst::FCMP_TRUE: {
1146 ResultReg = createResultReg(&X86::GR8RegClass);
1147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1148 ResultReg).addImm(1);
1154 UpdateValueMap(I, ResultReg);
1158 const Value *LHS = CI->getOperand(0);
1159 const Value *RHS = CI->getOperand(1);
1161 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1162 // We don't have to materialize a zero constant for this case and can just use
1163 // %x again on the RHS.
1164 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1165 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1166 if (RHSC && RHSC->isNullValue())
1170 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1171 static unsigned SETFOpcTable[2][3] = {
1172 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1173 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1175 unsigned *SETFOpc = nullptr;
1176 switch (Predicate) {
1178 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1179 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1182 ResultReg = createResultReg(&X86::GR8RegClass);
1184 if (!X86FastEmitCompare(LHS, RHS, VT))
1187 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1188 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1191 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1193 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1194 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1195 UpdateValueMap(I, ResultReg);
1201 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1202 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1203 unsigned Opc = X86::getSETFromCond(CC);
1206 std::swap(LHS, RHS);
1208 // Emit a compare of LHS/RHS.
1209 if (!X86FastEmitCompare(LHS, RHS, VT))
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1213 UpdateValueMap(I, ResultReg);
1217 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1218 EVT DstVT = TLI.getValueType(I->getType());
1219 if (!TLI.isTypeLegal(DstVT))
1222 unsigned ResultReg = getRegForValue(I->getOperand(0));
1226 // Handle zero-extension from i1 to i8, which is common.
1227 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1228 if (SrcVT.SimpleTy == MVT::i1) {
1229 // Set the high bits to zero.
1230 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1237 if (DstVT == MVT::i64) {
1238 // Handle extension to 64-bits via sub-register shenanigans.
1241 switch (SrcVT.SimpleTy) {
1242 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1243 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1244 case MVT::i32: MovInst = X86::MOV32rr; break;
1245 default: llvm_unreachable("Unexpected zext to i64 source type");
1248 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1252 ResultReg = createResultReg(&X86::GR64RegClass);
1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1255 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1256 } else if (DstVT != MVT::i8) {
1257 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1258 ResultReg, /*Kill=*/true);
1263 UpdateValueMap(I, ResultReg);
1268 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1269 // Unconditional branches are selected by tablegen-generated code.
1270 // Handle a conditional branch.
1271 const BranchInst *BI = cast<BranchInst>(I);
1272 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1273 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1275 // Fold the common case of a conditional branch with a comparison
1276 // in the same block (values defined on other blocks may not have
1277 // initialized registers).
1278 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1279 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1280 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1282 // Try to optimize or fold the cmp.
1283 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1284 switch (Predicate) {
1286 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1287 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1290 const Value *CmpLHS = CI->getOperand(0);
1291 const Value *CmpRHS = CI->getOperand(1);
1293 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1295 // We don't have to materialize a zero constant for this case and can just
1296 // use %x again on the RHS.
1297 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1298 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1299 if (CmpRHSC && CmpRHSC->isNullValue())
1303 // Try to take advantage of fallthrough opportunities.
1304 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1305 std::swap(TrueMBB, FalseMBB);
1306 Predicate = CmpInst::getInversePredicate(Predicate);
1309 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1310 // code check. Instead two branch instructions are required to check all
1311 // the flags. First we change the predicate to a supported conditon code,
1312 // which will be the first branch. Later one we will emit the second
1314 bool NeedExtraBranch = false;
1315 switch (Predicate) {
1317 case CmpInst::FCMP_OEQ:
1318 std::swap(TrueMBB, FalseMBB); // fall-through
1319 case CmpInst::FCMP_UNE:
1320 NeedExtraBranch = true;
1321 Predicate = CmpInst::FCMP_ONE;
1328 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1329 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1331 BranchOpc = X86::GetCondBranchFromCond(CC);
1333 std::swap(CmpLHS, CmpRHS);
1335 // Emit a compare of the LHS and RHS, setting the flags.
1336 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1342 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1344 if (NeedExtraBranch) {
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1349 // Obtain the branch weight and add the TrueBB to the successor list.
1350 uint32_t BranchWeight = 0;
1352 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1353 TrueMBB->getBasicBlock());
1354 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1356 // Emits an unconditional branch to the FalseBB, obtains the branch
1357 // weight, and adds it to the successor list.
1358 FastEmitBranch(FalseMBB, DbgLoc);
1362 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1363 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1364 // typically happen for _Bool and C++ bools.
1366 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1367 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1368 unsigned TestOpc = 0;
1369 switch (SourceVT.SimpleTy) {
1371 case MVT::i8: TestOpc = X86::TEST8ri; break;
1372 case MVT::i16: TestOpc = X86::TEST16ri; break;
1373 case MVT::i32: TestOpc = X86::TEST32ri; break;
1374 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1377 unsigned OpReg = getRegForValue(TI->getOperand(0));
1378 if (OpReg == 0) return false;
1379 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1380 .addReg(OpReg).addImm(1);
1382 unsigned JmpOpc = X86::JNE_4;
1383 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1384 std::swap(TrueMBB, FalseMBB);
1388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1390 FastEmitBranch(FalseMBB, DbgLoc);
1391 uint32_t BranchWeight = 0;
1393 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1394 TrueMBB->getBasicBlock());
1395 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1401 // Otherwise do a clumsy setcc and re-test it.
1402 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1403 // in an explicit cast, so make sure to handle that correctly.
1404 unsigned OpReg = getRegForValue(BI->getCondition());
1405 if (OpReg == 0) return false;
1407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1408 .addReg(OpReg).addImm(1);
1409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1411 FastEmitBranch(FalseMBB, DbgLoc);
1412 uint32_t BranchWeight = 0;
1414 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1415 TrueMBB->getBasicBlock());
1416 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1420 bool X86FastISel::X86SelectShift(const Instruction *I) {
1421 unsigned CReg = 0, OpReg = 0;
1422 const TargetRegisterClass *RC = nullptr;
1423 if (I->getType()->isIntegerTy(8)) {
1425 RC = &X86::GR8RegClass;
1426 switch (I->getOpcode()) {
1427 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1428 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1429 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1430 default: return false;
1432 } else if (I->getType()->isIntegerTy(16)) {
1434 RC = &X86::GR16RegClass;
1435 switch (I->getOpcode()) {
1436 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1437 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1438 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1439 default: return false;
1441 } else if (I->getType()->isIntegerTy(32)) {
1443 RC = &X86::GR32RegClass;
1444 switch (I->getOpcode()) {
1445 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1446 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1447 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1448 default: return false;
1450 } else if (I->getType()->isIntegerTy(64)) {
1452 RC = &X86::GR64RegClass;
1453 switch (I->getOpcode()) {
1454 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1455 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1456 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1457 default: return false;
1464 if (!isTypeLegal(I->getType(), VT))
1467 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1468 if (Op0Reg == 0) return false;
1470 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1471 if (Op1Reg == 0) return false;
1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1473 CReg).addReg(Op1Reg);
1475 // The shift instruction uses X86::CL. If we defined a super-register
1476 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1477 if (CReg != X86::CL)
1478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1479 TII.get(TargetOpcode::KILL), X86::CL)
1480 .addReg(CReg, RegState::Kill);
1482 unsigned ResultReg = createResultReg(RC);
1483 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1485 UpdateValueMap(I, ResultReg);
1489 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1490 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1491 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1492 const static bool S = true; // IsSigned
1493 const static bool U = false; // !IsSigned
1494 const static unsigned Copy = TargetOpcode::COPY;
1495 // For the X86 DIV/IDIV instruction, in most cases the dividend
1496 // (numerator) must be in a specific register pair highreg:lowreg,
1497 // producing the quotient in lowreg and the remainder in highreg.
1498 // For most data types, to set up the instruction, the dividend is
1499 // copied into lowreg, and lowreg is sign-extended or zero-extended
1500 // into highreg. The exception is i8, where the dividend is defined
1501 // as a single register rather than a register pair, and we
1502 // therefore directly sign-extend or zero-extend the dividend into
1503 // lowreg, instead of copying, and ignore the highreg.
1504 const static struct DivRemEntry {
1505 // The following portion depends only on the data type.
1506 const TargetRegisterClass *RC;
1507 unsigned LowInReg; // low part of the register pair
1508 unsigned HighInReg; // high part of the register pair
1509 // The following portion depends on both the data type and the operation.
1510 struct DivRemResult {
1511 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1512 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1513 // highreg, or copying a zero into highreg.
1514 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1515 // zero/sign-extending into lowreg for i8.
1516 unsigned DivRemResultReg; // Register containing the desired result.
1517 bool IsOpSigned; // Whether to use signed or unsigned form.
1518 } ResultTable[NumOps];
1519 } OpTable[NumTypes] = {
1520 { &X86::GR8RegClass, X86::AX, 0, {
1521 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1522 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1523 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1524 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1527 { &X86::GR16RegClass, X86::AX, X86::DX, {
1528 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1529 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1530 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1531 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1534 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1535 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1536 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1537 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1538 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1541 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1542 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1543 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1544 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1545 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1551 if (!isTypeLegal(I->getType(), VT))
1554 unsigned TypeIndex, OpIndex;
1555 switch (VT.SimpleTy) {
1556 default: return false;
1557 case MVT::i8: TypeIndex = 0; break;
1558 case MVT::i16: TypeIndex = 1; break;
1559 case MVT::i32: TypeIndex = 2; break;
1560 case MVT::i64: TypeIndex = 3;
1561 if (!Subtarget->is64Bit())
1566 switch (I->getOpcode()) {
1567 default: llvm_unreachable("Unexpected div/rem opcode");
1568 case Instruction::SDiv: OpIndex = 0; break;
1569 case Instruction::SRem: OpIndex = 1; break;
1570 case Instruction::UDiv: OpIndex = 2; break;
1571 case Instruction::URem: OpIndex = 3; break;
1574 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1575 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1576 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1579 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1583 // Move op0 into low-order input register.
1584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1585 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1586 // Zero-extend or sign-extend into high-order input register.
1587 if (OpEntry.OpSignExtend) {
1588 if (OpEntry.IsOpSigned)
1589 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1590 TII.get(OpEntry.OpSignExtend));
1592 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1594 TII.get(X86::MOV32r0), Zero32);
1596 // Copy the zero into the appropriate sub/super/identical physical
1597 // register. Unfortunately the operations needed are not uniform enough to
1598 // fit neatly into the table above.
1599 if (VT.SimpleTy == MVT::i16) {
1600 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1601 TII.get(Copy), TypeEntry.HighInReg)
1602 .addReg(Zero32, 0, X86::sub_16bit);
1603 } else if (VT.SimpleTy == MVT::i32) {
1604 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1605 TII.get(Copy), TypeEntry.HighInReg)
1607 } else if (VT.SimpleTy == MVT::i64) {
1608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1609 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1610 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1614 // Generate the DIV/IDIV instruction.
1615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1616 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1617 // For i8 remainder, we can't reference AH directly, as we'll end
1618 // up with bogus copies like %R9B = COPY %AH. Reference AX
1619 // instead to prevent AH references in a REX instruction.
1621 // The current assumption of the fast register allocator is that isel
1622 // won't generate explicit references to the GPR8_NOREX registers. If
1623 // the allocator and/or the backend get enhanced to be more robust in
1624 // that regard, this can be, and should be, removed.
1625 unsigned ResultReg = 0;
1626 if ((I->getOpcode() == Instruction::SRem ||
1627 I->getOpcode() == Instruction::URem) &&
1628 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1629 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1630 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1632 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1634 // Shift AX right by 8 bits instead of using AH.
1635 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1636 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1638 // Now reference the 8-bit subreg of the result.
1639 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1640 /*Kill=*/true, X86::sub_8bit);
1642 // Copy the result out of the physreg if we haven't already.
1644 ResultReg = createResultReg(TypeEntry.RC);
1645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1646 .addReg(OpEntry.DivRemResultReg);
1648 UpdateValueMap(I, ResultReg);
1653 /// \brief Emit a conditional move instruction (if the are supported) to lower
1655 bool X86FastISel::X86FastEmitCMoveSelect(const Instruction *I) {
1657 if (!isTypeLegal(I->getType(), RetVT))
1660 // Check if the subtarget supports these instructions.
1661 if (!Subtarget->hasCMov())
1664 // FIXME: Add support for i8.
1666 switch (RetVT.SimpleTy) {
1667 default: return false;
1668 case MVT::i16: Opc = X86::CMOVNE16rr; break;
1669 case MVT::i32: Opc = X86::CMOVNE32rr; break;
1670 case MVT::i64: Opc = X86::CMOVNE64rr; break;
1673 const Value *Cond = I->getOperand(0);
1674 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1675 bool NeedTest = true;
1677 // Optimize conditons coming from a compare.
1678 if (const auto *CI = dyn_cast<CmpInst>(Cond)) {
1679 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1681 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1682 static unsigned SETFOpcTable[2][3] = {
1683 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1684 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1686 unsigned *SETFOpc = nullptr;
1687 switch (Predicate) {
1689 case CmpInst::FCMP_OEQ:
1690 SETFOpc = &SETFOpcTable[0][0];
1691 Predicate = CmpInst::ICMP_NE;
1693 case CmpInst::FCMP_UNE:
1694 SETFOpc = &SETFOpcTable[1][0];
1695 Predicate = CmpInst::ICMP_NE;
1701 std::tie(CC, NeedSwap) = getX86ConditonCode(Predicate);
1702 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1703 Opc = X86::getCMovFromCond(CC, RC->getSize());
1705 const Value *CmpLHS = CI->getOperand(0);
1706 const Value *CmpRHS = CI->getOperand(1);
1708 std::swap(CmpLHS, CmpRHS);
1710 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1711 // Emit a compare of the LHS and RHS, setting the flags.
1712 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1716 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1717 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1720 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1722 auto const &II = TII.get(SETFOpc[2]);
1723 if (II.getNumDefs()) {
1724 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1725 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1726 .addReg(FlagReg2).addReg(FlagReg1);
1728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1729 .addReg(FlagReg2).addReg(FlagReg1);
1736 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1737 // garbage. Indeed, only the less significant bit is supposed to be
1738 // accurate. If we read more than the lsb, we may see non-zero values
1739 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1740 // the select. This is achieved by performing TEST against 1.
1741 unsigned CondReg = getRegForValue(Cond);
1744 bool CondIsKill = hasTrivialKill(Cond);
1746 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1747 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1750 const Value *LHS = I->getOperand(1);
1751 const Value *RHS = I->getOperand(2);
1753 unsigned RHSReg = getRegForValue(RHS);
1754 bool RHSIsKill = hasTrivialKill(RHS);
1756 unsigned LHSReg = getRegForValue(LHS);
1757 bool LHSIsKill = hasTrivialKill(LHS);
1759 if (!LHSReg || !RHSReg)
1762 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1764 UpdateValueMap(I, ResultReg);
1768 /// \brief Emit SSE instructions to lower the select.
1770 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1771 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1772 /// SSE instructions are available.
1773 bool X86FastISel::X86FastEmitSSESelect(const Instruction *I) {
1775 if (!isTypeLegal(I->getType(), RetVT))
1778 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1782 if (I->getType() != CI->getOperand(0)->getType() ||
1783 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1784 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1787 const Value *CmpLHS = CI->getOperand(0);
1788 const Value *CmpRHS = CI->getOperand(1);
1789 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1791 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1792 // We don't have to materialize a zero constant for this case and can just use
1793 // %x again on the RHS.
1794 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1795 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1796 if (CmpRHSC && CmpRHSC->isNullValue())
1802 std::tie(CC, NeedSwap) = getX86SSECondtionCode(Predicate);
1807 std::swap(CmpLHS, CmpRHS);
1809 static unsigned OpcTable[2][2][4] = {
1810 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1811 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1812 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1813 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1816 bool HasAVX = Subtarget->hasAVX();
1817 unsigned *Opc = nullptr;
1818 switch (RetVT.SimpleTy) {
1819 default: return false;
1820 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1821 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1824 const Value *LHS = I->getOperand(1);
1825 const Value *RHS = I->getOperand(2);
1827 unsigned LHSReg = getRegForValue(LHS);
1828 bool LHSIsKill = hasTrivialKill(LHS);
1830 unsigned RHSReg = getRegForValue(RHS);
1831 bool RHSIsKill = hasTrivialKill(RHS);
1833 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1834 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1836 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1837 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1839 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1842 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1843 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1844 CmpRHSReg, CmpRHSIsKill, CC);
1845 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1847 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1849 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1850 AndReg, /*IsKill=*/true);
1851 UpdateValueMap(I, ResultReg);
1855 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1857 if (!isTypeLegal(I->getType(), RetVT))
1860 // Check if we can fold the select.
1861 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
1862 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1863 const Value *Opnd = nullptr;
1864 switch (Predicate) {
1866 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
1867 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
1869 // No need for a select anymore - this is an unconditional move.
1871 unsigned OpReg = getRegForValue(Opnd);
1874 bool OpIsKill = hasTrivialKill(Opnd);
1875 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1876 unsigned ResultReg = createResultReg(RC);
1877 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1878 TII.get(TargetOpcode::COPY), ResultReg)
1879 .addReg(OpReg, getKillRegState(OpIsKill));
1880 UpdateValueMap(I, ResultReg);
1885 // First try to use real conditional move instructions.
1886 if (X86FastEmitCMoveSelect(I))
1889 // Try to use a sequence of SSE instructions to simulate a conditonal move.
1890 if (X86FastEmitSSESelect(I))
1896 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1897 // fpext from float to double.
1898 if (X86ScalarSSEf64 &&
1899 I->getType()->isDoubleTy()) {
1900 const Value *V = I->getOperand(0);
1901 if (V->getType()->isFloatTy()) {
1902 unsigned OpReg = getRegForValue(V);
1903 if (OpReg == 0) return false;
1904 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1905 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1906 TII.get(X86::CVTSS2SDrr), ResultReg)
1908 UpdateValueMap(I, ResultReg);
1916 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1917 if (X86ScalarSSEf64) {
1918 if (I->getType()->isFloatTy()) {
1919 const Value *V = I->getOperand(0);
1920 if (V->getType()->isDoubleTy()) {
1921 unsigned OpReg = getRegForValue(V);
1922 if (OpReg == 0) return false;
1923 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1925 TII.get(X86::CVTSD2SSrr), ResultReg)
1927 UpdateValueMap(I, ResultReg);
1936 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1937 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1938 EVT DstVT = TLI.getValueType(I->getType());
1940 // This code only handles truncation to byte.
1941 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1943 if (!TLI.isTypeLegal(SrcVT))
1946 unsigned InputReg = getRegForValue(I->getOperand(0));
1948 // Unhandled operand. Halt "fast" selection and bail.
1951 if (SrcVT == MVT::i8) {
1952 // Truncate from i8 to i1; no code needed.
1953 UpdateValueMap(I, InputReg);
1957 if (!Subtarget->is64Bit()) {
1958 // If we're on x86-32; we can't extract an i8 from a general register.
1959 // First issue a copy to GR16_ABCD or GR32_ABCD.
1960 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1961 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1962 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1963 unsigned CopyReg = createResultReg(CopyRC);
1964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1965 CopyReg).addReg(InputReg);
1969 // Issue an extract_subreg.
1970 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1971 InputReg, /*Kill=*/true,
1976 UpdateValueMap(I, ResultReg);
1980 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1981 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1984 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1985 X86AddressMode SrcAM, uint64_t Len) {
1987 // Make sure we don't bloat code by inlining very large memcpy's.
1988 if (!IsMemcpySmall(Len))
1991 bool i64Legal = Subtarget->is64Bit();
1993 // We don't care about alignment here since we just emit integer accesses.
1996 if (Len >= 8 && i64Legal)
2007 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2008 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2009 assert(RV && "Failed to emit load or store??");
2011 unsigned Size = VT.getSizeInBits()/8;
2013 DestAM.Disp += Size;
2020 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
2021 switch (I.getIntrinsicID()) {
2022 case Intrinsic::sadd_with_overflow:
2023 case Intrinsic::uadd_with_overflow:
2024 case Intrinsic::smul_with_overflow:
2025 case Intrinsic::umul_with_overflow:
2032 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
2033 // FIXME: Handle more intrinsics.
2034 switch (I.getIntrinsicID()) {
2035 default: return false;
2036 case Intrinsic::frameaddress: {
2037 Type *RetTy = I.getCalledFunction()->getReturnType();
2040 if (!isTypeLegal(RetTy, VT))
2044 const TargetRegisterClass *RC = nullptr;
2046 switch (VT.SimpleTy) {
2047 default: llvm_unreachable("Invalid result type for frameaddress.");
2048 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2049 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2052 // This needs to be set before we call getFrameRegister, otherwise we get
2053 // the wrong frame register.
2054 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2055 MFI->setFrameAddressIsTaken(true);
2057 const X86RegisterInfo *RegInfo =
2058 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2059 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2060 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2061 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2062 "Invalid Frame Register!");
2064 // Always make a copy of the frame register to to a vreg first, so that we
2065 // never directly reference the frame register (the TwoAddressInstruction-
2066 // Pass doesn't like that).
2067 unsigned SrcReg = createResultReg(RC);
2068 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2069 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2071 // Now recursively load from the frame address.
2072 // movq (%rbp), %rax
2073 // movq (%rax), %rax
2074 // movq (%rax), %rax
2077 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2079 DestReg = createResultReg(RC);
2080 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2081 TII.get(Opc), DestReg), SrcReg);
2085 UpdateValueMap(&I, SrcReg);
2088 case Intrinsic::memcpy: {
2089 const MemCpyInst &MCI = cast<MemCpyInst>(I);
2090 // Don't handle volatile or variable length memcpys.
2091 if (MCI.isVolatile())
2094 if (isa<ConstantInt>(MCI.getLength())) {
2095 // Small memcpy's are common enough that we want to do them
2096 // without a call if possible.
2097 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
2098 if (IsMemcpySmall(Len)) {
2099 X86AddressMode DestAM, SrcAM;
2100 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
2101 !X86SelectAddress(MCI.getRawSource(), SrcAM))
2103 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2108 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2109 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
2112 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
2115 return DoSelectCall(&I, "memcpy");
2117 case Intrinsic::memset: {
2118 const MemSetInst &MSI = cast<MemSetInst>(I);
2120 if (MSI.isVolatile())
2123 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2124 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
2127 if (MSI.getDestAddressSpace() > 255)
2130 return DoSelectCall(&I, "memset");
2132 case Intrinsic::stackprotector: {
2133 // Emit code to store the stack guard onto the stack.
2134 EVT PtrTy = TLI.getPointerTy();
2136 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2137 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2139 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2141 // Grab the frame index.
2143 if (!X86SelectAddress(Slot, AM)) return false;
2144 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2147 case Intrinsic::dbg_declare: {
2148 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2150 assert(DI->getAddress() && "Null address should be checked earlier!");
2151 if (!X86SelectAddress(DI->getAddress(), AM))
2153 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2154 // FIXME may need to add RegState::Debug to any registers produced,
2155 // although ESP/EBP should be the only ones at the moment.
2156 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2157 addImm(0).addMetadata(DI->getVariable());
2160 case Intrinsic::trap: {
2161 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2164 case Intrinsic::sqrt: {
2165 if (!Subtarget->hasSSE1())
2168 Type *RetTy = I.getCalledFunction()->getReturnType();
2171 if (!isTypeLegal(RetTy, VT))
2174 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
2175 // is not generated by FastISel yet.
2176 // FIXME: Update this code once tablegen can handle it.
2177 static const unsigned SqrtOpc[2][2] = {
2178 {X86::SQRTSSr, X86::VSQRTSSr},
2179 {X86::SQRTSDr, X86::VSQRTSDr}
2181 bool HasAVX = Subtarget->hasAVX();
2183 const TargetRegisterClass *RC;
2184 switch (VT.SimpleTy) {
2185 default: return false;
2186 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2187 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2190 const Value *SrcVal = I.getArgOperand(0);
2191 unsigned SrcReg = getRegForValue(SrcVal);
2196 unsigned ImplicitDefReg = 0;
2198 ImplicitDefReg = createResultReg(RC);
2199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2200 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2203 unsigned ResultReg = createResultReg(RC);
2204 MachineInstrBuilder MIB;
2205 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2209 MIB.addReg(ImplicitDefReg);
2213 UpdateValueMap(&I, ResultReg);
2216 case Intrinsic::sadd_with_overflow:
2217 case Intrinsic::uadd_with_overflow:
2218 case Intrinsic::ssub_with_overflow:
2219 case Intrinsic::usub_with_overflow:
2220 case Intrinsic::smul_with_overflow:
2221 case Intrinsic::umul_with_overflow: {
2222 // This implements the basic lowering of the xalu with overflow intrinsics
2223 // into add/sub/mul folowed by either seto or setb.
2224 const Function *Callee = I.getCalledFunction();
2225 auto *Ty = cast<StructType>(Callee->getReturnType());
2226 Type *RetTy = Ty->getTypeAtIndex(0U);
2227 Type *CondTy = Ty->getTypeAtIndex(1);
2230 if (!isTypeLegal(RetTy, VT))
2233 if (VT < MVT::i8 || VT > MVT::i64)
2236 const Value *LHS = I.getArgOperand(0);
2237 const Value *RHS = I.getArgOperand(1);
2239 // Canonicalize immediates to the RHS.
2240 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2241 isCommutativeIntrinsic(I))
2242 std::swap(LHS, RHS);
2244 unsigned BaseOpc, CondOpc;
2245 switch (I.getIntrinsicID()) {
2246 default: llvm_unreachable("Unexpected intrinsic!");
2247 case Intrinsic::sadd_with_overflow:
2248 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2249 case Intrinsic::uadd_with_overflow:
2250 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2251 case Intrinsic::ssub_with_overflow:
2252 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2253 case Intrinsic::usub_with_overflow:
2254 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2255 case Intrinsic::smul_with_overflow:
2256 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2257 case Intrinsic::umul_with_overflow:
2258 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2261 unsigned LHSReg = getRegForValue(LHS);
2264 bool LHSIsKill = hasTrivialKill(LHS);
2266 unsigned ResultReg = 0;
2267 // Check if we have an immediate version.
2268 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2269 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2276 RHSReg = getRegForValue(RHS);
2279 RHSIsKill = hasTrivialKill(RHS);
2280 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2284 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2285 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2286 static const unsigned MULOpc[] =
2287 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2288 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2289 // First copy the first operand into RAX, which is an implicit input to
2290 // the X86::MUL*r instruction.
2291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2292 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2293 .addReg(LHSReg, getKillRegState(LHSIsKill));
2294 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2295 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2301 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2302 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2306 UpdateValueMap(&I, ResultReg, 2);
2309 case Intrinsic::x86_sse_cvttss2si:
2310 case Intrinsic::x86_sse_cvttss2si64:
2311 case Intrinsic::x86_sse2_cvttsd2si:
2312 case Intrinsic::x86_sse2_cvttsd2si64: {
2314 switch (I.getIntrinsicID()) {
2315 default: llvm_unreachable("Unexpected intrinsic.");
2316 case Intrinsic::x86_sse_cvttss2si:
2317 case Intrinsic::x86_sse_cvttss2si64:
2318 if (!Subtarget->hasSSE1())
2320 IsInputDouble = false;
2322 case Intrinsic::x86_sse2_cvttsd2si:
2323 case Intrinsic::x86_sse2_cvttsd2si64:
2324 if (!Subtarget->hasSSE2())
2326 IsInputDouble = true;
2330 Type *RetTy = I.getCalledFunction()->getReturnType();
2332 if (!isTypeLegal(RetTy, VT))
2335 static const unsigned CvtOpc[2][2][2] = {
2336 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2337 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2338 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2339 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2341 bool HasAVX = Subtarget->hasAVX();
2343 switch (VT.SimpleTy) {
2344 default: llvm_unreachable("Unexpected result type.");
2345 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2346 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2349 // Check if we can fold insertelement instructions into the convert.
2350 const Value *Op = I.getArgOperand(0);
2351 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2352 const Value *Index = IE->getOperand(2);
2353 if (!isa<ConstantInt>(Index))
2355 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2358 Op = IE->getOperand(1);
2361 Op = IE->getOperand(0);
2364 unsigned Reg = getRegForValue(Op);
2368 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2369 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2372 UpdateValueMap(&I, ResultReg);
2378 bool X86FastISel::FastLowerArguments() {
2379 if (!FuncInfo.CanLowerReturn)
2382 const Function *F = FuncInfo.Fn;
2386 CallingConv::ID CC = F->getCallingConv();
2387 if (CC != CallingConv::C)
2390 if (Subtarget->isCallingConvWin64(CC))
2393 if (!Subtarget->is64Bit())
2396 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2397 unsigned GPRCnt = 0;
2398 unsigned FPRCnt = 0;
2400 for (auto const &Arg : F->args()) {
2401 // The first argument is at index 1.
2403 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2404 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2405 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2406 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2409 Type *ArgTy = Arg.getType();
2410 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2413 EVT ArgVT = TLI.getValueType(ArgTy);
2414 if (!ArgVT.isSimple()) return false;
2415 switch (ArgVT.getSimpleVT().SimpleTy) {
2416 default: return false;
2423 if (!Subtarget->hasSSE1())
2436 static const MCPhysReg GPR32ArgRegs[] = {
2437 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2439 static const MCPhysReg GPR64ArgRegs[] = {
2440 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2442 static const MCPhysReg XMMArgRegs[] = {
2443 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2444 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2447 unsigned GPRIdx = 0;
2448 unsigned FPRIdx = 0;
2449 for (auto const &Arg : F->args()) {
2450 MVT VT = TLI.getSimpleValueType(Arg.getType());
2451 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2453 switch (VT.SimpleTy) {
2454 default: llvm_unreachable("Unexpected value type.");
2455 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2456 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2457 case MVT::f32: // fall-through
2458 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2460 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2461 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2462 // Without this, EmitLiveInCopies may eliminate the livein if its only
2463 // use is a bitcast (which isn't turned into an instruction).
2464 unsigned ResultReg = createResultReg(RC);
2465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2466 TII.get(TargetOpcode::COPY), ResultReg)
2467 .addReg(DstReg, getKillRegState(true));
2468 UpdateValueMap(&Arg, ResultReg);
2473 bool X86FastISel::X86SelectCall(const Instruction *I) {
2474 const CallInst *CI = cast<CallInst>(I);
2475 const Value *Callee = CI->getCalledValue();
2477 // Can't handle inline asm yet.
2478 if (isa<InlineAsm>(Callee))
2481 // Handle intrinsic calls.
2482 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2483 return X86VisitIntrinsicCall(*II);
2485 // Allow SelectionDAG isel to handle tail calls.
2486 if (cast<CallInst>(I)->isTailCall())
2489 return DoSelectCall(I, nullptr);
2492 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2493 const ImmutableCallSite &CS) {
2494 if (Subtarget.is64Bit())
2496 if (Subtarget.getTargetTriple().isOSMSVCRT())
2498 CallingConv::ID CC = CS.getCallingConv();
2499 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2501 if (!CS.paramHasAttr(1, Attribute::StructRet))
2503 if (CS.paramHasAttr(1, Attribute::InReg))
2508 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2509 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2510 const CallInst *CI = cast<CallInst>(I);
2511 const Value *Callee = CI->getCalledValue();
2513 // Handle only C and fastcc calling conventions for now.
2514 ImmutableCallSite CS(CI);
2515 CallingConv::ID CC = CS.getCallingConv();
2516 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2517 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2518 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2519 CC != CallingConv::X86_64_SysV)
2522 // fastcc with -tailcallopt is intended to provide a guaranteed
2523 // tail call optimization. Fastisel doesn't know how to do that.
2524 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2527 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2528 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2529 bool isVarArg = FTy->isVarArg();
2531 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2532 // x86-32. Special handling for x86-64 is implemented.
2533 if (isVarArg && isWin64)
2536 // Don't know about inalloca yet.
2537 if (CS.hasInAllocaArgument())
2540 // Fast-isel doesn't know about callee-pop yet.
2541 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2542 TM.Options.GuaranteedTailCallOpt))
2545 // Check whether the function can return without sret-demotion.
2546 SmallVector<ISD::OutputArg, 4> Outs;
2547 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2548 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2549 *FuncInfo.MF, FTy->isVarArg(),
2550 Outs, FTy->getContext());
2551 if (!CanLowerReturn)
2554 // Materialize callee address in a register. FIXME: GV address can be
2555 // handled with a CALLpcrel32 instead.
2556 X86AddressMode CalleeAM;
2557 if (!X86SelectCallAddress(Callee, CalleeAM))
2559 unsigned CalleeOp = 0;
2560 const GlobalValue *GV = nullptr;
2561 if (CalleeAM.GV != nullptr) {
2563 } else if (CalleeAM.Base.Reg != 0) {
2564 CalleeOp = CalleeAM.Base.Reg;
2568 // Deal with call operands first.
2569 SmallVector<const Value *, 8> ArgVals;
2570 SmallVector<unsigned, 8> Args;
2571 SmallVector<MVT, 8> ArgVTs;
2572 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2573 unsigned arg_size = CS.arg_size();
2574 Args.reserve(arg_size);
2575 ArgVals.reserve(arg_size);
2576 ArgVTs.reserve(arg_size);
2577 ArgFlags.reserve(arg_size);
2578 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2580 // If we're lowering a mem intrinsic instead of a regular call, skip the
2581 // last two arguments, which should not passed to the underlying functions.
2582 if (MemIntName && e-i <= 2)
2585 ISD::ArgFlagsTy Flags;
2586 unsigned AttrInd = i - CS.arg_begin() + 1;
2587 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2589 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2592 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2593 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2594 Type *ElementTy = Ty->getElementType();
2595 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2596 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2598 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2600 Flags.setByValSize(FrameSize);
2601 Flags.setByValAlign(FrameAlign);
2602 if (!IsMemcpySmall(FrameSize))
2606 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2608 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2611 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2612 // instruction. This is safe because it is common to all fastisel supported
2613 // calling conventions on x86.
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2615 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2616 CI->getBitWidth() == 16) {
2618 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2620 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2626 // Passing bools around ends up doing a trunc to i1 and passing it.
2627 // Codegen this as an argument + "and 1".
2628 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2629 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2630 ArgVal->hasOneUse()) {
2631 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2632 ArgReg = getRegForValue(ArgVal);
2633 if (ArgReg == 0) return false;
2636 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2638 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2639 ArgVal->hasOneUse(), 1);
2641 ArgReg = getRegForValue(ArgVal);
2644 if (ArgReg == 0) return false;
2646 Type *ArgTy = ArgVal->getType();
2648 if (!isTypeLegal(ArgTy, ArgVT))
2650 if (ArgVT == MVT::x86mmx)
2652 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2653 Flags.setOrigAlign(OriginalAlignment);
2655 Args.push_back(ArgReg);
2656 ArgVals.push_back(ArgVal);
2657 ArgVTs.push_back(ArgVT);
2658 ArgFlags.push_back(Flags);
2661 // Analyze operands of the call, assigning locations to each operand.
2662 SmallVector<CCValAssign, 16> ArgLocs;
2663 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2664 I->getParent()->getContext());
2666 // Allocate shadow area for Win64
2668 CCInfo.AllocateStack(32, 8);
2670 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2672 // Get a count of how many bytes are to be pushed on the stack.
2673 unsigned NumBytes = CCInfo.getNextStackOffset();
2675 // Issue CALLSEQ_START
2676 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2680 // Process argument: walk the register/memloc assignments, inserting
2682 SmallVector<unsigned, 4> RegArgs;
2683 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2684 CCValAssign &VA = ArgLocs[i];
2685 unsigned Arg = Args[VA.getValNo()];
2686 EVT ArgVT = ArgVTs[VA.getValNo()];
2688 // Promote the value if needed.
2689 switch (VA.getLocInfo()) {
2690 case CCValAssign::Full: break;
2691 case CCValAssign::SExt: {
2692 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2693 "Unexpected extend");
2694 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2696 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2697 ArgVT = VA.getLocVT();
2700 case CCValAssign::ZExt: {
2701 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2702 "Unexpected extend");
2703 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2705 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2706 ArgVT = VA.getLocVT();
2709 case CCValAssign::AExt: {
2710 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2711 "Unexpected extend");
2712 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2715 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2718 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2721 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2722 ArgVT = VA.getLocVT();
2725 case CCValAssign::BCvt: {
2726 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2727 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2728 assert(BC != 0 && "Failed to emit a bitcast!");
2730 ArgVT = VA.getLocVT();
2733 case CCValAssign::VExt:
2734 // VExt has not been implemented, so this should be impossible to reach
2735 // for now. However, fallback to Selection DAG isel once implemented.
2737 case CCValAssign::Indirect:
2738 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2741 case CCValAssign::FPExt:
2742 llvm_unreachable("Unexpected loc info!");
2745 if (VA.isRegLoc()) {
2746 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2747 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2748 RegArgs.push_back(VA.getLocReg());
2750 unsigned LocMemOffset = VA.getLocMemOffset();
2752 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2753 getTargetMachine()->getRegisterInfo());
2754 AM.Base.Reg = RegInfo->getStackRegister();
2755 AM.Disp = LocMemOffset;
2756 const Value *ArgVal = ArgVals[VA.getValNo()];
2757 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2759 if (Flags.isByVal()) {
2760 X86AddressMode SrcAM;
2761 SrcAM.Base.Reg = Arg;
2762 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2763 assert(Res && "memcpy length already checked!"); (void)Res;
2764 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2765 // If this is a really simple value, emit this with the Value* version
2766 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2767 // as it can cause us to reevaluate the argument.
2768 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2771 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2777 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2779 if (Subtarget->isPICStyleGOT()) {
2780 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2781 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2782 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2785 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2786 // Count the number of XMM registers allocated.
2787 static const MCPhysReg XMMArgRegs[] = {
2788 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2789 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2791 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2793 X86::AL).addImm(NumXMMRegs);
2797 MachineInstrBuilder MIB;
2799 // Register-indirect call.
2801 if (Subtarget->is64Bit())
2802 CallOpc = X86::CALL64r;
2804 CallOpc = X86::CALL32r;
2805 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2810 assert(GV && "Not a direct call");
2812 if (Subtarget->is64Bit())
2813 CallOpc = X86::CALL64pcrel32;
2815 CallOpc = X86::CALLpcrel32;
2817 // See if we need any target-specific flags on the GV operand.
2818 unsigned char OpFlags = 0;
2820 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2821 // external symbols most go through the PLT in PIC mode. If the symbol
2822 // has hidden or protected visibility, or if it is static or local, then
2823 // we don't need to use the PLT - we can directly call it.
2824 if (Subtarget->isTargetELF() &&
2825 TM.getRelocationModel() == Reloc::PIC_ &&
2826 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2827 OpFlags = X86II::MO_PLT;
2828 } else if (Subtarget->isPICStyleStubAny() &&
2829 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2830 (!Subtarget->getTargetTriple().isMacOSX() ||
2831 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2832 // PC-relative references to external symbols should go through $stub,
2833 // unless we're building with the leopard linker or later, which
2834 // automatically synthesizes these stubs.
2835 OpFlags = X86II::MO_DARWIN_STUB;
2839 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2841 MIB.addExternalSymbol(MemIntName, OpFlags);
2843 MIB.addGlobalAddress(GV, 0, OpFlags);
2846 // Add a register mask with the call-preserved registers.
2847 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2848 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2850 // Add an implicit use GOT pointer in EBX.
2851 if (Subtarget->isPICStyleGOT())
2852 MIB.addReg(X86::EBX, RegState::Implicit);
2854 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2855 MIB.addReg(X86::AL, RegState::Implicit);
2857 // Add implicit physical register uses to the call.
2858 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2859 MIB.addReg(RegArgs[i], RegState::Implicit);
2861 // Issue CALLSEQ_END
2862 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2863 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2865 .addImm(NumBytes).addImm(NumBytesCallee);
2867 // Build info for return calling conv lowering code.
2868 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2869 SmallVector<ISD::InputArg, 32> Ins;
2870 SmallVector<EVT, 4> RetTys;
2871 ComputeValueVTs(TLI, I->getType(), RetTys);
2872 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2874 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2875 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2876 for (unsigned j = 0; j != NumRegs; ++j) {
2877 ISD::InputArg MyFlags;
2878 MyFlags.VT = RegisterVT;
2879 MyFlags.Used = !CS.getInstruction()->use_empty();
2880 if (CS.paramHasAttr(0, Attribute::SExt))
2881 MyFlags.Flags.setSExt();
2882 if (CS.paramHasAttr(0, Attribute::ZExt))
2883 MyFlags.Flags.setZExt();
2884 if (CS.paramHasAttr(0, Attribute::InReg))
2885 MyFlags.Flags.setInReg();
2886 Ins.push_back(MyFlags);
2890 // Now handle call return values.
2891 SmallVector<unsigned, 4> UsedRegs;
2892 SmallVector<CCValAssign, 16> RVLocs;
2893 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2894 I->getParent()->getContext());
2895 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2896 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2897 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2898 EVT CopyVT = RVLocs[i].getValVT();
2899 unsigned CopyReg = ResultReg + i;
2901 // If this is a call to a function that returns an fp value on the x87 fp
2902 // stack, but where we prefer to use the value in xmm registers, copy it
2903 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2904 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2905 RVLocs[i].getLocReg() == X86::ST1)) {
2906 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2908 CopyReg = createResultReg(&X86::RFP80RegClass);
2910 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2911 TII.get(X86::FpPOP_RETVAL), CopyReg);
2913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2914 TII.get(TargetOpcode::COPY),
2915 CopyReg).addReg(RVLocs[i].getLocReg());
2916 UsedRegs.push_back(RVLocs[i].getLocReg());
2919 if (CopyVT != RVLocs[i].getValVT()) {
2920 // Round the F80 the right size, which also moves to the appropriate xmm
2921 // register. This is accomplished by storing the F80 value in memory and
2922 // then loading it back. Ewww...
2923 EVT ResVT = RVLocs[i].getValVT();
2924 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2925 unsigned MemSize = ResVT.getSizeInBits()/8;
2926 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2927 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2930 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2931 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2932 TII.get(Opc), ResultReg + i), FI);
2937 UpdateValueMap(I, ResultReg, RVLocs.size());
2939 // Set all unused physreg defs as dead.
2940 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2947 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2948 switch (I->getOpcode()) {
2950 case Instruction::Load:
2951 return X86SelectLoad(I);
2952 case Instruction::Store:
2953 return X86SelectStore(I);
2954 case Instruction::Ret:
2955 return X86SelectRet(I);
2956 case Instruction::ICmp:
2957 case Instruction::FCmp:
2958 return X86SelectCmp(I);
2959 case Instruction::ZExt:
2960 return X86SelectZExt(I);
2961 case Instruction::Br:
2962 return X86SelectBranch(I);
2963 case Instruction::Call:
2964 return X86SelectCall(I);
2965 case Instruction::LShr:
2966 case Instruction::AShr:
2967 case Instruction::Shl:
2968 return X86SelectShift(I);
2969 case Instruction::SDiv:
2970 case Instruction::UDiv:
2971 case Instruction::SRem:
2972 case Instruction::URem:
2973 return X86SelectDivRem(I);
2974 case Instruction::Select:
2975 return X86SelectSelect(I);
2976 case Instruction::Trunc:
2977 return X86SelectTrunc(I);
2978 case Instruction::FPExt:
2979 return X86SelectFPExt(I);
2980 case Instruction::FPTrunc:
2981 return X86SelectFPTrunc(I);
2982 case Instruction::IntToPtr: // Deliberate fall-through.
2983 case Instruction::PtrToInt: {
2984 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2985 EVT DstVT = TLI.getValueType(I->getType());
2986 if (DstVT.bitsGT(SrcVT))
2987 return X86SelectZExt(I);
2988 if (DstVT.bitsLT(SrcVT))
2989 return X86SelectTrunc(I);
2990 unsigned Reg = getRegForValue(I->getOperand(0));
2991 if (Reg == 0) return false;
2992 UpdateValueMap(I, Reg);
3000 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3002 if (!isTypeLegal(C->getType(), VT))
3005 // Can't handle alternate code models yet.
3006 if (TM.getCodeModel() != CodeModel::Small)
3009 // Get opcode and regclass of the output for the given load instruction.
3011 const TargetRegisterClass *RC = nullptr;
3012 switch (VT.SimpleTy) {
3016 RC = &X86::GR8RegClass;
3020 RC = &X86::GR16RegClass;
3024 RC = &X86::GR32RegClass;
3027 // Must be in x86-64 mode.
3029 RC = &X86::GR64RegClass;
3032 if (X86ScalarSSEf32) {
3033 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3034 RC = &X86::FR32RegClass;
3036 Opc = X86::LD_Fp32m;
3037 RC = &X86::RFP32RegClass;
3041 if (X86ScalarSSEf64) {
3042 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3043 RC = &X86::FR64RegClass;
3045 Opc = X86::LD_Fp64m;
3046 RC = &X86::RFP64RegClass;
3050 // No f80 support yet.
3054 // Materialize addresses with LEA/MOV instructions.
3055 if (isa<GlobalValue>(C)) {
3057 if (X86SelectAddress(C, AM)) {
3058 // If the expression is just a basereg, then we're done, otherwise we need
3060 if (AM.BaseType == X86AddressMode::RegBase &&
3061 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3064 unsigned ResultReg = createResultReg(RC);
3065 if (TM.getRelocationModel() == Reloc::Static &&
3066 TLI.getPointerTy() == MVT::i64) {
3067 // The displacement code be more than 32 bits away so we need to use
3068 // an instruction with a 64 bit immediate
3070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3071 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
3073 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3074 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3075 TII.get(Opc), ResultReg), AM);
3082 // MachineConstantPool wants an explicit alignment.
3083 unsigned Align = DL.getPrefTypeAlignment(C->getType());
3085 // Alignment of vector types. FIXME!
3086 Align = DL.getTypeAllocSize(C->getType());
3089 // x86-32 PIC requires a PIC base register for constant pools.
3090 unsigned PICBase = 0;
3091 unsigned char OpFlag = 0;
3092 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3093 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3094 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3095 } else if (Subtarget->isPICStyleGOT()) {
3096 OpFlag = X86II::MO_GOTOFF;
3097 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3098 } else if (Subtarget->isPICStyleRIPRel() &&
3099 TM.getCodeModel() == CodeModel::Small) {
3103 // Create the load from the constant pool.
3104 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
3105 unsigned ResultReg = createResultReg(RC);
3106 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3107 TII.get(Opc), ResultReg),
3108 MCPOffset, PICBase, OpFlag);
3113 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3114 // Fail on dynamic allocas. At this point, getRegForValue has already
3115 // checked its CSE maps, so if we're here trying to handle a dynamic
3116 // alloca, we're not going to succeed. X86SelectAddress has a
3117 // check for dynamic allocas, because it's called directly from
3118 // various places, but TargetMaterializeAlloca also needs a check
3119 // in order to avoid recursion between getRegForValue,
3120 // X86SelectAddrss, and TargetMaterializeAlloca.
3121 if (!FuncInfo.StaticAllocaMap.count(C))
3123 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3126 if (!X86SelectAddress(C, AM))
3128 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3129 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3130 unsigned ResultReg = createResultReg(RC);
3131 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3132 TII.get(Opc), ResultReg), AM);
3136 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3138 if (!isTypeLegal(CF->getType(), VT))
3141 // Get opcode and regclass for the given zero.
3143 const TargetRegisterClass *RC = nullptr;
3144 switch (VT.SimpleTy) {
3147 if (X86ScalarSSEf32) {
3148 Opc = X86::FsFLD0SS;
3149 RC = &X86::FR32RegClass;
3151 Opc = X86::LD_Fp032;
3152 RC = &X86::RFP32RegClass;
3156 if (X86ScalarSSEf64) {
3157 Opc = X86::FsFLD0SD;
3158 RC = &X86::FR64RegClass;
3160 Opc = X86::LD_Fp064;
3161 RC = &X86::RFP64RegClass;
3165 // No f80 support yet.
3169 unsigned ResultReg = createResultReg(RC);
3170 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3175 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3176 const LoadInst *LI) {
3177 const Value *Ptr = LI->getPointerOperand();
3179 if (!X86SelectAddress(Ptr, AM))
3182 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3184 unsigned Size = DL.getTypeAllocSize(LI->getType());
3185 unsigned Alignment = LI->getAlignment();
3187 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3188 Alignment = DL.getABITypeAlignment(LI->getType());
3190 SmallVector<MachineOperand, 8> AddrOps;
3191 AM.getFullAddress(AddrOps);
3193 MachineInstr *Result =
3194 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3198 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3199 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3200 MI->eraseFromParent();
3206 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3207 const TargetLibraryInfo *libInfo) {
3208 return new X86FastISel(funcInfo, libInfo);