blob: 4eec15779a1af96b4a865ab01a3cda72c6cd003a [file] [log] [blame]
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001//===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
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"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000025#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/IR/CallSite.h"
31#include "llvm/IR/CallingConv.h"
Reid Kleckner28865802016-04-14 18:29:59 +000032#include "llvm/IR/DebugInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000033#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"
David Majnemerca194852015-02-10 22:00:34 +000040#include "llvm/MC/MCAsmInfo.h"
Rafael Espindolace4c2bc2015-06-23 12:21:54 +000041#include "llvm/MC/MCSymbol.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000042#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Target/TargetOptions.h"
44using namespace llvm;
45
46namespace {
47
48class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
52
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
57 bool X86ScalarSSEf64;
58 bool X86ScalarSSEf32;
59
60public:
61 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62 const TargetLibraryInfo *libInfo)
Eric Christophera1c535b2015-02-02 23:03:45 +000063 : FastISel(funcInfo, libInfo) {
64 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000065 X86ScalarSSEf64 = Subtarget->hasSSE2();
66 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 }
68
69 bool fastSelectInstruction(const Instruction *I) override;
70
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
74 /// possible.
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
77
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81
82#include "X86GenFastISel.inc"
83
84private:
Benjamin Kramerbdc49562016-06-12 15:39:02 +000085 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
86 const DebugLoc &DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000087
Pete Cooperd0dae3e2015-05-05 23:41:53 +000088 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000089 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000090
Pete Cooperd0dae3e2015-05-05 23:41:53 +000091 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000092 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000094 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000095 MachineMemOperand *MMO = nullptr, bool Aligned = false);
96
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 unsigned &ResultReg);
99
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102
103 bool X86SelectLoad(const Instruction *I);
104
105 bool X86SelectStore(const Instruction *I);
106
107 bool X86SelectRet(const Instruction *I);
108
109 bool X86SelectCmp(const Instruction *I);
110
111 bool X86SelectZExt(const Instruction *I);
112
113 bool X86SelectBranch(const Instruction *I);
114
115 bool X86SelectShift(const Instruction *I);
116
117 bool X86SelectDivRem(const Instruction *I);
118
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
120
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
122
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
124
125 bool X86SelectSelect(const Instruction *I);
126
127 bool X86SelectTrunc(const Instruction *I);
128
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
131
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000134 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000135
136 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000137 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000138 }
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
141 }
142
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
144
145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148 unsigned fastMaterializeConstant(const Constant *C) override;
149
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
151
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
153
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159 }
160
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
162
163 bool IsMemcpySmall(uint64_t Len);
164
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
167
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
169 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000170
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
172 X86AddressMode &AM);
Craig Topper7ef6ea32016-12-05 04:51:31 +0000173
174 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
175 const TargetRegisterClass *RC, unsigned Op0,
176 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
177 unsigned Op2, bool Op2IsKill, unsigned Op3,
178 bool Op3IsKill);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000179};
180
181} // end anonymous namespace.
182
183static std::pair<X86::CondCode, bool>
184getX86ConditionCode(CmpInst::Predicate Predicate) {
185 X86::CondCode CC = X86::COND_INVALID;
186 bool NeedSwap = false;
187 switch (Predicate) {
188 default: break;
189 // Floating-point Predicates
190 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000191 case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000192 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000193 case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000194 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000195 case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000196 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000197 case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000198 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
199 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
200 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
201 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000202 case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000203 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
204
205 // Integer Predicates
206 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
207 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
208 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
209 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
210 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
211 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
212 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
213 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
214 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
215 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
216 }
217
218 return std::make_pair(CC, NeedSwap);
219}
220
221static std::pair<unsigned, bool>
222getX86SSEConditionCode(CmpInst::Predicate Predicate) {
223 unsigned CC;
224 bool NeedSwap = false;
225
226 // SSE Condition code mapping:
227 // 0 - EQ
228 // 1 - LT
229 // 2 - LE
230 // 3 - UNORD
231 // 4 - NEQ
232 // 5 - NLT
233 // 6 - NLE
234 // 7 - ORD
235 switch (Predicate) {
236 default: llvm_unreachable("Unexpected predicate");
237 case CmpInst::FCMP_OEQ: CC = 0; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000238 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000239 case CmpInst::FCMP_OLT: CC = 1; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000240 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000241 case CmpInst::FCMP_OLE: CC = 2; break;
242 case CmpInst::FCMP_UNO: CC = 3; break;
243 case CmpInst::FCMP_UNE: CC = 4; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000244 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000245 case CmpInst::FCMP_UGE: CC = 5; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000246 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000247 case CmpInst::FCMP_UGT: CC = 6; break;
248 case CmpInst::FCMP_ORD: CC = 7; break;
249 case CmpInst::FCMP_UEQ:
250 case CmpInst::FCMP_ONE: CC = 8; break;
251 }
252
253 return std::make_pair(CC, NeedSwap);
254}
255
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000256/// \brief Adds a complex addressing mode to the given machine instr builder.
257/// Note, this will constrain the index register. If its not possible to
258/// constrain the given index register, then a new one will be created. The
259/// IndexReg field of the addressing mode will be updated to match in this case.
260const MachineInstrBuilder &
261X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
262 X86AddressMode &AM) {
263 // First constrain the index register. It needs to be a GR64_NOSP.
264 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
265 MIB->getNumOperands() +
266 X86::AddrIndexReg);
267 return ::addFullAddress(MIB, AM);
268}
269
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000270/// \brief Check if it is possible to fold the condition from the XALU intrinsic
271/// into the user. The condition code will only be updated on success.
272bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
273 const Value *Cond) {
274 if (!isa<ExtractValueInst>(Cond))
275 return false;
276
277 const auto *EV = cast<ExtractValueInst>(Cond);
278 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
279 return false;
280
281 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
282 MVT RetVT;
283 const Function *Callee = II->getCalledFunction();
284 Type *RetTy =
285 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
286 if (!isTypeLegal(RetTy, RetVT))
287 return false;
288
289 if (RetVT != MVT::i32 && RetVT != MVT::i64)
290 return false;
291
292 X86::CondCode TmpCC;
293 switch (II->getIntrinsicID()) {
294 default: return false;
295 case Intrinsic::sadd_with_overflow:
296 case Intrinsic::ssub_with_overflow:
297 case Intrinsic::smul_with_overflow:
298 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
299 case Intrinsic::uadd_with_overflow:
300 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
301 }
302
303 // Check if both instructions are in the same basic block.
304 if (II->getParent() != I->getParent())
305 return false;
306
307 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000308 BasicBlock::const_iterator Start(I);
309 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000310 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
311 // We only expect extractvalue instructions between the intrinsic and the
312 // instruction to be selected.
313 if (!isa<ExtractValueInst>(Itr))
314 return false;
315
316 // Check that the extractvalue operand comes from the intrinsic.
317 const auto *EVI = cast<ExtractValueInst>(Itr);
318 if (EVI->getAggregateOperand() != II)
319 return false;
320 }
321
322 CC = TmpCC;
323 return true;
324}
325
326bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000327 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000328 if (evt == MVT::Other || !evt.isSimple())
329 // Unhandled type. Halt "fast" selection and bail.
330 return false;
331
332 VT = evt.getSimpleVT();
333 // For now, require SSE/SSE2 for performing floating-point operations,
334 // since x87 requires additional work.
335 if (VT == MVT::f64 && !X86ScalarSSEf64)
336 return false;
337 if (VT == MVT::f32 && !X86ScalarSSEf32)
338 return false;
339 // Similarly, no f80 support yet.
340 if (VT == MVT::f80)
341 return false;
342 // We only handle legal types. For example, on x86-32 the instruction
343 // selector contains all of the 64-bit instructions from x86-64,
344 // under the assumption that i64 won't be used if the target doesn't
345 // support it.
346 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
347}
348
349#include "X86GenCallingConv.inc"
350
351/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
352/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
353/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000354bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000355 MachineMemOperand *MMO, unsigned &ResultReg,
356 unsigned Alignment) {
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000357 bool HasSSE41 = Subtarget->hasSSE41();
Craig Topperca9c0802016-06-02 04:19:45 +0000358 bool HasAVX = Subtarget->hasAVX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000359 bool HasAVX2 = Subtarget->hasAVX2();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000360 bool HasAVX512 = Subtarget->hasAVX512();
361 bool HasVLX = Subtarget->hasVLX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000362 bool IsNonTemporal = MMO && MMO->isNonTemporal();
363
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000364 // Get opcode and regclass of the output for the given load instruction.
365 unsigned Opc = 0;
366 const TargetRegisterClass *RC = nullptr;
367 switch (VT.getSimpleVT().SimpleTy) {
368 default: return false;
369 case MVT::i1:
370 case MVT::i8:
371 Opc = X86::MOV8rm;
372 RC = &X86::GR8RegClass;
373 break;
374 case MVT::i16:
375 Opc = X86::MOV16rm;
376 RC = &X86::GR16RegClass;
377 break;
378 case MVT::i32:
379 Opc = X86::MOV32rm;
380 RC = &X86::GR32RegClass;
381 break;
382 case MVT::i64:
383 // Must be in x86-64 mode.
384 Opc = X86::MOV64rm;
385 RC = &X86::GR64RegClass;
386 break;
387 case MVT::f32:
388 if (X86ScalarSSEf32) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000389 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000390 RC = &X86::FR32RegClass;
391 } else {
392 Opc = X86::LD_Fp32m;
393 RC = &X86::RFP32RegClass;
394 }
395 break;
396 case MVT::f64:
397 if (X86ScalarSSEf64) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000398 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000399 RC = &X86::FR64RegClass;
400 } else {
401 Opc = X86::LD_Fp64m;
402 RC = &X86::RFP64RegClass;
403 }
404 break;
405 case MVT::f80:
406 // No f80 support yet.
407 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000408 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000409 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000410 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
411 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000412 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000413 Opc = HasVLX ? X86::VMOVAPSZ128rm :
414 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000415 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000416 Opc = HasVLX ? X86::VMOVUPSZ128rm :
417 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000418 RC = &X86::VR128RegClass;
419 break;
420 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000421 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000422 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
423 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000424 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000425 Opc = HasVLX ? X86::VMOVAPDZ128rm :
426 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000427 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000428 Opc = HasVLX ? X86::VMOVUPDZ128rm :
429 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000430 RC = &X86::VR128RegClass;
431 break;
432 case MVT::v4i32:
433 case MVT::v2i64:
434 case MVT::v8i16:
435 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000436 if (IsNonTemporal && Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000437 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
438 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000439 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000440 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
441 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000442 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000443 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
444 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000445 RC = &X86::VR128RegClass;
446 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000447 case MVT::v8f32:
448 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000449 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000450 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
451 else if (Alignment >= 32)
452 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000453 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000454 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000455 RC = &X86::VR256RegClass;
456 break;
457 case MVT::v4f64:
458 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000459 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
460 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000461 else if (Alignment >= 32)
462 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000463 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000464 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000465 RC = &X86::VR256RegClass;
466 break;
467 case MVT::v8i32:
468 case MVT::v4i64:
469 case MVT::v16i16:
470 case MVT::v32i8:
471 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000472 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
473 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000474 else if (Alignment >= 32)
475 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000476 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000477 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000478 RC = &X86::VR256RegClass;
479 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000480 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000481 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000482 if (IsNonTemporal && Alignment >= 64)
483 Opc = X86::VMOVNTDQAZrm;
484 else
485 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000486 RC = &X86::VR512RegClass;
487 break;
488 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000489 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000490 if (IsNonTemporal && Alignment >= 64)
491 Opc = X86::VMOVNTDQAZrm;
492 else
493 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000494 RC = &X86::VR512RegClass;
495 break;
496 case MVT::v8i64:
497 case MVT::v16i32:
498 case MVT::v32i16:
499 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000500 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000501 // Note: There are a lot more choices based on type with AVX-512, but
502 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000503 if (IsNonTemporal && Alignment >= 64)
504 Opc = X86::VMOVNTDQAZrm;
505 else
506 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000507 RC = &X86::VR512RegClass;
508 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000509 }
510
511 ResultReg = createResultReg(RC);
512 MachineInstrBuilder MIB =
513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
514 addFullAddress(MIB, AM);
515 if (MMO)
516 MIB->addMemOperand(*FuncInfo.MF, MMO);
517 return true;
518}
519
520/// X86FastEmitStore - Emit a machine instruction to store a value Val of
521/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
522/// and a displacement offset, or a GlobalAddress,
523/// i.e. V. Return true if it is possible.
524bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000525 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000526 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000527 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000528 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000529 bool HasAVX = Subtarget->hasAVX();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000530 bool HasAVX512 = Subtarget->hasAVX512();
531 bool HasVLX = Subtarget->hasVLX();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000532 bool IsNonTemporal = MMO && MMO->isNonTemporal();
533
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000534 // Get opcode and regclass of the output for the given store instruction.
535 unsigned Opc = 0;
536 switch (VT.getSimpleVT().SimpleTy) {
537 case MVT::f80: // No f80 support yet.
538 default: return false;
539 case MVT::i1: {
540 // Mask out all but lowest bit.
541 unsigned AndResult = createResultReg(&X86::GR8RegClass);
542 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
543 TII.get(X86::AND8ri), AndResult)
544 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
545 ValReg = AndResult;
Justin Bognerb03fd122016-08-17 05:10:15 +0000546 LLVM_FALLTHROUGH; // handle i1 as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000547 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000548 case MVT::i8: Opc = X86::MOV8mr; break;
549 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000550 case MVT::i32:
551 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
552 break;
553 case MVT::i64:
554 // Must be in x86-64 mode.
555 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
556 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000557 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000558 if (X86ScalarSSEf32) {
559 if (IsNonTemporal && HasSSE4A)
560 Opc = X86::MOVNTSS;
561 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000562 Opc = HasAVX512 ? X86::VMOVSSZmr :
563 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000564 } else
565 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000566 break;
567 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000568 if (X86ScalarSSEf32) {
569 if (IsNonTemporal && HasSSE4A)
570 Opc = X86::MOVNTSD;
571 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000572 Opc = HasAVX512 ? X86::VMOVSDZmr :
573 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000574 } else
575 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000576 break;
577 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000578 if (Aligned) {
579 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000580 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
581 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000582 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000583 Opc = HasVLX ? X86::VMOVAPSZ128mr :
584 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000585 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000586 Opc = HasVLX ? X86::VMOVUPSZ128mr :
587 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000588 break;
589 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000590 if (Aligned) {
591 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000592 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
593 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000594 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000595 Opc = HasVLX ? X86::VMOVAPDZ128mr :
596 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000597 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000598 Opc = HasVLX ? X86::VMOVUPDZ128mr :
599 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000600 break;
601 case MVT::v4i32:
602 case MVT::v2i64:
603 case MVT::v8i16:
604 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000605 if (Aligned) {
606 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000607 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
608 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000609 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000610 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
611 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000612 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000613 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
614 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000615 break;
616 case MVT::v8f32:
617 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000618 if (Aligned) {
619 if (IsNonTemporal)
620 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
621 else
622 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
623 } else
624 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000625 break;
626 case MVT::v4f64:
627 assert(HasAVX);
628 if (Aligned) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000629 if (IsNonTemporal)
630 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
631 else
632 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000633 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000634 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000635 break;
636 case MVT::v8i32:
637 case MVT::v4i64:
638 case MVT::v16i16:
639 case MVT::v32i8:
640 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000641 if (Aligned) {
642 if (IsNonTemporal)
643 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
644 else
645 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
646 } else
647 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000648 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000649 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000650 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000651 if (Aligned)
652 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
653 else
654 Opc = X86::VMOVUPSZmr;
655 break;
656 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000657 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000658 if (Aligned) {
659 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
660 } else
661 Opc = X86::VMOVUPDZmr;
662 break;
663 case MVT::v8i64:
664 case MVT::v16i32:
665 case MVT::v32i16:
666 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000667 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000668 // Note: There are a lot more choices based on type with AVX-512, but
669 // there's really no advantage when the store isn't masked.
670 if (Aligned)
671 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
672 else
673 Opc = X86::VMOVDQU64Zmr;
674 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000675 }
676
Quentin Colombetbf200682016-04-27 22:33:42 +0000677 const MCInstrDesc &Desc = TII.get(Opc);
678 // Some of the instructions in the previous switch use FR128 instead
679 // of FR32 for ValReg. Make sure the register we feed the instruction
680 // matches its register class constraints.
681 // Note: This is fine to do a copy from FR32 to FR128, this is the
682 // same registers behind the scene and actually why it did not trigger
683 // any bugs before.
684 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000685 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000687 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
688 if (MMO)
689 MIB->addMemOperand(*FuncInfo.MF, MMO);
690
691 return true;
692}
693
694bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000695 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000696 MachineMemOperand *MMO, bool Aligned) {
697 // Handle 'null' like i32/i64 0.
698 if (isa<ConstantPointerNull>(Val))
699 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
700
701 // If this is a store of a simple constant, fold the constant into the store.
702 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
703 unsigned Opc = 0;
704 bool Signed = true;
705 switch (VT.getSimpleVT().SimpleTy) {
706 default: break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000707 case MVT::i1:
708 Signed = false;
709 LLVM_FALLTHROUGH; // Handle as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000710 case MVT::i8: Opc = X86::MOV8mi; break;
711 case MVT::i16: Opc = X86::MOV16mi; break;
712 case MVT::i32: Opc = X86::MOV32mi; break;
713 case MVT::i64:
714 // Must be a 32-bit sign extended value.
715 if (isInt<32>(CI->getSExtValue()))
716 Opc = X86::MOV64mi32;
717 break;
718 }
719
720 if (Opc) {
721 MachineInstrBuilder MIB =
722 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
723 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
724 : CI->getZExtValue());
725 if (MMO)
726 MIB->addMemOperand(*FuncInfo.MF, MMO);
727 return true;
728 }
729 }
730
731 unsigned ValReg = getRegForValue(Val);
732 if (ValReg == 0)
733 return false;
734
735 bool ValKill = hasTrivialKill(Val);
736 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
737}
738
739/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
740/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
741/// ISD::SIGN_EXTEND).
742bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
743 unsigned Src, EVT SrcVT,
744 unsigned &ResultReg) {
745 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
746 Src, /*TODO: Kill=*/false);
747 if (RR == 0)
748 return false;
749
750 ResultReg = RR;
751 return true;
752}
753
754bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
755 // Handle constant address.
756 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
757 // Can't handle alternate code models yet.
758 if (TM.getCodeModel() != CodeModel::Small)
759 return false;
760
761 // Can't handle TLS yet.
762 if (GV->isThreadLocal())
763 return false;
764
765 // RIP-relative addresses can't have additional register operands, so if
766 // we've already folded stuff into the addressing mode, just force the
767 // global value into its own register, which we can use as the basereg.
768 if (!Subtarget->isPICStyleRIPRel() ||
769 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
770 // Okay, we've committed to selecting this global. Set up the address.
771 AM.GV = GV;
772
773 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000774 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000775
776 // If this reference is relative to the pic base, set it now.
777 if (isGlobalRelativeToPICBase(GVFlags)) {
778 // FIXME: How do we know Base.Reg is free??
779 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
780 }
781
782 // Unless the ABI requires an extra load, return a direct reference to
783 // the global.
784 if (!isGlobalStubReference(GVFlags)) {
785 if (Subtarget->isPICStyleRIPRel()) {
786 // Use rip-relative addressing if we can. Above we verified that the
787 // base and index registers are unused.
788 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
789 AM.Base.Reg = X86::RIP;
790 }
791 AM.GVOpFlags = GVFlags;
792 return true;
793 }
794
795 // Ok, we need to do a load from a stub. If we've already loaded from
796 // this stub, reuse the loaded pointer, otherwise emit the load now.
797 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
798 unsigned LoadReg;
799 if (I != LocalValueMap.end() && I->second != 0) {
800 LoadReg = I->second;
801 } else {
802 // Issue load from stub.
803 unsigned Opc = 0;
804 const TargetRegisterClass *RC = nullptr;
805 X86AddressMode StubAM;
806 StubAM.Base.Reg = AM.Base.Reg;
807 StubAM.GV = GV;
808 StubAM.GVOpFlags = GVFlags;
809
810 // Prepare for inserting code in the local-value area.
811 SavePoint SaveInsertPt = enterLocalValueArea();
812
Mehdi Amini44ede332015-07-09 02:09:04 +0000813 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000814 Opc = X86::MOV64rm;
815 RC = &X86::GR64RegClass;
816
817 if (Subtarget->isPICStyleRIPRel())
818 StubAM.Base.Reg = X86::RIP;
819 } else {
820 Opc = X86::MOV32rm;
821 RC = &X86::GR32RegClass;
822 }
823
824 LoadReg = createResultReg(RC);
825 MachineInstrBuilder LoadMI =
826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
827 addFullAddress(LoadMI, StubAM);
828
829 // Ok, back to normal mode.
830 leaveLocalValueArea(SaveInsertPt);
831
832 // Prevent loading GV stub multiple times in same MBB.
833 LocalValueMap[V] = LoadReg;
834 }
835
836 // Now construct the final address. Note that the Disp, Scale,
837 // and Index values may already be set here.
838 AM.Base.Reg = LoadReg;
839 AM.GV = nullptr;
840 return true;
841 }
842 }
843
844 // If all else fails, try to materialize the value in a register.
845 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
846 if (AM.Base.Reg == 0) {
847 AM.Base.Reg = getRegForValue(V);
848 return AM.Base.Reg != 0;
849 }
850 if (AM.IndexReg == 0) {
851 assert(AM.Scale == 1 && "Scale with no index!");
852 AM.IndexReg = getRegForValue(V);
853 return AM.IndexReg != 0;
854 }
855 }
856
857 return false;
858}
859
860/// X86SelectAddress - Attempt to fill in an address from the given value.
861///
862bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
863 SmallVector<const Value *, 32> GEPs;
864redo_gep:
865 const User *U = nullptr;
866 unsigned Opcode = Instruction::UserOp1;
867 if (const Instruction *I = dyn_cast<Instruction>(V)) {
868 // Don't walk into other basic blocks; it's possible we haven't
869 // visited them yet, so the instructions may not yet be assigned
870 // virtual registers.
871 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
872 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
873 Opcode = I->getOpcode();
874 U = I;
875 }
876 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
877 Opcode = C->getOpcode();
878 U = C;
879 }
880
881 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
882 if (Ty->getAddressSpace() > 255)
883 // Fast instruction selection doesn't support the special
884 // address spaces.
885 return false;
886
887 switch (Opcode) {
888 default: break;
889 case Instruction::BitCast:
890 // Look past bitcasts.
891 return X86SelectAddress(U->getOperand(0), AM);
892
893 case Instruction::IntToPtr:
894 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000895 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
896 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000897 return X86SelectAddress(U->getOperand(0), AM);
898 break;
899
900 case Instruction::PtrToInt:
901 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000902 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000903 return X86SelectAddress(U->getOperand(0), AM);
904 break;
905
906 case Instruction::Alloca: {
907 // Do static allocas.
908 const AllocaInst *A = cast<AllocaInst>(V);
909 DenseMap<const AllocaInst *, int>::iterator SI =
910 FuncInfo.StaticAllocaMap.find(A);
911 if (SI != FuncInfo.StaticAllocaMap.end()) {
912 AM.BaseType = X86AddressMode::FrameIndexBase;
913 AM.Base.FrameIndex = SI->second;
914 return true;
915 }
916 break;
917 }
918
919 case Instruction::Add: {
920 // Adds of constants are common and easy enough.
921 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
922 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
923 // They have to fit in the 32-bit signed displacement field though.
924 if (isInt<32>(Disp)) {
925 AM.Disp = (uint32_t)Disp;
926 return X86SelectAddress(U->getOperand(0), AM);
927 }
928 }
929 break;
930 }
931
932 case Instruction::GetElementPtr: {
933 X86AddressMode SavedAM = AM;
934
935 // Pattern-match simple GEPs.
936 uint64_t Disp = (int32_t)AM.Disp;
937 unsigned IndexReg = AM.IndexReg;
938 unsigned Scale = AM.Scale;
939 gep_type_iterator GTI = gep_type_begin(U);
940 // Iterate through the indices, folding what we can. Constants can be
941 // folded, and one dynamic index can be handled, if the scale is supported.
942 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
943 i != e; ++i, ++GTI) {
944 const Value *Op = *i;
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000945 if (StructType *STy = GTI.getStructTypeOrNull()) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000946 const StructLayout *SL = DL.getStructLayout(STy);
947 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
948 continue;
949 }
950
951 // A array/variable index is always of the form i*S where S is the
952 // constant scale size. See if we can push the scale into immediates.
953 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
954 for (;;) {
955 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
956 // Constant-offset addressing.
957 Disp += CI->getSExtValue() * S;
958 break;
959 }
960 if (canFoldAddIntoGEP(U, Op)) {
961 // A compatible add with a constant operand. Fold the constant.
962 ConstantInt *CI =
963 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
964 Disp += CI->getSExtValue() * S;
965 // Iterate on the other operand.
966 Op = cast<AddOperator>(Op)->getOperand(0);
967 continue;
968 }
969 if (IndexReg == 0 &&
970 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
971 (S == 1 || S == 2 || S == 4 || S == 8)) {
972 // Scaled-index addressing.
973 Scale = S;
974 IndexReg = getRegForGEPIndex(Op).first;
975 if (IndexReg == 0)
976 return false;
977 break;
978 }
979 // Unsupported.
980 goto unsupported_gep;
981 }
982 }
983
984 // Check for displacement overflow.
985 if (!isInt<32>(Disp))
986 break;
987
988 AM.IndexReg = IndexReg;
989 AM.Scale = Scale;
990 AM.Disp = (uint32_t)Disp;
991 GEPs.push_back(V);
992
993 if (const GetElementPtrInst *GEP =
994 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
995 // Ok, the GEP indices were covered by constant-offset and scaled-index
996 // addressing. Update the address state and move on to examining the base.
997 V = GEP;
998 goto redo_gep;
999 } else if (X86SelectAddress(U->getOperand(0), AM)) {
1000 return true;
1001 }
1002
1003 // If we couldn't merge the gep value into this addr mode, revert back to
1004 // our address and just match the value instead of completely failing.
1005 AM = SavedAM;
1006
David Majnemerd7708772016-06-24 04:05:21 +00001007 for (const Value *I : reverse(GEPs))
1008 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001009 return true;
1010
1011 return false;
1012 unsupported_gep:
1013 // Ok, the GEP indices weren't all covered.
1014 break;
1015 }
1016 }
1017
1018 return handleConstantAddresses(V, AM);
1019}
1020
1021/// X86SelectCallAddress - Attempt to fill in an address from the given value.
1022///
1023bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1024 const User *U = nullptr;
1025 unsigned Opcode = Instruction::UserOp1;
1026 const Instruction *I = dyn_cast<Instruction>(V);
1027 // Record if the value is defined in the same basic block.
1028 //
1029 // This information is crucial to know whether or not folding an
1030 // operand is valid.
1031 // Indeed, FastISel generates or reuses a virtual register for all
1032 // operands of all instructions it selects. Obviously, the definition and
1033 // its uses must use the same virtual register otherwise the produced
1034 // code is incorrect.
1035 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1036 // registers for values that are alive across basic blocks. This ensures
1037 // that the values are consistently set between across basic block, even
1038 // if different instruction selection mechanisms are used (e.g., a mix of
1039 // SDISel and FastISel).
1040 // For values local to a basic block, the instruction selection process
1041 // generates these virtual registers with whatever method is appropriate
1042 // for its needs. In particular, FastISel and SDISel do not share the way
1043 // local virtual registers are set.
1044 // Therefore, this is impossible (or at least unsafe) to share values
1045 // between basic blocks unless they use the same instruction selection
1046 // method, which is not guarantee for X86.
1047 // Moreover, things like hasOneUse could not be used accurately, if we
1048 // allow to reference values across basic blocks whereas they are not
1049 // alive across basic blocks initially.
1050 bool InMBB = true;
1051 if (I) {
1052 Opcode = I->getOpcode();
1053 U = I;
1054 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1055 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1056 Opcode = C->getOpcode();
1057 U = C;
1058 }
1059
1060 switch (Opcode) {
1061 default: break;
1062 case Instruction::BitCast:
1063 // Look past bitcasts if its operand is in the same BB.
1064 if (InMBB)
1065 return X86SelectCallAddress(U->getOperand(0), AM);
1066 break;
1067
1068 case Instruction::IntToPtr:
1069 // Look past no-op inttoptrs if its operand is in the same BB.
1070 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001071 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1072 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001073 return X86SelectCallAddress(U->getOperand(0), AM);
1074 break;
1075
1076 case Instruction::PtrToInt:
1077 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001078 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001079 return X86SelectCallAddress(U->getOperand(0), AM);
1080 break;
1081 }
1082
1083 // Handle constant address.
1084 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1085 // Can't handle alternate code models yet.
1086 if (TM.getCodeModel() != CodeModel::Small)
1087 return false;
1088
1089 // RIP-relative addresses can't have additional register operands.
1090 if (Subtarget->isPICStyleRIPRel() &&
1091 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1092 return false;
1093
1094 // Can't handle DLL Import.
1095 if (GV->hasDLLImportStorageClass())
1096 return false;
1097
1098 // Can't handle TLS.
1099 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1100 if (GVar->isThreadLocal())
1101 return false;
1102
1103 // Okay, we've committed to selecting this global. Set up the basic address.
1104 AM.GV = GV;
1105
1106 // No ABI requires an extra load for anything other than DLLImport, which
1107 // we rejected above. Return a direct reference to the global.
1108 if (Subtarget->isPICStyleRIPRel()) {
1109 // Use rip-relative addressing if we can. Above we verified that the
1110 // base and index registers are unused.
1111 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1112 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001113 } else {
1114 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001115 }
1116
1117 return true;
1118 }
1119
1120 // If all else fails, try to materialize the value in a register.
1121 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1122 if (AM.Base.Reg == 0) {
1123 AM.Base.Reg = getRegForValue(V);
1124 return AM.Base.Reg != 0;
1125 }
1126 if (AM.IndexReg == 0) {
1127 assert(AM.Scale == 1 && "Scale with no index!");
1128 AM.IndexReg = getRegForValue(V);
1129 return AM.IndexReg != 0;
1130 }
1131 }
1132
1133 return false;
1134}
1135
1136
1137/// X86SelectStore - Select and emit code to implement store instructions.
1138bool X86FastISel::X86SelectStore(const Instruction *I) {
1139 // Atomic stores need special handling.
1140 const StoreInst *S = cast<StoreInst>(I);
1141
1142 if (S->isAtomic())
1143 return false;
1144
Manman Ren57518142016-04-11 21:08:06 +00001145 const Value *PtrV = I->getOperand(1);
1146 if (TLI.supportSwiftError()) {
1147 // Swifterror values can come from either a function parameter with
1148 // swifterror attribute or an alloca with swifterror attribute.
1149 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1150 if (Arg->hasSwiftErrorAttr())
1151 return false;
1152 }
1153
1154 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1155 if (Alloca->isSwiftError())
1156 return false;
1157 }
1158 }
1159
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001160 const Value *Val = S->getValueOperand();
1161 const Value *Ptr = S->getPointerOperand();
1162
1163 MVT VT;
1164 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1165 return false;
1166
1167 unsigned Alignment = S->getAlignment();
1168 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1169 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1170 Alignment = ABIAlignment;
1171 bool Aligned = Alignment >= ABIAlignment;
1172
1173 X86AddressMode AM;
1174 if (!X86SelectAddress(Ptr, AM))
1175 return false;
1176
1177 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1178}
1179
1180/// X86SelectRet - Select and emit code to implement ret instructions.
1181bool X86FastISel::X86SelectRet(const Instruction *I) {
1182 const ReturnInst *Ret = cast<ReturnInst>(I);
1183 const Function &F = *I->getParent()->getParent();
1184 const X86MachineFunctionInfo *X86MFInfo =
1185 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1186
1187 if (!FuncInfo.CanLowerReturn)
1188 return false;
1189
Manman Ren57518142016-04-11 21:08:06 +00001190 if (TLI.supportSwiftError() &&
1191 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1192 return false;
1193
Manman Rened967f32016-01-12 01:08:46 +00001194 if (TLI.supportSplitCSR(FuncInfo.MF))
1195 return false;
1196
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001197 CallingConv::ID CC = F.getCallingConv();
1198 if (CC != CallingConv::C &&
1199 CC != CallingConv::Fast &&
1200 CC != CallingConv::X86_FastCall &&
Nico Weberecdf45b2016-07-14 13:54:26 +00001201 CC != CallingConv::X86_StdCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001202 CC != CallingConv::X86_ThisCall &&
Nico Weber8d66df12016-07-15 20:18:37 +00001203 CC != CallingConv::X86_64_SysV &&
1204 CC != CallingConv::X86_64_Win64)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001205 return false;
1206
Nico Weberc7bf6462016-07-12 01:30:35 +00001207 // Don't handle popping bytes if they don't fit the ret's immediate.
1208 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001209 return false;
1210
1211 // fastcc with -tailcallopt is intended to provide a guaranteed
1212 // tail call optimization. Fastisel doesn't know how to do that.
1213 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1214 return false;
1215
1216 // Let SDISel handle vararg functions.
1217 if (F.isVarArg())
1218 return false;
1219
1220 // Build a list of return value registers.
1221 SmallVector<unsigned, 4> RetRegs;
1222
1223 if (Ret->getNumOperands() > 0) {
1224 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001225 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001226
1227 // Analyze operands of the call, assigning locations to each operand.
1228 SmallVector<CCValAssign, 16> ValLocs;
1229 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1230 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1231
1232 const Value *RV = Ret->getOperand(0);
1233 unsigned Reg = getRegForValue(RV);
1234 if (Reg == 0)
1235 return false;
1236
1237 // Only handle a single return value for now.
1238 if (ValLocs.size() != 1)
1239 return false;
1240
1241 CCValAssign &VA = ValLocs[0];
1242
1243 // Don't bother handling odd stuff for now.
1244 if (VA.getLocInfo() != CCValAssign::Full)
1245 return false;
1246 // Only handle register returns for now.
1247 if (!VA.isRegLoc())
1248 return false;
1249
1250 // The calling-convention tables for x87 returns don't tell
1251 // the whole story.
1252 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1253 return false;
1254
1255 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001256 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001257 EVT DstVT = VA.getValVT();
1258 // Special handling for extended integers.
1259 if (SrcVT != DstVT) {
1260 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1261 return false;
1262
1263 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1264 return false;
1265
1266 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1267
1268 if (SrcVT == MVT::i1) {
1269 if (Outs[0].Flags.isSExt())
1270 return false;
1271 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1272 SrcVT = MVT::i8;
1273 }
1274 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1275 ISD::SIGN_EXTEND;
1276 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1277 SrcReg, /*TODO: Kill=*/false);
1278 }
1279
1280 // Make the copy.
1281 unsigned DstReg = VA.getLocReg();
1282 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1283 // Avoid a cross-class copy. This is very unlikely.
1284 if (!SrcRC->contains(DstReg))
1285 return false;
1286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1287 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1288
1289 // Add register to return instruction.
1290 RetRegs.push_back(VA.getLocReg());
1291 }
1292
Manman Ren1c3f65a2016-04-26 18:08:06 +00001293 // Swift calling convention does not require we copy the sret argument
1294 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1295
Dimitry Andric227b9282016-01-03 17:22:03 +00001296 // All x86 ABIs require that for returning structs by value we copy
1297 // the sret argument into %rax/%eax (depending on ABI) for the return.
1298 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001299 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001300 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001301 unsigned Reg = X86MFInfo->getSRetReturnReg();
1302 assert(Reg &&
1303 "SRetReturnReg should have been set in LowerFormalArguments()!");
1304 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1306 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1307 RetRegs.push_back(RetReg);
1308 }
1309
1310 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001311 MachineInstrBuilder MIB;
1312 if (X86MFInfo->getBytesToPopOnReturn()) {
1313 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1314 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1315 .addImm(X86MFInfo->getBytesToPopOnReturn());
1316 } else {
1317 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1318 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1319 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001320 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1321 MIB.addReg(RetRegs[i], RegState::Implicit);
1322 return true;
1323}
1324
1325/// X86SelectLoad - Select and emit code to implement load instructions.
1326///
1327bool X86FastISel::X86SelectLoad(const Instruction *I) {
1328 const LoadInst *LI = cast<LoadInst>(I);
1329
1330 // Atomic loads need special handling.
1331 if (LI->isAtomic())
1332 return false;
1333
Manman Ren57518142016-04-11 21:08:06 +00001334 const Value *SV = I->getOperand(0);
1335 if (TLI.supportSwiftError()) {
1336 // Swifterror values can come from either a function parameter with
1337 // swifterror attribute or an alloca with swifterror attribute.
1338 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1339 if (Arg->hasSwiftErrorAttr())
1340 return false;
1341 }
1342
1343 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1344 if (Alloca->isSwiftError())
1345 return false;
1346 }
1347 }
1348
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001349 MVT VT;
1350 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1351 return false;
1352
1353 const Value *Ptr = LI->getPointerOperand();
1354
1355 X86AddressMode AM;
1356 if (!X86SelectAddress(Ptr, AM))
1357 return false;
1358
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001359 unsigned Alignment = LI->getAlignment();
1360 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1361 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1362 Alignment = ABIAlignment;
1363
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001364 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001365 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1366 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001367 return false;
1368
1369 updateValueMap(I, ResultReg);
1370 return true;
1371}
1372
1373static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1374 bool HasAVX = Subtarget->hasAVX();
1375 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1376 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1377
1378 switch (VT.getSimpleVT().SimpleTy) {
1379 default: return 0;
1380 case MVT::i8: return X86::CMP8rr;
1381 case MVT::i16: return X86::CMP16rr;
1382 case MVT::i32: return X86::CMP32rr;
1383 case MVT::i64: return X86::CMP64rr;
1384 case MVT::f32:
1385 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1386 case MVT::f64:
1387 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1388 }
1389}
1390
Rafael Espindola19141f22015-03-16 14:05:49 +00001391/// If we have a comparison with RHS as the RHS of the comparison, return an
1392/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001393static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001394 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001395 switch (VT.getSimpleVT().SimpleTy) {
1396 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001397 default:
1398 return 0;
1399 case MVT::i8:
1400 return X86::CMP8ri;
1401 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001402 if (isInt<8>(Val))
1403 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001404 return X86::CMP16ri;
1405 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001406 if (isInt<8>(Val))
1407 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001408 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001409 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001410 if (isInt<8>(Val))
1411 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001412 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1413 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001414 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001415 return X86::CMP64ri32;
1416 return 0;
1417 }
1418}
1419
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001420bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1421 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001422 unsigned Op0Reg = getRegForValue(Op0);
1423 if (Op0Reg == 0) return false;
1424
1425 // Handle 'null' like i32/i64 0.
1426 if (isa<ConstantPointerNull>(Op1))
1427 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1428
1429 // We have two options: compare with register or immediate. If the RHS of
1430 // the compare is an immediate that we can fold into this compare, use
1431 // CMPri, otherwise use CMPrr.
1432 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1433 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1435 .addReg(Op0Reg)
1436 .addImm(Op1C->getSExtValue());
1437 return true;
1438 }
1439 }
1440
1441 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1442 if (CompareOpc == 0) return false;
1443
1444 unsigned Op1Reg = getRegForValue(Op1);
1445 if (Op1Reg == 0) return false;
1446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1447 .addReg(Op0Reg)
1448 .addReg(Op1Reg);
1449
1450 return true;
1451}
1452
1453bool X86FastISel::X86SelectCmp(const Instruction *I) {
1454 const CmpInst *CI = cast<CmpInst>(I);
1455
1456 MVT VT;
1457 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1458 return false;
1459
Elena Demikhovskyad0a56f2016-07-06 14:15:43 +00001460 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1461 return false;
1462
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001463 // Try to optimize or fold the cmp.
1464 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1465 unsigned ResultReg = 0;
1466 switch (Predicate) {
1467 default: break;
1468 case CmpInst::FCMP_FALSE: {
1469 ResultReg = createResultReg(&X86::GR32RegClass);
1470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1471 ResultReg);
1472 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1473 X86::sub_8bit);
1474 if (!ResultReg)
1475 return false;
1476 break;
1477 }
1478 case CmpInst::FCMP_TRUE: {
1479 ResultReg = createResultReg(&X86::GR8RegClass);
1480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1481 ResultReg).addImm(1);
1482 break;
1483 }
1484 }
1485
1486 if (ResultReg) {
1487 updateValueMap(I, ResultReg);
1488 return true;
1489 }
1490
1491 const Value *LHS = CI->getOperand(0);
1492 const Value *RHS = CI->getOperand(1);
1493
1494 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1495 // We don't have to materialize a zero constant for this case and can just use
1496 // %x again on the RHS.
1497 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1498 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1499 if (RHSC && RHSC->isNullValue())
1500 RHS = LHS;
1501 }
1502
1503 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00001504 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001505 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1506 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1507 };
Craig Topper428169a2016-09-05 07:14:21 +00001508 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001509 switch (Predicate) {
1510 default: break;
1511 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1512 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1513 }
1514
1515 ResultReg = createResultReg(&X86::GR8RegClass);
1516 if (SETFOpc) {
1517 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1518 return false;
1519
1520 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1521 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1523 FlagReg1);
1524 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1525 FlagReg2);
1526 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1527 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1528 updateValueMap(I, ResultReg);
1529 return true;
1530 }
1531
1532 X86::CondCode CC;
1533 bool SwapArgs;
1534 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1535 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1536 unsigned Opc = X86::getSETFromCond(CC);
1537
1538 if (SwapArgs)
1539 std::swap(LHS, RHS);
1540
1541 // Emit a compare of LHS/RHS.
1542 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1543 return false;
1544
1545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1546 updateValueMap(I, ResultReg);
1547 return true;
1548}
1549
1550bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001551 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001552 if (!TLI.isTypeLegal(DstVT))
1553 return false;
1554
1555 unsigned ResultReg = getRegForValue(I->getOperand(0));
1556 if (ResultReg == 0)
1557 return false;
1558
1559 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001560 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Craig Topper088ba172016-12-05 06:09:55 +00001561 if (SrcVT == MVT::i1) {
Craig Topper58647b12017-03-12 03:37:37 +00001562 if (!Subtarget->is64Bit()) {
1563 // If this isn't a 64-bit target we need to constrain the reg class
1564 // to avoid high registers here otherwise we might use a high register
1565 // to copy from a mask register.
1566 unsigned OldReg = ResultReg;
1567 ResultReg = createResultReg(&X86::GR8_ABCD_LRegClass);
1568 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1569 TII.get(TargetOpcode::COPY), ResultReg)
1570 .addReg(OldReg);
1571 }
1572
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001573 // Set the high bits to zero.
1574 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1575 SrcVT = MVT::i8;
1576
1577 if (ResultReg == 0)
1578 return false;
1579 }
1580
1581 if (DstVT == MVT::i64) {
1582 // Handle extension to 64-bits via sub-register shenanigans.
1583 unsigned MovInst;
1584
1585 switch (SrcVT.SimpleTy) {
1586 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1587 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1588 case MVT::i32: MovInst = X86::MOV32rr; break;
1589 default: llvm_unreachable("Unexpected zext to i64 source type");
1590 }
1591
1592 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1594 .addReg(ResultReg);
1595
1596 ResultReg = createResultReg(&X86::GR64RegClass);
1597 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1598 ResultReg)
1599 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1600 } else if (DstVT != MVT::i8) {
1601 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1602 ResultReg, /*Kill=*/true);
1603 if (ResultReg == 0)
1604 return false;
1605 }
1606
1607 updateValueMap(I, ResultReg);
1608 return true;
1609}
1610
1611bool X86FastISel::X86SelectBranch(const Instruction *I) {
1612 // Unconditional branches are selected by tablegen-generated code.
1613 // Handle a conditional branch.
1614 const BranchInst *BI = cast<BranchInst>(I);
1615 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1616 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1617
1618 // Fold the common case of a conditional branch with a comparison
1619 // in the same block (values defined on other blocks may not have
1620 // initialized registers).
1621 X86::CondCode CC;
1622 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1623 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001624 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001625
1626 // Try to optimize or fold the cmp.
1627 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1628 switch (Predicate) {
1629 default: break;
1630 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1631 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1632 }
1633
1634 const Value *CmpLHS = CI->getOperand(0);
1635 const Value *CmpRHS = CI->getOperand(1);
1636
1637 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1638 // 0.0.
1639 // We don't have to materialize a zero constant for this case and can just
1640 // use %x again on the RHS.
1641 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1642 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1643 if (CmpRHSC && CmpRHSC->isNullValue())
1644 CmpRHS = CmpLHS;
1645 }
1646
1647 // Try to take advantage of fallthrough opportunities.
1648 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1649 std::swap(TrueMBB, FalseMBB);
1650 Predicate = CmpInst::getInversePredicate(Predicate);
1651 }
1652
1653 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1654 // code check. Instead two branch instructions are required to check all
1655 // the flags. First we change the predicate to a supported condition code,
1656 // which will be the first branch. Later one we will emit the second
1657 // branch.
1658 bool NeedExtraBranch = false;
1659 switch (Predicate) {
1660 default: break;
1661 case CmpInst::FCMP_OEQ:
Justin Bognerb03fd122016-08-17 05:10:15 +00001662 std::swap(TrueMBB, FalseMBB);
1663 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001664 case CmpInst::FCMP_UNE:
1665 NeedExtraBranch = true;
1666 Predicate = CmpInst::FCMP_ONE;
1667 break;
1668 }
1669
1670 bool SwapArgs;
1671 unsigned BranchOpc;
1672 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1673 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1674
1675 BranchOpc = X86::GetCondBranchFromCond(CC);
1676 if (SwapArgs)
1677 std::swap(CmpLHS, CmpRHS);
1678
1679 // Emit a compare of the LHS and RHS, setting the flags.
1680 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1681 return false;
1682
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1684 .addMBB(TrueMBB);
1685
1686 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1687 // to UNE above).
1688 if (NeedExtraBranch) {
1689 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1690 .addMBB(TrueMBB);
1691 }
1692
Matthias Braun17af6072015-08-26 01:38:00 +00001693 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001694 return true;
1695 }
1696 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1697 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1698 // typically happen for _Bool and C++ bools.
1699 MVT SourceVT;
1700 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1701 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1702 unsigned TestOpc = 0;
1703 switch (SourceVT.SimpleTy) {
1704 default: break;
1705 case MVT::i8: TestOpc = X86::TEST8ri; break;
1706 case MVT::i16: TestOpc = X86::TEST16ri; break;
1707 case MVT::i32: TestOpc = X86::TEST32ri; break;
1708 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1709 }
1710 if (TestOpc) {
1711 unsigned OpReg = getRegForValue(TI->getOperand(0));
1712 if (OpReg == 0) return false;
Guy Blank9ae797a2016-08-21 08:02:27 +00001713
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1715 .addReg(OpReg).addImm(1);
1716
1717 unsigned JmpOpc = X86::JNE_1;
1718 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1719 std::swap(TrueMBB, FalseMBB);
1720 JmpOpc = X86::JE_1;
1721 }
1722
1723 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1724 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001725
1726 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001727 return true;
1728 }
1729 }
1730 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1731 // Fake request the condition, otherwise the intrinsic might be completely
1732 // optimized away.
1733 unsigned TmpReg = getRegForValue(BI->getCondition());
1734 if (TmpReg == 0)
1735 return false;
1736
1737 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1738
1739 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1740 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001741 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001742 return true;
1743 }
1744
1745 // Otherwise do a clumsy setcc and re-test it.
1746 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1747 // in an explicit cast, so make sure to handle that correctly.
1748 unsigned OpReg = getRegForValue(BI->getCondition());
1749 if (OpReg == 0) return false;
1750
Guy Blank2bdc74a2016-09-28 11:22:17 +00001751 // In case OpReg is a K register, COPY to a GPR
1752 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1753 unsigned KOpReg = OpReg;
Craig Topper784f2412017-03-13 21:58:54 +00001754 OpReg = createResultReg(Subtarget->is64Bit() ? &X86::GR8RegClass
1755 : &X86::GR8_ABCD_LRegClass);
Guy Blank2bdc74a2016-09-28 11:22:17 +00001756 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1757 TII.get(TargetOpcode::COPY), OpReg)
1758 .addReg(KOpReg);
1759 }
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1761 .addReg(OpReg)
1762 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001763 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1764 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001765 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001766 return true;
1767}
1768
1769bool X86FastISel::X86SelectShift(const Instruction *I) {
1770 unsigned CReg = 0, OpReg = 0;
1771 const TargetRegisterClass *RC = nullptr;
1772 if (I->getType()->isIntegerTy(8)) {
1773 CReg = X86::CL;
1774 RC = &X86::GR8RegClass;
1775 switch (I->getOpcode()) {
1776 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1777 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1778 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1779 default: return false;
1780 }
1781 } else if (I->getType()->isIntegerTy(16)) {
1782 CReg = X86::CX;
1783 RC = &X86::GR16RegClass;
1784 switch (I->getOpcode()) {
1785 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1786 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1787 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1788 default: return false;
1789 }
1790 } else if (I->getType()->isIntegerTy(32)) {
1791 CReg = X86::ECX;
1792 RC = &X86::GR32RegClass;
1793 switch (I->getOpcode()) {
1794 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1795 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1796 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1797 default: return false;
1798 }
1799 } else if (I->getType()->isIntegerTy(64)) {
1800 CReg = X86::RCX;
1801 RC = &X86::GR64RegClass;
1802 switch (I->getOpcode()) {
1803 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1804 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1805 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1806 default: return false;
1807 }
1808 } else {
1809 return false;
1810 }
1811
1812 MVT VT;
1813 if (!isTypeLegal(I->getType(), VT))
1814 return false;
1815
1816 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1817 if (Op0Reg == 0) return false;
1818
1819 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1820 if (Op1Reg == 0) return false;
1821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1822 CReg).addReg(Op1Reg);
1823
1824 // The shift instruction uses X86::CL. If we defined a super-register
1825 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1826 if (CReg != X86::CL)
1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1828 TII.get(TargetOpcode::KILL), X86::CL)
1829 .addReg(CReg, RegState::Kill);
1830
1831 unsigned ResultReg = createResultReg(RC);
1832 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1833 .addReg(Op0Reg);
1834 updateValueMap(I, ResultReg);
1835 return true;
1836}
1837
1838bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1839 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1840 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1841 const static bool S = true; // IsSigned
1842 const static bool U = false; // !IsSigned
1843 const static unsigned Copy = TargetOpcode::COPY;
1844 // For the X86 DIV/IDIV instruction, in most cases the dividend
1845 // (numerator) must be in a specific register pair highreg:lowreg,
1846 // producing the quotient in lowreg and the remainder in highreg.
1847 // For most data types, to set up the instruction, the dividend is
1848 // copied into lowreg, and lowreg is sign-extended or zero-extended
1849 // into highreg. The exception is i8, where the dividend is defined
1850 // as a single register rather than a register pair, and we
1851 // therefore directly sign-extend or zero-extend the dividend into
1852 // lowreg, instead of copying, and ignore the highreg.
1853 const static struct DivRemEntry {
1854 // The following portion depends only on the data type.
1855 const TargetRegisterClass *RC;
1856 unsigned LowInReg; // low part of the register pair
1857 unsigned HighInReg; // high part of the register pair
1858 // The following portion depends on both the data type and the operation.
1859 struct DivRemResult {
1860 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1861 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1862 // highreg, or copying a zero into highreg.
1863 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1864 // zero/sign-extending into lowreg for i8.
1865 unsigned DivRemResultReg; // Register containing the desired result.
1866 bool IsOpSigned; // Whether to use signed or unsigned form.
1867 } ResultTable[NumOps];
1868 } OpTable[NumTypes] = {
1869 { &X86::GR8RegClass, X86::AX, 0, {
1870 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1871 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1872 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1873 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1874 }
1875 }, // i8
1876 { &X86::GR16RegClass, X86::AX, X86::DX, {
1877 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1878 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1879 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1880 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1881 }
1882 }, // i16
1883 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1884 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1885 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1886 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1887 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1888 }
1889 }, // i32
1890 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1891 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1892 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1893 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1894 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1895 }
1896 }, // i64
1897 };
1898
1899 MVT VT;
1900 if (!isTypeLegal(I->getType(), VT))
1901 return false;
1902
1903 unsigned TypeIndex, OpIndex;
1904 switch (VT.SimpleTy) {
1905 default: return false;
1906 case MVT::i8: TypeIndex = 0; break;
1907 case MVT::i16: TypeIndex = 1; break;
1908 case MVT::i32: TypeIndex = 2; break;
1909 case MVT::i64: TypeIndex = 3;
1910 if (!Subtarget->is64Bit())
1911 return false;
1912 break;
1913 }
1914
1915 switch (I->getOpcode()) {
1916 default: llvm_unreachable("Unexpected div/rem opcode");
1917 case Instruction::SDiv: OpIndex = 0; break;
1918 case Instruction::SRem: OpIndex = 1; break;
1919 case Instruction::UDiv: OpIndex = 2; break;
1920 case Instruction::URem: OpIndex = 3; break;
1921 }
1922
1923 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1924 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1925 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1926 if (Op0Reg == 0)
1927 return false;
1928 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1929 if (Op1Reg == 0)
1930 return false;
1931
1932 // Move op0 into low-order input register.
1933 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1934 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1935 // Zero-extend or sign-extend into high-order input register.
1936 if (OpEntry.OpSignExtend) {
1937 if (OpEntry.IsOpSigned)
1938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1939 TII.get(OpEntry.OpSignExtend));
1940 else {
1941 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1943 TII.get(X86::MOV32r0), Zero32);
1944
1945 // Copy the zero into the appropriate sub/super/identical physical
1946 // register. Unfortunately the operations needed are not uniform enough
1947 // to fit neatly into the table above.
Craig Topper088ba172016-12-05 06:09:55 +00001948 if (VT == MVT::i16) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1950 TII.get(Copy), TypeEntry.HighInReg)
1951 .addReg(Zero32, 0, X86::sub_16bit);
Craig Topper088ba172016-12-05 06:09:55 +00001952 } else if (VT == MVT::i32) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001953 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1954 TII.get(Copy), TypeEntry.HighInReg)
1955 .addReg(Zero32);
Craig Topper088ba172016-12-05 06:09:55 +00001956 } else if (VT == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1958 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1959 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1960 }
1961 }
1962 }
1963 // Generate the DIV/IDIV instruction.
1964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1965 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1966 // For i8 remainder, we can't reference AH directly, as we'll end
1967 // up with bogus copies like %R9B = COPY %AH. Reference AX
1968 // instead to prevent AH references in a REX instruction.
1969 //
1970 // The current assumption of the fast register allocator is that isel
1971 // won't generate explicit references to the GPR8_NOREX registers. If
1972 // the allocator and/or the backend get enhanced to be more robust in
1973 // that regard, this can be, and should be, removed.
1974 unsigned ResultReg = 0;
1975 if ((I->getOpcode() == Instruction::SRem ||
1976 I->getOpcode() == Instruction::URem) &&
1977 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1978 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1979 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1981 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1982
1983 // Shift AX right by 8 bits instead of using AH.
1984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1985 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1986
1987 // Now reference the 8-bit subreg of the result.
1988 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1989 /*Kill=*/true, X86::sub_8bit);
1990 }
1991 // Copy the result out of the physreg if we haven't already.
1992 if (!ResultReg) {
1993 ResultReg = createResultReg(TypeEntry.RC);
1994 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1995 .addReg(OpEntry.DivRemResultReg);
1996 }
1997 updateValueMap(I, ResultReg);
1998
1999 return true;
2000}
2001
2002/// \brief Emit a conditional move instruction (if the are supported) to lower
2003/// the select.
2004bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2005 // Check if the subtarget supports these instructions.
2006 if (!Subtarget->hasCMov())
2007 return false;
2008
2009 // FIXME: Add support for i8.
2010 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2011 return false;
2012
2013 const Value *Cond = I->getOperand(0);
2014 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2015 bool NeedTest = true;
2016 X86::CondCode CC = X86::COND_NE;
2017
2018 // Optimize conditions coming from a compare if both instructions are in the
2019 // same basic block (values defined in other basic blocks may not have
2020 // initialized registers).
2021 const auto *CI = dyn_cast<CmpInst>(Cond);
2022 if (CI && (CI->getParent() == I->getParent())) {
2023 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2024
2025 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00002026 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002027 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2028 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2029 };
Craig Topper428169a2016-09-05 07:14:21 +00002030 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002031 switch (Predicate) {
2032 default: break;
2033 case CmpInst::FCMP_OEQ:
2034 SETFOpc = &SETFOpcTable[0][0];
2035 Predicate = CmpInst::ICMP_NE;
2036 break;
2037 case CmpInst::FCMP_UNE:
2038 SETFOpc = &SETFOpcTable[1][0];
2039 Predicate = CmpInst::ICMP_NE;
2040 break;
2041 }
2042
2043 bool NeedSwap;
2044 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
2045 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2046
2047 const Value *CmpLHS = CI->getOperand(0);
2048 const Value *CmpRHS = CI->getOperand(1);
2049 if (NeedSwap)
2050 std::swap(CmpLHS, CmpRHS);
2051
Mehdi Amini44ede332015-07-09 02:09:04 +00002052 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002053 // Emit a compare of the LHS and RHS, setting the flags.
2054 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2055 return false;
2056
2057 if (SETFOpc) {
2058 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2059 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2060 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2061 FlagReg1);
2062 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2063 FlagReg2);
2064 auto const &II = TII.get(SETFOpc[2]);
2065 if (II.getNumDefs()) {
2066 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2068 .addReg(FlagReg2).addReg(FlagReg1);
2069 } else {
2070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2071 .addReg(FlagReg2).addReg(FlagReg1);
2072 }
2073 }
2074 NeedTest = false;
2075 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2076 // Fake request the condition, otherwise the intrinsic might be completely
2077 // optimized away.
2078 unsigned TmpReg = getRegForValue(Cond);
2079 if (TmpReg == 0)
2080 return false;
2081
2082 NeedTest = false;
2083 }
2084
2085 if (NeedTest) {
2086 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2087 // garbage. Indeed, only the less significant bit is supposed to be
2088 // accurate. If we read more than the lsb, we may see non-zero values
2089 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2090 // the select. This is achieved by performing TEST against 1.
2091 unsigned CondReg = getRegForValue(Cond);
2092 if (CondReg == 0)
2093 return false;
2094 bool CondIsKill = hasTrivialKill(Cond);
2095
Guy Blank2bdc74a2016-09-28 11:22:17 +00002096 // In case OpReg is a K register, COPY to a GPR
2097 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2098 unsigned KCondReg = CondReg;
2099 CondReg = createResultReg(&X86::GR8RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002100 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002101 TII.get(TargetOpcode::COPY), CondReg)
2102 .addReg(KCondReg, getKillRegState(CondIsKill));
2103 }
2104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2105 .addReg(CondReg, getKillRegState(CondIsKill))
2106 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002107 }
2108
2109 const Value *LHS = I->getOperand(1);
2110 const Value *RHS = I->getOperand(2);
2111
2112 unsigned RHSReg = getRegForValue(RHS);
2113 bool RHSIsKill = hasTrivialKill(RHS);
2114
2115 unsigned LHSReg = getRegForValue(LHS);
2116 bool LHSIsKill = hasTrivialKill(LHS);
2117
2118 if (!LHSReg || !RHSReg)
2119 return false;
2120
2121 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2122 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2123 LHSReg, LHSIsKill);
2124 updateValueMap(I, ResultReg);
2125 return true;
2126}
2127
Sanjay Patel302404b2015-03-05 21:46:54 +00002128/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002129///
2130/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2131/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002132/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002133bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2134 // Optimize conditions coming from a compare if both instructions are in the
2135 // same basic block (values defined in other basic blocks may not have
2136 // initialized registers).
2137 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2138 if (!CI || (CI->getParent() != I->getParent()))
2139 return false;
2140
2141 if (I->getType() != CI->getOperand(0)->getType() ||
2142 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2143 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2144 return false;
2145
2146 const Value *CmpLHS = CI->getOperand(0);
2147 const Value *CmpRHS = CI->getOperand(1);
2148 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2149
2150 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2151 // We don't have to materialize a zero constant for this case and can just use
2152 // %x again on the RHS.
2153 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2154 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2155 if (CmpRHSC && CmpRHSC->isNullValue())
2156 CmpRHS = CmpLHS;
2157 }
2158
2159 unsigned CC;
2160 bool NeedSwap;
2161 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2162 if (CC > 7)
2163 return false;
2164
2165 if (NeedSwap)
2166 std::swap(CmpLHS, CmpRHS);
2167
Sanjay Patel302404b2015-03-05 21:46:54 +00002168 // Choose the SSE instruction sequence based on data type (float or double).
Craig Topper428169a2016-09-05 07:14:21 +00002169 static const uint16_t OpcTable[2][4] = {
Craig Topper6413f8a2016-12-06 04:58:39 +00002170 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2171 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002172 };
2173
Craig Topper428169a2016-09-05 07:14:21 +00002174 const uint16_t *Opc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002175 switch (RetVT.SimpleTy) {
2176 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002177 case MVT::f32: Opc = &OpcTable[0][0]; break;
2178 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002179 }
2180
2181 const Value *LHS = I->getOperand(1);
2182 const Value *RHS = I->getOperand(2);
2183
2184 unsigned LHSReg = getRegForValue(LHS);
2185 bool LHSIsKill = hasTrivialKill(LHS);
2186
2187 unsigned RHSReg = getRegForValue(RHS);
2188 bool RHSIsKill = hasTrivialKill(RHS);
2189
2190 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2191 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2192
2193 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2194 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2195
2196 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2197 return false;
2198
2199 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002200 unsigned ResultReg;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002201
2202 if (Subtarget->hasAVX512()) {
2203 // If we have AVX512 we can use a mask compare and masked movss/sd.
2204 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2205 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2206
2207 unsigned CmpOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002208 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002209 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2210 CmpRHSReg, CmpRHSIsKill, CC);
2211
2212 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2213 // bits of the result register since its not based on any of the inputs.
2214 unsigned ImplicitDefReg = createResultReg(VR128X);
2215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2216 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2217
2218 // Place RHSReg is the passthru of the masked movss/sd operation and put
2219 // LHS in the input. The mask input comes from the compare.
2220 unsigned MovOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002221 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002222 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2223 CmpReg, true, ImplicitDefReg, true,
2224 LHSReg, LHSIsKill);
2225
2226 ResultReg = createResultReg(RC);
2227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2228 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2229
2230 } else if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002231 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2232
Sanjay Patel302404b2015-03-05 21:46:54 +00002233 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2234 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2235 // uses XMM0 as the selection register. That may need just as many
2236 // instructions as the AND/ANDN/OR sequence due to register moves, so
2237 // don't bother.
2238 unsigned CmpOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002239 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
Sanjay Patel302404b2015-03-05 21:46:54 +00002240 unsigned BlendOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002241 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2242
Craig Topper7ef6ea32016-12-05 04:51:31 +00002243 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002244 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002245 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2246 LHSReg, LHSIsKill, CmpReg, true);
2247 ResultReg = createResultReg(RC);
2248 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2249 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002250 } else {
Craig Topper6413f8a2016-12-06 04:58:39 +00002251 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
Sanjay Patel302404b2015-03-05 21:46:54 +00002252 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2253 CmpRHSReg, CmpRHSIsKill, CC);
Craig Topper6413f8a2016-12-06 04:58:39 +00002254 unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
Sanjay Patel302404b2015-03-05 21:46:54 +00002255 LHSReg, LHSIsKill);
Craig Topper6413f8a2016-12-06 04:58:39 +00002256 unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
Sanjay Patel302404b2015-03-05 21:46:54 +00002257 RHSReg, RHSIsKill);
Craig Topper6413f8a2016-12-06 04:58:39 +00002258 unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2259 AndReg, /*IsKill=*/true);
2260 ResultReg = createResultReg(RC);
2261 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2262 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002263 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002264 updateValueMap(I, ResultReg);
2265 return true;
2266}
2267
2268bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2269 // These are pseudo CMOV instructions and will be later expanded into control-
2270 // flow.
2271 unsigned Opc;
2272 switch (RetVT.SimpleTy) {
2273 default: return false;
2274 case MVT::i8: Opc = X86::CMOV_GR8; break;
2275 case MVT::i16: Opc = X86::CMOV_GR16; break;
2276 case MVT::i32: Opc = X86::CMOV_GR32; break;
2277 case MVT::f32: Opc = X86::CMOV_FR32; break;
2278 case MVT::f64: Opc = X86::CMOV_FR64; break;
2279 }
2280
2281 const Value *Cond = I->getOperand(0);
2282 X86::CondCode CC = X86::COND_NE;
2283
2284 // Optimize conditions coming from a compare if both instructions are in the
2285 // same basic block (values defined in other basic blocks may not have
2286 // initialized registers).
2287 const auto *CI = dyn_cast<CmpInst>(Cond);
2288 if (CI && (CI->getParent() == I->getParent())) {
2289 bool NeedSwap;
2290 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2291 if (CC > X86::LAST_VALID_COND)
2292 return false;
2293
2294 const Value *CmpLHS = CI->getOperand(0);
2295 const Value *CmpRHS = CI->getOperand(1);
2296
2297 if (NeedSwap)
2298 std::swap(CmpLHS, CmpRHS);
2299
Mehdi Amini44ede332015-07-09 02:09:04 +00002300 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002301 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2302 return false;
2303 } else {
2304 unsigned CondReg = getRegForValue(Cond);
2305 if (CondReg == 0)
2306 return false;
2307 bool CondIsKill = hasTrivialKill(Cond);
Guy Blank9ae797a2016-08-21 08:02:27 +00002308
Guy Blank2bdc74a2016-09-28 11:22:17 +00002309 // In case OpReg is a K register, COPY to a GPR
2310 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2311 unsigned KCondReg = CondReg;
2312 CondReg = createResultReg(&X86::GR8RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002313 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002314 TII.get(TargetOpcode::COPY), CondReg)
2315 .addReg(KCondReg, getKillRegState(CondIsKill));
2316 }
2317 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2318 .addReg(CondReg, getKillRegState(CondIsKill))
2319 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002320 }
2321
2322 const Value *LHS = I->getOperand(1);
2323 const Value *RHS = I->getOperand(2);
2324
2325 unsigned LHSReg = getRegForValue(LHS);
2326 bool LHSIsKill = hasTrivialKill(LHS);
2327
2328 unsigned RHSReg = getRegForValue(RHS);
2329 bool RHSIsKill = hasTrivialKill(RHS);
2330
2331 if (!LHSReg || !RHSReg)
2332 return false;
2333
2334 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2335
2336 unsigned ResultReg =
2337 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2338 updateValueMap(I, ResultReg);
2339 return true;
2340}
2341
2342bool X86FastISel::X86SelectSelect(const Instruction *I) {
2343 MVT RetVT;
2344 if (!isTypeLegal(I->getType(), RetVT))
2345 return false;
2346
2347 // Check if we can fold the select.
2348 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2349 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2350 const Value *Opnd = nullptr;
2351 switch (Predicate) {
2352 default: break;
2353 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2354 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2355 }
2356 // No need for a select anymore - this is an unconditional move.
2357 if (Opnd) {
2358 unsigned OpReg = getRegForValue(Opnd);
2359 if (OpReg == 0)
2360 return false;
2361 bool OpIsKill = hasTrivialKill(Opnd);
2362 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2363 unsigned ResultReg = createResultReg(RC);
2364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2365 TII.get(TargetOpcode::COPY), ResultReg)
2366 .addReg(OpReg, getKillRegState(OpIsKill));
2367 updateValueMap(I, ResultReg);
2368 return true;
2369 }
2370 }
2371
2372 // First try to use real conditional move instructions.
2373 if (X86FastEmitCMoveSelect(RetVT, I))
2374 return true;
2375
2376 // Try to use a sequence of SSE instructions to simulate a conditional move.
2377 if (X86FastEmitSSESelect(RetVT, I))
2378 return true;
2379
2380 // Fall-back to pseudo conditional move instructions, which will be later
2381 // converted to control-flow.
2382 if (X86FastEmitPseudoSelect(RetVT, I))
2383 return true;
2384
2385 return false;
2386}
2387
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002388bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002389 // The target-independent selection algorithm in FastISel already knows how
2390 // to select a SINT_TO_FP if the target is SSE but not AVX.
2391 // Early exit if the subtarget doesn't have AVX.
2392 if (!Subtarget->hasAVX())
2393 return false;
2394
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002395 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2396 return false;
2397
2398 // Select integer to float/double conversion.
2399 unsigned OpReg = getRegForValue(I->getOperand(0));
2400 if (OpReg == 0)
2401 return false;
2402
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002403 const TargetRegisterClass *RC = nullptr;
2404 unsigned Opcode;
2405
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002406 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002407 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002408 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002409 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002410 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002411 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002412 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002413 RC = &X86::FR32RegClass;
2414 } else
2415 return false;
2416
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002417 unsigned ImplicitDefReg = createResultReg(RC);
2418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2419 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2420 unsigned ResultReg =
2421 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002422 updateValueMap(I, ResultReg);
2423 return true;
2424}
2425
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002426// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2427bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2428 unsigned TargetOpc,
2429 const TargetRegisterClass *RC) {
2430 assert((I->getOpcode() == Instruction::FPExt ||
2431 I->getOpcode() == Instruction::FPTrunc) &&
2432 "Instruction must be an FPExt or FPTrunc!");
2433
2434 unsigned OpReg = getRegForValue(I->getOperand(0));
2435 if (OpReg == 0)
2436 return false;
2437
Ayman Musa9b802e42017-03-01 10:20:48 +00002438 unsigned ImplicitDefReg;
2439 if (Subtarget->hasAVX()) {
2440 ImplicitDefReg = createResultReg(RC);
2441 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2442 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2443
2444 }
2445
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002446 unsigned ResultReg = createResultReg(RC);
2447 MachineInstrBuilder MIB;
2448 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2449 ResultReg);
Ayman Musa4b2c9682017-02-23 13:15:44 +00002450
Ayman Musa9b802e42017-03-01 10:20:48 +00002451 if (Subtarget->hasAVX())
Ayman Musa4b2c9682017-02-23 13:15:44 +00002452 MIB.addReg(ImplicitDefReg);
Ayman Musa9b802e42017-03-01 10:20:48 +00002453
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002454 MIB.addReg(OpReg);
2455 updateValueMap(I, ResultReg);
2456 return true;
2457}
2458
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002459bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002460 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2461 I->getOperand(0)->getType()->isFloatTy()) {
2462 // fpext from float to double.
2463 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2464 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002465 }
2466
2467 return false;
2468}
2469
2470bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002471 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2472 I->getOperand(0)->getType()->isDoubleTy()) {
2473 // fptrunc from double to float.
2474 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2475 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002476 }
2477
2478 return false;
2479}
2480
2481bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002482 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2483 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002484
2485 // This code only handles truncation to byte.
2486 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2487 return false;
2488 if (!TLI.isTypeLegal(SrcVT))
2489 return false;
2490
2491 unsigned InputReg = getRegForValue(I->getOperand(0));
2492 if (!InputReg)
2493 // Unhandled operand. Halt "fast" selection and bail.
2494 return false;
2495
2496 if (SrcVT == MVT::i8) {
2497 // Truncate from i8 to i1; no code needed.
2498 updateValueMap(I, InputReg);
2499 return true;
2500 }
2501
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002502 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002503 if (!Subtarget->is64Bit()) {
2504 // If we're on x86-32; we can't extract an i8 from a general register.
2505 // First issue a copy to GR16_ABCD or GR32_ABCD.
2506 const TargetRegisterClass *CopyRC =
2507 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2508 unsigned CopyReg = createResultReg(CopyRC);
2509 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2510 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2511 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002512 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002513 }
2514
2515 // Issue an extract_subreg.
2516 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002517 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002518 X86::sub_8bit);
2519 if (!ResultReg)
2520 return false;
2521
2522 updateValueMap(I, ResultReg);
2523 return true;
2524}
2525
2526bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2527 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2528}
2529
2530bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2531 X86AddressMode SrcAM, uint64_t Len) {
2532
2533 // Make sure we don't bloat code by inlining very large memcpy's.
2534 if (!IsMemcpySmall(Len))
2535 return false;
2536
2537 bool i64Legal = Subtarget->is64Bit();
2538
2539 // We don't care about alignment here since we just emit integer accesses.
2540 while (Len) {
2541 MVT VT;
2542 if (Len >= 8 && i64Legal)
2543 VT = MVT::i64;
2544 else if (Len >= 4)
2545 VT = MVT::i32;
2546 else if (Len >= 2)
2547 VT = MVT::i16;
2548 else
2549 VT = MVT::i8;
2550
2551 unsigned Reg;
2552 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2553 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2554 assert(RV && "Failed to emit load or store??");
2555
2556 unsigned Size = VT.getSizeInBits()/8;
2557 Len -= Size;
2558 DestAM.Disp += Size;
2559 SrcAM.Disp += Size;
2560 }
2561
2562 return true;
2563}
2564
2565bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2566 // FIXME: Handle more intrinsics.
2567 switch (II->getIntrinsicID()) {
2568 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002569 case Intrinsic::convert_from_fp16:
2570 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002571 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002572 return false;
2573
2574 const Value *Op = II->getArgOperand(0);
2575 unsigned InputReg = getRegForValue(Op);
2576 if (InputReg == 0)
2577 return false;
2578
2579 // F16C only allows converting from float to half and from half to float.
2580 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2581 if (IsFloatToHalf) {
2582 if (!Op->getType()->isFloatTy())
2583 return false;
2584 } else {
2585 if (!II->getType()->isFloatTy())
2586 return false;
2587 }
2588
2589 unsigned ResultReg = 0;
2590 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2591 if (IsFloatToHalf) {
2592 // 'InputReg' is implicitly promoted from register class FR32 to
2593 // register class VR128 by method 'constrainOperandRegClass' which is
2594 // directly called by 'fastEmitInst_ri'.
2595 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002596 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2597 // It's consistent with the other FP instructions, which are usually
2598 // controlled by MXCSR.
2599 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002600
2601 // Move the lower 32-bits of ResultReg to another register of class GR32.
2602 ResultReg = createResultReg(&X86::GR32RegClass);
2603 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2604 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2605 .addReg(InputReg, RegState::Kill);
2606
2607 // The result value is in the lower 16-bits of ResultReg.
2608 unsigned RegIdx = X86::sub_16bit;
2609 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2610 } else {
2611 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2612 // Explicitly sign-extend the input to 32-bit.
2613 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2614 /*Kill=*/false);
2615
2616 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2617 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2618 InputReg, /*Kill=*/true);
2619
2620 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2621
2622 // The result value is in the lower 32-bits of ResultReg.
2623 // Emit an explicit copy from register class VR128 to register class FR32.
2624 ResultReg = createResultReg(&X86::FR32RegClass);
2625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2626 TII.get(TargetOpcode::COPY), ResultReg)
2627 .addReg(InputReg, RegState::Kill);
2628 }
2629
2630 updateValueMap(II, ResultReg);
2631 return true;
2632 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002633 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002634 MachineFunction *MF = FuncInfo.MF;
2635 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2636 return false;
2637
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002638 Type *RetTy = II->getCalledFunction()->getReturnType();
2639
2640 MVT VT;
2641 if (!isTypeLegal(RetTy, VT))
2642 return false;
2643
2644 unsigned Opc;
2645 const TargetRegisterClass *RC = nullptr;
2646
2647 switch (VT.SimpleTy) {
2648 default: llvm_unreachable("Invalid result type for frameaddress.");
2649 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2650 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2651 }
2652
2653 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2654 // we get the wrong frame register.
Matthias Braun941a7052016-07-28 18:40:00 +00002655 MachineFrameInfo &MFI = MF->getFrameInfo();
2656 MFI.setFrameAddressIsTaken(true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002657
Eric Christophera1c535b2015-02-02 23:03:45 +00002658 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002659 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002660 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2661 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2662 "Invalid Frame Register!");
2663
2664 // Always make a copy of the frame register to to a vreg first, so that we
2665 // never directly reference the frame register (the TwoAddressInstruction-
2666 // Pass doesn't like that).
2667 unsigned SrcReg = createResultReg(RC);
2668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2669 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2670
2671 // Now recursively load from the frame address.
2672 // movq (%rbp), %rax
2673 // movq (%rax), %rax
2674 // movq (%rax), %rax
2675 // ...
2676 unsigned DestReg;
2677 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2678 while (Depth--) {
2679 DestReg = createResultReg(RC);
2680 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2681 TII.get(Opc), DestReg), SrcReg);
2682 SrcReg = DestReg;
2683 }
2684
2685 updateValueMap(II, SrcReg);
2686 return true;
2687 }
2688 case Intrinsic::memcpy: {
2689 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2690 // Don't handle volatile or variable length memcpys.
2691 if (MCI->isVolatile())
2692 return false;
2693
2694 if (isa<ConstantInt>(MCI->getLength())) {
2695 // Small memcpy's are common enough that we want to do them
2696 // without a call if possible.
2697 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2698 if (IsMemcpySmall(Len)) {
2699 X86AddressMode DestAM, SrcAM;
2700 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2701 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2702 return false;
2703 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2704 return true;
2705 }
2706 }
2707
2708 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2709 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2710 return false;
2711
2712 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2713 return false;
2714
Pete Cooper67cf9a72015-11-19 05:56:52 +00002715 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002716 }
2717 case Intrinsic::memset: {
2718 const MemSetInst *MSI = cast<MemSetInst>(II);
2719
2720 if (MSI->isVolatile())
2721 return false;
2722
2723 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2724 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2725 return false;
2726
2727 if (MSI->getDestAddressSpace() > 255)
2728 return false;
2729
Pete Cooper67cf9a72015-11-19 05:56:52 +00002730 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002731 }
2732 case Intrinsic::stackprotector: {
2733 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002734 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002735
2736 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2737 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2738
2739 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2740
2741 // Grab the frame index.
2742 X86AddressMode AM;
2743 if (!X86SelectAddress(Slot, AM)) return false;
2744 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2745 return true;
2746 }
2747 case Intrinsic::dbg_declare: {
2748 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2749 X86AddressMode AM;
2750 assert(DI->getAddress() && "Null address should be checked earlier!");
2751 if (!X86SelectAddress(DI->getAddress(), AM))
2752 return false;
2753 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2754 // FIXME may need to add RegState::Debug to any registers produced,
2755 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002756 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2757 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002758 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2759 .addImm(0)
2760 .addMetadata(DI->getVariable())
2761 .addMetadata(DI->getExpression());
2762 return true;
2763 }
2764 case Intrinsic::trap: {
2765 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2766 return true;
2767 }
2768 case Intrinsic::sqrt: {
2769 if (!Subtarget->hasSSE1())
2770 return false;
2771
2772 Type *RetTy = II->getCalledFunction()->getReturnType();
2773
2774 MVT VT;
2775 if (!isTypeLegal(RetTy, VT))
2776 return false;
2777
2778 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2779 // is not generated by FastISel yet.
2780 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002781 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002782 {X86::SQRTSSr, X86::VSQRTSSr},
2783 {X86::SQRTSDr, X86::VSQRTSDr}
2784 };
2785 bool HasAVX = Subtarget->hasAVX();
2786 unsigned Opc;
2787 const TargetRegisterClass *RC;
2788 switch (VT.SimpleTy) {
2789 default: return false;
2790 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2791 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2792 }
2793
2794 const Value *SrcVal = II->getArgOperand(0);
2795 unsigned SrcReg = getRegForValue(SrcVal);
2796
2797 if (SrcReg == 0)
2798 return false;
2799
2800 unsigned ImplicitDefReg = 0;
2801 if (HasAVX) {
2802 ImplicitDefReg = createResultReg(RC);
2803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2804 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2805 }
2806
2807 unsigned ResultReg = createResultReg(RC);
2808 MachineInstrBuilder MIB;
2809 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2810 ResultReg);
2811
2812 if (ImplicitDefReg)
2813 MIB.addReg(ImplicitDefReg);
2814
2815 MIB.addReg(SrcReg);
2816
2817 updateValueMap(II, ResultReg);
2818 return true;
2819 }
2820 case Intrinsic::sadd_with_overflow:
2821 case Intrinsic::uadd_with_overflow:
2822 case Intrinsic::ssub_with_overflow:
2823 case Intrinsic::usub_with_overflow:
2824 case Intrinsic::smul_with_overflow:
2825 case Intrinsic::umul_with_overflow: {
2826 // This implements the basic lowering of the xalu with overflow intrinsics
2827 // into add/sub/mul followed by either seto or setb.
2828 const Function *Callee = II->getCalledFunction();
2829 auto *Ty = cast<StructType>(Callee->getReturnType());
2830 Type *RetTy = Ty->getTypeAtIndex(0U);
Zvi Rackover6f76f462016-11-15 13:50:35 +00002831 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2832 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2833 "Overflow value expected to be an i1");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002834
2835 MVT VT;
2836 if (!isTypeLegal(RetTy, VT))
2837 return false;
2838
2839 if (VT < MVT::i8 || VT > MVT::i64)
2840 return false;
2841
2842 const Value *LHS = II->getArgOperand(0);
2843 const Value *RHS = II->getArgOperand(1);
2844
2845 // Canonicalize immediate to the RHS.
2846 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2847 isCommutativeIntrinsic(II))
2848 std::swap(LHS, RHS);
2849
2850 bool UseIncDec = false;
2851 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2852 UseIncDec = true;
2853
2854 unsigned BaseOpc, CondOpc;
2855 switch (II->getIntrinsicID()) {
2856 default: llvm_unreachable("Unexpected intrinsic!");
2857 case Intrinsic::sadd_with_overflow:
2858 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2859 CondOpc = X86::SETOr;
2860 break;
2861 case Intrinsic::uadd_with_overflow:
2862 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2863 case Intrinsic::ssub_with_overflow:
2864 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2865 CondOpc = X86::SETOr;
2866 break;
2867 case Intrinsic::usub_with_overflow:
2868 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2869 case Intrinsic::smul_with_overflow:
2870 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2871 case Intrinsic::umul_with_overflow:
2872 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2873 }
2874
2875 unsigned LHSReg = getRegForValue(LHS);
2876 if (LHSReg == 0)
2877 return false;
2878 bool LHSIsKill = hasTrivialKill(LHS);
2879
2880 unsigned ResultReg = 0;
2881 // Check if we have an immediate version.
2882 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002883 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002884 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2885 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2886 };
2887
2888 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2889 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2890 bool IsDec = BaseOpc == X86ISD::DEC;
2891 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2892 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2893 .addReg(LHSReg, getKillRegState(LHSIsKill));
2894 } else
2895 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2896 CI->getZExtValue());
2897 }
2898
2899 unsigned RHSReg;
2900 bool RHSIsKill;
2901 if (!ResultReg) {
2902 RHSReg = getRegForValue(RHS);
2903 if (RHSReg == 0)
2904 return false;
2905 RHSIsKill = hasTrivialKill(RHS);
2906 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2907 RHSIsKill);
2908 }
2909
2910 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2911 // it manually.
2912 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002913 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002914 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002915 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002916 // First copy the first operand into RAX, which is an implicit input to
2917 // the X86::MUL*r instruction.
2918 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2919 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2920 .addReg(LHSReg, getKillRegState(LHSIsKill));
2921 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2922 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2923 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002924 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002925 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2926 if (VT == MVT::i8) {
2927 // Copy the first operand into AL, which is an implicit input to the
2928 // X86::IMUL8r instruction.
2929 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2930 TII.get(TargetOpcode::COPY), X86::AL)
2931 .addReg(LHSReg, getKillRegState(LHSIsKill));
2932 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2933 RHSIsKill);
2934 } else
2935 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2936 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2937 RHSReg, RHSIsKill);
2938 }
2939
2940 if (!ResultReg)
2941 return false;
2942
Zvi Rackoverf0b9b57b2016-11-15 13:29:23 +00002943 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2944 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002945 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2947 ResultReg2);
2948
2949 updateValueMap(II, ResultReg, 2);
2950 return true;
2951 }
2952 case Intrinsic::x86_sse_cvttss2si:
2953 case Intrinsic::x86_sse_cvttss2si64:
2954 case Intrinsic::x86_sse2_cvttsd2si:
2955 case Intrinsic::x86_sse2_cvttsd2si64: {
2956 bool IsInputDouble;
2957 switch (II->getIntrinsicID()) {
2958 default: llvm_unreachable("Unexpected intrinsic.");
2959 case Intrinsic::x86_sse_cvttss2si:
2960 case Intrinsic::x86_sse_cvttss2si64:
2961 if (!Subtarget->hasSSE1())
2962 return false;
2963 IsInputDouble = false;
2964 break;
2965 case Intrinsic::x86_sse2_cvttsd2si:
2966 case Intrinsic::x86_sse2_cvttsd2si64:
2967 if (!Subtarget->hasSSE2())
2968 return false;
2969 IsInputDouble = true;
2970 break;
2971 }
2972
2973 Type *RetTy = II->getCalledFunction()->getReturnType();
2974 MVT VT;
2975 if (!isTypeLegal(RetTy, VT))
2976 return false;
2977
Craig Topper66111882016-06-02 04:19:42 +00002978 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002979 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2980 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2981 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2982 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2983 };
2984 bool HasAVX = Subtarget->hasAVX();
2985 unsigned Opc;
2986 switch (VT.SimpleTy) {
2987 default: llvm_unreachable("Unexpected result type.");
2988 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2989 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2990 }
2991
2992 // Check if we can fold insertelement instructions into the convert.
2993 const Value *Op = II->getArgOperand(0);
2994 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2995 const Value *Index = IE->getOperand(2);
2996 if (!isa<ConstantInt>(Index))
2997 break;
2998 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2999
3000 if (Idx == 0) {
3001 Op = IE->getOperand(1);
3002 break;
3003 }
3004 Op = IE->getOperand(0);
3005 }
3006
3007 unsigned Reg = getRegForValue(Op);
3008 if (Reg == 0)
3009 return false;
3010
3011 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3013 .addReg(Reg);
3014
3015 updateValueMap(II, ResultReg);
3016 return true;
3017 }
3018 }
3019}
3020
3021bool X86FastISel::fastLowerArguments() {
3022 if (!FuncInfo.CanLowerReturn)
3023 return false;
3024
3025 const Function *F = FuncInfo.Fn;
3026 if (F->isVarArg())
3027 return false;
3028
3029 CallingConv::ID CC = F->getCallingConv();
3030 if (CC != CallingConv::C)
3031 return false;
3032
3033 if (Subtarget->isCallingConvWin64(CC))
3034 return false;
3035
3036 if (!Subtarget->is64Bit())
3037 return false;
3038
3039 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3040 unsigned GPRCnt = 0;
3041 unsigned FPRCnt = 0;
3042 unsigned Idx = 0;
3043 for (auto const &Arg : F->args()) {
3044 // The first argument is at index 1.
3045 ++Idx;
3046 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
3047 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
3048 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00003049 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00003050 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003051 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
3052 return false;
3053
3054 Type *ArgTy = Arg.getType();
3055 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3056 return false;
3057
Mehdi Amini44ede332015-07-09 02:09:04 +00003058 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003059 if (!ArgVT.isSimple()) return false;
3060 switch (ArgVT.getSimpleVT().SimpleTy) {
3061 default: return false;
3062 case MVT::i32:
3063 case MVT::i64:
3064 ++GPRCnt;
3065 break;
3066 case MVT::f32:
3067 case MVT::f64:
3068 if (!Subtarget->hasSSE1())
3069 return false;
3070 ++FPRCnt;
3071 break;
3072 }
3073
3074 if (GPRCnt > 6)
3075 return false;
3076
3077 if (FPRCnt > 8)
3078 return false;
3079 }
3080
3081 static const MCPhysReg GPR32ArgRegs[] = {
3082 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3083 };
3084 static const MCPhysReg GPR64ArgRegs[] = {
3085 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3086 };
3087 static const MCPhysReg XMMArgRegs[] = {
3088 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3089 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3090 };
3091
3092 unsigned GPRIdx = 0;
3093 unsigned FPRIdx = 0;
3094 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003095 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003096 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3097 unsigned SrcReg;
3098 switch (VT.SimpleTy) {
3099 default: llvm_unreachable("Unexpected value type.");
3100 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3101 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003102 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003103 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3104 }
3105 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3106 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3107 // Without this, EmitLiveInCopies may eliminate the livein if its only
3108 // use is a bitcast (which isn't turned into an instruction).
3109 unsigned ResultReg = createResultReg(RC);
3110 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3111 TII.get(TargetOpcode::COPY), ResultReg)
3112 .addReg(DstReg, getKillRegState(true));
3113 updateValueMap(&Arg, ResultReg);
3114 }
3115 return true;
3116}
3117
Nico Weberaf7e8462016-07-14 01:52:51 +00003118static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3119 CallingConv::ID CC,
3120 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003121 if (Subtarget->is64Bit())
3122 return 0;
3123 if (Subtarget->getTargetTriple().isOSMSVCRT())
3124 return 0;
3125 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3126 CC == CallingConv::HiPE)
3127 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003128
3129 if (CS)
3130 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00003131 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003132 return 0;
3133
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003134 return 4;
3135}
3136
3137bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3138 auto &OutVals = CLI.OutVals;
3139 auto &OutFlags = CLI.OutFlags;
3140 auto &OutRegs = CLI.OutRegs;
3141 auto &Ins = CLI.Ins;
3142 auto &InRegs = CLI.InRegs;
3143 CallingConv::ID CC = CLI.CallConv;
3144 bool &IsTailCall = CLI.IsTailCall;
3145 bool IsVarArg = CLI.IsVarArg;
3146 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003147 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003148
3149 bool Is64Bit = Subtarget->is64Bit();
3150 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3151
3152 // Handle only C, fastcc, and webkit_js calling conventions for now.
3153 switch (CC) {
3154 default: return false;
3155 case CallingConv::C:
3156 case CallingConv::Fast:
3157 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003158 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003159 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003160 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003161 case CallingConv::X86_ThisCall:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003162 case CallingConv::X86_64_Win64:
3163 case CallingConv::X86_64_SysV:
3164 break;
3165 }
3166
3167 // Allow SelectionDAG isel to handle tail calls.
3168 if (IsTailCall)
3169 return false;
3170
3171 // fastcc with -tailcallopt is intended to provide a guaranteed
3172 // tail call optimization. Fastisel doesn't know how to do that.
3173 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3174 return false;
3175
3176 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3177 // x86-32. Special handling for x86-64 is implemented.
3178 if (IsVarArg && IsWin64)
3179 return false;
3180
3181 // Don't know about inalloca yet.
3182 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3183 return false;
3184
Manman Ren57518142016-04-11 21:08:06 +00003185 for (auto Flag : CLI.OutFlags)
3186 if (Flag.isSwiftError())
3187 return false;
3188
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003189 SmallVector<MVT, 16> OutVTs;
3190 SmallVector<unsigned, 16> ArgRegs;
3191
3192 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3193 // instruction. This is safe because it is common to all FastISel supported
3194 // calling conventions on x86.
3195 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3196 Value *&Val = OutVals[i];
3197 ISD::ArgFlagsTy Flags = OutFlags[i];
3198 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3199 if (CI->getBitWidth() < 32) {
3200 if (Flags.isSExt())
3201 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3202 else
3203 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3204 }
3205 }
3206
3207 // Passing bools around ends up doing a trunc to i1 and passing it.
3208 // Codegen this as an argument + "and 1".
3209 MVT VT;
3210 auto *TI = dyn_cast<TruncInst>(Val);
3211 unsigned ResultReg;
3212 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3213 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3214 TI->hasOneUse()) {
3215 Value *PrevVal = TI->getOperand(0);
3216 ResultReg = getRegForValue(PrevVal);
3217
3218 if (!ResultReg)
3219 return false;
3220
3221 if (!isTypeLegal(PrevVal->getType(), VT))
3222 return false;
3223
3224 ResultReg =
3225 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3226 } else {
3227 if (!isTypeLegal(Val->getType(), VT))
3228 return false;
3229 ResultReg = getRegForValue(Val);
3230 }
3231
3232 if (!ResultReg)
3233 return false;
3234
3235 ArgRegs.push_back(ResultReg);
3236 OutVTs.push_back(VT);
3237 }
3238
3239 // Analyze operands of the call, assigning locations to each operand.
3240 SmallVector<CCValAssign, 16> ArgLocs;
3241 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3242
3243 // Allocate shadow area for Win64
3244 if (IsWin64)
3245 CCInfo.AllocateStack(32, 8);
3246
3247 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3248
3249 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003250 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003251
3252 // Issue CALLSEQ_START
3253 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003255 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003256
3257 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003258 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003259 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3260 CCValAssign const &VA = ArgLocs[i];
3261 const Value *ArgVal = OutVals[VA.getValNo()];
3262 MVT ArgVT = OutVTs[VA.getValNo()];
3263
3264 if (ArgVT == MVT::x86mmx)
3265 return false;
3266
3267 unsigned ArgReg = ArgRegs[VA.getValNo()];
3268
3269 // Promote the value if needed.
3270 switch (VA.getLocInfo()) {
3271 case CCValAssign::Full: break;
3272 case CCValAssign::SExt: {
3273 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3274 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003275
Craig Topper088ba172016-12-05 06:09:55 +00003276 if (ArgVT == MVT::i1)
David Majnemer2c5aeab2016-05-04 00:22:23 +00003277 return false;
3278
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003279 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3280 ArgVT, ArgReg);
3281 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3282 ArgVT = VA.getLocVT();
3283 break;
3284 }
3285 case CCValAssign::ZExt: {
3286 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3287 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003288
3289 // Handle zero-extension from i1 to i8, which is common.
Craig Topper088ba172016-12-05 06:09:55 +00003290 if (ArgVT == MVT::i1) {
David Majnemer2c5aeab2016-05-04 00:22:23 +00003291 // Set the high bits to zero.
3292 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3293 ArgVT = MVT::i8;
3294
3295 if (ArgReg == 0)
3296 return false;
3297 }
3298
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003299 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3300 ArgVT, ArgReg);
3301 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3302 ArgVT = VA.getLocVT();
3303 break;
3304 }
3305 case CCValAssign::AExt: {
3306 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3307 "Unexpected extend");
3308 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3309 ArgVT, ArgReg);
3310 if (!Emitted)
3311 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3312 ArgVT, ArgReg);
3313 if (!Emitted)
3314 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3315 ArgVT, ArgReg);
3316
3317 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3318 ArgVT = VA.getLocVT();
3319 break;
3320 }
3321 case CCValAssign::BCvt: {
3322 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3323 /*TODO: Kill=*/false);
3324 assert(ArgReg && "Failed to emit a bitcast!");
3325 ArgVT = VA.getLocVT();
3326 break;
3327 }
3328 case CCValAssign::VExt:
3329 // VExt has not been implemented, so this should be impossible to reach
3330 // for now. However, fallback to Selection DAG isel once implemented.
3331 return false;
3332 case CCValAssign::AExtUpper:
3333 case CCValAssign::SExtUpper:
3334 case CCValAssign::ZExtUpper:
3335 case CCValAssign::FPExt:
3336 llvm_unreachable("Unexpected loc info!");
3337 case CCValAssign::Indirect:
3338 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3339 // support this.
3340 return false;
3341 }
3342
3343 if (VA.isRegLoc()) {
3344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3345 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3346 OutRegs.push_back(VA.getLocReg());
3347 } else {
3348 assert(VA.isMemLoc());
3349
3350 // Don't emit stores for undef values.
3351 if (isa<UndefValue>(ArgVal))
3352 continue;
3353
3354 unsigned LocMemOffset = VA.getLocMemOffset();
3355 X86AddressMode AM;
3356 AM.Base.Reg = RegInfo->getStackRegister();
3357 AM.Disp = LocMemOffset;
3358 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3359 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3360 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003361 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3362 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003363 if (Flags.isByVal()) {
3364 X86AddressMode SrcAM;
3365 SrcAM.Base.Reg = ArgReg;
3366 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3367 return false;
3368 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3369 // If this is a really simple value, emit this with the Value* version
3370 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3371 // as it can cause us to reevaluate the argument.
3372 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3373 return false;
3374 } else {
3375 bool ValIsKill = hasTrivialKill(ArgVal);
3376 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3377 return false;
3378 }
3379 }
3380 }
3381
3382 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3383 // GOT pointer.
3384 if (Subtarget->isPICStyleGOT()) {
3385 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3387 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3388 }
3389
3390 if (Is64Bit && IsVarArg && !IsWin64) {
3391 // From AMD64 ABI document:
3392 // For calls that may call functions that use varargs or stdargs
3393 // (prototype-less calls or calls to functions containing ellipsis (...) in
3394 // the declaration) %al is used as hidden argument to specify the number
3395 // of SSE registers used. The contents of %al do not need to match exactly
3396 // the number of registers, but must be an ubound on the number of SSE
3397 // registers used and is in the range 0 - 8 inclusive.
3398
3399 // Count the number of XMM registers allocated.
3400 static const MCPhysReg XMMArgRegs[] = {
3401 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3402 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3403 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003404 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003405 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3406 && "SSE registers cannot be used when SSE is disabled");
3407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3408 X86::AL).addImm(NumXMMRegs);
3409 }
3410
3411 // Materialize callee address in a register. FIXME: GV address can be
3412 // handled with a CALLpcrel32 instead.
3413 X86AddressMode CalleeAM;
3414 if (!X86SelectCallAddress(Callee, CalleeAM))
3415 return false;
3416
3417 unsigned CalleeOp = 0;
3418 const GlobalValue *GV = nullptr;
3419 if (CalleeAM.GV != nullptr) {
3420 GV = CalleeAM.GV;
3421 } else if (CalleeAM.Base.Reg != 0) {
3422 CalleeOp = CalleeAM.Base.Reg;
3423 } else
3424 return false;
3425
3426 // Issue the call.
3427 MachineInstrBuilder MIB;
3428 if (CalleeOp) {
3429 // Register-indirect call.
3430 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3431 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3432 .addReg(CalleeOp);
3433 } else {
3434 // Direct call.
3435 assert(GV && "Not a direct call");
3436 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3437
3438 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003439 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003440 // Ignore NonLazyBind attribute in FastISel
3441 if (OpFlags == X86II::MO_GOTPCREL)
3442 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003443
3444 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003445 if (Symbol)
3446 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003447 else
3448 MIB.addGlobalAddress(GV, 0, OpFlags);
3449 }
3450
3451 // Add a register mask operand representing the call-preserved registers.
3452 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003453 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003454
3455 // Add an implicit use GOT pointer in EBX.
3456 if (Subtarget->isPICStyleGOT())
3457 MIB.addReg(X86::EBX, RegState::Implicit);
3458
3459 if (Is64Bit && IsVarArg && !IsWin64)
3460 MIB.addReg(X86::AL, RegState::Implicit);
3461
3462 // Add implicit physical register uses to the call.
3463 for (auto Reg : OutRegs)
3464 MIB.addReg(Reg, RegState::Implicit);
3465
3466 // Issue CALLSEQ_END
3467 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003468 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3469 TM.Options.GuaranteedTailCallOpt)
3470 ? NumBytes // Callee pops everything.
3471 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003472 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3474 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3475
3476 // Now handle call return values.
3477 SmallVector<CCValAssign, 16> RVLocs;
3478 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3479 CLI.RetTy->getContext());
3480 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3481
3482 // Copy all of the result registers out of their specified physreg.
3483 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3484 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3485 CCValAssign &VA = RVLocs[i];
3486 EVT CopyVT = VA.getValVT();
3487 unsigned CopyReg = ResultReg + i;
3488
3489 // If this is x86-64, and we disabled SSE, we can't return FP values
3490 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3491 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3492 report_fatal_error("SSE register return with SSE disabled");
3493 }
3494
3495 // If we prefer to use the value in xmm registers, copy it out as f80 and
3496 // use a truncate to move it from fp stack reg to xmm reg.
3497 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3498 isScalarFPTypeInSSEReg(VA.getValVT())) {
3499 CopyVT = MVT::f80;
3500 CopyReg = createResultReg(&X86::RFP80RegClass);
3501 }
3502
3503 // Copy out the result.
3504 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3505 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3506 InRegs.push_back(VA.getLocReg());
3507
3508 // Round the f80 to the right size, which also moves it to the appropriate
3509 // xmm register. This is accomplished by storing the f80 value in memory
3510 // and then loading it back.
3511 if (CopyVT != VA.getValVT()) {
3512 EVT ResVT = VA.getValVT();
3513 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3514 unsigned MemSize = ResVT.getSizeInBits()/8;
3515 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3516 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3517 TII.get(Opc)), FI)
3518 .addReg(CopyReg);
3519 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3520 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3521 TII.get(Opc), ResultReg + i), FI);
3522 }
3523 }
3524
3525 CLI.ResultReg = ResultReg;
3526 CLI.NumResultRegs = RVLocs.size();
3527 CLI.Call = MIB;
3528
3529 return true;
3530}
3531
3532bool
3533X86FastISel::fastSelectInstruction(const Instruction *I) {
3534 switch (I->getOpcode()) {
3535 default: break;
3536 case Instruction::Load:
3537 return X86SelectLoad(I);
3538 case Instruction::Store:
3539 return X86SelectStore(I);
3540 case Instruction::Ret:
3541 return X86SelectRet(I);
3542 case Instruction::ICmp:
3543 case Instruction::FCmp:
3544 return X86SelectCmp(I);
3545 case Instruction::ZExt:
3546 return X86SelectZExt(I);
3547 case Instruction::Br:
3548 return X86SelectBranch(I);
3549 case Instruction::LShr:
3550 case Instruction::AShr:
3551 case Instruction::Shl:
3552 return X86SelectShift(I);
3553 case Instruction::SDiv:
3554 case Instruction::UDiv:
3555 case Instruction::SRem:
3556 case Instruction::URem:
3557 return X86SelectDivRem(I);
3558 case Instruction::Select:
3559 return X86SelectSelect(I);
3560 case Instruction::Trunc:
3561 return X86SelectTrunc(I);
3562 case Instruction::FPExt:
3563 return X86SelectFPExt(I);
3564 case Instruction::FPTrunc:
3565 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003566 case Instruction::SIToFP:
3567 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003568 case Instruction::IntToPtr: // Deliberate fall-through.
3569 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003570 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3571 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003572 if (DstVT.bitsGT(SrcVT))
3573 return X86SelectZExt(I);
3574 if (DstVT.bitsLT(SrcVT))
3575 return X86SelectTrunc(I);
3576 unsigned Reg = getRegForValue(I->getOperand(0));
3577 if (Reg == 0) return false;
3578 updateValueMap(I, Reg);
3579 return true;
3580 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003581 case Instruction::BitCast: {
3582 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3583 if (!Subtarget->hasSSE2())
3584 return false;
3585
3586 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3587 EVT DstVT = TLI.getValueType(DL, I->getType());
3588
3589 if (!SrcVT.isSimple() || !DstVT.isSimple())
3590 return false;
3591
Craig Topperdb8467a2016-12-05 05:50:51 +00003592 MVT SVT = SrcVT.getSimpleVT();
3593 MVT DVT = DstVT.getSimpleVT();
3594
3595 if (!SVT.is128BitVector() &&
3596 !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3597 !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3598 (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3599 DVT.getScalarSizeInBits() >= 32))))
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003600 return false;
3601
3602 unsigned Reg = getRegForValue(I->getOperand(0));
3603 if (Reg == 0)
3604 return false;
3605
3606 // No instruction is needed for conversion. Reuse the register used by
3607 // the fist operand.
3608 updateValueMap(I, Reg);
3609 return true;
3610 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003611 }
3612
3613 return false;
3614}
3615
3616unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3617 if (VT > MVT::i64)
3618 return 0;
3619
3620 uint64_t Imm = CI->getZExtValue();
3621 if (Imm == 0) {
3622 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3623 switch (VT.SimpleTy) {
3624 default: llvm_unreachable("Unexpected value type");
3625 case MVT::i1:
3626 case MVT::i8:
3627 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3628 X86::sub_8bit);
3629 case MVT::i16:
3630 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3631 X86::sub_16bit);
3632 case MVT::i32:
3633 return SrcReg;
3634 case MVT::i64: {
3635 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3636 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3637 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3638 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3639 return ResultReg;
3640 }
3641 }
3642 }
3643
3644 unsigned Opc = 0;
3645 switch (VT.SimpleTy) {
3646 default: llvm_unreachable("Unexpected value type");
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003647 case MVT::i1: VT = MVT::i8; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003648 case MVT::i8: Opc = X86::MOV8ri; break;
3649 case MVT::i16: Opc = X86::MOV16ri; break;
3650 case MVT::i32: Opc = X86::MOV32ri; break;
3651 case MVT::i64: {
3652 if (isUInt<32>(Imm))
3653 Opc = X86::MOV32ri;
3654 else if (isInt<32>(Imm))
3655 Opc = X86::MOV64ri32;
3656 else
3657 Opc = X86::MOV64ri;
3658 break;
3659 }
3660 }
3661 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3662 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3663 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3665 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3666 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3667 return ResultReg;
3668 }
3669 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3670}
3671
3672unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3673 if (CFP->isNullValue())
3674 return fastMaterializeFloatZero(CFP);
3675
3676 // Can't handle alternate code models yet.
3677 CodeModel::Model CM = TM.getCodeModel();
3678 if (CM != CodeModel::Small && CM != CodeModel::Large)
3679 return 0;
3680
3681 // Get opcode and regclass of the output for the given load instruction.
3682 unsigned Opc = 0;
3683 const TargetRegisterClass *RC = nullptr;
3684 switch (VT.SimpleTy) {
3685 default: return 0;
3686 case MVT::f32:
3687 if (X86ScalarSSEf32) {
3688 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3689 RC = &X86::FR32RegClass;
3690 } else {
3691 Opc = X86::LD_Fp32m;
3692 RC = &X86::RFP32RegClass;
3693 }
3694 break;
3695 case MVT::f64:
3696 if (X86ScalarSSEf64) {
3697 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3698 RC = &X86::FR64RegClass;
3699 } else {
3700 Opc = X86::LD_Fp64m;
3701 RC = &X86::RFP64RegClass;
3702 }
3703 break;
3704 case MVT::f80:
3705 // No f80 support yet.
3706 return 0;
3707 }
3708
3709 // MachineConstantPool wants an explicit alignment.
3710 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3711 if (Align == 0) {
3712 // Alignment of vector types. FIXME!
3713 Align = DL.getTypeAllocSize(CFP->getType());
3714 }
3715
3716 // x86-32 PIC requires a PIC base register for constant pools.
3717 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003718 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3719 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003720 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003721 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003722 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003723 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003724 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003725
3726 // Create the load from the constant pool.
3727 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3728 unsigned ResultReg = createResultReg(RC);
3729
3730 if (CM == CodeModel::Large) {
3731 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3732 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3733 AddrReg)
3734 .addConstantPoolIndex(CPI, 0, OpFlag);
3735 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3736 TII.get(Opc), ResultReg);
3737 addDirectMem(MIB, AddrReg);
3738 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003739 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3740 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003741 MIB->addMemOperand(*FuncInfo.MF, MMO);
3742 return ResultReg;
3743 }
3744
3745 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3746 TII.get(Opc), ResultReg),
3747 CPI, PICBase, OpFlag);
3748 return ResultReg;
3749}
3750
3751unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3752 // Can't handle alternate code models yet.
3753 if (TM.getCodeModel() != CodeModel::Small)
3754 return 0;
3755
3756 // Materialize addresses with LEA/MOV instructions.
3757 X86AddressMode AM;
3758 if (X86SelectAddress(GV, AM)) {
3759 // If the expression is just a basereg, then we're done, otherwise we need
3760 // to emit an LEA.
3761 if (AM.BaseType == X86AddressMode::RegBase &&
3762 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3763 return AM.Base.Reg;
3764
3765 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3766 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003767 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003768 // The displacement code could be more than 32 bits away so we need to use
3769 // an instruction with a 64 bit immediate
3770 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3771 ResultReg)
3772 .addGlobalAddress(GV);
3773 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003774 unsigned Opc =
3775 TLI.getPointerTy(DL) == MVT::i32
3776 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3777 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003778 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3779 TII.get(Opc), ResultReg), AM);
3780 }
3781 return ResultReg;
3782 }
3783 return 0;
3784}
3785
3786unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003787 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003788
3789 // Only handle simple types.
3790 if (!CEVT.isSimple())
3791 return 0;
3792 MVT VT = CEVT.getSimpleVT();
3793
3794 if (const auto *CI = dyn_cast<ConstantInt>(C))
3795 return X86MaterializeInt(CI, VT);
3796 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3797 return X86MaterializeFP(CFP, VT);
3798 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3799 return X86MaterializeGV(GV, VT);
3800
3801 return 0;
3802}
3803
3804unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3805 // Fail on dynamic allocas. At this point, getRegForValue has already
3806 // checked its CSE maps, so if we're here trying to handle a dynamic
3807 // alloca, we're not going to succeed. X86SelectAddress has a
3808 // check for dynamic allocas, because it's called directly from
3809 // various places, but targetMaterializeAlloca also needs a check
3810 // in order to avoid recursion between getRegForValue,
3811 // X86SelectAddrss, and targetMaterializeAlloca.
3812 if (!FuncInfo.StaticAllocaMap.count(C))
3813 return 0;
3814 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3815
3816 X86AddressMode AM;
3817 if (!X86SelectAddress(C, AM))
3818 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003819 unsigned Opc =
3820 TLI.getPointerTy(DL) == MVT::i32
3821 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3822 : X86::LEA64r;
3823 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003824 unsigned ResultReg = createResultReg(RC);
3825 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3826 TII.get(Opc), ResultReg), AM);
3827 return ResultReg;
3828}
3829
3830unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3831 MVT VT;
3832 if (!isTypeLegal(CF->getType(), VT))
3833 return 0;
3834
3835 // Get opcode and regclass for the given zero.
3836 unsigned Opc = 0;
3837 const TargetRegisterClass *RC = nullptr;
3838 switch (VT.SimpleTy) {
3839 default: return 0;
3840 case MVT::f32:
3841 if (X86ScalarSSEf32) {
3842 Opc = X86::FsFLD0SS;
3843 RC = &X86::FR32RegClass;
3844 } else {
3845 Opc = X86::LD_Fp032;
3846 RC = &X86::RFP32RegClass;
3847 }
3848 break;
3849 case MVT::f64:
3850 if (X86ScalarSSEf64) {
3851 Opc = X86::FsFLD0SD;
3852 RC = &X86::FR64RegClass;
3853 } else {
3854 Opc = X86::LD_Fp064;
3855 RC = &X86::RFP64RegClass;
3856 }
3857 break;
3858 case MVT::f80:
3859 // No f80 support yet.
3860 return 0;
3861 }
3862
3863 unsigned ResultReg = createResultReg(RC);
3864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3865 return ResultReg;
3866}
3867
3868
3869bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3870 const LoadInst *LI) {
3871 const Value *Ptr = LI->getPointerOperand();
3872 X86AddressMode AM;
3873 if (!X86SelectAddress(Ptr, AM))
3874 return false;
3875
3876 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3877
3878 unsigned Size = DL.getTypeAllocSize(LI->getType());
3879 unsigned Alignment = LI->getAlignment();
3880
3881 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3882 Alignment = DL.getABITypeAlignment(LI->getType());
3883
3884 SmallVector<MachineOperand, 8> AddrOps;
3885 AM.getFullAddress(AddrOps);
3886
Keno Fischere70b31f2015-06-08 20:09:58 +00003887 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003888 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003889 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003890 if (!Result)
3891 return false;
3892
Pete Cooperd31583d2015-05-06 21:37:19 +00003893 // The index register could be in the wrong register class. Unfortunately,
3894 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3895 // to just look at OpNo + the offset to the index reg. We actually need to
3896 // scan the instruction to find the index reg and see if its the correct reg
3897 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003898 unsigned OperandNo = 0;
3899 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3900 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3901 MachineOperand &MO = *I;
3902 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003903 continue;
3904 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003905 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003906 MO.getReg(), OperandNo);
3907 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003908 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003909 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003910 }
3911
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003912 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003913 MI->eraseFromParent();
3914 return true;
3915}
3916
Craig Topper7ef6ea32016-12-05 04:51:31 +00003917unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
3918 const TargetRegisterClass *RC,
3919 unsigned Op0, bool Op0IsKill,
3920 unsigned Op1, bool Op1IsKill,
3921 unsigned Op2, bool Op2IsKill,
3922 unsigned Op3, bool Op3IsKill) {
3923 const MCInstrDesc &II = TII.get(MachineInstOpcode);
3924
3925 unsigned ResultReg = createResultReg(RC);
3926 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
3927 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
3928 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
3929 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 3);
3930
3931 if (II.getNumDefs() >= 1)
3932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
3933 .addReg(Op0, getKillRegState(Op0IsKill))
3934 .addReg(Op1, getKillRegState(Op1IsKill))
3935 .addReg(Op2, getKillRegState(Op2IsKill))
3936 .addReg(Op3, getKillRegState(Op3IsKill));
3937 else {
3938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
3939 .addReg(Op0, getKillRegState(Op0IsKill))
3940 .addReg(Op1, getKillRegState(Op1IsKill))
3941 .addReg(Op2, getKillRegState(Op2IsKill))
3942 .addReg(Op3, getKillRegState(Op3IsKill));
3943 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3944 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
3945 }
3946 return ResultReg;
3947}
3948
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003949
3950namespace llvm {
3951 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3952 const TargetLibraryInfo *libInfo) {
3953 return new X86FastISel(funcInfo, libInfo);
3954 }
3955}