blob: 654283f32f6f926140d05002eb6e001f1247c249 [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
Craig Topper619b7592017-09-02 18:53:46 +0000113 bool X86SelectSExt(const Instruction *I);
114
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000115 bool X86SelectBranch(const Instruction *I);
116
117 bool X86SelectShift(const Instruction *I);
118
119 bool X86SelectDivRem(const Instruction *I);
120
121 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
122
123 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
124
125 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
126
127 bool X86SelectSelect(const Instruction *I);
128
129 bool X86SelectTrunc(const Instruction *I);
130
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000131 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
132 const TargetRegisterClass *RC);
133
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000134 bool X86SelectFPExt(const Instruction *I);
135 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000136 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000137
138 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000139 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000140 }
141 const X86TargetMachine *getTargetMachine() const {
142 return static_cast<const X86TargetMachine *>(&TM);
143 }
144
145 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
146
147 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
148 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
149 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
150 unsigned fastMaterializeConstant(const Constant *C) override;
151
152 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
153
154 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
155
156 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
157 /// computed in an SSE register, not on the X87 floating point stack.
158 bool isScalarFPTypeInSSEReg(EVT VT) const {
159 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
160 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
161 }
162
163 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
164
165 bool IsMemcpySmall(uint64_t Len);
166
167 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
168 X86AddressMode SrcAM, uint64_t Len);
169
170 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
171 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000172
173 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
174 X86AddressMode &AM);
Craig Topper7ef6ea32016-12-05 04:51:31 +0000175
176 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
177 const TargetRegisterClass *RC, unsigned Op0,
178 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
179 unsigned Op2, bool Op2IsKill, unsigned Op3,
180 bool Op3IsKill);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000181};
182
183} // end anonymous namespace.
184
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000185static std::pair<unsigned, bool>
186getX86SSEConditionCode(CmpInst::Predicate Predicate) {
187 unsigned CC;
188 bool NeedSwap = false;
189
190 // SSE Condition code mapping:
191 // 0 - EQ
192 // 1 - LT
193 // 2 - LE
194 // 3 - UNORD
195 // 4 - NEQ
196 // 5 - NLT
197 // 6 - NLE
198 // 7 - ORD
199 switch (Predicate) {
200 default: llvm_unreachable("Unexpected predicate");
201 case CmpInst::FCMP_OEQ: CC = 0; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000202 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000203 case CmpInst::FCMP_OLT: CC = 1; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000204 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000205 case CmpInst::FCMP_OLE: CC = 2; break;
206 case CmpInst::FCMP_UNO: CC = 3; break;
207 case CmpInst::FCMP_UNE: CC = 4; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000208 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000209 case CmpInst::FCMP_UGE: CC = 5; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000210 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000211 case CmpInst::FCMP_UGT: CC = 6; break;
212 case CmpInst::FCMP_ORD: CC = 7; break;
Craig Topper4f8656a2017-10-09 01:05:15 +0000213 case CmpInst::FCMP_UEQ: CC = 8; break;
214 case CmpInst::FCMP_ONE: CC = 12; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000215 }
216
217 return std::make_pair(CC, NeedSwap);
218}
219
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000220/// \brief Adds a complex addressing mode to the given machine instr builder.
221/// Note, this will constrain the index register. If its not possible to
222/// constrain the given index register, then a new one will be created. The
223/// IndexReg field of the addressing mode will be updated to match in this case.
224const MachineInstrBuilder &
225X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
226 X86AddressMode &AM) {
227 // First constrain the index register. It needs to be a GR64_NOSP.
228 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
229 MIB->getNumOperands() +
230 X86::AddrIndexReg);
231 return ::addFullAddress(MIB, AM);
232}
233
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000234/// \brief Check if it is possible to fold the condition from the XALU intrinsic
235/// into the user. The condition code will only be updated on success.
236bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
237 const Value *Cond) {
238 if (!isa<ExtractValueInst>(Cond))
239 return false;
240
241 const auto *EV = cast<ExtractValueInst>(Cond);
242 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
243 return false;
244
245 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
246 MVT RetVT;
247 const Function *Callee = II->getCalledFunction();
248 Type *RetTy =
249 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
250 if (!isTypeLegal(RetTy, RetVT))
251 return false;
252
253 if (RetVT != MVT::i32 && RetVT != MVT::i64)
254 return false;
255
256 X86::CondCode TmpCC;
257 switch (II->getIntrinsicID()) {
258 default: return false;
259 case Intrinsic::sadd_with_overflow:
260 case Intrinsic::ssub_with_overflow:
261 case Intrinsic::smul_with_overflow:
262 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
263 case Intrinsic::uadd_with_overflow:
264 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
265 }
266
267 // Check if both instructions are in the same basic block.
268 if (II->getParent() != I->getParent())
269 return false;
270
271 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000272 BasicBlock::const_iterator Start(I);
273 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000274 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
275 // We only expect extractvalue instructions between the intrinsic and the
276 // instruction to be selected.
277 if (!isa<ExtractValueInst>(Itr))
278 return false;
279
280 // Check that the extractvalue operand comes from the intrinsic.
281 const auto *EVI = cast<ExtractValueInst>(Itr);
282 if (EVI->getAggregateOperand() != II)
283 return false;
284 }
285
286 CC = TmpCC;
287 return true;
288}
289
290bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000291 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000292 if (evt == MVT::Other || !evt.isSimple())
293 // Unhandled type. Halt "fast" selection and bail.
294 return false;
295
296 VT = evt.getSimpleVT();
297 // For now, require SSE/SSE2 for performing floating-point operations,
298 // since x87 requires additional work.
299 if (VT == MVT::f64 && !X86ScalarSSEf64)
300 return false;
301 if (VT == MVT::f32 && !X86ScalarSSEf32)
302 return false;
303 // Similarly, no f80 support yet.
304 if (VT == MVT::f80)
305 return false;
306 // We only handle legal types. For example, on x86-32 the instruction
307 // selector contains all of the 64-bit instructions from x86-64,
308 // under the assumption that i64 won't be used if the target doesn't
309 // support it.
310 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
311}
312
313#include "X86GenCallingConv.inc"
314
315/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
316/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
317/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000318bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000319 MachineMemOperand *MMO, unsigned &ResultReg,
320 unsigned Alignment) {
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000321 bool HasSSE41 = Subtarget->hasSSE41();
Craig Topperca9c0802016-06-02 04:19:45 +0000322 bool HasAVX = Subtarget->hasAVX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000323 bool HasAVX2 = Subtarget->hasAVX2();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000324 bool HasAVX512 = Subtarget->hasAVX512();
325 bool HasVLX = Subtarget->hasVLX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000326 bool IsNonTemporal = MMO && MMO->isNonTemporal();
327
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000328 // Get opcode and regclass of the output for the given load instruction.
329 unsigned Opc = 0;
330 const TargetRegisterClass *RC = nullptr;
331 switch (VT.getSimpleVT().SimpleTy) {
332 default: return false;
333 case MVT::i1:
334 case MVT::i8:
335 Opc = X86::MOV8rm;
336 RC = &X86::GR8RegClass;
337 break;
338 case MVT::i16:
339 Opc = X86::MOV16rm;
340 RC = &X86::GR16RegClass;
341 break;
342 case MVT::i32:
343 Opc = X86::MOV32rm;
344 RC = &X86::GR32RegClass;
345 break;
346 case MVT::i64:
347 // Must be in x86-64 mode.
348 Opc = X86::MOV64rm;
349 RC = &X86::GR64RegClass;
350 break;
351 case MVT::f32:
352 if (X86ScalarSSEf32) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000353 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000354 RC = HasAVX512 ? &X86::FR32XRegClass : &X86::FR32RegClass;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000355 } else {
356 Opc = X86::LD_Fp32m;
357 RC = &X86::RFP32RegClass;
358 }
359 break;
360 case MVT::f64:
361 if (X86ScalarSSEf64) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000362 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000363 RC = HasAVX512 ? &X86::FR64XRegClass : &X86::FR64RegClass;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000364 } else {
365 Opc = X86::LD_Fp64m;
366 RC = &X86::RFP64RegClass;
367 }
368 break;
369 case MVT::f80:
370 // No f80 support yet.
371 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000372 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000373 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000374 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
375 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000376 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000377 Opc = HasVLX ? X86::VMOVAPSZ128rm :
378 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000379 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000380 Opc = HasVLX ? X86::VMOVUPSZ128rm :
381 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000382 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000383 break;
384 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000385 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000386 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
387 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000388 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000389 Opc = HasVLX ? X86::VMOVAPDZ128rm :
390 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000391 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000392 Opc = HasVLX ? X86::VMOVUPDZ128rm :
393 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000394 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000395 break;
396 case MVT::v4i32:
397 case MVT::v2i64:
398 case MVT::v8i16:
399 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000400 if (IsNonTemporal && Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000401 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
402 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000403 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000404 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
405 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000406 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000407 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
408 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000409 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000410 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000411 case MVT::v8f32:
412 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000413 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000414 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
Simon Pilgrimf7113fd2017-06-06 14:18:39 +0000415 else if (IsNonTemporal && Alignment >= 16)
416 return false; // Force split for X86::VMOVNTDQArm
Craig Topperdfc4fc92016-09-05 23:58:40 +0000417 else if (Alignment >= 32)
418 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000419 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000420 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000421 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
Craig Topperca9c0802016-06-02 04:19:45 +0000422 break;
423 case MVT::v4f64:
424 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000425 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topper728fa7b2017-10-27 20:13:10 +0000426 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
Simon Pilgrimf7113fd2017-06-06 14:18:39 +0000427 else if (IsNonTemporal && Alignment >= 16)
428 return false; // Force split for X86::VMOVNTDQArm
Craig Topperdfc4fc92016-09-05 23:58:40 +0000429 else if (Alignment >= 32)
430 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000431 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000432 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000433 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
Craig Topperca9c0802016-06-02 04:19:45 +0000434 break;
435 case MVT::v8i32:
436 case MVT::v4i64:
437 case MVT::v16i16:
438 case MVT::v32i8:
439 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000440 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topper728fa7b2017-10-27 20:13:10 +0000441 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
Simon Pilgrimf7113fd2017-06-06 14:18:39 +0000442 else if (IsNonTemporal && Alignment >= 16)
443 return false; // Force split for X86::VMOVNTDQArm
Craig Topperdfc4fc92016-09-05 23:58:40 +0000444 else if (Alignment >= 32)
445 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000446 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000447 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
Craig Topper912f3b82017-10-29 05:14:26 +0000448 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
Craig Topperca9c0802016-06-02 04:19:45 +0000449 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000450 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000451 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000452 if (IsNonTemporal && Alignment >= 64)
453 Opc = X86::VMOVNTDQAZrm;
454 else
455 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000456 RC = &X86::VR512RegClass;
457 break;
458 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000459 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000460 if (IsNonTemporal && Alignment >= 64)
461 Opc = X86::VMOVNTDQAZrm;
462 else
463 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000464 RC = &X86::VR512RegClass;
465 break;
466 case MVT::v8i64:
467 case MVT::v16i32:
468 case MVT::v32i16:
469 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000470 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000471 // Note: There are a lot more choices based on type with AVX-512, but
472 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000473 if (IsNonTemporal && Alignment >= 64)
474 Opc = X86::VMOVNTDQAZrm;
475 else
476 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000477 RC = &X86::VR512RegClass;
478 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000479 }
480
481 ResultReg = createResultReg(RC);
482 MachineInstrBuilder MIB =
483 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
484 addFullAddress(MIB, AM);
485 if (MMO)
486 MIB->addMemOperand(*FuncInfo.MF, MMO);
487 return true;
488}
489
490/// X86FastEmitStore - Emit a machine instruction to store a value Val of
491/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
492/// and a displacement offset, or a GlobalAddress,
493/// i.e. V. Return true if it is possible.
494bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000495 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000496 MachineMemOperand *MMO, bool Aligned) {
Simon Pilgrimb6702ea2017-04-10 16:58:07 +0000497 bool HasSSE1 = Subtarget->hasSSE1();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000498 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000499 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000500 bool HasAVX = Subtarget->hasAVX();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000501 bool HasAVX512 = Subtarget->hasAVX512();
502 bool HasVLX = Subtarget->hasVLX();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000503 bool IsNonTemporal = MMO && MMO->isNonTemporal();
504
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000505 // Get opcode and regclass of the output for the given store instruction.
506 unsigned Opc = 0;
507 switch (VT.getSimpleVT().SimpleTy) {
508 case MVT::f80: // No f80 support yet.
509 default: return false;
510 case MVT::i1: {
511 // Mask out all but lowest bit.
512 unsigned AndResult = createResultReg(&X86::GR8RegClass);
513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
514 TII.get(X86::AND8ri), AndResult)
515 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
516 ValReg = AndResult;
Justin Bognerb03fd122016-08-17 05:10:15 +0000517 LLVM_FALLTHROUGH; // handle i1 as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000518 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000519 case MVT::i8: Opc = X86::MOV8mr; break;
520 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000521 case MVT::i32:
522 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
523 break;
524 case MVT::i64:
525 // Must be in x86-64 mode.
526 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
527 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000528 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000529 if (X86ScalarSSEf32) {
530 if (IsNonTemporal && HasSSE4A)
531 Opc = X86::MOVNTSS;
532 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000533 Opc = HasAVX512 ? X86::VMOVSSZmr :
534 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000535 } else
536 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000537 break;
538 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000539 if (X86ScalarSSEf32) {
540 if (IsNonTemporal && HasSSE4A)
541 Opc = X86::MOVNTSD;
542 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000543 Opc = HasAVX512 ? X86::VMOVSDZmr :
544 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000545 } else
546 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000547 break;
Simon Pilgrimb6702ea2017-04-10 16:58:07 +0000548 case MVT::x86mmx:
549 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
550 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000551 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000552 if (Aligned) {
553 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000554 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
555 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000556 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000557 Opc = HasVLX ? X86::VMOVAPSZ128mr :
558 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000559 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000560 Opc = HasVLX ? X86::VMOVUPSZ128mr :
561 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000562 break;
563 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000564 if (Aligned) {
565 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000566 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
567 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000568 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000569 Opc = HasVLX ? X86::VMOVAPDZ128mr :
570 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000571 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000572 Opc = HasVLX ? X86::VMOVUPDZ128mr :
573 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000574 break;
575 case MVT::v4i32:
576 case MVT::v2i64:
577 case MVT::v8i16:
578 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000579 if (Aligned) {
580 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000581 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
582 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000583 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000584 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
585 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000586 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000587 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
588 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000589 break;
590 case MVT::v8f32:
591 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000592 if (Aligned) {
593 if (IsNonTemporal)
594 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
595 else
596 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
597 } else
598 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000599 break;
600 case MVT::v4f64:
601 assert(HasAVX);
602 if (Aligned) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000603 if (IsNonTemporal)
604 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
605 else
606 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000607 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000608 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000609 break;
610 case MVT::v8i32:
611 case MVT::v4i64:
612 case MVT::v16i16:
613 case MVT::v32i8:
614 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000615 if (Aligned) {
616 if (IsNonTemporal)
617 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
618 else
619 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
620 } else
621 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000622 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000623 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000624 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000625 if (Aligned)
626 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
627 else
628 Opc = X86::VMOVUPSZmr;
629 break;
630 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000631 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000632 if (Aligned) {
633 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
634 } else
635 Opc = X86::VMOVUPDZmr;
636 break;
637 case MVT::v8i64:
638 case MVT::v16i32:
639 case MVT::v32i16:
640 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000641 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000642 // Note: There are a lot more choices based on type with AVX-512, but
643 // there's really no advantage when the store isn't masked.
644 if (Aligned)
645 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
646 else
647 Opc = X86::VMOVDQU64Zmr;
648 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000649 }
650
Quentin Colombetbf200682016-04-27 22:33:42 +0000651 const MCInstrDesc &Desc = TII.get(Opc);
652 // Some of the instructions in the previous switch use FR128 instead
653 // of FR32 for ValReg. Make sure the register we feed the instruction
654 // matches its register class constraints.
655 // Note: This is fine to do a copy from FR32 to FR128, this is the
656 // same registers behind the scene and actually why it did not trigger
657 // any bugs before.
658 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000659 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000660 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000661 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
662 if (MMO)
663 MIB->addMemOperand(*FuncInfo.MF, MMO);
664
665 return true;
666}
667
668bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000669 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000670 MachineMemOperand *MMO, bool Aligned) {
671 // Handle 'null' like i32/i64 0.
672 if (isa<ConstantPointerNull>(Val))
673 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
674
675 // If this is a store of a simple constant, fold the constant into the store.
676 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
677 unsigned Opc = 0;
678 bool Signed = true;
679 switch (VT.getSimpleVT().SimpleTy) {
680 default: break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000681 case MVT::i1:
682 Signed = false;
683 LLVM_FALLTHROUGH; // Handle as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000684 case MVT::i8: Opc = X86::MOV8mi; break;
685 case MVT::i16: Opc = X86::MOV16mi; break;
686 case MVT::i32: Opc = X86::MOV32mi; break;
687 case MVT::i64:
688 // Must be a 32-bit sign extended value.
689 if (isInt<32>(CI->getSExtValue()))
690 Opc = X86::MOV64mi32;
691 break;
692 }
693
694 if (Opc) {
695 MachineInstrBuilder MIB =
696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
697 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
698 : CI->getZExtValue());
699 if (MMO)
700 MIB->addMemOperand(*FuncInfo.MF, MMO);
701 return true;
702 }
703 }
704
705 unsigned ValReg = getRegForValue(Val);
706 if (ValReg == 0)
707 return false;
708
709 bool ValKill = hasTrivialKill(Val);
710 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
711}
712
713/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
714/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
715/// ISD::SIGN_EXTEND).
716bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
717 unsigned Src, EVT SrcVT,
718 unsigned &ResultReg) {
719 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
720 Src, /*TODO: Kill=*/false);
721 if (RR == 0)
722 return false;
723
724 ResultReg = RR;
725 return true;
726}
727
728bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
729 // Handle constant address.
730 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
731 // Can't handle alternate code models yet.
732 if (TM.getCodeModel() != CodeModel::Small)
733 return false;
734
735 // Can't handle TLS yet.
736 if (GV->isThreadLocal())
737 return false;
738
739 // RIP-relative addresses can't have additional register operands, so if
740 // we've already folded stuff into the addressing mode, just force the
741 // global value into its own register, which we can use as the basereg.
742 if (!Subtarget->isPICStyleRIPRel() ||
743 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
744 // Okay, we've committed to selecting this global. Set up the address.
745 AM.GV = GV;
746
747 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000748 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000749
750 // If this reference is relative to the pic base, set it now.
751 if (isGlobalRelativeToPICBase(GVFlags)) {
752 // FIXME: How do we know Base.Reg is free??
753 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
754 }
755
756 // Unless the ABI requires an extra load, return a direct reference to
757 // the global.
758 if (!isGlobalStubReference(GVFlags)) {
759 if (Subtarget->isPICStyleRIPRel()) {
760 // Use rip-relative addressing if we can. Above we verified that the
761 // base and index registers are unused.
762 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
763 AM.Base.Reg = X86::RIP;
764 }
765 AM.GVOpFlags = GVFlags;
766 return true;
767 }
768
769 // Ok, we need to do a load from a stub. If we've already loaded from
770 // this stub, reuse the loaded pointer, otherwise emit the load now.
771 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
772 unsigned LoadReg;
773 if (I != LocalValueMap.end() && I->second != 0) {
774 LoadReg = I->second;
775 } else {
776 // Issue load from stub.
777 unsigned Opc = 0;
778 const TargetRegisterClass *RC = nullptr;
779 X86AddressMode StubAM;
780 StubAM.Base.Reg = AM.Base.Reg;
781 StubAM.GV = GV;
782 StubAM.GVOpFlags = GVFlags;
783
784 // Prepare for inserting code in the local-value area.
785 SavePoint SaveInsertPt = enterLocalValueArea();
786
Mehdi Amini44ede332015-07-09 02:09:04 +0000787 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000788 Opc = X86::MOV64rm;
789 RC = &X86::GR64RegClass;
790
791 if (Subtarget->isPICStyleRIPRel())
792 StubAM.Base.Reg = X86::RIP;
793 } else {
794 Opc = X86::MOV32rm;
795 RC = &X86::GR32RegClass;
796 }
797
798 LoadReg = createResultReg(RC);
799 MachineInstrBuilder LoadMI =
800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
801 addFullAddress(LoadMI, StubAM);
802
803 // Ok, back to normal mode.
804 leaveLocalValueArea(SaveInsertPt);
805
806 // Prevent loading GV stub multiple times in same MBB.
807 LocalValueMap[V] = LoadReg;
808 }
809
810 // Now construct the final address. Note that the Disp, Scale,
811 // and Index values may already be set here.
812 AM.Base.Reg = LoadReg;
813 AM.GV = nullptr;
814 return true;
815 }
816 }
817
818 // If all else fails, try to materialize the value in a register.
819 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
820 if (AM.Base.Reg == 0) {
821 AM.Base.Reg = getRegForValue(V);
822 return AM.Base.Reg != 0;
823 }
824 if (AM.IndexReg == 0) {
825 assert(AM.Scale == 1 && "Scale with no index!");
826 AM.IndexReg = getRegForValue(V);
827 return AM.IndexReg != 0;
828 }
829 }
830
831 return false;
832}
833
834/// X86SelectAddress - Attempt to fill in an address from the given value.
835///
836bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
837 SmallVector<const Value *, 32> GEPs;
838redo_gep:
839 const User *U = nullptr;
840 unsigned Opcode = Instruction::UserOp1;
841 if (const Instruction *I = dyn_cast<Instruction>(V)) {
842 // Don't walk into other basic blocks; it's possible we haven't
843 // visited them yet, so the instructions may not yet be assigned
844 // virtual registers.
845 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
846 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
847 Opcode = I->getOpcode();
848 U = I;
849 }
850 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
851 Opcode = C->getOpcode();
852 U = C;
853 }
854
855 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
856 if (Ty->getAddressSpace() > 255)
857 // Fast instruction selection doesn't support the special
858 // address spaces.
859 return false;
860
861 switch (Opcode) {
862 default: break;
863 case Instruction::BitCast:
864 // Look past bitcasts.
865 return X86SelectAddress(U->getOperand(0), AM);
866
867 case Instruction::IntToPtr:
868 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000869 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
870 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000871 return X86SelectAddress(U->getOperand(0), AM);
872 break;
873
874 case Instruction::PtrToInt:
875 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000876 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000877 return X86SelectAddress(U->getOperand(0), AM);
878 break;
879
880 case Instruction::Alloca: {
881 // Do static allocas.
882 const AllocaInst *A = cast<AllocaInst>(V);
883 DenseMap<const AllocaInst *, int>::iterator SI =
884 FuncInfo.StaticAllocaMap.find(A);
885 if (SI != FuncInfo.StaticAllocaMap.end()) {
886 AM.BaseType = X86AddressMode::FrameIndexBase;
887 AM.Base.FrameIndex = SI->second;
888 return true;
889 }
890 break;
891 }
892
893 case Instruction::Add: {
894 // Adds of constants are common and easy enough.
895 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
896 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
897 // They have to fit in the 32-bit signed displacement field though.
898 if (isInt<32>(Disp)) {
899 AM.Disp = (uint32_t)Disp;
900 return X86SelectAddress(U->getOperand(0), AM);
901 }
902 }
903 break;
904 }
905
906 case Instruction::GetElementPtr: {
907 X86AddressMode SavedAM = AM;
908
909 // Pattern-match simple GEPs.
910 uint64_t Disp = (int32_t)AM.Disp;
911 unsigned IndexReg = AM.IndexReg;
912 unsigned Scale = AM.Scale;
913 gep_type_iterator GTI = gep_type_begin(U);
914 // Iterate through the indices, folding what we can. Constants can be
915 // folded, and one dynamic index can be handled, if the scale is supported.
916 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
917 i != e; ++i, ++GTI) {
918 const Value *Op = *i;
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000919 if (StructType *STy = GTI.getStructTypeOrNull()) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000920 const StructLayout *SL = DL.getStructLayout(STy);
921 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
922 continue;
923 }
924
925 // A array/variable index is always of the form i*S where S is the
926 // constant scale size. See if we can push the scale into immediates.
927 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
928 for (;;) {
929 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
930 // Constant-offset addressing.
931 Disp += CI->getSExtValue() * S;
932 break;
933 }
934 if (canFoldAddIntoGEP(U, Op)) {
935 // A compatible add with a constant operand. Fold the constant.
936 ConstantInt *CI =
937 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
938 Disp += CI->getSExtValue() * S;
939 // Iterate on the other operand.
940 Op = cast<AddOperator>(Op)->getOperand(0);
941 continue;
942 }
943 if (IndexReg == 0 &&
944 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
945 (S == 1 || S == 2 || S == 4 || S == 8)) {
946 // Scaled-index addressing.
947 Scale = S;
948 IndexReg = getRegForGEPIndex(Op).first;
949 if (IndexReg == 0)
950 return false;
951 break;
952 }
953 // Unsupported.
954 goto unsupported_gep;
955 }
956 }
957
958 // Check for displacement overflow.
959 if (!isInt<32>(Disp))
960 break;
961
962 AM.IndexReg = IndexReg;
963 AM.Scale = Scale;
964 AM.Disp = (uint32_t)Disp;
965 GEPs.push_back(V);
966
967 if (const GetElementPtrInst *GEP =
968 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
969 // Ok, the GEP indices were covered by constant-offset and scaled-index
970 // addressing. Update the address state and move on to examining the base.
971 V = GEP;
972 goto redo_gep;
973 } else if (X86SelectAddress(U->getOperand(0), AM)) {
974 return true;
975 }
976
977 // If we couldn't merge the gep value into this addr mode, revert back to
978 // our address and just match the value instead of completely failing.
979 AM = SavedAM;
980
David Majnemerd7708772016-06-24 04:05:21 +0000981 for (const Value *I : reverse(GEPs))
982 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000983 return true;
984
985 return false;
986 unsupported_gep:
987 // Ok, the GEP indices weren't all covered.
988 break;
989 }
990 }
991
992 return handleConstantAddresses(V, AM);
993}
994
995/// X86SelectCallAddress - Attempt to fill in an address from the given value.
996///
997bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
998 const User *U = nullptr;
999 unsigned Opcode = Instruction::UserOp1;
1000 const Instruction *I = dyn_cast<Instruction>(V);
1001 // Record if the value is defined in the same basic block.
1002 //
1003 // This information is crucial to know whether or not folding an
1004 // operand is valid.
1005 // Indeed, FastISel generates or reuses a virtual register for all
1006 // operands of all instructions it selects. Obviously, the definition and
1007 // its uses must use the same virtual register otherwise the produced
1008 // code is incorrect.
1009 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1010 // registers for values that are alive across basic blocks. This ensures
1011 // that the values are consistently set between across basic block, even
1012 // if different instruction selection mechanisms are used (e.g., a mix of
1013 // SDISel and FastISel).
1014 // For values local to a basic block, the instruction selection process
1015 // generates these virtual registers with whatever method is appropriate
1016 // for its needs. In particular, FastISel and SDISel do not share the way
1017 // local virtual registers are set.
1018 // Therefore, this is impossible (or at least unsafe) to share values
1019 // between basic blocks unless they use the same instruction selection
1020 // method, which is not guarantee for X86.
1021 // Moreover, things like hasOneUse could not be used accurately, if we
1022 // allow to reference values across basic blocks whereas they are not
1023 // alive across basic blocks initially.
1024 bool InMBB = true;
1025 if (I) {
1026 Opcode = I->getOpcode();
1027 U = I;
1028 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1029 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1030 Opcode = C->getOpcode();
1031 U = C;
1032 }
1033
1034 switch (Opcode) {
1035 default: break;
1036 case Instruction::BitCast:
1037 // Look past bitcasts if its operand is in the same BB.
1038 if (InMBB)
1039 return X86SelectCallAddress(U->getOperand(0), AM);
1040 break;
1041
1042 case Instruction::IntToPtr:
1043 // Look past no-op inttoptrs if its operand is in the same BB.
1044 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001045 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1046 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001047 return X86SelectCallAddress(U->getOperand(0), AM);
1048 break;
1049
1050 case Instruction::PtrToInt:
1051 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001052 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001053 return X86SelectCallAddress(U->getOperand(0), AM);
1054 break;
1055 }
1056
1057 // Handle constant address.
1058 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1059 // Can't handle alternate code models yet.
1060 if (TM.getCodeModel() != CodeModel::Small)
1061 return false;
1062
1063 // RIP-relative addresses can't have additional register operands.
1064 if (Subtarget->isPICStyleRIPRel() &&
1065 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1066 return false;
1067
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001068 // Can't handle TLS.
1069 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1070 if (GVar->isThreadLocal())
1071 return false;
1072
1073 // Okay, we've committed to selecting this global. Set up the basic address.
1074 AM.GV = GV;
1075
Reid Kleckner7662d502017-08-05 00:10:43 +00001076 // Return a direct reference to the global. Fastisel can handle calls to
1077 // functions that require loads, such as dllimport and nonlazybind
1078 // functions.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001079 if (Subtarget->isPICStyleRIPRel()) {
1080 // Use rip-relative addressing if we can. Above we verified that the
1081 // base and index registers are unused.
1082 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1083 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001084 } else {
1085 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001086 }
1087
1088 return true;
1089 }
1090
1091 // If all else fails, try to materialize the value in a register.
1092 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1093 if (AM.Base.Reg == 0) {
1094 AM.Base.Reg = getRegForValue(V);
1095 return AM.Base.Reg != 0;
1096 }
1097 if (AM.IndexReg == 0) {
1098 assert(AM.Scale == 1 && "Scale with no index!");
1099 AM.IndexReg = getRegForValue(V);
1100 return AM.IndexReg != 0;
1101 }
1102 }
1103
1104 return false;
1105}
1106
1107
1108/// X86SelectStore - Select and emit code to implement store instructions.
1109bool X86FastISel::X86SelectStore(const Instruction *I) {
1110 // Atomic stores need special handling.
1111 const StoreInst *S = cast<StoreInst>(I);
1112
1113 if (S->isAtomic())
1114 return false;
1115
Manman Ren57518142016-04-11 21:08:06 +00001116 const Value *PtrV = I->getOperand(1);
1117 if (TLI.supportSwiftError()) {
1118 // Swifterror values can come from either a function parameter with
1119 // swifterror attribute or an alloca with swifterror attribute.
1120 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1121 if (Arg->hasSwiftErrorAttr())
1122 return false;
1123 }
1124
1125 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1126 if (Alloca->isSwiftError())
1127 return false;
1128 }
1129 }
1130
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001131 const Value *Val = S->getValueOperand();
1132 const Value *Ptr = S->getPointerOperand();
1133
1134 MVT VT;
1135 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1136 return false;
1137
1138 unsigned Alignment = S->getAlignment();
1139 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1140 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1141 Alignment = ABIAlignment;
1142 bool Aligned = Alignment >= ABIAlignment;
1143
1144 X86AddressMode AM;
1145 if (!X86SelectAddress(Ptr, AM))
1146 return false;
1147
1148 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1149}
1150
1151/// X86SelectRet - Select and emit code to implement ret instructions.
1152bool X86FastISel::X86SelectRet(const Instruction *I) {
1153 const ReturnInst *Ret = cast<ReturnInst>(I);
1154 const Function &F = *I->getParent()->getParent();
1155 const X86MachineFunctionInfo *X86MFInfo =
1156 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1157
1158 if (!FuncInfo.CanLowerReturn)
1159 return false;
1160
Manman Ren57518142016-04-11 21:08:06 +00001161 if (TLI.supportSwiftError() &&
1162 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1163 return false;
1164
Manman Rened967f32016-01-12 01:08:46 +00001165 if (TLI.supportSplitCSR(FuncInfo.MF))
1166 return false;
1167
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001168 CallingConv::ID CC = F.getCallingConv();
1169 if (CC != CallingConv::C &&
1170 CC != CallingConv::Fast &&
1171 CC != CallingConv::X86_FastCall &&
Nico Weberecdf45b2016-07-14 13:54:26 +00001172 CC != CallingConv::X86_StdCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001173 CC != CallingConv::X86_ThisCall &&
Nico Weber8d66df12016-07-15 20:18:37 +00001174 CC != CallingConv::X86_64_SysV &&
Martin Storsjo2f24e932017-07-17 20:05:19 +00001175 CC != CallingConv::Win64)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001176 return false;
1177
Nico Weberc7bf6462016-07-12 01:30:35 +00001178 // Don't handle popping bytes if they don't fit the ret's immediate.
1179 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001180 return false;
1181
1182 // fastcc with -tailcallopt is intended to provide a guaranteed
1183 // tail call optimization. Fastisel doesn't know how to do that.
1184 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1185 return false;
1186
1187 // Let SDISel handle vararg functions.
1188 if (F.isVarArg())
1189 return false;
1190
1191 // Build a list of return value registers.
1192 SmallVector<unsigned, 4> RetRegs;
1193
1194 if (Ret->getNumOperands() > 0) {
1195 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001196 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001197
1198 // Analyze operands of the call, assigning locations to each operand.
1199 SmallVector<CCValAssign, 16> ValLocs;
1200 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1201 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1202
1203 const Value *RV = Ret->getOperand(0);
1204 unsigned Reg = getRegForValue(RV);
1205 if (Reg == 0)
1206 return false;
1207
1208 // Only handle a single return value for now.
1209 if (ValLocs.size() != 1)
1210 return false;
1211
1212 CCValAssign &VA = ValLocs[0];
1213
1214 // Don't bother handling odd stuff for now.
1215 if (VA.getLocInfo() != CCValAssign::Full)
1216 return false;
1217 // Only handle register returns for now.
1218 if (!VA.isRegLoc())
1219 return false;
1220
1221 // The calling-convention tables for x87 returns don't tell
1222 // the whole story.
1223 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1224 return false;
1225
1226 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001227 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001228 EVT DstVT = VA.getValVT();
1229 // Special handling for extended integers.
1230 if (SrcVT != DstVT) {
1231 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1232 return false;
1233
1234 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1235 return false;
1236
1237 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1238
1239 if (SrcVT == MVT::i1) {
1240 if (Outs[0].Flags.isSExt())
1241 return false;
1242 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1243 SrcVT = MVT::i8;
1244 }
1245 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1246 ISD::SIGN_EXTEND;
1247 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1248 SrcReg, /*TODO: Kill=*/false);
1249 }
1250
1251 // Make the copy.
1252 unsigned DstReg = VA.getLocReg();
1253 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1254 // Avoid a cross-class copy. This is very unlikely.
1255 if (!SrcRC->contains(DstReg))
1256 return false;
1257 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1258 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1259
1260 // Add register to return instruction.
1261 RetRegs.push_back(VA.getLocReg());
1262 }
1263
Manman Ren1c3f65a2016-04-26 18:08:06 +00001264 // Swift calling convention does not require we copy the sret argument
1265 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1266
Dimitry Andric227b9282016-01-03 17:22:03 +00001267 // All x86 ABIs require that for returning structs by value we copy
1268 // the sret argument into %rax/%eax (depending on ABI) for the return.
1269 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001270 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001271 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001272 unsigned Reg = X86MFInfo->getSRetReturnReg();
1273 assert(Reg &&
1274 "SRetReturnReg should have been set in LowerFormalArguments()!");
1275 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1277 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1278 RetRegs.push_back(RetReg);
1279 }
1280
1281 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001282 MachineInstrBuilder MIB;
1283 if (X86MFInfo->getBytesToPopOnReturn()) {
1284 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1285 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1286 .addImm(X86MFInfo->getBytesToPopOnReturn());
1287 } else {
1288 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1289 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1290 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001291 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1292 MIB.addReg(RetRegs[i], RegState::Implicit);
1293 return true;
1294}
1295
1296/// X86SelectLoad - Select and emit code to implement load instructions.
1297///
1298bool X86FastISel::X86SelectLoad(const Instruction *I) {
1299 const LoadInst *LI = cast<LoadInst>(I);
1300
1301 // Atomic loads need special handling.
1302 if (LI->isAtomic())
1303 return false;
1304
Manman Ren57518142016-04-11 21:08:06 +00001305 const Value *SV = I->getOperand(0);
1306 if (TLI.supportSwiftError()) {
1307 // Swifterror values can come from either a function parameter with
1308 // swifterror attribute or an alloca with swifterror attribute.
1309 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1310 if (Arg->hasSwiftErrorAttr())
1311 return false;
1312 }
1313
1314 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1315 if (Alloca->isSwiftError())
1316 return false;
1317 }
1318 }
1319
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001320 MVT VT;
1321 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1322 return false;
1323
1324 const Value *Ptr = LI->getPointerOperand();
1325
1326 X86AddressMode AM;
1327 if (!X86SelectAddress(Ptr, AM))
1328 return false;
1329
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001330 unsigned Alignment = LI->getAlignment();
1331 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1332 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1333 Alignment = ABIAlignment;
1334
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001335 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001336 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1337 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001338 return false;
1339
1340 updateValueMap(I, ResultReg);
1341 return true;
1342}
1343
1344static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
Craig Topper9f01f602017-10-30 21:09:19 +00001345 bool HasAVX512 = Subtarget->hasAVX512();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001346 bool HasAVX = Subtarget->hasAVX();
1347 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1348 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1349
1350 switch (VT.getSimpleVT().SimpleTy) {
1351 default: return 0;
1352 case MVT::i8: return X86::CMP8rr;
1353 case MVT::i16: return X86::CMP16rr;
1354 case MVT::i32: return X86::CMP32rr;
1355 case MVT::i64: return X86::CMP64rr;
1356 case MVT::f32:
Craig Topper9f01f602017-10-30 21:09:19 +00001357 return X86ScalarSSEf32 ? (HasAVX512 ? X86::VUCOMISSZrr : HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001358 case MVT::f64:
Craig Topper9f01f602017-10-30 21:09:19 +00001359 return X86ScalarSSEf64 ? (HasAVX512 ? X86::VUCOMISDZrr : HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001360 }
1361}
1362
Rafael Espindola19141f22015-03-16 14:05:49 +00001363/// If we have a comparison with RHS as the RHS of the comparison, return an
1364/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001365static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001366 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001367 switch (VT.getSimpleVT().SimpleTy) {
1368 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001369 default:
1370 return 0;
1371 case MVT::i8:
1372 return X86::CMP8ri;
1373 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001374 if (isInt<8>(Val))
1375 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001376 return X86::CMP16ri;
1377 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001378 if (isInt<8>(Val))
1379 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001380 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001381 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001382 if (isInt<8>(Val))
1383 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001384 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1385 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001386 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001387 return X86::CMP64ri32;
1388 return 0;
1389 }
1390}
1391
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001392bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1393 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001394 unsigned Op0Reg = getRegForValue(Op0);
1395 if (Op0Reg == 0) return false;
1396
1397 // Handle 'null' like i32/i64 0.
1398 if (isa<ConstantPointerNull>(Op1))
1399 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1400
1401 // We have two options: compare with register or immediate. If the RHS of
1402 // the compare is an immediate that we can fold into this compare, use
1403 // CMPri, otherwise use CMPrr.
1404 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1405 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1406 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1407 .addReg(Op0Reg)
1408 .addImm(Op1C->getSExtValue());
1409 return true;
1410 }
1411 }
1412
1413 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1414 if (CompareOpc == 0) return false;
1415
1416 unsigned Op1Reg = getRegForValue(Op1);
1417 if (Op1Reg == 0) return false;
1418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1419 .addReg(Op0Reg)
1420 .addReg(Op1Reg);
1421
1422 return true;
1423}
1424
1425bool X86FastISel::X86SelectCmp(const Instruction *I) {
1426 const CmpInst *CI = cast<CmpInst>(I);
1427
1428 MVT VT;
1429 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1430 return false;
1431
1432 // Try to optimize or fold the cmp.
1433 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1434 unsigned ResultReg = 0;
1435 switch (Predicate) {
1436 default: break;
1437 case CmpInst::FCMP_FALSE: {
1438 ResultReg = createResultReg(&X86::GR32RegClass);
1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1440 ResultReg);
1441 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1442 X86::sub_8bit);
1443 if (!ResultReg)
1444 return false;
1445 break;
1446 }
1447 case CmpInst::FCMP_TRUE: {
1448 ResultReg = createResultReg(&X86::GR8RegClass);
1449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1450 ResultReg).addImm(1);
1451 break;
1452 }
1453 }
1454
1455 if (ResultReg) {
1456 updateValueMap(I, ResultReg);
1457 return true;
1458 }
1459
1460 const Value *LHS = CI->getOperand(0);
1461 const Value *RHS = CI->getOperand(1);
1462
1463 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1464 // We don't have to materialize a zero constant for this case and can just use
1465 // %x again on the RHS.
1466 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1467 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1468 if (RHSC && RHSC->isNullValue())
1469 RHS = LHS;
1470 }
1471
1472 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00001473 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001474 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1475 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1476 };
Craig Topper428169a2016-09-05 07:14:21 +00001477 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001478 switch (Predicate) {
1479 default: break;
1480 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1481 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1482 }
1483
1484 ResultReg = createResultReg(&X86::GR8RegClass);
1485 if (SETFOpc) {
1486 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1487 return false;
1488
1489 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1490 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1492 FlagReg1);
1493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1494 FlagReg2);
1495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1496 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1497 updateValueMap(I, ResultReg);
1498 return true;
1499 }
1500
1501 X86::CondCode CC;
1502 bool SwapArgs;
Igor Bregerdb754552017-05-11 06:36:37 +00001503 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001504 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1505 unsigned Opc = X86::getSETFromCond(CC);
1506
1507 if (SwapArgs)
1508 std::swap(LHS, RHS);
1509
1510 // Emit a compare of LHS/RHS.
1511 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1512 return false;
1513
1514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1515 updateValueMap(I, ResultReg);
1516 return true;
1517}
1518
1519bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001520 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001521 if (!TLI.isTypeLegal(DstVT))
1522 return false;
1523
1524 unsigned ResultReg = getRegForValue(I->getOperand(0));
1525 if (ResultReg == 0)
1526 return false;
1527
1528 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001529 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Craig Topper088ba172016-12-05 06:09:55 +00001530 if (SrcVT == MVT::i1) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001531 // Set the high bits to zero.
1532 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1533 SrcVT = MVT::i8;
1534
1535 if (ResultReg == 0)
1536 return false;
1537 }
1538
1539 if (DstVT == MVT::i64) {
1540 // Handle extension to 64-bits via sub-register shenanigans.
1541 unsigned MovInst;
1542
1543 switch (SrcVT.SimpleTy) {
1544 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1545 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1546 case MVT::i32: MovInst = X86::MOV32rr; break;
1547 default: llvm_unreachable("Unexpected zext to i64 source type");
1548 }
1549
1550 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1551 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1552 .addReg(ResultReg);
1553
1554 ResultReg = createResultReg(&X86::GR64RegClass);
1555 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1556 ResultReg)
1557 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
Craig Topper619b7592017-09-02 18:53:46 +00001558 } else if (DstVT == MVT::i16) {
1559 // i8->i16 doesn't exist in the autogenerated isel table. Need to zero
1560 // extend to 32-bits and then extract down to 16-bits.
1561 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVZX32rr8),
1563 Result32).addReg(ResultReg);
1564
1565 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, /*Kill=*/true,
1566 X86::sub_16bit);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001567 } else if (DstVT != MVT::i8) {
1568 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1569 ResultReg, /*Kill=*/true);
1570 if (ResultReg == 0)
1571 return false;
1572 }
1573
1574 updateValueMap(I, ResultReg);
1575 return true;
1576}
1577
Craig Topper619b7592017-09-02 18:53:46 +00001578bool X86FastISel::X86SelectSExt(const Instruction *I) {
1579 EVT DstVT = TLI.getValueType(DL, I->getType());
1580 if (!TLI.isTypeLegal(DstVT))
1581 return false;
1582
1583 unsigned ResultReg = getRegForValue(I->getOperand(0));
1584 if (ResultReg == 0)
1585 return false;
1586
1587 // Handle sign-extension from i1 to i8.
1588 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1589 if (SrcVT == MVT::i1) {
1590 // Set the high bits to zero.
1591 unsigned ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg,
1592 /*TODO: Kill=*/false);
1593 if (ZExtReg == 0)
1594 return false;
1595
1596 // Negate the result to make an 8-bit sign extended value.
1597 ResultReg = createResultReg(&X86::GR8RegClass);
1598 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::NEG8r),
1599 ResultReg).addReg(ZExtReg);
1600
1601 SrcVT = MVT::i8;
1602 }
1603
1604 if (DstVT == MVT::i16) {
1605 // i8->i16 doesn't exist in the autogenerated isel table. Need to sign
1606 // extend to 32-bits and then extract down to 16-bits.
1607 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVSX32rr8),
1609 Result32).addReg(ResultReg);
1610
1611 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, /*Kill=*/true,
1612 X86::sub_16bit);
1613 } else if (DstVT != MVT::i8) {
1614 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND,
1615 ResultReg, /*Kill=*/true);
1616 if (ResultReg == 0)
1617 return false;
1618 }
1619
1620 updateValueMap(I, ResultReg);
1621 return true;
1622}
1623
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001624bool X86FastISel::X86SelectBranch(const Instruction *I) {
1625 // Unconditional branches are selected by tablegen-generated code.
1626 // Handle a conditional branch.
1627 const BranchInst *BI = cast<BranchInst>(I);
1628 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1629 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1630
1631 // Fold the common case of a conditional branch with a comparison
1632 // in the same block (values defined on other blocks may not have
1633 // initialized registers).
1634 X86::CondCode CC;
1635 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1636 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001637 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001638
1639 // Try to optimize or fold the cmp.
1640 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1641 switch (Predicate) {
1642 default: break;
1643 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1644 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1645 }
1646
1647 const Value *CmpLHS = CI->getOperand(0);
1648 const Value *CmpRHS = CI->getOperand(1);
1649
1650 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1651 // 0.0.
1652 // We don't have to materialize a zero constant for this case and can just
1653 // use %x again on the RHS.
1654 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1655 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1656 if (CmpRHSC && CmpRHSC->isNullValue())
1657 CmpRHS = CmpLHS;
1658 }
1659
1660 // Try to take advantage of fallthrough opportunities.
1661 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1662 std::swap(TrueMBB, FalseMBB);
1663 Predicate = CmpInst::getInversePredicate(Predicate);
1664 }
1665
1666 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1667 // code check. Instead two branch instructions are required to check all
1668 // the flags. First we change the predicate to a supported condition code,
1669 // which will be the first branch. Later one we will emit the second
1670 // branch.
1671 bool NeedExtraBranch = false;
1672 switch (Predicate) {
1673 default: break;
1674 case CmpInst::FCMP_OEQ:
Justin Bognerb03fd122016-08-17 05:10:15 +00001675 std::swap(TrueMBB, FalseMBB);
1676 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001677 case CmpInst::FCMP_UNE:
1678 NeedExtraBranch = true;
1679 Predicate = CmpInst::FCMP_ONE;
1680 break;
1681 }
1682
1683 bool SwapArgs;
1684 unsigned BranchOpc;
Igor Bregerdb754552017-05-11 06:36:37 +00001685 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001686 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1687
1688 BranchOpc = X86::GetCondBranchFromCond(CC);
1689 if (SwapArgs)
1690 std::swap(CmpLHS, CmpRHS);
1691
1692 // Emit a compare of the LHS and RHS, setting the flags.
1693 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1694 return false;
1695
1696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1697 .addMBB(TrueMBB);
1698
1699 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1700 // to UNE above).
1701 if (NeedExtraBranch) {
1702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1703 .addMBB(TrueMBB);
1704 }
1705
Matthias Braun17af6072015-08-26 01:38:00 +00001706 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001707 return true;
1708 }
1709 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1710 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1711 // typically happen for _Bool and C++ bools.
1712 MVT SourceVT;
1713 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1714 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1715 unsigned TestOpc = 0;
1716 switch (SourceVT.SimpleTy) {
1717 default: break;
1718 case MVT::i8: TestOpc = X86::TEST8ri; break;
1719 case MVT::i16: TestOpc = X86::TEST16ri; break;
1720 case MVT::i32: TestOpc = X86::TEST32ri; break;
1721 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1722 }
1723 if (TestOpc) {
1724 unsigned OpReg = getRegForValue(TI->getOperand(0));
1725 if (OpReg == 0) return false;
Guy Blank9ae797a2016-08-21 08:02:27 +00001726
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001727 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1728 .addReg(OpReg).addImm(1);
1729
1730 unsigned JmpOpc = X86::JNE_1;
1731 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1732 std::swap(TrueMBB, FalseMBB);
1733 JmpOpc = X86::JE_1;
1734 }
1735
1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1737 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001738
1739 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001740 return true;
1741 }
1742 }
1743 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1744 // Fake request the condition, otherwise the intrinsic might be completely
1745 // optimized away.
1746 unsigned TmpReg = getRegForValue(BI->getCondition());
1747 if (TmpReg == 0)
1748 return false;
1749
1750 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1751
1752 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1753 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001754 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001755 return true;
1756 }
1757
1758 // Otherwise do a clumsy setcc and re-test it.
1759 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1760 // in an explicit cast, so make sure to handle that correctly.
1761 unsigned OpReg = getRegForValue(BI->getCondition());
1762 if (OpReg == 0) return false;
1763
Guy Blank2bdc74a2016-09-28 11:22:17 +00001764 // In case OpReg is a K register, COPY to a GPR
1765 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1766 unsigned KOpReg = OpReg;
Craig Topper058f2f62017-03-28 16:35:29 +00001767 OpReg = createResultReg(&X86::GR32RegClass);
Guy Blank2bdc74a2016-09-28 11:22:17 +00001768 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1769 TII.get(TargetOpcode::COPY), OpReg)
1770 .addReg(KOpReg);
Craig Topper058f2f62017-03-28 16:35:29 +00001771 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, /*Kill=*/true,
1772 X86::sub_8bit);
Guy Blank2bdc74a2016-09-28 11:22:17 +00001773 }
1774 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1775 .addReg(OpReg)
1776 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001777 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1778 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001779 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001780 return true;
1781}
1782
1783bool X86FastISel::X86SelectShift(const Instruction *I) {
1784 unsigned CReg = 0, OpReg = 0;
1785 const TargetRegisterClass *RC = nullptr;
Craig Topperd6945322017-10-27 21:00:59 +00001786 assert(!I->getType()->isIntegerTy(8) &&
1787 "i8 shifts should be handled by autogenerated table");
1788 if (I->getType()->isIntegerTy(16)) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001789 CReg = X86::CX;
1790 RC = &X86::GR16RegClass;
1791 switch (I->getOpcode()) {
Craig Topper202b5592017-10-28 19:56:56 +00001792 default: llvm_unreachable("Unexpected shift opcode");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001793 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1794 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1795 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001796 }
1797 } else if (I->getType()->isIntegerTy(32)) {
1798 CReg = X86::ECX;
1799 RC = &X86::GR32RegClass;
1800 switch (I->getOpcode()) {
Craig Topper202b5592017-10-28 19:56:56 +00001801 default: llvm_unreachable("Unexpected shift opcode");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001802 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1803 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1804 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001805 }
1806 } else if (I->getType()->isIntegerTy(64)) {
1807 CReg = X86::RCX;
1808 RC = &X86::GR64RegClass;
1809 switch (I->getOpcode()) {
Craig Topper202b5592017-10-28 19:56:56 +00001810 default: llvm_unreachable("Unexpected shift opcode");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001811 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1812 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1813 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001814 }
1815 } else {
1816 return false;
1817 }
1818
1819 MVT VT;
1820 if (!isTypeLegal(I->getType(), VT))
1821 return false;
1822
1823 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1824 if (Op0Reg == 0) return false;
1825
1826 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1827 if (Op1Reg == 0) return false;
1828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1829 CReg).addReg(Op1Reg);
1830
1831 // The shift instruction uses X86::CL. If we defined a super-register
1832 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
Craig Topperd6945322017-10-27 21:00:59 +00001833 assert(CReg != X86::CL && "CReg should be a super register of CL");
1834 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1835 TII.get(TargetOpcode::KILL), X86::CL)
1836 .addReg(CReg, RegState::Kill);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001837
1838 unsigned ResultReg = createResultReg(RC);
1839 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1840 .addReg(Op0Reg);
1841 updateValueMap(I, ResultReg);
1842 return true;
1843}
1844
1845bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1846 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1847 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1848 const static bool S = true; // IsSigned
1849 const static bool U = false; // !IsSigned
1850 const static unsigned Copy = TargetOpcode::COPY;
1851 // For the X86 DIV/IDIV instruction, in most cases the dividend
1852 // (numerator) must be in a specific register pair highreg:lowreg,
1853 // producing the quotient in lowreg and the remainder in highreg.
1854 // For most data types, to set up the instruction, the dividend is
1855 // copied into lowreg, and lowreg is sign-extended or zero-extended
1856 // into highreg. The exception is i8, where the dividend is defined
1857 // as a single register rather than a register pair, and we
1858 // therefore directly sign-extend or zero-extend the dividend into
1859 // lowreg, instead of copying, and ignore the highreg.
1860 const static struct DivRemEntry {
1861 // The following portion depends only on the data type.
1862 const TargetRegisterClass *RC;
1863 unsigned LowInReg; // low part of the register pair
1864 unsigned HighInReg; // high part of the register pair
1865 // The following portion depends on both the data type and the operation.
1866 struct DivRemResult {
1867 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1868 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1869 // highreg, or copying a zero into highreg.
1870 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1871 // zero/sign-extending into lowreg for i8.
1872 unsigned DivRemResultReg; // Register containing the desired result.
1873 bool IsOpSigned; // Whether to use signed or unsigned form.
1874 } ResultTable[NumOps];
1875 } OpTable[NumTypes] = {
1876 { &X86::GR8RegClass, X86::AX, 0, {
1877 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1878 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1879 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1880 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1881 }
1882 }, // i8
1883 { &X86::GR16RegClass, X86::AX, X86::DX, {
1884 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1885 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1886 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1887 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1888 }
1889 }, // i16
1890 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1891 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1892 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1893 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1894 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1895 }
1896 }, // i32
1897 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1898 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1899 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1900 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1901 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1902 }
1903 }, // i64
1904 };
1905
1906 MVT VT;
1907 if (!isTypeLegal(I->getType(), VT))
1908 return false;
1909
1910 unsigned TypeIndex, OpIndex;
1911 switch (VT.SimpleTy) {
1912 default: return false;
1913 case MVT::i8: TypeIndex = 0; break;
1914 case MVT::i16: TypeIndex = 1; break;
1915 case MVT::i32: TypeIndex = 2; break;
1916 case MVT::i64: TypeIndex = 3;
1917 if (!Subtarget->is64Bit())
1918 return false;
1919 break;
1920 }
1921
1922 switch (I->getOpcode()) {
1923 default: llvm_unreachable("Unexpected div/rem opcode");
1924 case Instruction::SDiv: OpIndex = 0; break;
1925 case Instruction::SRem: OpIndex = 1; break;
1926 case Instruction::UDiv: OpIndex = 2; break;
1927 case Instruction::URem: OpIndex = 3; break;
1928 }
1929
1930 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1931 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1932 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1933 if (Op0Reg == 0)
1934 return false;
1935 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1936 if (Op1Reg == 0)
1937 return false;
1938
1939 // Move op0 into low-order input register.
1940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1941 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1942 // Zero-extend or sign-extend into high-order input register.
1943 if (OpEntry.OpSignExtend) {
1944 if (OpEntry.IsOpSigned)
1945 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1946 TII.get(OpEntry.OpSignExtend));
1947 else {
1948 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1950 TII.get(X86::MOV32r0), Zero32);
1951
1952 // Copy the zero into the appropriate sub/super/identical physical
1953 // register. Unfortunately the operations needed are not uniform enough
1954 // to fit neatly into the table above.
Craig Topper088ba172016-12-05 06:09:55 +00001955 if (VT == MVT::i16) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1957 TII.get(Copy), TypeEntry.HighInReg)
1958 .addReg(Zero32, 0, X86::sub_16bit);
Craig Topper088ba172016-12-05 06:09:55 +00001959 } else if (VT == MVT::i32) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1961 TII.get(Copy), TypeEntry.HighInReg)
1962 .addReg(Zero32);
Craig Topper088ba172016-12-05 06:09:55 +00001963 } else if (VT == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1965 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1966 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1967 }
1968 }
1969 }
1970 // Generate the DIV/IDIV instruction.
1971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1972 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1973 // For i8 remainder, we can't reference AH directly, as we'll end
1974 // up with bogus copies like %R9B = COPY %AH. Reference AX
1975 // instead to prevent AH references in a REX instruction.
1976 //
1977 // The current assumption of the fast register allocator is that isel
Craig Topperb7e4c942017-09-26 21:35:11 +00001978 // won't generate explicit references to the GR8_NOREX registers. If
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001979 // the allocator and/or the backend get enhanced to be more robust in
1980 // that regard, this can be, and should be, removed.
1981 unsigned ResultReg = 0;
1982 if ((I->getOpcode() == Instruction::SRem ||
1983 I->getOpcode() == Instruction::URem) &&
1984 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1985 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1986 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1987 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1988 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1989
1990 // Shift AX right by 8 bits instead of using AH.
1991 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1992 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1993
1994 // Now reference the 8-bit subreg of the result.
1995 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1996 /*Kill=*/true, X86::sub_8bit);
1997 }
1998 // Copy the result out of the physreg if we haven't already.
1999 if (!ResultReg) {
2000 ResultReg = createResultReg(TypeEntry.RC);
2001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
2002 .addReg(OpEntry.DivRemResultReg);
2003 }
2004 updateValueMap(I, ResultReg);
2005
2006 return true;
2007}
2008
2009/// \brief Emit a conditional move instruction (if the are supported) to lower
2010/// the select.
2011bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2012 // Check if the subtarget supports these instructions.
2013 if (!Subtarget->hasCMov())
2014 return false;
2015
2016 // FIXME: Add support for i8.
2017 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2018 return false;
2019
2020 const Value *Cond = I->getOperand(0);
2021 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2022 bool NeedTest = true;
2023 X86::CondCode CC = X86::COND_NE;
2024
2025 // Optimize conditions coming from a compare if both instructions are in the
2026 // same basic block (values defined in other basic blocks may not have
2027 // initialized registers).
2028 const auto *CI = dyn_cast<CmpInst>(Cond);
2029 if (CI && (CI->getParent() == I->getParent())) {
2030 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2031
2032 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00002033 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002034 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2035 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2036 };
Craig Topper428169a2016-09-05 07:14:21 +00002037 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002038 switch (Predicate) {
2039 default: break;
2040 case CmpInst::FCMP_OEQ:
2041 SETFOpc = &SETFOpcTable[0][0];
2042 Predicate = CmpInst::ICMP_NE;
2043 break;
2044 case CmpInst::FCMP_UNE:
2045 SETFOpc = &SETFOpcTable[1][0];
2046 Predicate = CmpInst::ICMP_NE;
2047 break;
2048 }
2049
2050 bool NeedSwap;
Igor Bregerdb754552017-05-11 06:36:37 +00002051 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002052 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2053
2054 const Value *CmpLHS = CI->getOperand(0);
2055 const Value *CmpRHS = CI->getOperand(1);
2056 if (NeedSwap)
2057 std::swap(CmpLHS, CmpRHS);
2058
Mehdi Amini44ede332015-07-09 02:09:04 +00002059 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002060 // Emit a compare of the LHS and RHS, setting the flags.
2061 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2062 return false;
2063
2064 if (SETFOpc) {
2065 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2066 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2068 FlagReg1);
2069 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2070 FlagReg2);
2071 auto const &II = TII.get(SETFOpc[2]);
2072 if (II.getNumDefs()) {
2073 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2075 .addReg(FlagReg2).addReg(FlagReg1);
2076 } else {
2077 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2078 .addReg(FlagReg2).addReg(FlagReg1);
2079 }
2080 }
2081 NeedTest = false;
2082 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2083 // Fake request the condition, otherwise the intrinsic might be completely
2084 // optimized away.
2085 unsigned TmpReg = getRegForValue(Cond);
2086 if (TmpReg == 0)
2087 return false;
2088
2089 NeedTest = false;
2090 }
2091
2092 if (NeedTest) {
2093 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2094 // garbage. Indeed, only the less significant bit is supposed to be
2095 // accurate. If we read more than the lsb, we may see non-zero values
2096 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2097 // the select. This is achieved by performing TEST against 1.
2098 unsigned CondReg = getRegForValue(Cond);
2099 if (CondReg == 0)
2100 return false;
2101 bool CondIsKill = hasTrivialKill(Cond);
2102
Guy Blank2bdc74a2016-09-28 11:22:17 +00002103 // In case OpReg is a K register, COPY to a GPR
2104 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2105 unsigned KCondReg = CondReg;
Craig Topper058f2f62017-03-28 16:35:29 +00002106 CondReg = createResultReg(&X86::GR32RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002108 TII.get(TargetOpcode::COPY), CondReg)
2109 .addReg(KCondReg, getKillRegState(CondIsKill));
Craig Topper058f2f62017-03-28 16:35:29 +00002110 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2111 X86::sub_8bit);
Guy Blank2bdc74a2016-09-28 11:22:17 +00002112 }
2113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2114 .addReg(CondReg, getKillRegState(CondIsKill))
2115 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002116 }
2117
2118 const Value *LHS = I->getOperand(1);
2119 const Value *RHS = I->getOperand(2);
2120
2121 unsigned RHSReg = getRegForValue(RHS);
2122 bool RHSIsKill = hasTrivialKill(RHS);
2123
2124 unsigned LHSReg = getRegForValue(LHS);
2125 bool LHSIsKill = hasTrivialKill(LHS);
2126
2127 if (!LHSReg || !RHSReg)
2128 return false;
2129
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00002130 const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
2131 unsigned Opc = X86::getCMovFromCond(CC, TRI.getRegSizeInBits(*RC)/8);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002132 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2133 LHSReg, LHSIsKill);
2134 updateValueMap(I, ResultReg);
2135 return true;
2136}
2137
Sanjay Patel302404b2015-03-05 21:46:54 +00002138/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002139///
2140/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2141/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002142/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002143bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2144 // Optimize conditions coming from a compare if both instructions are in the
2145 // same basic block (values defined in other basic blocks may not have
2146 // initialized registers).
2147 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2148 if (!CI || (CI->getParent() != I->getParent()))
2149 return false;
2150
2151 if (I->getType() != CI->getOperand(0)->getType() ||
2152 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2153 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2154 return false;
2155
2156 const Value *CmpLHS = CI->getOperand(0);
2157 const Value *CmpRHS = CI->getOperand(1);
2158 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2159
2160 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2161 // We don't have to materialize a zero constant for this case and can just use
2162 // %x again on the RHS.
2163 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2164 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2165 if (CmpRHSC && CmpRHSC->isNullValue())
2166 CmpRHS = CmpLHS;
2167 }
2168
2169 unsigned CC;
2170 bool NeedSwap;
2171 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
Craig Topper4f8656a2017-10-09 01:05:15 +00002172 if (CC > 7 && !Subtarget->hasAVX())
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002173 return false;
2174
2175 if (NeedSwap)
2176 std::swap(CmpLHS, CmpRHS);
2177
Sanjay Patel302404b2015-03-05 21:46:54 +00002178 // Choose the SSE instruction sequence based on data type (float or double).
Craig Topper428169a2016-09-05 07:14:21 +00002179 static const uint16_t OpcTable[2][4] = {
Craig Topper6413f8a2016-12-06 04:58:39 +00002180 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2181 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002182 };
2183
Craig Topper428169a2016-09-05 07:14:21 +00002184 const uint16_t *Opc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002185 switch (RetVT.SimpleTy) {
2186 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002187 case MVT::f32: Opc = &OpcTable[0][0]; break;
2188 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002189 }
2190
2191 const Value *LHS = I->getOperand(1);
2192 const Value *RHS = I->getOperand(2);
2193
2194 unsigned LHSReg = getRegForValue(LHS);
2195 bool LHSIsKill = hasTrivialKill(LHS);
2196
2197 unsigned RHSReg = getRegForValue(RHS);
2198 bool RHSIsKill = hasTrivialKill(RHS);
2199
2200 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2201 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2202
2203 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2204 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2205
2206 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2207 return false;
2208
2209 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002210 unsigned ResultReg;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002211
2212 if (Subtarget->hasAVX512()) {
2213 // If we have AVX512 we can use a mask compare and masked movss/sd.
2214 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2215 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2216
2217 unsigned CmpOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002218 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002219 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2220 CmpRHSReg, CmpRHSIsKill, CC);
2221
2222 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2223 // bits of the result register since its not based on any of the inputs.
2224 unsigned ImplicitDefReg = createResultReg(VR128X);
2225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2226 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2227
2228 // Place RHSReg is the passthru of the masked movss/sd operation and put
2229 // LHS in the input. The mask input comes from the compare.
2230 unsigned MovOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002231 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
Craig Topper7ef6ea32016-12-05 04:51:31 +00002232 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2233 CmpReg, true, ImplicitDefReg, true,
2234 LHSReg, LHSIsKill);
2235
2236 ResultReg = createResultReg(RC);
2237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2238 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2239
2240 } else if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002241 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2242
Sanjay Patel302404b2015-03-05 21:46:54 +00002243 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2244 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2245 // uses XMM0 as the selection register. That may need just as many
2246 // instructions as the AND/ANDN/OR sequence due to register moves, so
2247 // don't bother.
2248 unsigned CmpOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002249 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
Sanjay Patel302404b2015-03-05 21:46:54 +00002250 unsigned BlendOpcode =
Craig Topper088ba172016-12-05 06:09:55 +00002251 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2252
Craig Topper7ef6ea32016-12-05 04:51:31 +00002253 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002254 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002255 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2256 LHSReg, LHSIsKill, CmpReg, true);
2257 ResultReg = createResultReg(RC);
2258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2259 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002260 } else {
Craig Topper6413f8a2016-12-06 04:58:39 +00002261 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
Sanjay Patel302404b2015-03-05 21:46:54 +00002262 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2263 CmpRHSReg, CmpRHSIsKill, CC);
Craig Topper6413f8a2016-12-06 04:58:39 +00002264 unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
Sanjay Patel302404b2015-03-05 21:46:54 +00002265 LHSReg, LHSIsKill);
Craig Topper6413f8a2016-12-06 04:58:39 +00002266 unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
Sanjay Patel302404b2015-03-05 21:46:54 +00002267 RHSReg, RHSIsKill);
Craig Topper6413f8a2016-12-06 04:58:39 +00002268 unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2269 AndReg, /*IsKill=*/true);
2270 ResultReg = createResultReg(RC);
2271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2272 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002273 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002274 updateValueMap(I, ResultReg);
2275 return true;
2276}
2277
2278bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2279 // These are pseudo CMOV instructions and will be later expanded into control-
2280 // flow.
2281 unsigned Opc;
2282 switch (RetVT.SimpleTy) {
2283 default: return false;
2284 case MVT::i8: Opc = X86::CMOV_GR8; break;
2285 case MVT::i16: Opc = X86::CMOV_GR16; break;
2286 case MVT::i32: Opc = X86::CMOV_GR32; break;
2287 case MVT::f32: Opc = X86::CMOV_FR32; break;
2288 case MVT::f64: Opc = X86::CMOV_FR64; break;
2289 }
2290
2291 const Value *Cond = I->getOperand(0);
2292 X86::CondCode CC = X86::COND_NE;
2293
2294 // Optimize conditions coming from a compare if both instructions are in the
2295 // same basic block (values defined in other basic blocks may not have
2296 // initialized registers).
2297 const auto *CI = dyn_cast<CmpInst>(Cond);
2298 if (CI && (CI->getParent() == I->getParent())) {
2299 bool NeedSwap;
Igor Bregerdb754552017-05-11 06:36:37 +00002300 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002301 if (CC > X86::LAST_VALID_COND)
2302 return false;
2303
2304 const Value *CmpLHS = CI->getOperand(0);
2305 const Value *CmpRHS = CI->getOperand(1);
2306
2307 if (NeedSwap)
2308 std::swap(CmpLHS, CmpRHS);
2309
Mehdi Amini44ede332015-07-09 02:09:04 +00002310 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002311 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2312 return false;
2313 } else {
2314 unsigned CondReg = getRegForValue(Cond);
2315 if (CondReg == 0)
2316 return false;
2317 bool CondIsKill = hasTrivialKill(Cond);
Guy Blank9ae797a2016-08-21 08:02:27 +00002318
Guy Blank2bdc74a2016-09-28 11:22:17 +00002319 // In case OpReg is a K register, COPY to a GPR
2320 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2321 unsigned KCondReg = CondReg;
Craig Topper058f2f62017-03-28 16:35:29 +00002322 CondReg = createResultReg(&X86::GR32RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002323 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002324 TII.get(TargetOpcode::COPY), CondReg)
2325 .addReg(KCondReg, getKillRegState(CondIsKill));
Craig Topper058f2f62017-03-28 16:35:29 +00002326 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2327 X86::sub_8bit);
Guy Blank2bdc74a2016-09-28 11:22:17 +00002328 }
2329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2330 .addReg(CondReg, getKillRegState(CondIsKill))
2331 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002332 }
2333
2334 const Value *LHS = I->getOperand(1);
2335 const Value *RHS = I->getOperand(2);
2336
2337 unsigned LHSReg = getRegForValue(LHS);
2338 bool LHSIsKill = hasTrivialKill(LHS);
2339
2340 unsigned RHSReg = getRegForValue(RHS);
2341 bool RHSIsKill = hasTrivialKill(RHS);
2342
2343 if (!LHSReg || !RHSReg)
2344 return false;
2345
2346 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2347
2348 unsigned ResultReg =
2349 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2350 updateValueMap(I, ResultReg);
2351 return true;
2352}
2353
2354bool X86FastISel::X86SelectSelect(const Instruction *I) {
2355 MVT RetVT;
2356 if (!isTypeLegal(I->getType(), RetVT))
2357 return false;
2358
2359 // Check if we can fold the select.
2360 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2361 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2362 const Value *Opnd = nullptr;
2363 switch (Predicate) {
2364 default: break;
2365 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2366 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2367 }
2368 // No need for a select anymore - this is an unconditional move.
2369 if (Opnd) {
2370 unsigned OpReg = getRegForValue(Opnd);
2371 if (OpReg == 0)
2372 return false;
2373 bool OpIsKill = hasTrivialKill(Opnd);
2374 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2375 unsigned ResultReg = createResultReg(RC);
2376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2377 TII.get(TargetOpcode::COPY), ResultReg)
2378 .addReg(OpReg, getKillRegState(OpIsKill));
2379 updateValueMap(I, ResultReg);
2380 return true;
2381 }
2382 }
2383
2384 // First try to use real conditional move instructions.
2385 if (X86FastEmitCMoveSelect(RetVT, I))
2386 return true;
2387
2388 // Try to use a sequence of SSE instructions to simulate a conditional move.
2389 if (X86FastEmitSSESelect(RetVT, I))
2390 return true;
2391
2392 // Fall-back to pseudo conditional move instructions, which will be later
2393 // converted to control-flow.
2394 if (X86FastEmitPseudoSelect(RetVT, I))
2395 return true;
2396
2397 return false;
2398}
2399
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002400bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002401 // The target-independent selection algorithm in FastISel already knows how
2402 // to select a SINT_TO_FP if the target is SSE but not AVX.
2403 // Early exit if the subtarget doesn't have AVX.
2404 if (!Subtarget->hasAVX())
2405 return false;
2406
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002407 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2408 return false;
2409
2410 // Select integer to float/double conversion.
2411 unsigned OpReg = getRegForValue(I->getOperand(0));
2412 if (OpReg == 0)
2413 return false;
2414
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002415 const TargetRegisterClass *RC = nullptr;
2416 unsigned Opcode;
2417
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002418 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002419 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002420 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002421 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002422 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002423 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002424 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002425 RC = &X86::FR32RegClass;
2426 } else
2427 return false;
2428
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002429 unsigned ImplicitDefReg = createResultReg(RC);
2430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2431 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2432 unsigned ResultReg =
2433 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002434 updateValueMap(I, ResultReg);
2435 return true;
2436}
2437
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002438// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2439bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2440 unsigned TargetOpc,
2441 const TargetRegisterClass *RC) {
2442 assert((I->getOpcode() == Instruction::FPExt ||
2443 I->getOpcode() == Instruction::FPTrunc) &&
2444 "Instruction must be an FPExt or FPTrunc!");
2445
2446 unsigned OpReg = getRegForValue(I->getOperand(0));
2447 if (OpReg == 0)
2448 return false;
2449
Ayman Musa9b802e42017-03-01 10:20:48 +00002450 unsigned ImplicitDefReg;
2451 if (Subtarget->hasAVX()) {
2452 ImplicitDefReg = createResultReg(RC);
2453 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2454 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2455
2456 }
2457
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002458 unsigned ResultReg = createResultReg(RC);
2459 MachineInstrBuilder MIB;
2460 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2461 ResultReg);
Ayman Musa4b2c9682017-02-23 13:15:44 +00002462
Ayman Musa9b802e42017-03-01 10:20:48 +00002463 if (Subtarget->hasAVX())
Ayman Musa4b2c9682017-02-23 13:15:44 +00002464 MIB.addReg(ImplicitDefReg);
Ayman Musa9b802e42017-03-01 10:20:48 +00002465
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002466 MIB.addReg(OpReg);
2467 updateValueMap(I, ResultReg);
2468 return true;
2469}
2470
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002471bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002472 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2473 I->getOperand(0)->getType()->isFloatTy()) {
Craig Topper5f2289a2017-10-29 02:50:31 +00002474 bool HasAVX512 = Subtarget->hasAVX512();
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002475 // fpext from float to double.
Craig Topper5f2289a2017-10-29 02:50:31 +00002476 unsigned Opc =
2477 HasAVX512 ? X86::VCVTSS2SDZrr
2478 : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2479 return X86SelectFPExtOrFPTrunc(
2480 I, Opc, HasAVX512 ? &X86::FR64XRegClass : &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002481 }
2482
2483 return false;
2484}
2485
2486bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002487 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2488 I->getOperand(0)->getType()->isDoubleTy()) {
Craig Topper5f2289a2017-10-29 02:50:31 +00002489 bool HasAVX512 = Subtarget->hasAVX512();
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002490 // fptrunc from double to float.
Craig Topper5f2289a2017-10-29 02:50:31 +00002491 unsigned Opc =
2492 HasAVX512 ? X86::VCVTSD2SSZrr
2493 : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2494 return X86SelectFPExtOrFPTrunc(
2495 I, Opc, HasAVX512 ? &X86::FR32XRegClass : &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002496 }
2497
2498 return false;
2499}
2500
2501bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002502 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2503 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002504
2505 // This code only handles truncation to byte.
Craig Topperf7ae1012017-08-30 18:08:58 +00002506 if (DstVT != MVT::i8 && DstVT != MVT::i1)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002507 return false;
2508 if (!TLI.isTypeLegal(SrcVT))
2509 return false;
2510
2511 unsigned InputReg = getRegForValue(I->getOperand(0));
2512 if (!InputReg)
2513 // Unhandled operand. Halt "fast" selection and bail.
2514 return false;
2515
2516 if (SrcVT == MVT::i8) {
2517 // Truncate from i8 to i1; no code needed.
2518 updateValueMap(I, InputReg);
2519 return true;
2520 }
2521
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002522 // Issue an extract_subreg.
2523 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Craig Toppere92327e2017-09-18 19:21:21 +00002524 InputReg, false,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002525 X86::sub_8bit);
2526 if (!ResultReg)
2527 return false;
2528
2529 updateValueMap(I, ResultReg);
2530 return true;
2531}
2532
2533bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2534 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2535}
2536
2537bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2538 X86AddressMode SrcAM, uint64_t Len) {
2539
2540 // Make sure we don't bloat code by inlining very large memcpy's.
2541 if (!IsMemcpySmall(Len))
2542 return false;
2543
2544 bool i64Legal = Subtarget->is64Bit();
2545
2546 // We don't care about alignment here since we just emit integer accesses.
2547 while (Len) {
2548 MVT VT;
2549 if (Len >= 8 && i64Legal)
2550 VT = MVT::i64;
2551 else if (Len >= 4)
2552 VT = MVT::i32;
2553 else if (Len >= 2)
2554 VT = MVT::i16;
2555 else
2556 VT = MVT::i8;
2557
2558 unsigned Reg;
2559 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2560 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2561 assert(RV && "Failed to emit load or store??");
2562
2563 unsigned Size = VT.getSizeInBits()/8;
2564 Len -= Size;
2565 DestAM.Disp += Size;
2566 SrcAM.Disp += Size;
2567 }
2568
2569 return true;
2570}
2571
2572bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2573 // FIXME: Handle more intrinsics.
2574 switch (II->getIntrinsicID()) {
2575 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002576 case Intrinsic::convert_from_fp16:
2577 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002578 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002579 return false;
2580
2581 const Value *Op = II->getArgOperand(0);
2582 unsigned InputReg = getRegForValue(Op);
2583 if (InputReg == 0)
2584 return false;
2585
2586 // F16C only allows converting from float to half and from half to float.
2587 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2588 if (IsFloatToHalf) {
2589 if (!Op->getType()->isFloatTy())
2590 return false;
2591 } else {
2592 if (!II->getType()->isFloatTy())
2593 return false;
2594 }
2595
2596 unsigned ResultReg = 0;
2597 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2598 if (IsFloatToHalf) {
2599 // 'InputReg' is implicitly promoted from register class FR32 to
2600 // register class VR128 by method 'constrainOperandRegClass' which is
2601 // directly called by 'fastEmitInst_ri'.
2602 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002603 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2604 // It's consistent with the other FP instructions, which are usually
2605 // controlled by MXCSR.
2606 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002607
2608 // Move the lower 32-bits of ResultReg to another register of class GR32.
2609 ResultReg = createResultReg(&X86::GR32RegClass);
2610 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2611 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2612 .addReg(InputReg, RegState::Kill);
2613
2614 // The result value is in the lower 16-bits of ResultReg.
2615 unsigned RegIdx = X86::sub_16bit;
2616 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2617 } else {
2618 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2619 // Explicitly sign-extend the input to 32-bit.
2620 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2621 /*Kill=*/false);
2622
2623 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2624 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2625 InputReg, /*Kill=*/true);
2626
2627 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2628
2629 // The result value is in the lower 32-bits of ResultReg.
2630 // Emit an explicit copy from register class VR128 to register class FR32.
2631 ResultReg = createResultReg(&X86::FR32RegClass);
2632 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2633 TII.get(TargetOpcode::COPY), ResultReg)
2634 .addReg(InputReg, RegState::Kill);
2635 }
2636
2637 updateValueMap(II, ResultReg);
2638 return true;
2639 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002640 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002641 MachineFunction *MF = FuncInfo.MF;
2642 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2643 return false;
2644
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002645 Type *RetTy = II->getCalledFunction()->getReturnType();
2646
2647 MVT VT;
2648 if (!isTypeLegal(RetTy, VT))
2649 return false;
2650
2651 unsigned Opc;
2652 const TargetRegisterClass *RC = nullptr;
2653
2654 switch (VT.SimpleTy) {
2655 default: llvm_unreachable("Invalid result type for frameaddress.");
2656 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2657 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2658 }
2659
2660 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2661 // we get the wrong frame register.
Matthias Braun941a7052016-07-28 18:40:00 +00002662 MachineFrameInfo &MFI = MF->getFrameInfo();
2663 MFI.setFrameAddressIsTaken(true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002664
Eric Christophera1c535b2015-02-02 23:03:45 +00002665 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002666 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002667 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2668 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2669 "Invalid Frame Register!");
2670
2671 // Always make a copy of the frame register to to a vreg first, so that we
2672 // never directly reference the frame register (the TwoAddressInstruction-
2673 // Pass doesn't like that).
2674 unsigned SrcReg = createResultReg(RC);
2675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2676 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2677
2678 // Now recursively load from the frame address.
2679 // movq (%rbp), %rax
2680 // movq (%rax), %rax
2681 // movq (%rax), %rax
2682 // ...
2683 unsigned DestReg;
2684 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2685 while (Depth--) {
2686 DestReg = createResultReg(RC);
2687 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2688 TII.get(Opc), DestReg), SrcReg);
2689 SrcReg = DestReg;
2690 }
2691
2692 updateValueMap(II, SrcReg);
2693 return true;
2694 }
2695 case Intrinsic::memcpy: {
2696 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2697 // Don't handle volatile or variable length memcpys.
2698 if (MCI->isVolatile())
2699 return false;
2700
2701 if (isa<ConstantInt>(MCI->getLength())) {
2702 // Small memcpy's are common enough that we want to do them
2703 // without a call if possible.
2704 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2705 if (IsMemcpySmall(Len)) {
2706 X86AddressMode DestAM, SrcAM;
2707 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2708 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2709 return false;
2710 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2711 return true;
2712 }
2713 }
2714
2715 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2716 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2717 return false;
2718
2719 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2720 return false;
2721
Pete Cooper67cf9a72015-11-19 05:56:52 +00002722 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002723 }
2724 case Intrinsic::memset: {
2725 const MemSetInst *MSI = cast<MemSetInst>(II);
2726
2727 if (MSI->isVolatile())
2728 return false;
2729
2730 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2731 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2732 return false;
2733
2734 if (MSI->getDestAddressSpace() > 255)
2735 return false;
2736
Pete Cooper67cf9a72015-11-19 05:56:52 +00002737 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002738 }
2739 case Intrinsic::stackprotector: {
2740 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002741 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002742
2743 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2744 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2745
2746 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2747
2748 // Grab the frame index.
2749 X86AddressMode AM;
2750 if (!X86SelectAddress(Slot, AM)) return false;
2751 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2752 return true;
2753 }
2754 case Intrinsic::dbg_declare: {
2755 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2756 X86AddressMode AM;
2757 assert(DI->getAddress() && "Null address should be checked earlier!");
2758 if (!X86SelectAddress(DI->getAddress(), AM))
2759 return false;
2760 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2761 // FIXME may need to add RegState::Debug to any registers produced,
2762 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002763 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2764 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002765 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2766 .addImm(0)
2767 .addMetadata(DI->getVariable())
2768 .addMetadata(DI->getExpression());
2769 return true;
2770 }
2771 case Intrinsic::trap: {
2772 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2773 return true;
2774 }
2775 case Intrinsic::sqrt: {
2776 if (!Subtarget->hasSSE1())
2777 return false;
2778
2779 Type *RetTy = II->getCalledFunction()->getReturnType();
2780
2781 MVT VT;
2782 if (!isTypeLegal(RetTy, VT))
2783 return false;
2784
2785 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2786 // is not generated by FastISel yet.
2787 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002788 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002789 {X86::SQRTSSr, X86::VSQRTSSr},
2790 {X86::SQRTSDr, X86::VSQRTSDr}
2791 };
2792 bool HasAVX = Subtarget->hasAVX();
2793 unsigned Opc;
2794 const TargetRegisterClass *RC;
2795 switch (VT.SimpleTy) {
2796 default: return false;
2797 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2798 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2799 }
2800
2801 const Value *SrcVal = II->getArgOperand(0);
2802 unsigned SrcReg = getRegForValue(SrcVal);
2803
2804 if (SrcReg == 0)
2805 return false;
2806
2807 unsigned ImplicitDefReg = 0;
2808 if (HasAVX) {
2809 ImplicitDefReg = createResultReg(RC);
2810 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2811 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2812 }
2813
2814 unsigned ResultReg = createResultReg(RC);
2815 MachineInstrBuilder MIB;
2816 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2817 ResultReg);
2818
2819 if (ImplicitDefReg)
2820 MIB.addReg(ImplicitDefReg);
2821
2822 MIB.addReg(SrcReg);
2823
2824 updateValueMap(II, ResultReg);
2825 return true;
2826 }
2827 case Intrinsic::sadd_with_overflow:
2828 case Intrinsic::uadd_with_overflow:
2829 case Intrinsic::ssub_with_overflow:
2830 case Intrinsic::usub_with_overflow:
2831 case Intrinsic::smul_with_overflow:
2832 case Intrinsic::umul_with_overflow: {
2833 // This implements the basic lowering of the xalu with overflow intrinsics
2834 // into add/sub/mul followed by either seto or setb.
2835 const Function *Callee = II->getCalledFunction();
2836 auto *Ty = cast<StructType>(Callee->getReturnType());
2837 Type *RetTy = Ty->getTypeAtIndex(0U);
Zvi Rackover6f76f462016-11-15 13:50:35 +00002838 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2839 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2840 "Overflow value expected to be an i1");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002841
2842 MVT VT;
2843 if (!isTypeLegal(RetTy, VT))
2844 return false;
2845
2846 if (VT < MVT::i8 || VT > MVT::i64)
2847 return false;
2848
2849 const Value *LHS = II->getArgOperand(0);
2850 const Value *RHS = II->getArgOperand(1);
2851
2852 // Canonicalize immediate to the RHS.
2853 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2854 isCommutativeIntrinsic(II))
2855 std::swap(LHS, RHS);
2856
2857 bool UseIncDec = false;
2858 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2859 UseIncDec = true;
2860
2861 unsigned BaseOpc, CondOpc;
2862 switch (II->getIntrinsicID()) {
2863 default: llvm_unreachable("Unexpected intrinsic!");
2864 case Intrinsic::sadd_with_overflow:
2865 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2866 CondOpc = X86::SETOr;
2867 break;
2868 case Intrinsic::uadd_with_overflow:
2869 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2870 case Intrinsic::ssub_with_overflow:
2871 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2872 CondOpc = X86::SETOr;
2873 break;
2874 case Intrinsic::usub_with_overflow:
2875 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2876 case Intrinsic::smul_with_overflow:
2877 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2878 case Intrinsic::umul_with_overflow:
2879 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2880 }
2881
2882 unsigned LHSReg = getRegForValue(LHS);
2883 if (LHSReg == 0)
2884 return false;
2885 bool LHSIsKill = hasTrivialKill(LHS);
2886
2887 unsigned ResultReg = 0;
2888 // Check if we have an immediate version.
2889 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002890 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002891 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2892 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2893 };
2894
2895 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2896 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2897 bool IsDec = BaseOpc == X86ISD::DEC;
2898 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2899 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2900 .addReg(LHSReg, getKillRegState(LHSIsKill));
2901 } else
2902 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2903 CI->getZExtValue());
2904 }
2905
2906 unsigned RHSReg;
2907 bool RHSIsKill;
2908 if (!ResultReg) {
2909 RHSReg = getRegForValue(RHS);
2910 if (RHSReg == 0)
2911 return false;
2912 RHSIsKill = hasTrivialKill(RHS);
2913 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2914 RHSIsKill);
2915 }
2916
2917 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2918 // it manually.
2919 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002920 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002921 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002922 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002923 // First copy the first operand into RAX, which is an implicit input to
2924 // the X86::MUL*r instruction.
2925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2926 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2927 .addReg(LHSReg, getKillRegState(LHSIsKill));
2928 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2929 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2930 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002931 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002932 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2933 if (VT == MVT::i8) {
2934 // Copy the first operand into AL, which is an implicit input to the
2935 // X86::IMUL8r instruction.
2936 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2937 TII.get(TargetOpcode::COPY), X86::AL)
2938 .addReg(LHSReg, getKillRegState(LHSIsKill));
2939 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2940 RHSIsKill);
2941 } else
2942 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2943 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2944 RHSReg, RHSIsKill);
2945 }
2946
2947 if (!ResultReg)
2948 return false;
2949
Zvi Rackoverf0b9b57b2016-11-15 13:29:23 +00002950 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2951 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002952 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2953 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2954 ResultReg2);
2955
2956 updateValueMap(II, ResultReg, 2);
2957 return true;
2958 }
2959 case Intrinsic::x86_sse_cvttss2si:
2960 case Intrinsic::x86_sse_cvttss2si64:
2961 case Intrinsic::x86_sse2_cvttsd2si:
2962 case Intrinsic::x86_sse2_cvttsd2si64: {
2963 bool IsInputDouble;
2964 switch (II->getIntrinsicID()) {
2965 default: llvm_unreachable("Unexpected intrinsic.");
2966 case Intrinsic::x86_sse_cvttss2si:
2967 case Intrinsic::x86_sse_cvttss2si64:
2968 if (!Subtarget->hasSSE1())
2969 return false;
2970 IsInputDouble = false;
2971 break;
2972 case Intrinsic::x86_sse2_cvttsd2si:
2973 case Intrinsic::x86_sse2_cvttsd2si64:
2974 if (!Subtarget->hasSSE2())
2975 return false;
2976 IsInputDouble = true;
2977 break;
2978 }
2979
2980 Type *RetTy = II->getCalledFunction()->getReturnType();
2981 MVT VT;
2982 if (!isTypeLegal(RetTy, VT))
2983 return false;
2984
Craig Topper66111882016-06-02 04:19:42 +00002985 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002986 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2987 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2988 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2989 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2990 };
2991 bool HasAVX = Subtarget->hasAVX();
2992 unsigned Opc;
2993 switch (VT.SimpleTy) {
2994 default: llvm_unreachable("Unexpected result type.");
2995 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2996 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2997 }
2998
2999 // Check if we can fold insertelement instructions into the convert.
3000 const Value *Op = II->getArgOperand(0);
3001 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
3002 const Value *Index = IE->getOperand(2);
3003 if (!isa<ConstantInt>(Index))
3004 break;
3005 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3006
3007 if (Idx == 0) {
3008 Op = IE->getOperand(1);
3009 break;
3010 }
3011 Op = IE->getOperand(0);
3012 }
3013
3014 unsigned Reg = getRegForValue(Op);
3015 if (Reg == 0)
3016 return false;
3017
3018 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3020 .addReg(Reg);
3021
3022 updateValueMap(II, ResultReg);
3023 return true;
3024 }
3025 }
3026}
3027
3028bool X86FastISel::fastLowerArguments() {
3029 if (!FuncInfo.CanLowerReturn)
3030 return false;
3031
3032 const Function *F = FuncInfo.Fn;
3033 if (F->isVarArg())
3034 return false;
3035
3036 CallingConv::ID CC = F->getCallingConv();
3037 if (CC != CallingConv::C)
3038 return false;
3039
3040 if (Subtarget->isCallingConvWin64(CC))
3041 return false;
3042
3043 if (!Subtarget->is64Bit())
3044 return false;
3045
Davide Italianoa63981a2017-07-12 15:26:06 +00003046 if (Subtarget->useSoftFloat())
3047 return false;
3048
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003049 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3050 unsigned GPRCnt = 0;
3051 unsigned FPRCnt = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003052 for (auto const &Arg : F->args()) {
Reid Kleckner6652a522017-04-28 18:37:16 +00003053 if (Arg.hasAttribute(Attribute::ByVal) ||
3054 Arg.hasAttribute(Attribute::InReg) ||
3055 Arg.hasAttribute(Attribute::StructRet) ||
3056 Arg.hasAttribute(Attribute::SwiftSelf) ||
3057 Arg.hasAttribute(Attribute::SwiftError) ||
3058 Arg.hasAttribute(Attribute::Nest))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003059 return false;
3060
3061 Type *ArgTy = Arg.getType();
3062 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3063 return false;
3064
Mehdi Amini44ede332015-07-09 02:09:04 +00003065 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003066 if (!ArgVT.isSimple()) return false;
3067 switch (ArgVT.getSimpleVT().SimpleTy) {
3068 default: return false;
3069 case MVT::i32:
3070 case MVT::i64:
3071 ++GPRCnt;
3072 break;
3073 case MVT::f32:
3074 case MVT::f64:
3075 if (!Subtarget->hasSSE1())
3076 return false;
3077 ++FPRCnt;
3078 break;
3079 }
3080
3081 if (GPRCnt > 6)
3082 return false;
3083
3084 if (FPRCnt > 8)
3085 return false;
3086 }
3087
3088 static const MCPhysReg GPR32ArgRegs[] = {
3089 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3090 };
3091 static const MCPhysReg GPR64ArgRegs[] = {
3092 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3093 };
3094 static const MCPhysReg XMMArgRegs[] = {
3095 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3096 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3097 };
3098
3099 unsigned GPRIdx = 0;
3100 unsigned FPRIdx = 0;
3101 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003102 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003103 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3104 unsigned SrcReg;
3105 switch (VT.SimpleTy) {
3106 default: llvm_unreachable("Unexpected value type.");
3107 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3108 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003109 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003110 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3111 }
3112 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3113 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3114 // Without this, EmitLiveInCopies may eliminate the livein if its only
3115 // use is a bitcast (which isn't turned into an instruction).
3116 unsigned ResultReg = createResultReg(RC);
3117 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3118 TII.get(TargetOpcode::COPY), ResultReg)
3119 .addReg(DstReg, getKillRegState(true));
3120 updateValueMap(&Arg, ResultReg);
3121 }
3122 return true;
3123}
3124
Nico Weberaf7e8462016-07-14 01:52:51 +00003125static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3126 CallingConv::ID CC,
3127 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003128 if (Subtarget->is64Bit())
3129 return 0;
3130 if (Subtarget->getTargetTriple().isOSMSVCRT())
3131 return 0;
3132 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3133 CC == CallingConv::HiPE)
3134 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003135
3136 if (CS)
Reid Klecknerfb502d22017-04-14 20:19:02 +00003137 if (CS->arg_empty() || !CS->paramHasAttr(0, Attribute::StructRet) ||
3138 CS->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003139 return 0;
3140
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003141 return 4;
3142}
3143
3144bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3145 auto &OutVals = CLI.OutVals;
3146 auto &OutFlags = CLI.OutFlags;
3147 auto &OutRegs = CLI.OutRegs;
3148 auto &Ins = CLI.Ins;
3149 auto &InRegs = CLI.InRegs;
3150 CallingConv::ID CC = CLI.CallConv;
3151 bool &IsTailCall = CLI.IsTailCall;
3152 bool IsVarArg = CLI.IsVarArg;
3153 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003154 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003155
3156 bool Is64Bit = Subtarget->is64Bit();
3157 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3158
Oren Ben Simhondbd4bba2017-05-03 13:07:19 +00003159 const CallInst *CI =
3160 CLI.CS ? dyn_cast<CallInst>(CLI.CS->getInstruction()) : nullptr;
3161 const Function *CalledFn = CI ? CI->getCalledFunction() : nullptr;
3162
3163 // Functions with no_caller_saved_registers that need special handling.
3164 if ((CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3165 (CalledFn && CalledFn->hasFnAttribute("no_caller_saved_registers")))
3166 return false;
3167
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003168 // Handle only C, fastcc, and webkit_js calling conventions for now.
3169 switch (CC) {
3170 default: return false;
3171 case CallingConv::C:
3172 case CallingConv::Fast:
3173 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003174 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003175 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003176 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003177 case CallingConv::X86_ThisCall:
Martin Storsjo2f24e932017-07-17 20:05:19 +00003178 case CallingConv::Win64:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003179 case CallingConv::X86_64_SysV:
3180 break;
3181 }
3182
3183 // Allow SelectionDAG isel to handle tail calls.
3184 if (IsTailCall)
3185 return false;
3186
3187 // fastcc with -tailcallopt is intended to provide a guaranteed
3188 // tail call optimization. Fastisel doesn't know how to do that.
3189 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3190 return false;
3191
3192 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3193 // x86-32. Special handling for x86-64 is implemented.
3194 if (IsVarArg && IsWin64)
3195 return false;
3196
3197 // Don't know about inalloca yet.
3198 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3199 return false;
3200
Manman Ren57518142016-04-11 21:08:06 +00003201 for (auto Flag : CLI.OutFlags)
3202 if (Flag.isSwiftError())
3203 return false;
3204
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003205 SmallVector<MVT, 16> OutVTs;
3206 SmallVector<unsigned, 16> ArgRegs;
3207
3208 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3209 // instruction. This is safe because it is common to all FastISel supported
3210 // calling conventions on x86.
3211 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3212 Value *&Val = OutVals[i];
3213 ISD::ArgFlagsTy Flags = OutFlags[i];
3214 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3215 if (CI->getBitWidth() < 32) {
3216 if (Flags.isSExt())
3217 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3218 else
3219 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3220 }
3221 }
3222
3223 // Passing bools around ends up doing a trunc to i1 and passing it.
3224 // Codegen this as an argument + "and 1".
3225 MVT VT;
3226 auto *TI = dyn_cast<TruncInst>(Val);
3227 unsigned ResultReg;
3228 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3229 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3230 TI->hasOneUse()) {
3231 Value *PrevVal = TI->getOperand(0);
3232 ResultReg = getRegForValue(PrevVal);
3233
3234 if (!ResultReg)
3235 return false;
3236
3237 if (!isTypeLegal(PrevVal->getType(), VT))
3238 return false;
3239
3240 ResultReg =
3241 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3242 } else {
3243 if (!isTypeLegal(Val->getType(), VT))
3244 return false;
3245 ResultReg = getRegForValue(Val);
3246 }
3247
3248 if (!ResultReg)
3249 return false;
3250
3251 ArgRegs.push_back(ResultReg);
3252 OutVTs.push_back(VT);
3253 }
3254
3255 // Analyze operands of the call, assigning locations to each operand.
3256 SmallVector<CCValAssign, 16> ArgLocs;
3257 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3258
3259 // Allocate shadow area for Win64
3260 if (IsWin64)
3261 CCInfo.AllocateStack(32, 8);
3262
3263 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3264
3265 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003266 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003267
3268 // Issue CALLSEQ_START
3269 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Serge Pavlovd526b132017-05-09 13:35:13 +00003271 .addImm(NumBytes).addImm(0).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003272
3273 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003274 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003275 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3276 CCValAssign const &VA = ArgLocs[i];
3277 const Value *ArgVal = OutVals[VA.getValNo()];
3278 MVT ArgVT = OutVTs[VA.getValNo()];
3279
3280 if (ArgVT == MVT::x86mmx)
3281 return false;
3282
3283 unsigned ArgReg = ArgRegs[VA.getValNo()];
3284
3285 // Promote the value if needed.
3286 switch (VA.getLocInfo()) {
3287 case CCValAssign::Full: break;
3288 case CCValAssign::SExt: {
3289 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3290 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003291
Craig Topper088ba172016-12-05 06:09:55 +00003292 if (ArgVT == MVT::i1)
David Majnemer2c5aeab2016-05-04 00:22:23 +00003293 return false;
3294
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003295 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3296 ArgVT, ArgReg);
3297 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3298 ArgVT = VA.getLocVT();
3299 break;
3300 }
3301 case CCValAssign::ZExt: {
3302 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3303 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003304
3305 // Handle zero-extension from i1 to i8, which is common.
Craig Topper088ba172016-12-05 06:09:55 +00003306 if (ArgVT == MVT::i1) {
David Majnemer2c5aeab2016-05-04 00:22:23 +00003307 // Set the high bits to zero.
3308 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3309 ArgVT = MVT::i8;
3310
3311 if (ArgReg == 0)
3312 return false;
3313 }
3314
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003315 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3316 ArgVT, ArgReg);
3317 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3318 ArgVT = VA.getLocVT();
3319 break;
3320 }
3321 case CCValAssign::AExt: {
3322 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3323 "Unexpected extend");
3324 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3325 ArgVT, ArgReg);
3326 if (!Emitted)
3327 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3328 ArgVT, ArgReg);
3329 if (!Emitted)
3330 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3331 ArgVT, ArgReg);
3332
3333 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3334 ArgVT = VA.getLocVT();
3335 break;
3336 }
3337 case CCValAssign::BCvt: {
3338 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3339 /*TODO: Kill=*/false);
3340 assert(ArgReg && "Failed to emit a bitcast!");
3341 ArgVT = VA.getLocVT();
3342 break;
3343 }
3344 case CCValAssign::VExt:
3345 // VExt has not been implemented, so this should be impossible to reach
3346 // for now. However, fallback to Selection DAG isel once implemented.
3347 return false;
3348 case CCValAssign::AExtUpper:
3349 case CCValAssign::SExtUpper:
3350 case CCValAssign::ZExtUpper:
3351 case CCValAssign::FPExt:
3352 llvm_unreachable("Unexpected loc info!");
3353 case CCValAssign::Indirect:
3354 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3355 // support this.
3356 return false;
3357 }
3358
3359 if (VA.isRegLoc()) {
3360 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3361 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3362 OutRegs.push_back(VA.getLocReg());
3363 } else {
3364 assert(VA.isMemLoc());
3365
3366 // Don't emit stores for undef values.
3367 if (isa<UndefValue>(ArgVal))
3368 continue;
3369
3370 unsigned LocMemOffset = VA.getLocMemOffset();
3371 X86AddressMode AM;
3372 AM.Base.Reg = RegInfo->getStackRegister();
3373 AM.Disp = LocMemOffset;
3374 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3375 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3376 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003377 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3378 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003379 if (Flags.isByVal()) {
3380 X86AddressMode SrcAM;
3381 SrcAM.Base.Reg = ArgReg;
3382 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3383 return false;
3384 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3385 // If this is a really simple value, emit this with the Value* version
3386 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3387 // as it can cause us to reevaluate the argument.
3388 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3389 return false;
3390 } else {
3391 bool ValIsKill = hasTrivialKill(ArgVal);
3392 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3393 return false;
3394 }
3395 }
3396 }
3397
3398 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3399 // GOT pointer.
3400 if (Subtarget->isPICStyleGOT()) {
3401 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3403 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3404 }
3405
3406 if (Is64Bit && IsVarArg && !IsWin64) {
3407 // From AMD64 ABI document:
3408 // For calls that may call functions that use varargs or stdargs
3409 // (prototype-less calls or calls to functions containing ellipsis (...) in
3410 // the declaration) %al is used as hidden argument to specify the number
3411 // of SSE registers used. The contents of %al do not need to match exactly
3412 // the number of registers, but must be an ubound on the number of SSE
3413 // registers used and is in the range 0 - 8 inclusive.
3414
3415 // Count the number of XMM registers allocated.
3416 static const MCPhysReg XMMArgRegs[] = {
3417 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3418 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3419 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003420 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003421 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3422 && "SSE registers cannot be used when SSE is disabled");
3423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3424 X86::AL).addImm(NumXMMRegs);
3425 }
3426
3427 // Materialize callee address in a register. FIXME: GV address can be
3428 // handled with a CALLpcrel32 instead.
3429 X86AddressMode CalleeAM;
3430 if (!X86SelectCallAddress(Callee, CalleeAM))
3431 return false;
3432
3433 unsigned CalleeOp = 0;
3434 const GlobalValue *GV = nullptr;
3435 if (CalleeAM.GV != nullptr) {
3436 GV = CalleeAM.GV;
3437 } else if (CalleeAM.Base.Reg != 0) {
3438 CalleeOp = CalleeAM.Base.Reg;
3439 } else
3440 return false;
3441
3442 // Issue the call.
3443 MachineInstrBuilder MIB;
3444 if (CalleeOp) {
3445 // Register-indirect call.
3446 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3447 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3448 .addReg(CalleeOp);
3449 } else {
3450 // Direct call.
3451 assert(GV && "Not a direct call");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003452 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003453 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003454 // Ignore NonLazyBind attribute in FastISel
3455 if (OpFlags == X86II::MO_GOTPCREL)
3456 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003457
Reid Kleckner7662d502017-08-05 00:10:43 +00003458 // This will be a direct call, or an indirect call through memory for
3459 // NonLazyBind calls or dllimport calls.
3460 bool NeedLoad = OpFlags == X86II::MO_DLLIMPORT;
3461 unsigned CallOpc = NeedLoad
3462 ? (Is64Bit ? X86::CALL64m : X86::CALL32m)
3463 : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
3464
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003465 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Reid Kleckner7662d502017-08-05 00:10:43 +00003466 if (NeedLoad)
3467 MIB.addReg(Is64Bit ? X86::RIP : 0).addImm(1).addReg(0);
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003468 if (Symbol)
3469 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003470 else
3471 MIB.addGlobalAddress(GV, 0, OpFlags);
Reid Kleckner7662d502017-08-05 00:10:43 +00003472 if (NeedLoad)
3473 MIB.addReg(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003474 }
3475
3476 // Add a register mask operand representing the call-preserved registers.
3477 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003478 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003479
3480 // Add an implicit use GOT pointer in EBX.
3481 if (Subtarget->isPICStyleGOT())
3482 MIB.addReg(X86::EBX, RegState::Implicit);
3483
3484 if (Is64Bit && IsVarArg && !IsWin64)
3485 MIB.addReg(X86::AL, RegState::Implicit);
3486
3487 // Add implicit physical register uses to the call.
3488 for (auto Reg : OutRegs)
3489 MIB.addReg(Reg, RegState::Implicit);
3490
3491 // Issue CALLSEQ_END
3492 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003493 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3494 TM.Options.GuaranteedTailCallOpt)
3495 ? NumBytes // Callee pops everything.
3496 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003497 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3499 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3500
3501 // Now handle call return values.
3502 SmallVector<CCValAssign, 16> RVLocs;
3503 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3504 CLI.RetTy->getContext());
3505 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3506
3507 // Copy all of the result registers out of their specified physreg.
3508 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3509 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3510 CCValAssign &VA = RVLocs[i];
3511 EVT CopyVT = VA.getValVT();
3512 unsigned CopyReg = ResultReg + i;
Craig Topper533b1bd2017-03-30 21:02:52 +00003513 unsigned SrcReg = VA.getLocReg();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003514
3515 // If this is x86-64, and we disabled SSE, we can't return FP values
3516 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3517 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3518 report_fatal_error("SSE register return with SSE disabled");
3519 }
3520
3521 // If we prefer to use the value in xmm registers, copy it out as f80 and
3522 // use a truncate to move it from fp stack reg to xmm reg.
Craig Topper533b1bd2017-03-30 21:02:52 +00003523 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003524 isScalarFPTypeInSSEReg(VA.getValVT())) {
3525 CopyVT = MVT::f80;
3526 CopyReg = createResultReg(&X86::RFP80RegClass);
3527 }
3528
3529 // Copy out the result.
3530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Craig Topper533b1bd2017-03-30 21:02:52 +00003531 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003532 InRegs.push_back(VA.getLocReg());
3533
3534 // Round the f80 to the right size, which also moves it to the appropriate
3535 // xmm register. This is accomplished by storing the f80 value in memory
3536 // and then loading it back.
3537 if (CopyVT != VA.getValVT()) {
3538 EVT ResVT = VA.getValVT();
3539 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3540 unsigned MemSize = ResVT.getSizeInBits()/8;
3541 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3542 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3543 TII.get(Opc)), FI)
3544 .addReg(CopyReg);
3545 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3546 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3547 TII.get(Opc), ResultReg + i), FI);
3548 }
3549 }
3550
3551 CLI.ResultReg = ResultReg;
3552 CLI.NumResultRegs = RVLocs.size();
3553 CLI.Call = MIB;
3554
3555 return true;
3556}
3557
3558bool
3559X86FastISel::fastSelectInstruction(const Instruction *I) {
3560 switch (I->getOpcode()) {
3561 default: break;
3562 case Instruction::Load:
3563 return X86SelectLoad(I);
3564 case Instruction::Store:
3565 return X86SelectStore(I);
3566 case Instruction::Ret:
3567 return X86SelectRet(I);
3568 case Instruction::ICmp:
3569 case Instruction::FCmp:
3570 return X86SelectCmp(I);
3571 case Instruction::ZExt:
3572 return X86SelectZExt(I);
Craig Topper619b7592017-09-02 18:53:46 +00003573 case Instruction::SExt:
3574 return X86SelectSExt(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003575 case Instruction::Br:
3576 return X86SelectBranch(I);
3577 case Instruction::LShr:
3578 case Instruction::AShr:
3579 case Instruction::Shl:
3580 return X86SelectShift(I);
3581 case Instruction::SDiv:
3582 case Instruction::UDiv:
3583 case Instruction::SRem:
3584 case Instruction::URem:
3585 return X86SelectDivRem(I);
3586 case Instruction::Select:
3587 return X86SelectSelect(I);
3588 case Instruction::Trunc:
3589 return X86SelectTrunc(I);
3590 case Instruction::FPExt:
3591 return X86SelectFPExt(I);
3592 case Instruction::FPTrunc:
3593 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003594 case Instruction::SIToFP:
3595 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003596 case Instruction::IntToPtr: // Deliberate fall-through.
3597 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003598 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3599 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003600 if (DstVT.bitsGT(SrcVT))
3601 return X86SelectZExt(I);
3602 if (DstVT.bitsLT(SrcVT))
3603 return X86SelectTrunc(I);
3604 unsigned Reg = getRegForValue(I->getOperand(0));
3605 if (Reg == 0) return false;
3606 updateValueMap(I, Reg);
3607 return true;
3608 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003609 case Instruction::BitCast: {
3610 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3611 if (!Subtarget->hasSSE2())
3612 return false;
3613
3614 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3615 EVT DstVT = TLI.getValueType(DL, I->getType());
3616
3617 if (!SrcVT.isSimple() || !DstVT.isSimple())
3618 return false;
3619
Craig Topperdb8467a2016-12-05 05:50:51 +00003620 MVT SVT = SrcVT.getSimpleVT();
3621 MVT DVT = DstVT.getSimpleVT();
3622
3623 if (!SVT.is128BitVector() &&
3624 !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3625 !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3626 (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3627 DVT.getScalarSizeInBits() >= 32))))
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003628 return false;
3629
3630 unsigned Reg = getRegForValue(I->getOperand(0));
3631 if (Reg == 0)
3632 return false;
3633
3634 // No instruction is needed for conversion. Reuse the register used by
3635 // the fist operand.
3636 updateValueMap(I, Reg);
3637 return true;
3638 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003639 }
3640
3641 return false;
3642}
3643
3644unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3645 if (VT > MVT::i64)
3646 return 0;
3647
3648 uint64_t Imm = CI->getZExtValue();
3649 if (Imm == 0) {
3650 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3651 switch (VT.SimpleTy) {
3652 default: llvm_unreachable("Unexpected value type");
3653 case MVT::i1:
3654 case MVT::i8:
3655 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3656 X86::sub_8bit);
3657 case MVT::i16:
3658 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3659 X86::sub_16bit);
3660 case MVT::i32:
3661 return SrcReg;
3662 case MVT::i64: {
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 }
3670 }
3671
3672 unsigned Opc = 0;
3673 switch (VT.SimpleTy) {
3674 default: llvm_unreachable("Unexpected value type");
Craig Topper058f2f62017-03-28 16:35:29 +00003675 case MVT::i1:
3676 // TODO: Support this properly.
3677 if (Subtarget->hasAVX512())
3678 return 0;
3679 VT = MVT::i8;
3680 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003681 case MVT::i8: Opc = X86::MOV8ri; break;
3682 case MVT::i16: Opc = X86::MOV16ri; break;
3683 case MVT::i32: Opc = X86::MOV32ri; break;
3684 case MVT::i64: {
3685 if (isUInt<32>(Imm))
3686 Opc = X86::MOV32ri;
3687 else if (isInt<32>(Imm))
3688 Opc = X86::MOV64ri32;
3689 else
3690 Opc = X86::MOV64ri;
3691 break;
3692 }
3693 }
3694 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3695 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3696 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3698 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3699 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3700 return ResultReg;
3701 }
3702 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3703}
3704
3705unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3706 if (CFP->isNullValue())
3707 return fastMaterializeFloatZero(CFP);
3708
3709 // Can't handle alternate code models yet.
3710 CodeModel::Model CM = TM.getCodeModel();
3711 if (CM != CodeModel::Small && CM != CodeModel::Large)
3712 return 0;
3713
3714 // Get opcode and regclass of the output for the given load instruction.
3715 unsigned Opc = 0;
3716 const TargetRegisterClass *RC = nullptr;
3717 switch (VT.SimpleTy) {
3718 default: return 0;
3719 case MVT::f32:
3720 if (X86ScalarSSEf32) {
Craig Topper1e30d782017-10-29 02:18:41 +00003721 Opc = Subtarget->hasAVX512()
3722 ? X86::VMOVSSZrm
3723 : Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
Craig Topper912f3b82017-10-29 05:14:26 +00003724 RC = Subtarget->hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003725 } else {
3726 Opc = X86::LD_Fp32m;
3727 RC = &X86::RFP32RegClass;
3728 }
3729 break;
3730 case MVT::f64:
3731 if (X86ScalarSSEf64) {
Craig Topper1e30d782017-10-29 02:18:41 +00003732 Opc = Subtarget->hasAVX512()
3733 ? X86::VMOVSDZrm
3734 : Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
Craig Topper912f3b82017-10-29 05:14:26 +00003735 RC = Subtarget->hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003736 } else {
3737 Opc = X86::LD_Fp64m;
3738 RC = &X86::RFP64RegClass;
3739 }
3740 break;
3741 case MVT::f80:
3742 // No f80 support yet.
3743 return 0;
3744 }
3745
3746 // MachineConstantPool wants an explicit alignment.
3747 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3748 if (Align == 0) {
3749 // Alignment of vector types. FIXME!
3750 Align = DL.getTypeAllocSize(CFP->getType());
3751 }
3752
3753 // x86-32 PIC requires a PIC base register for constant pools.
3754 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003755 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3756 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003757 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003758 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003759 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003760 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003761 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003762
3763 // Create the load from the constant pool.
3764 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3765 unsigned ResultReg = createResultReg(RC);
3766
3767 if (CM == CodeModel::Large) {
3768 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3769 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3770 AddrReg)
3771 .addConstantPoolIndex(CPI, 0, OpFlag);
3772 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3773 TII.get(Opc), ResultReg);
3774 addDirectMem(MIB, AddrReg);
3775 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003776 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3777 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003778 MIB->addMemOperand(*FuncInfo.MF, MMO);
3779 return ResultReg;
3780 }
3781
3782 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3783 TII.get(Opc), ResultReg),
3784 CPI, PICBase, OpFlag);
3785 return ResultReg;
3786}
3787
3788unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3789 // Can't handle alternate code models yet.
3790 if (TM.getCodeModel() != CodeModel::Small)
3791 return 0;
3792
3793 // Materialize addresses with LEA/MOV instructions.
3794 X86AddressMode AM;
3795 if (X86SelectAddress(GV, AM)) {
3796 // If the expression is just a basereg, then we're done, otherwise we need
3797 // to emit an LEA.
3798 if (AM.BaseType == X86AddressMode::RegBase &&
3799 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3800 return AM.Base.Reg;
3801
3802 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3803 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003804 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003805 // The displacement code could be more than 32 bits away so we need to use
3806 // an instruction with a 64 bit immediate
3807 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3808 ResultReg)
3809 .addGlobalAddress(GV);
3810 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003811 unsigned Opc =
3812 TLI.getPointerTy(DL) == MVT::i32
3813 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3814 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003815 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3816 TII.get(Opc), ResultReg), AM);
3817 }
3818 return ResultReg;
3819 }
3820 return 0;
3821}
3822
3823unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003824 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003825
3826 // Only handle simple types.
3827 if (!CEVT.isSimple())
3828 return 0;
3829 MVT VT = CEVT.getSimpleVT();
3830
3831 if (const auto *CI = dyn_cast<ConstantInt>(C))
3832 return X86MaterializeInt(CI, VT);
3833 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3834 return X86MaterializeFP(CFP, VT);
3835 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3836 return X86MaterializeGV(GV, VT);
3837
3838 return 0;
3839}
3840
3841unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3842 // Fail on dynamic allocas. At this point, getRegForValue has already
3843 // checked its CSE maps, so if we're here trying to handle a dynamic
3844 // alloca, we're not going to succeed. X86SelectAddress has a
3845 // check for dynamic allocas, because it's called directly from
3846 // various places, but targetMaterializeAlloca also needs a check
3847 // in order to avoid recursion between getRegForValue,
3848 // X86SelectAddrss, and targetMaterializeAlloca.
3849 if (!FuncInfo.StaticAllocaMap.count(C))
3850 return 0;
3851 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3852
3853 X86AddressMode AM;
3854 if (!X86SelectAddress(C, AM))
3855 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003856 unsigned Opc =
3857 TLI.getPointerTy(DL) == MVT::i32
3858 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3859 : X86::LEA64r;
3860 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003861 unsigned ResultReg = createResultReg(RC);
3862 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3863 TII.get(Opc), ResultReg), AM);
3864 return ResultReg;
3865}
3866
3867unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3868 MVT VT;
3869 if (!isTypeLegal(CF->getType(), VT))
3870 return 0;
3871
3872 // Get opcode and regclass for the given zero.
3873 unsigned Opc = 0;
3874 const TargetRegisterClass *RC = nullptr;
3875 switch (VT.SimpleTy) {
3876 default: return 0;
3877 case MVT::f32:
3878 if (X86ScalarSSEf32) {
3879 Opc = X86::FsFLD0SS;
3880 RC = &X86::FR32RegClass;
3881 } else {
3882 Opc = X86::LD_Fp032;
3883 RC = &X86::RFP32RegClass;
3884 }
3885 break;
3886 case MVT::f64:
3887 if (X86ScalarSSEf64) {
3888 Opc = X86::FsFLD0SD;
3889 RC = &X86::FR64RegClass;
3890 } else {
3891 Opc = X86::LD_Fp064;
3892 RC = &X86::RFP64RegClass;
3893 }
3894 break;
3895 case MVT::f80:
3896 // No f80 support yet.
3897 return 0;
3898 }
3899
3900 unsigned ResultReg = createResultReg(RC);
3901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3902 return ResultReg;
3903}
3904
3905
3906bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3907 const LoadInst *LI) {
3908 const Value *Ptr = LI->getPointerOperand();
3909 X86AddressMode AM;
3910 if (!X86SelectAddress(Ptr, AM))
3911 return false;
3912
3913 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3914
3915 unsigned Size = DL.getTypeAllocSize(LI->getType());
3916 unsigned Alignment = LI->getAlignment();
3917
3918 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3919 Alignment = DL.getABITypeAlignment(LI->getType());
3920
3921 SmallVector<MachineOperand, 8> AddrOps;
3922 AM.getFullAddress(AddrOps);
3923
Keno Fischere70b31f2015-06-08 20:09:58 +00003924 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003925 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003926 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003927 if (!Result)
3928 return false;
3929
Pete Cooperd31583d2015-05-06 21:37:19 +00003930 // The index register could be in the wrong register class. Unfortunately,
3931 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3932 // to just look at OpNo + the offset to the index reg. We actually need to
3933 // scan the instruction to find the index reg and see if its the correct reg
3934 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003935 unsigned OperandNo = 0;
3936 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3937 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3938 MachineOperand &MO = *I;
3939 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003940 continue;
3941 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003942 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003943 MO.getReg(), OperandNo);
3944 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003945 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003946 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003947 }
3948
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003949 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003950 MI->eraseFromParent();
3951 return true;
3952}
3953
Craig Topper7ef6ea32016-12-05 04:51:31 +00003954unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
3955 const TargetRegisterClass *RC,
3956 unsigned Op0, bool Op0IsKill,
3957 unsigned Op1, bool Op1IsKill,
3958 unsigned Op2, bool Op2IsKill,
3959 unsigned Op3, bool Op3IsKill) {
3960 const MCInstrDesc &II = TII.get(MachineInstOpcode);
3961
3962 unsigned ResultReg = createResultReg(RC);
3963 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
3964 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
3965 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
Craig Topperd3762582017-10-02 05:46:53 +00003966 Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3);
Craig Topper7ef6ea32016-12-05 04:51:31 +00003967
3968 if (II.getNumDefs() >= 1)
3969 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
3970 .addReg(Op0, getKillRegState(Op0IsKill))
3971 .addReg(Op1, getKillRegState(Op1IsKill))
3972 .addReg(Op2, getKillRegState(Op2IsKill))
3973 .addReg(Op3, getKillRegState(Op3IsKill));
3974 else {
3975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
3976 .addReg(Op0, getKillRegState(Op0IsKill))
3977 .addReg(Op1, getKillRegState(Op1IsKill))
3978 .addReg(Op2, getKillRegState(Op2IsKill))
3979 .addReg(Op3, getKillRegState(Op3IsKill));
3980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3981 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
3982 }
3983 return ResultReg;
3984}
3985
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003986
3987namespace llvm {
3988 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3989 const TargetLibraryInfo *libInfo) {
3990 return new X86FastISel(funcInfo, libInfo);
3991 }
3992}