blob: 41651d261480abf742cf22a9e8b43d7ecf3e0b43 [file] [log] [blame]
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001//===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the X86-specific support for the FastISel class. Much
11// of the target-specific code is generated by tablegen in the file
12// X86GenFastISel.inc, which is #included here.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86CallingConv.h"
18#include "X86InstrBuilder.h"
19#include "X86InstrInfo.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86RegisterInfo.h"
22#include "X86Subtarget.h"
23#include "X86TargetMachine.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000025#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/IR/CallSite.h"
31#include "llvm/IR/CallingConv.h"
Reid Kleckner28865802016-04-14 18:29:59 +000032#include "llvm/IR/DebugInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000033#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/GetElementPtrTypeIterator.h"
35#include "llvm/IR/GlobalAlias.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Operator.h"
David Majnemerca194852015-02-10 22:00:34 +000040#include "llvm/MC/MCAsmInfo.h"
Rafael Espindolace4c2bc2015-06-23 12:21:54 +000041#include "llvm/MC/MCSymbol.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000042#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Target/TargetOptions.h"
44using namespace llvm;
45
46namespace {
47
48class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
52
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
57 bool X86ScalarSSEf64;
58 bool X86ScalarSSEf32;
59
60public:
61 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62 const TargetLibraryInfo *libInfo)
Eric Christophera1c535b2015-02-02 23:03:45 +000063 : FastISel(funcInfo, libInfo) {
64 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000065 X86ScalarSSEf64 = Subtarget->hasSSE2();
66 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 }
68
69 bool fastSelectInstruction(const Instruction *I) override;
70
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
74 /// possible.
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
77
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81
82#include "X86GenFastISel.inc"
83
84private:
Benjamin Kramerbdc49562016-06-12 15:39:02 +000085 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
86 const DebugLoc &DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000087
Pete Cooperd0dae3e2015-05-05 23:41:53 +000088 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000089 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000090
Pete Cooperd0dae3e2015-05-05 23:41:53 +000091 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000092 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000094 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000095 MachineMemOperand *MMO = nullptr, bool Aligned = false);
96
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 unsigned &ResultReg);
99
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102
103 bool X86SelectLoad(const Instruction *I);
104
105 bool X86SelectStore(const Instruction *I);
106
107 bool X86SelectRet(const Instruction *I);
108
109 bool X86SelectCmp(const Instruction *I);
110
111 bool X86SelectZExt(const Instruction *I);
112
113 bool X86SelectBranch(const Instruction *I);
114
115 bool X86SelectShift(const Instruction *I);
116
117 bool X86SelectDivRem(const Instruction *I);
118
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
120
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
122
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
124
125 bool X86SelectSelect(const Instruction *I);
126
127 bool X86SelectTrunc(const Instruction *I);
128
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
131
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000134 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000135
136 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000137 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000138 }
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
141 }
142
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
144
145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148 unsigned fastMaterializeConstant(const Constant *C) override;
149
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
151
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
153
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159 }
160
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
162
163 bool IsMemcpySmall(uint64_t Len);
164
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
167
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
169 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000170
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
172 X86AddressMode &AM);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000173};
174
175} // end anonymous namespace.
176
177static std::pair<X86::CondCode, bool>
178getX86ConditionCode(CmpInst::Predicate Predicate) {
179 X86::CondCode CC = X86::COND_INVALID;
180 bool NeedSwap = false;
181 switch (Predicate) {
182 default: break;
183 // Floating-point Predicates
184 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000185 case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000186 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000187 case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000188 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000189 case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000190 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000191 case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000192 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
193 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
194 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
195 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000196 case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000197 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
198
199 // Integer Predicates
200 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
201 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
202 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
203 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
204 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
205 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
206 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
207 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
208 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
209 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
210 }
211
212 return std::make_pair(CC, NeedSwap);
213}
214
215static std::pair<unsigned, bool>
216getX86SSEConditionCode(CmpInst::Predicate Predicate) {
217 unsigned CC;
218 bool NeedSwap = false;
219
220 // SSE Condition code mapping:
221 // 0 - EQ
222 // 1 - LT
223 // 2 - LE
224 // 3 - UNORD
225 // 4 - NEQ
226 // 5 - NLT
227 // 6 - NLE
228 // 7 - ORD
229 switch (Predicate) {
230 default: llvm_unreachable("Unexpected predicate");
231 case CmpInst::FCMP_OEQ: CC = 0; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000232 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000233 case CmpInst::FCMP_OLT: CC = 1; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000234 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000235 case CmpInst::FCMP_OLE: CC = 2; break;
236 case CmpInst::FCMP_UNO: CC = 3; break;
237 case CmpInst::FCMP_UNE: CC = 4; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000238 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000239 case CmpInst::FCMP_UGE: CC = 5; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000240 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000241 case CmpInst::FCMP_UGT: CC = 6; break;
242 case CmpInst::FCMP_ORD: CC = 7; break;
243 case CmpInst::FCMP_UEQ:
244 case CmpInst::FCMP_ONE: CC = 8; break;
245 }
246
247 return std::make_pair(CC, NeedSwap);
248}
249
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000250/// \brief Adds a complex addressing mode to the given machine instr builder.
251/// Note, this will constrain the index register. If its not possible to
252/// constrain the given index register, then a new one will be created. The
253/// IndexReg field of the addressing mode will be updated to match in this case.
254const MachineInstrBuilder &
255X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
256 X86AddressMode &AM) {
257 // First constrain the index register. It needs to be a GR64_NOSP.
258 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
259 MIB->getNumOperands() +
260 X86::AddrIndexReg);
261 return ::addFullAddress(MIB, AM);
262}
263
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000264/// \brief Check if it is possible to fold the condition from the XALU intrinsic
265/// into the user. The condition code will only be updated on success.
266bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
267 const Value *Cond) {
268 if (!isa<ExtractValueInst>(Cond))
269 return false;
270
271 const auto *EV = cast<ExtractValueInst>(Cond);
272 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
273 return false;
274
275 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
276 MVT RetVT;
277 const Function *Callee = II->getCalledFunction();
278 Type *RetTy =
279 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
280 if (!isTypeLegal(RetTy, RetVT))
281 return false;
282
283 if (RetVT != MVT::i32 && RetVT != MVT::i64)
284 return false;
285
286 X86::CondCode TmpCC;
287 switch (II->getIntrinsicID()) {
288 default: return false;
289 case Intrinsic::sadd_with_overflow:
290 case Intrinsic::ssub_with_overflow:
291 case Intrinsic::smul_with_overflow:
292 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
293 case Intrinsic::uadd_with_overflow:
294 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
295 }
296
297 // Check if both instructions are in the same basic block.
298 if (II->getParent() != I->getParent())
299 return false;
300
301 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000302 BasicBlock::const_iterator Start(I);
303 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000304 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
305 // We only expect extractvalue instructions between the intrinsic and the
306 // instruction to be selected.
307 if (!isa<ExtractValueInst>(Itr))
308 return false;
309
310 // Check that the extractvalue operand comes from the intrinsic.
311 const auto *EVI = cast<ExtractValueInst>(Itr);
312 if (EVI->getAggregateOperand() != II)
313 return false;
314 }
315
316 CC = TmpCC;
317 return true;
318}
319
320bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000321 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000322 if (evt == MVT::Other || !evt.isSimple())
323 // Unhandled type. Halt "fast" selection and bail.
324 return false;
325
326 VT = evt.getSimpleVT();
327 // For now, require SSE/SSE2 for performing floating-point operations,
328 // since x87 requires additional work.
329 if (VT == MVT::f64 && !X86ScalarSSEf64)
330 return false;
331 if (VT == MVT::f32 && !X86ScalarSSEf32)
332 return false;
333 // Similarly, no f80 support yet.
334 if (VT == MVT::f80)
335 return false;
336 // We only handle legal types. For example, on x86-32 the instruction
337 // selector contains all of the 64-bit instructions from x86-64,
338 // under the assumption that i64 won't be used if the target doesn't
339 // support it.
340 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
341}
342
343#include "X86GenCallingConv.inc"
344
345/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
346/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
347/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000348bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000349 MachineMemOperand *MMO, unsigned &ResultReg,
350 unsigned Alignment) {
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000351 bool HasSSE41 = Subtarget->hasSSE41();
Craig Topperca9c0802016-06-02 04:19:45 +0000352 bool HasAVX = Subtarget->hasAVX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000353 bool HasAVX2 = Subtarget->hasAVX2();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000354 bool HasAVX512 = Subtarget->hasAVX512();
355 bool HasVLX = Subtarget->hasVLX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000356 bool IsNonTemporal = MMO && MMO->isNonTemporal();
357
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000358 // Get opcode and regclass of the output for the given load instruction.
359 unsigned Opc = 0;
360 const TargetRegisterClass *RC = nullptr;
361 switch (VT.getSimpleVT().SimpleTy) {
362 default: return false;
363 case MVT::i1:
364 case MVT::i8:
365 Opc = X86::MOV8rm;
366 RC = &X86::GR8RegClass;
367 break;
368 case MVT::i16:
369 Opc = X86::MOV16rm;
370 RC = &X86::GR16RegClass;
371 break;
372 case MVT::i32:
373 Opc = X86::MOV32rm;
374 RC = &X86::GR32RegClass;
375 break;
376 case MVT::i64:
377 // Must be in x86-64 mode.
378 Opc = X86::MOV64rm;
379 RC = &X86::GR64RegClass;
380 break;
381 case MVT::f32:
382 if (X86ScalarSSEf32) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000383 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000384 RC = &X86::FR32RegClass;
385 } else {
386 Opc = X86::LD_Fp32m;
387 RC = &X86::RFP32RegClass;
388 }
389 break;
390 case MVT::f64:
391 if (X86ScalarSSEf64) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000392 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000393 RC = &X86::FR64RegClass;
394 } else {
395 Opc = X86::LD_Fp64m;
396 RC = &X86::RFP64RegClass;
397 }
398 break;
399 case MVT::f80:
400 // No f80 support yet.
401 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000402 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000403 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000404 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
405 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000406 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000407 Opc = HasVLX ? X86::VMOVAPSZ128rm :
408 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000409 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000410 Opc = HasVLX ? X86::VMOVUPSZ128rm :
411 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000412 RC = &X86::VR128RegClass;
413 break;
414 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000415 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000416 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
417 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000418 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000419 Opc = HasVLX ? X86::VMOVAPDZ128rm :
420 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000421 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000422 Opc = HasVLX ? X86::VMOVUPDZ128rm :
423 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000424 RC = &X86::VR128RegClass;
425 break;
426 case MVT::v4i32:
427 case MVT::v2i64:
428 case MVT::v8i16:
429 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000430 if (IsNonTemporal && Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000431 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
432 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000433 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000434 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
435 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000436 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000437 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
438 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000439 RC = &X86::VR128RegClass;
440 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000441 case MVT::v8f32:
442 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000443 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000444 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
445 else if (Alignment >= 32)
446 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000447 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000448 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000449 RC = &X86::VR256RegClass;
450 break;
451 case MVT::v4f64:
452 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000453 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
454 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000455 else if (Alignment >= 32)
456 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000457 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000458 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000459 RC = &X86::VR256RegClass;
460 break;
461 case MVT::v8i32:
462 case MVT::v4i64:
463 case MVT::v16i16:
464 case MVT::v32i8:
465 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000466 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
467 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000468 else if (Alignment >= 32)
469 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000470 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000471 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000472 RC = &X86::VR256RegClass;
473 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000474 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000475 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000476 if (IsNonTemporal && Alignment >= 64)
477 Opc = X86::VMOVNTDQAZrm;
478 else
479 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000480 RC = &X86::VR512RegClass;
481 break;
482 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000483 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000484 if (IsNonTemporal && Alignment >= 64)
485 Opc = X86::VMOVNTDQAZrm;
486 else
487 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000488 RC = &X86::VR512RegClass;
489 break;
490 case MVT::v8i64:
491 case MVT::v16i32:
492 case MVT::v32i16:
493 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000494 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000495 // Note: There are a lot more choices based on type with AVX-512, but
496 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000497 if (IsNonTemporal && Alignment >= 64)
498 Opc = X86::VMOVNTDQAZrm;
499 else
500 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000501 RC = &X86::VR512RegClass;
502 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000503 }
504
505 ResultReg = createResultReg(RC);
506 MachineInstrBuilder MIB =
507 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
508 addFullAddress(MIB, AM);
509 if (MMO)
510 MIB->addMemOperand(*FuncInfo.MF, MMO);
511 return true;
512}
513
514/// X86FastEmitStore - Emit a machine instruction to store a value Val of
515/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
516/// and a displacement offset, or a GlobalAddress,
517/// i.e. V. Return true if it is possible.
518bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000519 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000520 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000521 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000522 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000523 bool HasAVX = Subtarget->hasAVX();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000524 bool HasAVX512 = Subtarget->hasAVX512();
525 bool HasVLX = Subtarget->hasVLX();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000526 bool IsNonTemporal = MMO && MMO->isNonTemporal();
527
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000528 // Get opcode and regclass of the output for the given store instruction.
529 unsigned Opc = 0;
530 switch (VT.getSimpleVT().SimpleTy) {
531 case MVT::f80: // No f80 support yet.
532 default: return false;
533 case MVT::i1: {
534 // Mask out all but lowest bit.
535 unsigned AndResult = createResultReg(&X86::GR8RegClass);
536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
537 TII.get(X86::AND8ri), AndResult)
538 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
539 ValReg = AndResult;
Justin Bognerb03fd122016-08-17 05:10:15 +0000540 LLVM_FALLTHROUGH; // handle i1 as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000541 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000542 case MVT::i8: Opc = X86::MOV8mr; break;
543 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000544 case MVT::i32:
545 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
546 break;
547 case MVT::i64:
548 // Must be in x86-64 mode.
549 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
550 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000551 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000552 if (X86ScalarSSEf32) {
553 if (IsNonTemporal && HasSSE4A)
554 Opc = X86::MOVNTSS;
555 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000556 Opc = HasAVX512 ? X86::VMOVSSZmr :
557 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000558 } else
559 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000560 break;
561 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000562 if (X86ScalarSSEf32) {
563 if (IsNonTemporal && HasSSE4A)
564 Opc = X86::MOVNTSD;
565 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000566 Opc = HasAVX512 ? X86::VMOVSDZmr :
567 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000568 } else
569 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000570 break;
571 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000572 if (Aligned) {
573 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000574 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
575 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000576 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000577 Opc = HasVLX ? X86::VMOVAPSZ128mr :
578 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000579 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000580 Opc = HasVLX ? X86::VMOVUPSZ128mr :
581 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000582 break;
583 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000584 if (Aligned) {
585 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000586 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
587 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000588 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000589 Opc = HasVLX ? X86::VMOVAPDZ128mr :
590 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000591 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000592 Opc = HasVLX ? X86::VMOVUPDZ128mr :
593 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000594 break;
595 case MVT::v4i32:
596 case MVT::v2i64:
597 case MVT::v8i16:
598 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000599 if (Aligned) {
600 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000601 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
602 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000603 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000604 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
605 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000606 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000607 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
608 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000609 break;
610 case MVT::v8f32:
611 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000612 if (Aligned) {
613 if (IsNonTemporal)
614 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
615 else
616 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
617 } else
618 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000619 break;
620 case MVT::v4f64:
621 assert(HasAVX);
622 if (Aligned) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000623 if (IsNonTemporal)
624 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
625 else
626 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000627 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000628 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000629 break;
630 case MVT::v8i32:
631 case MVT::v4i64:
632 case MVT::v16i16:
633 case MVT::v32i8:
634 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000635 if (Aligned) {
636 if (IsNonTemporal)
637 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
638 else
639 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
640 } else
641 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000642 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000643 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000644 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000645 if (Aligned)
646 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
647 else
648 Opc = X86::VMOVUPSZmr;
649 break;
650 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000651 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000652 if (Aligned) {
653 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
654 } else
655 Opc = X86::VMOVUPDZmr;
656 break;
657 case MVT::v8i64:
658 case MVT::v16i32:
659 case MVT::v32i16:
660 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000661 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000662 // Note: There are a lot more choices based on type with AVX-512, but
663 // there's really no advantage when the store isn't masked.
664 if (Aligned)
665 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
666 else
667 Opc = X86::VMOVDQU64Zmr;
668 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000669 }
670
Quentin Colombetbf200682016-04-27 22:33:42 +0000671 const MCInstrDesc &Desc = TII.get(Opc);
672 // Some of the instructions in the previous switch use FR128 instead
673 // of FR32 for ValReg. Make sure the register we feed the instruction
674 // matches its register class constraints.
675 // Note: This is fine to do a copy from FR32 to FR128, this is the
676 // same registers behind the scene and actually why it did not trigger
677 // any bugs before.
678 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000679 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000681 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
682 if (MMO)
683 MIB->addMemOperand(*FuncInfo.MF, MMO);
684
685 return true;
686}
687
688bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000689 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000690 MachineMemOperand *MMO, bool Aligned) {
691 // Handle 'null' like i32/i64 0.
692 if (isa<ConstantPointerNull>(Val))
693 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
694
695 // If this is a store of a simple constant, fold the constant into the store.
696 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
697 unsigned Opc = 0;
698 bool Signed = true;
699 switch (VT.getSimpleVT().SimpleTy) {
700 default: break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000701 case MVT::i1:
702 Signed = false;
703 LLVM_FALLTHROUGH; // Handle as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000704 case MVT::i8: Opc = X86::MOV8mi; break;
705 case MVT::i16: Opc = X86::MOV16mi; break;
706 case MVT::i32: Opc = X86::MOV32mi; break;
707 case MVT::i64:
708 // Must be a 32-bit sign extended value.
709 if (isInt<32>(CI->getSExtValue()))
710 Opc = X86::MOV64mi32;
711 break;
712 }
713
714 if (Opc) {
715 MachineInstrBuilder MIB =
716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
717 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
718 : CI->getZExtValue());
719 if (MMO)
720 MIB->addMemOperand(*FuncInfo.MF, MMO);
721 return true;
722 }
723 }
724
725 unsigned ValReg = getRegForValue(Val);
726 if (ValReg == 0)
727 return false;
728
729 bool ValKill = hasTrivialKill(Val);
730 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
731}
732
733/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
734/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
735/// ISD::SIGN_EXTEND).
736bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
737 unsigned Src, EVT SrcVT,
738 unsigned &ResultReg) {
739 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
740 Src, /*TODO: Kill=*/false);
741 if (RR == 0)
742 return false;
743
744 ResultReg = RR;
745 return true;
746}
747
748bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
749 // Handle constant address.
750 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
751 // Can't handle alternate code models yet.
752 if (TM.getCodeModel() != CodeModel::Small)
753 return false;
754
755 // Can't handle TLS yet.
756 if (GV->isThreadLocal())
757 return false;
758
759 // RIP-relative addresses can't have additional register operands, so if
760 // we've already folded stuff into the addressing mode, just force the
761 // global value into its own register, which we can use as the basereg.
762 if (!Subtarget->isPICStyleRIPRel() ||
763 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
764 // Okay, we've committed to selecting this global. Set up the address.
765 AM.GV = GV;
766
767 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000768 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000769
770 // If this reference is relative to the pic base, set it now.
771 if (isGlobalRelativeToPICBase(GVFlags)) {
772 // FIXME: How do we know Base.Reg is free??
773 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
774 }
775
776 // Unless the ABI requires an extra load, return a direct reference to
777 // the global.
778 if (!isGlobalStubReference(GVFlags)) {
779 if (Subtarget->isPICStyleRIPRel()) {
780 // Use rip-relative addressing if we can. Above we verified that the
781 // base and index registers are unused.
782 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
783 AM.Base.Reg = X86::RIP;
784 }
785 AM.GVOpFlags = GVFlags;
786 return true;
787 }
788
789 // Ok, we need to do a load from a stub. If we've already loaded from
790 // this stub, reuse the loaded pointer, otherwise emit the load now.
791 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
792 unsigned LoadReg;
793 if (I != LocalValueMap.end() && I->second != 0) {
794 LoadReg = I->second;
795 } else {
796 // Issue load from stub.
797 unsigned Opc = 0;
798 const TargetRegisterClass *RC = nullptr;
799 X86AddressMode StubAM;
800 StubAM.Base.Reg = AM.Base.Reg;
801 StubAM.GV = GV;
802 StubAM.GVOpFlags = GVFlags;
803
804 // Prepare for inserting code in the local-value area.
805 SavePoint SaveInsertPt = enterLocalValueArea();
806
Mehdi Amini44ede332015-07-09 02:09:04 +0000807 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000808 Opc = X86::MOV64rm;
809 RC = &X86::GR64RegClass;
810
811 if (Subtarget->isPICStyleRIPRel())
812 StubAM.Base.Reg = X86::RIP;
813 } else {
814 Opc = X86::MOV32rm;
815 RC = &X86::GR32RegClass;
816 }
817
818 LoadReg = createResultReg(RC);
819 MachineInstrBuilder LoadMI =
820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
821 addFullAddress(LoadMI, StubAM);
822
823 // Ok, back to normal mode.
824 leaveLocalValueArea(SaveInsertPt);
825
826 // Prevent loading GV stub multiple times in same MBB.
827 LocalValueMap[V] = LoadReg;
828 }
829
830 // Now construct the final address. Note that the Disp, Scale,
831 // and Index values may already be set here.
832 AM.Base.Reg = LoadReg;
833 AM.GV = nullptr;
834 return true;
835 }
836 }
837
838 // If all else fails, try to materialize the value in a register.
839 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
840 if (AM.Base.Reg == 0) {
841 AM.Base.Reg = getRegForValue(V);
842 return AM.Base.Reg != 0;
843 }
844 if (AM.IndexReg == 0) {
845 assert(AM.Scale == 1 && "Scale with no index!");
846 AM.IndexReg = getRegForValue(V);
847 return AM.IndexReg != 0;
848 }
849 }
850
851 return false;
852}
853
854/// X86SelectAddress - Attempt to fill in an address from the given value.
855///
856bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
857 SmallVector<const Value *, 32> GEPs;
858redo_gep:
859 const User *U = nullptr;
860 unsigned Opcode = Instruction::UserOp1;
861 if (const Instruction *I = dyn_cast<Instruction>(V)) {
862 // Don't walk into other basic blocks; it's possible we haven't
863 // visited them yet, so the instructions may not yet be assigned
864 // virtual registers.
865 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
866 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
867 Opcode = I->getOpcode();
868 U = I;
869 }
870 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
871 Opcode = C->getOpcode();
872 U = C;
873 }
874
875 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
876 if (Ty->getAddressSpace() > 255)
877 // Fast instruction selection doesn't support the special
878 // address spaces.
879 return false;
880
881 switch (Opcode) {
882 default: break;
883 case Instruction::BitCast:
884 // Look past bitcasts.
885 return X86SelectAddress(U->getOperand(0), AM);
886
887 case Instruction::IntToPtr:
888 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000889 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
890 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000891 return X86SelectAddress(U->getOperand(0), AM);
892 break;
893
894 case Instruction::PtrToInt:
895 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000896 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000897 return X86SelectAddress(U->getOperand(0), AM);
898 break;
899
900 case Instruction::Alloca: {
901 // Do static allocas.
902 const AllocaInst *A = cast<AllocaInst>(V);
903 DenseMap<const AllocaInst *, int>::iterator SI =
904 FuncInfo.StaticAllocaMap.find(A);
905 if (SI != FuncInfo.StaticAllocaMap.end()) {
906 AM.BaseType = X86AddressMode::FrameIndexBase;
907 AM.Base.FrameIndex = SI->second;
908 return true;
909 }
910 break;
911 }
912
913 case Instruction::Add: {
914 // Adds of constants are common and easy enough.
915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
916 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
917 // They have to fit in the 32-bit signed displacement field though.
918 if (isInt<32>(Disp)) {
919 AM.Disp = (uint32_t)Disp;
920 return X86SelectAddress(U->getOperand(0), AM);
921 }
922 }
923 break;
924 }
925
926 case Instruction::GetElementPtr: {
927 X86AddressMode SavedAM = AM;
928
929 // Pattern-match simple GEPs.
930 uint64_t Disp = (int32_t)AM.Disp;
931 unsigned IndexReg = AM.IndexReg;
932 unsigned Scale = AM.Scale;
933 gep_type_iterator GTI = gep_type_begin(U);
934 // Iterate through the indices, folding what we can. Constants can be
935 // folded, and one dynamic index can be handled, if the scale is supported.
936 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
937 i != e; ++i, ++GTI) {
938 const Value *Op = *i;
939 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
940 const StructLayout *SL = DL.getStructLayout(STy);
941 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
942 continue;
943 }
944
945 // A array/variable index is always of the form i*S where S is the
946 // constant scale size. See if we can push the scale into immediates.
947 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
948 for (;;) {
949 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
950 // Constant-offset addressing.
951 Disp += CI->getSExtValue() * S;
952 break;
953 }
954 if (canFoldAddIntoGEP(U, Op)) {
955 // A compatible add with a constant operand. Fold the constant.
956 ConstantInt *CI =
957 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
958 Disp += CI->getSExtValue() * S;
959 // Iterate on the other operand.
960 Op = cast<AddOperator>(Op)->getOperand(0);
961 continue;
962 }
963 if (IndexReg == 0 &&
964 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
965 (S == 1 || S == 2 || S == 4 || S == 8)) {
966 // Scaled-index addressing.
967 Scale = S;
968 IndexReg = getRegForGEPIndex(Op).first;
969 if (IndexReg == 0)
970 return false;
971 break;
972 }
973 // Unsupported.
974 goto unsupported_gep;
975 }
976 }
977
978 // Check for displacement overflow.
979 if (!isInt<32>(Disp))
980 break;
981
982 AM.IndexReg = IndexReg;
983 AM.Scale = Scale;
984 AM.Disp = (uint32_t)Disp;
985 GEPs.push_back(V);
986
987 if (const GetElementPtrInst *GEP =
988 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
989 // Ok, the GEP indices were covered by constant-offset and scaled-index
990 // addressing. Update the address state and move on to examining the base.
991 V = GEP;
992 goto redo_gep;
993 } else if (X86SelectAddress(U->getOperand(0), AM)) {
994 return true;
995 }
996
997 // If we couldn't merge the gep value into this addr mode, revert back to
998 // our address and just match the value instead of completely failing.
999 AM = SavedAM;
1000
David Majnemerd7708772016-06-24 04:05:21 +00001001 for (const Value *I : reverse(GEPs))
1002 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001003 return true;
1004
1005 return false;
1006 unsupported_gep:
1007 // Ok, the GEP indices weren't all covered.
1008 break;
1009 }
1010 }
1011
1012 return handleConstantAddresses(V, AM);
1013}
1014
1015/// X86SelectCallAddress - Attempt to fill in an address from the given value.
1016///
1017bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1018 const User *U = nullptr;
1019 unsigned Opcode = Instruction::UserOp1;
1020 const Instruction *I = dyn_cast<Instruction>(V);
1021 // Record if the value is defined in the same basic block.
1022 //
1023 // This information is crucial to know whether or not folding an
1024 // operand is valid.
1025 // Indeed, FastISel generates or reuses a virtual register for all
1026 // operands of all instructions it selects. Obviously, the definition and
1027 // its uses must use the same virtual register otherwise the produced
1028 // code is incorrect.
1029 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1030 // registers for values that are alive across basic blocks. This ensures
1031 // that the values are consistently set between across basic block, even
1032 // if different instruction selection mechanisms are used (e.g., a mix of
1033 // SDISel and FastISel).
1034 // For values local to a basic block, the instruction selection process
1035 // generates these virtual registers with whatever method is appropriate
1036 // for its needs. In particular, FastISel and SDISel do not share the way
1037 // local virtual registers are set.
1038 // Therefore, this is impossible (or at least unsafe) to share values
1039 // between basic blocks unless they use the same instruction selection
1040 // method, which is not guarantee for X86.
1041 // Moreover, things like hasOneUse could not be used accurately, if we
1042 // allow to reference values across basic blocks whereas they are not
1043 // alive across basic blocks initially.
1044 bool InMBB = true;
1045 if (I) {
1046 Opcode = I->getOpcode();
1047 U = I;
1048 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1049 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1050 Opcode = C->getOpcode();
1051 U = C;
1052 }
1053
1054 switch (Opcode) {
1055 default: break;
1056 case Instruction::BitCast:
1057 // Look past bitcasts if its operand is in the same BB.
1058 if (InMBB)
1059 return X86SelectCallAddress(U->getOperand(0), AM);
1060 break;
1061
1062 case Instruction::IntToPtr:
1063 // Look past no-op inttoptrs if its operand is in the same BB.
1064 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001065 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1066 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001067 return X86SelectCallAddress(U->getOperand(0), AM);
1068 break;
1069
1070 case Instruction::PtrToInt:
1071 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001072 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001073 return X86SelectCallAddress(U->getOperand(0), AM);
1074 break;
1075 }
1076
1077 // Handle constant address.
1078 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1079 // Can't handle alternate code models yet.
1080 if (TM.getCodeModel() != CodeModel::Small)
1081 return false;
1082
1083 // RIP-relative addresses can't have additional register operands.
1084 if (Subtarget->isPICStyleRIPRel() &&
1085 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1086 return false;
1087
1088 // Can't handle DLL Import.
1089 if (GV->hasDLLImportStorageClass())
1090 return false;
1091
1092 // Can't handle TLS.
1093 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1094 if (GVar->isThreadLocal())
1095 return false;
1096
1097 // Okay, we've committed to selecting this global. Set up the basic address.
1098 AM.GV = GV;
1099
1100 // No ABI requires an extra load for anything other than DLLImport, which
1101 // we rejected above. Return a direct reference to the global.
1102 if (Subtarget->isPICStyleRIPRel()) {
1103 // Use rip-relative addressing if we can. Above we verified that the
1104 // base and index registers are unused.
1105 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1106 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001107 } else {
1108 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001109 }
1110
1111 return true;
1112 }
1113
1114 // If all else fails, try to materialize the value in a register.
1115 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1116 if (AM.Base.Reg == 0) {
1117 AM.Base.Reg = getRegForValue(V);
1118 return AM.Base.Reg != 0;
1119 }
1120 if (AM.IndexReg == 0) {
1121 assert(AM.Scale == 1 && "Scale with no index!");
1122 AM.IndexReg = getRegForValue(V);
1123 return AM.IndexReg != 0;
1124 }
1125 }
1126
1127 return false;
1128}
1129
1130
1131/// X86SelectStore - Select and emit code to implement store instructions.
1132bool X86FastISel::X86SelectStore(const Instruction *I) {
1133 // Atomic stores need special handling.
1134 const StoreInst *S = cast<StoreInst>(I);
1135
1136 if (S->isAtomic())
1137 return false;
1138
Manman Ren57518142016-04-11 21:08:06 +00001139 const Value *PtrV = I->getOperand(1);
1140 if (TLI.supportSwiftError()) {
1141 // Swifterror values can come from either a function parameter with
1142 // swifterror attribute or an alloca with swifterror attribute.
1143 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1144 if (Arg->hasSwiftErrorAttr())
1145 return false;
1146 }
1147
1148 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1149 if (Alloca->isSwiftError())
1150 return false;
1151 }
1152 }
1153
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001154 const Value *Val = S->getValueOperand();
1155 const Value *Ptr = S->getPointerOperand();
1156
1157 MVT VT;
1158 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1159 return false;
1160
1161 unsigned Alignment = S->getAlignment();
1162 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1163 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1164 Alignment = ABIAlignment;
1165 bool Aligned = Alignment >= ABIAlignment;
1166
1167 X86AddressMode AM;
1168 if (!X86SelectAddress(Ptr, AM))
1169 return false;
1170
1171 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1172}
1173
1174/// X86SelectRet - Select and emit code to implement ret instructions.
1175bool X86FastISel::X86SelectRet(const Instruction *I) {
1176 const ReturnInst *Ret = cast<ReturnInst>(I);
1177 const Function &F = *I->getParent()->getParent();
1178 const X86MachineFunctionInfo *X86MFInfo =
1179 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1180
1181 if (!FuncInfo.CanLowerReturn)
1182 return false;
1183
Manman Ren57518142016-04-11 21:08:06 +00001184 if (TLI.supportSwiftError() &&
1185 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1186 return false;
1187
Manman Rened967f32016-01-12 01:08:46 +00001188 if (TLI.supportSplitCSR(FuncInfo.MF))
1189 return false;
1190
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001191 CallingConv::ID CC = F.getCallingConv();
1192 if (CC != CallingConv::C &&
1193 CC != CallingConv::Fast &&
1194 CC != CallingConv::X86_FastCall &&
Nico Weberecdf45b2016-07-14 13:54:26 +00001195 CC != CallingConv::X86_StdCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001196 CC != CallingConv::X86_ThisCall &&
Nico Weber8d66df12016-07-15 20:18:37 +00001197 CC != CallingConv::X86_64_SysV &&
1198 CC != CallingConv::X86_64_Win64)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001199 return false;
1200
Nico Weberc7bf6462016-07-12 01:30:35 +00001201 // Don't handle popping bytes if they don't fit the ret's immediate.
1202 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001203 return false;
1204
1205 // fastcc with -tailcallopt is intended to provide a guaranteed
1206 // tail call optimization. Fastisel doesn't know how to do that.
1207 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1208 return false;
1209
1210 // Let SDISel handle vararg functions.
1211 if (F.isVarArg())
1212 return false;
1213
1214 // Build a list of return value registers.
1215 SmallVector<unsigned, 4> RetRegs;
1216
1217 if (Ret->getNumOperands() > 0) {
1218 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001219 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001220
1221 // Analyze operands of the call, assigning locations to each operand.
1222 SmallVector<CCValAssign, 16> ValLocs;
1223 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1224 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1225
1226 const Value *RV = Ret->getOperand(0);
1227 unsigned Reg = getRegForValue(RV);
1228 if (Reg == 0)
1229 return false;
1230
1231 // Only handle a single return value for now.
1232 if (ValLocs.size() != 1)
1233 return false;
1234
1235 CCValAssign &VA = ValLocs[0];
1236
1237 // Don't bother handling odd stuff for now.
1238 if (VA.getLocInfo() != CCValAssign::Full)
1239 return false;
1240 // Only handle register returns for now.
1241 if (!VA.isRegLoc())
1242 return false;
1243
1244 // The calling-convention tables for x87 returns don't tell
1245 // the whole story.
1246 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1247 return false;
1248
1249 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001250 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001251 EVT DstVT = VA.getValVT();
1252 // Special handling for extended integers.
1253 if (SrcVT != DstVT) {
1254 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1255 return false;
1256
1257 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1258 return false;
1259
1260 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1261
1262 if (SrcVT == MVT::i1) {
1263 if (Outs[0].Flags.isSExt())
1264 return false;
1265 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1266 SrcVT = MVT::i8;
1267 }
1268 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1269 ISD::SIGN_EXTEND;
1270 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1271 SrcReg, /*TODO: Kill=*/false);
1272 }
1273
1274 // Make the copy.
1275 unsigned DstReg = VA.getLocReg();
1276 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1277 // Avoid a cross-class copy. This is very unlikely.
1278 if (!SrcRC->contains(DstReg))
1279 return false;
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1281 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1282
1283 // Add register to return instruction.
1284 RetRegs.push_back(VA.getLocReg());
1285 }
1286
Manman Ren1c3f65a2016-04-26 18:08:06 +00001287 // Swift calling convention does not require we copy the sret argument
1288 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1289
Dimitry Andric227b9282016-01-03 17:22:03 +00001290 // All x86 ABIs require that for returning structs by value we copy
1291 // the sret argument into %rax/%eax (depending on ABI) for the return.
1292 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001293 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001294 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001295 unsigned Reg = X86MFInfo->getSRetReturnReg();
1296 assert(Reg &&
1297 "SRetReturnReg should have been set in LowerFormalArguments()!");
1298 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1300 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1301 RetRegs.push_back(RetReg);
1302 }
1303
1304 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001305 MachineInstrBuilder MIB;
1306 if (X86MFInfo->getBytesToPopOnReturn()) {
1307 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1308 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1309 .addImm(X86MFInfo->getBytesToPopOnReturn());
1310 } else {
1311 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1312 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1313 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001314 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1315 MIB.addReg(RetRegs[i], RegState::Implicit);
1316 return true;
1317}
1318
1319/// X86SelectLoad - Select and emit code to implement load instructions.
1320///
1321bool X86FastISel::X86SelectLoad(const Instruction *I) {
1322 const LoadInst *LI = cast<LoadInst>(I);
1323
1324 // Atomic loads need special handling.
1325 if (LI->isAtomic())
1326 return false;
1327
Manman Ren57518142016-04-11 21:08:06 +00001328 const Value *SV = I->getOperand(0);
1329 if (TLI.supportSwiftError()) {
1330 // Swifterror values can come from either a function parameter with
1331 // swifterror attribute or an alloca with swifterror attribute.
1332 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1333 if (Arg->hasSwiftErrorAttr())
1334 return false;
1335 }
1336
1337 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1338 if (Alloca->isSwiftError())
1339 return false;
1340 }
1341 }
1342
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001343 MVT VT;
1344 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1345 return false;
1346
1347 const Value *Ptr = LI->getPointerOperand();
1348
1349 X86AddressMode AM;
1350 if (!X86SelectAddress(Ptr, AM))
1351 return false;
1352
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001353 unsigned Alignment = LI->getAlignment();
1354 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1355 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1356 Alignment = ABIAlignment;
1357
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001358 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001359 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1360 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001361 return false;
1362
1363 updateValueMap(I, ResultReg);
1364 return true;
1365}
1366
1367static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1368 bool HasAVX = Subtarget->hasAVX();
1369 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1370 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1371
1372 switch (VT.getSimpleVT().SimpleTy) {
1373 default: return 0;
1374 case MVT::i8: return X86::CMP8rr;
1375 case MVT::i16: return X86::CMP16rr;
1376 case MVT::i32: return X86::CMP32rr;
1377 case MVT::i64: return X86::CMP64rr;
1378 case MVT::f32:
1379 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1380 case MVT::f64:
1381 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1382 }
1383}
1384
Rafael Espindola19141f22015-03-16 14:05:49 +00001385/// If we have a comparison with RHS as the RHS of the comparison, return an
1386/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001387static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001388 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001389 switch (VT.getSimpleVT().SimpleTy) {
1390 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001391 default:
1392 return 0;
1393 case MVT::i8:
1394 return X86::CMP8ri;
1395 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001396 if (isInt<8>(Val))
1397 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001398 return X86::CMP16ri;
1399 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001400 if (isInt<8>(Val))
1401 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001402 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001403 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001404 if (isInt<8>(Val))
1405 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001406 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1407 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001408 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001409 return X86::CMP64ri32;
1410 return 0;
1411 }
1412}
1413
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001414bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1415 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001416 unsigned Op0Reg = getRegForValue(Op0);
1417 if (Op0Reg == 0) return false;
1418
1419 // Handle 'null' like i32/i64 0.
1420 if (isa<ConstantPointerNull>(Op1))
1421 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1422
1423 // We have two options: compare with register or immediate. If the RHS of
1424 // the compare is an immediate that we can fold into this compare, use
1425 // CMPri, otherwise use CMPrr.
1426 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1427 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1429 .addReg(Op0Reg)
1430 .addImm(Op1C->getSExtValue());
1431 return true;
1432 }
1433 }
1434
1435 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1436 if (CompareOpc == 0) return false;
1437
1438 unsigned Op1Reg = getRegForValue(Op1);
1439 if (Op1Reg == 0) return false;
1440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1441 .addReg(Op0Reg)
1442 .addReg(Op1Reg);
1443
1444 return true;
1445}
1446
1447bool X86FastISel::X86SelectCmp(const Instruction *I) {
1448 const CmpInst *CI = cast<CmpInst>(I);
1449
1450 MVT VT;
1451 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1452 return false;
1453
Elena Demikhovskyad0a56f2016-07-06 14:15:43 +00001454 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1455 return false;
1456
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001457 // Try to optimize or fold the cmp.
1458 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1459 unsigned ResultReg = 0;
1460 switch (Predicate) {
1461 default: break;
1462 case CmpInst::FCMP_FALSE: {
1463 ResultReg = createResultReg(&X86::GR32RegClass);
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1465 ResultReg);
1466 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1467 X86::sub_8bit);
1468 if (!ResultReg)
1469 return false;
1470 break;
1471 }
1472 case CmpInst::FCMP_TRUE: {
1473 ResultReg = createResultReg(&X86::GR8RegClass);
1474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1475 ResultReg).addImm(1);
1476 break;
1477 }
1478 }
1479
1480 if (ResultReg) {
1481 updateValueMap(I, ResultReg);
1482 return true;
1483 }
1484
1485 const Value *LHS = CI->getOperand(0);
1486 const Value *RHS = CI->getOperand(1);
1487
1488 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1489 // We don't have to materialize a zero constant for this case and can just use
1490 // %x again on the RHS.
1491 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1492 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1493 if (RHSC && RHSC->isNullValue())
1494 RHS = LHS;
1495 }
1496
1497 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00001498 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001499 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1500 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1501 };
Craig Topper428169a2016-09-05 07:14:21 +00001502 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001503 switch (Predicate) {
1504 default: break;
1505 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1506 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1507 }
1508
1509 ResultReg = createResultReg(&X86::GR8RegClass);
1510 if (SETFOpc) {
1511 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1512 return false;
1513
1514 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1515 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1517 FlagReg1);
1518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1519 FlagReg2);
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1521 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1522 updateValueMap(I, ResultReg);
1523 return true;
1524 }
1525
1526 X86::CondCode CC;
1527 bool SwapArgs;
1528 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1529 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1530 unsigned Opc = X86::getSETFromCond(CC);
1531
1532 if (SwapArgs)
1533 std::swap(LHS, RHS);
1534
1535 // Emit a compare of LHS/RHS.
1536 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1537 return false;
1538
1539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1540 updateValueMap(I, ResultReg);
1541 return true;
1542}
1543
1544bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001545 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001546 if (!TLI.isTypeLegal(DstVT))
1547 return false;
1548
1549 unsigned ResultReg = getRegForValue(I->getOperand(0));
1550 if (ResultReg == 0)
1551 return false;
1552
1553 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001554 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001555 if (SrcVT.SimpleTy == MVT::i1) {
1556 // Set the high bits to zero.
1557 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1558 SrcVT = MVT::i8;
1559
1560 if (ResultReg == 0)
1561 return false;
1562 }
1563
1564 if (DstVT == MVT::i64) {
1565 // Handle extension to 64-bits via sub-register shenanigans.
1566 unsigned MovInst;
1567
1568 switch (SrcVT.SimpleTy) {
1569 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1570 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1571 case MVT::i32: MovInst = X86::MOV32rr; break;
1572 default: llvm_unreachable("Unexpected zext to i64 source type");
1573 }
1574
1575 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1577 .addReg(ResultReg);
1578
1579 ResultReg = createResultReg(&X86::GR64RegClass);
1580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1581 ResultReg)
1582 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1583 } else if (DstVT != MVT::i8) {
1584 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1585 ResultReg, /*Kill=*/true);
1586 if (ResultReg == 0)
1587 return false;
1588 }
1589
1590 updateValueMap(I, ResultReg);
1591 return true;
1592}
1593
1594bool X86FastISel::X86SelectBranch(const Instruction *I) {
1595 // Unconditional branches are selected by tablegen-generated code.
1596 // Handle a conditional branch.
1597 const BranchInst *BI = cast<BranchInst>(I);
1598 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1599 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1600
1601 // Fold the common case of a conditional branch with a comparison
1602 // in the same block (values defined on other blocks may not have
1603 // initialized registers).
1604 X86::CondCode CC;
1605 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1606 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001607 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001608
1609 // Try to optimize or fold the cmp.
1610 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1611 switch (Predicate) {
1612 default: break;
1613 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1614 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1615 }
1616
1617 const Value *CmpLHS = CI->getOperand(0);
1618 const Value *CmpRHS = CI->getOperand(1);
1619
1620 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1621 // 0.0.
1622 // We don't have to materialize a zero constant for this case and can just
1623 // use %x again on the RHS.
1624 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1625 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1626 if (CmpRHSC && CmpRHSC->isNullValue())
1627 CmpRHS = CmpLHS;
1628 }
1629
1630 // Try to take advantage of fallthrough opportunities.
1631 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1632 std::swap(TrueMBB, FalseMBB);
1633 Predicate = CmpInst::getInversePredicate(Predicate);
1634 }
1635
1636 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1637 // code check. Instead two branch instructions are required to check all
1638 // the flags. First we change the predicate to a supported condition code,
1639 // which will be the first branch. Later one we will emit the second
1640 // branch.
1641 bool NeedExtraBranch = false;
1642 switch (Predicate) {
1643 default: break;
1644 case CmpInst::FCMP_OEQ:
Justin Bognerb03fd122016-08-17 05:10:15 +00001645 std::swap(TrueMBB, FalseMBB);
1646 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001647 case CmpInst::FCMP_UNE:
1648 NeedExtraBranch = true;
1649 Predicate = CmpInst::FCMP_ONE;
1650 break;
1651 }
1652
1653 bool SwapArgs;
1654 unsigned BranchOpc;
1655 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1656 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1657
1658 BranchOpc = X86::GetCondBranchFromCond(CC);
1659 if (SwapArgs)
1660 std::swap(CmpLHS, CmpRHS);
1661
1662 // Emit a compare of the LHS and RHS, setting the flags.
1663 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1664 return false;
1665
1666 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1667 .addMBB(TrueMBB);
1668
1669 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1670 // to UNE above).
1671 if (NeedExtraBranch) {
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1673 .addMBB(TrueMBB);
1674 }
1675
Matthias Braun17af6072015-08-26 01:38:00 +00001676 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001677 return true;
1678 }
1679 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1680 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1681 // typically happen for _Bool and C++ bools.
1682 MVT SourceVT;
1683 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1684 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1685 unsigned TestOpc = 0;
1686 switch (SourceVT.SimpleTy) {
1687 default: break;
1688 case MVT::i8: TestOpc = X86::TEST8ri; break;
1689 case MVT::i16: TestOpc = X86::TEST16ri; break;
1690 case MVT::i32: TestOpc = X86::TEST32ri; break;
1691 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1692 }
1693 if (TestOpc) {
1694 unsigned OpReg = getRegForValue(TI->getOperand(0));
1695 if (OpReg == 0) return false;
Guy Blank9ae797a2016-08-21 08:02:27 +00001696
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1698 .addReg(OpReg).addImm(1);
1699
1700 unsigned JmpOpc = X86::JNE_1;
1701 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1702 std::swap(TrueMBB, FalseMBB);
1703 JmpOpc = X86::JE_1;
1704 }
1705
1706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1707 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001708
1709 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001710 return true;
1711 }
1712 }
1713 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1714 // Fake request the condition, otherwise the intrinsic might be completely
1715 // optimized away.
1716 unsigned TmpReg = getRegForValue(BI->getCondition());
1717 if (TmpReg == 0)
1718 return false;
1719
1720 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1721
1722 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1723 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001724 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001725 return true;
1726 }
1727
1728 // Otherwise do a clumsy setcc and re-test it.
1729 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1730 // in an explicit cast, so make sure to handle that correctly.
1731 unsigned OpReg = getRegForValue(BI->getCondition());
1732 if (OpReg == 0) return false;
1733
Guy Blank9ae797a2016-08-21 08:02:27 +00001734 // In case OpReg is a K register, kortest against itself.
1735 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass)
1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::KORTESTWrr))
1737 .addReg(OpReg)
1738 .addReg(OpReg);
1739 else
1740 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1741 .addReg(OpReg)
1742 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001743 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1744 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001745 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001746 return true;
1747}
1748
1749bool X86FastISel::X86SelectShift(const Instruction *I) {
1750 unsigned CReg = 0, OpReg = 0;
1751 const TargetRegisterClass *RC = nullptr;
1752 if (I->getType()->isIntegerTy(8)) {
1753 CReg = X86::CL;
1754 RC = &X86::GR8RegClass;
1755 switch (I->getOpcode()) {
1756 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1757 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1758 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1759 default: return false;
1760 }
1761 } else if (I->getType()->isIntegerTy(16)) {
1762 CReg = X86::CX;
1763 RC = &X86::GR16RegClass;
1764 switch (I->getOpcode()) {
1765 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1766 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1767 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1768 default: return false;
1769 }
1770 } else if (I->getType()->isIntegerTy(32)) {
1771 CReg = X86::ECX;
1772 RC = &X86::GR32RegClass;
1773 switch (I->getOpcode()) {
1774 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1775 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1776 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1777 default: return false;
1778 }
1779 } else if (I->getType()->isIntegerTy(64)) {
1780 CReg = X86::RCX;
1781 RC = &X86::GR64RegClass;
1782 switch (I->getOpcode()) {
1783 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1784 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1785 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1786 default: return false;
1787 }
1788 } else {
1789 return false;
1790 }
1791
1792 MVT VT;
1793 if (!isTypeLegal(I->getType(), VT))
1794 return false;
1795
1796 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1797 if (Op0Reg == 0) return false;
1798
1799 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1800 if (Op1Reg == 0) return false;
1801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1802 CReg).addReg(Op1Reg);
1803
1804 // The shift instruction uses X86::CL. If we defined a super-register
1805 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1806 if (CReg != X86::CL)
1807 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1808 TII.get(TargetOpcode::KILL), X86::CL)
1809 .addReg(CReg, RegState::Kill);
1810
1811 unsigned ResultReg = createResultReg(RC);
1812 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1813 .addReg(Op0Reg);
1814 updateValueMap(I, ResultReg);
1815 return true;
1816}
1817
1818bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1819 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1820 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1821 const static bool S = true; // IsSigned
1822 const static bool U = false; // !IsSigned
1823 const static unsigned Copy = TargetOpcode::COPY;
1824 // For the X86 DIV/IDIV instruction, in most cases the dividend
1825 // (numerator) must be in a specific register pair highreg:lowreg,
1826 // producing the quotient in lowreg and the remainder in highreg.
1827 // For most data types, to set up the instruction, the dividend is
1828 // copied into lowreg, and lowreg is sign-extended or zero-extended
1829 // into highreg. The exception is i8, where the dividend is defined
1830 // as a single register rather than a register pair, and we
1831 // therefore directly sign-extend or zero-extend the dividend into
1832 // lowreg, instead of copying, and ignore the highreg.
1833 const static struct DivRemEntry {
1834 // The following portion depends only on the data type.
1835 const TargetRegisterClass *RC;
1836 unsigned LowInReg; // low part of the register pair
1837 unsigned HighInReg; // high part of the register pair
1838 // The following portion depends on both the data type and the operation.
1839 struct DivRemResult {
1840 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1841 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1842 // highreg, or copying a zero into highreg.
1843 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1844 // zero/sign-extending into lowreg for i8.
1845 unsigned DivRemResultReg; // Register containing the desired result.
1846 bool IsOpSigned; // Whether to use signed or unsigned form.
1847 } ResultTable[NumOps];
1848 } OpTable[NumTypes] = {
1849 { &X86::GR8RegClass, X86::AX, 0, {
1850 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1851 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1852 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1853 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1854 }
1855 }, // i8
1856 { &X86::GR16RegClass, X86::AX, X86::DX, {
1857 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1858 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1859 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1860 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1861 }
1862 }, // i16
1863 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1864 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1865 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1866 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1867 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1868 }
1869 }, // i32
1870 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1871 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1872 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1873 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1874 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1875 }
1876 }, // i64
1877 };
1878
1879 MVT VT;
1880 if (!isTypeLegal(I->getType(), VT))
1881 return false;
1882
1883 unsigned TypeIndex, OpIndex;
1884 switch (VT.SimpleTy) {
1885 default: return false;
1886 case MVT::i8: TypeIndex = 0; break;
1887 case MVT::i16: TypeIndex = 1; break;
1888 case MVT::i32: TypeIndex = 2; break;
1889 case MVT::i64: TypeIndex = 3;
1890 if (!Subtarget->is64Bit())
1891 return false;
1892 break;
1893 }
1894
1895 switch (I->getOpcode()) {
1896 default: llvm_unreachable("Unexpected div/rem opcode");
1897 case Instruction::SDiv: OpIndex = 0; break;
1898 case Instruction::SRem: OpIndex = 1; break;
1899 case Instruction::UDiv: OpIndex = 2; break;
1900 case Instruction::URem: OpIndex = 3; break;
1901 }
1902
1903 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1904 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1905 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1906 if (Op0Reg == 0)
1907 return false;
1908 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1909 if (Op1Reg == 0)
1910 return false;
1911
1912 // Move op0 into low-order input register.
1913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1914 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1915 // Zero-extend or sign-extend into high-order input register.
1916 if (OpEntry.OpSignExtend) {
1917 if (OpEntry.IsOpSigned)
1918 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1919 TII.get(OpEntry.OpSignExtend));
1920 else {
1921 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1922 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1923 TII.get(X86::MOV32r0), Zero32);
1924
1925 // Copy the zero into the appropriate sub/super/identical physical
1926 // register. Unfortunately the operations needed are not uniform enough
1927 // to fit neatly into the table above.
1928 if (VT.SimpleTy == MVT::i16) {
1929 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1930 TII.get(Copy), TypeEntry.HighInReg)
1931 .addReg(Zero32, 0, X86::sub_16bit);
1932 } else if (VT.SimpleTy == MVT::i32) {
1933 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1934 TII.get(Copy), TypeEntry.HighInReg)
1935 .addReg(Zero32);
1936 } else if (VT.SimpleTy == MVT::i64) {
1937 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1938 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1939 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1940 }
1941 }
1942 }
1943 // Generate the DIV/IDIV instruction.
1944 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1945 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1946 // For i8 remainder, we can't reference AH directly, as we'll end
1947 // up with bogus copies like %R9B = COPY %AH. Reference AX
1948 // instead to prevent AH references in a REX instruction.
1949 //
1950 // The current assumption of the fast register allocator is that isel
1951 // won't generate explicit references to the GPR8_NOREX registers. If
1952 // the allocator and/or the backend get enhanced to be more robust in
1953 // that regard, this can be, and should be, removed.
1954 unsigned ResultReg = 0;
1955 if ((I->getOpcode() == Instruction::SRem ||
1956 I->getOpcode() == Instruction::URem) &&
1957 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1958 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1959 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1961 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1962
1963 // Shift AX right by 8 bits instead of using AH.
1964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1965 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1966
1967 // Now reference the 8-bit subreg of the result.
1968 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1969 /*Kill=*/true, X86::sub_8bit);
1970 }
1971 // Copy the result out of the physreg if we haven't already.
1972 if (!ResultReg) {
1973 ResultReg = createResultReg(TypeEntry.RC);
1974 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1975 .addReg(OpEntry.DivRemResultReg);
1976 }
1977 updateValueMap(I, ResultReg);
1978
1979 return true;
1980}
1981
1982/// \brief Emit a conditional move instruction (if the are supported) to lower
1983/// the select.
1984bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1985 // Check if the subtarget supports these instructions.
1986 if (!Subtarget->hasCMov())
1987 return false;
1988
1989 // FIXME: Add support for i8.
1990 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1991 return false;
1992
1993 const Value *Cond = I->getOperand(0);
1994 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1995 bool NeedTest = true;
1996 X86::CondCode CC = X86::COND_NE;
1997
1998 // Optimize conditions coming from a compare if both instructions are in the
1999 // same basic block (values defined in other basic blocks may not have
2000 // initialized registers).
2001 const auto *CI = dyn_cast<CmpInst>(Cond);
2002 if (CI && (CI->getParent() == I->getParent())) {
2003 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2004
2005 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00002006 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002007 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2008 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2009 };
Craig Topper428169a2016-09-05 07:14:21 +00002010 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002011 switch (Predicate) {
2012 default: break;
2013 case CmpInst::FCMP_OEQ:
2014 SETFOpc = &SETFOpcTable[0][0];
2015 Predicate = CmpInst::ICMP_NE;
2016 break;
2017 case CmpInst::FCMP_UNE:
2018 SETFOpc = &SETFOpcTable[1][0];
2019 Predicate = CmpInst::ICMP_NE;
2020 break;
2021 }
2022
2023 bool NeedSwap;
2024 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
2025 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2026
2027 const Value *CmpLHS = CI->getOperand(0);
2028 const Value *CmpRHS = CI->getOperand(1);
2029 if (NeedSwap)
2030 std::swap(CmpLHS, CmpRHS);
2031
Mehdi Amini44ede332015-07-09 02:09:04 +00002032 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002033 // Emit a compare of the LHS and RHS, setting the flags.
2034 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2035 return false;
2036
2037 if (SETFOpc) {
2038 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2039 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2040 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2041 FlagReg1);
2042 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2043 FlagReg2);
2044 auto const &II = TII.get(SETFOpc[2]);
2045 if (II.getNumDefs()) {
2046 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2048 .addReg(FlagReg2).addReg(FlagReg1);
2049 } else {
2050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2051 .addReg(FlagReg2).addReg(FlagReg1);
2052 }
2053 }
2054 NeedTest = false;
2055 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2056 // Fake request the condition, otherwise the intrinsic might be completely
2057 // optimized away.
2058 unsigned TmpReg = getRegForValue(Cond);
2059 if (TmpReg == 0)
2060 return false;
2061
2062 NeedTest = false;
2063 }
2064
2065 if (NeedTest) {
2066 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2067 // garbage. Indeed, only the less significant bit is supposed to be
2068 // accurate. If we read more than the lsb, we may see non-zero values
2069 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2070 // the select. This is achieved by performing TEST against 1.
2071 unsigned CondReg = getRegForValue(Cond);
2072 if (CondReg == 0)
2073 return false;
2074 bool CondIsKill = hasTrivialKill(Cond);
2075
Guy Blank9ae797a2016-08-21 08:02:27 +00002076 // In case OpReg is a K register, kortest against itself.
2077 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass)
2078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2079 TII.get(X86::KORTESTWrr))
2080 .addReg(CondReg, getKillRegState(CondIsKill))
2081 .addReg(CondReg);
2082 else
2083 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2084 .addReg(CondReg, getKillRegState(CondIsKill))
2085 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002086 }
2087
2088 const Value *LHS = I->getOperand(1);
2089 const Value *RHS = I->getOperand(2);
2090
2091 unsigned RHSReg = getRegForValue(RHS);
2092 bool RHSIsKill = hasTrivialKill(RHS);
2093
2094 unsigned LHSReg = getRegForValue(LHS);
2095 bool LHSIsKill = hasTrivialKill(LHS);
2096
2097 if (!LHSReg || !RHSReg)
2098 return false;
2099
2100 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2101 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2102 LHSReg, LHSIsKill);
2103 updateValueMap(I, ResultReg);
2104 return true;
2105}
2106
Sanjay Patel302404b2015-03-05 21:46:54 +00002107/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002108///
2109/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2110/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002111/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002112bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2113 // Optimize conditions coming from a compare if both instructions are in the
2114 // same basic block (values defined in other basic blocks may not have
2115 // initialized registers).
2116 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2117 if (!CI || (CI->getParent() != I->getParent()))
2118 return false;
2119
2120 if (I->getType() != CI->getOperand(0)->getType() ||
2121 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2122 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2123 return false;
2124
2125 const Value *CmpLHS = CI->getOperand(0);
2126 const Value *CmpRHS = CI->getOperand(1);
2127 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2128
2129 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2130 // We don't have to materialize a zero constant for this case and can just use
2131 // %x again on the RHS.
2132 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2133 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2134 if (CmpRHSC && CmpRHSC->isNullValue())
2135 CmpRHS = CmpLHS;
2136 }
2137
2138 unsigned CC;
2139 bool NeedSwap;
2140 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2141 if (CC > 7)
2142 return false;
2143
2144 if (NeedSwap)
2145 std::swap(CmpLHS, CmpRHS);
2146
Sanjay Patel302404b2015-03-05 21:46:54 +00002147 // Choose the SSE instruction sequence based on data type (float or double).
Craig Topper428169a2016-09-05 07:14:21 +00002148 static const uint16_t OpcTable[2][4] = {
Sanjay Patel302404b2015-03-05 21:46:54 +00002149 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2150 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002151 };
2152
Craig Topper428169a2016-09-05 07:14:21 +00002153 const uint16_t *Opc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002154 switch (RetVT.SimpleTy) {
2155 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002156 case MVT::f32: Opc = &OpcTable[0][0]; break;
2157 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002158 }
2159
2160 const Value *LHS = I->getOperand(1);
2161 const Value *RHS = I->getOperand(2);
2162
2163 unsigned LHSReg = getRegForValue(LHS);
2164 bool LHSIsKill = hasTrivialKill(LHS);
2165
2166 unsigned RHSReg = getRegForValue(RHS);
2167 bool RHSIsKill = hasTrivialKill(RHS);
2168
2169 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2170 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2171
2172 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2173 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2174
2175 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2176 return false;
2177
2178 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002179 unsigned ResultReg;
2180
2181 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002182 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2183 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2184
Sanjay Patel302404b2015-03-05 21:46:54 +00002185 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2186 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2187 // uses XMM0 as the selection register. That may need just as many
2188 // instructions as the AND/ANDN/OR sequence due to register moves, so
2189 // don't bother.
2190 unsigned CmpOpcode =
2191 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2192 unsigned BlendOpcode =
2193 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2194
Matthias Braun818c78d2015-08-31 18:25:11 +00002195 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002196 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002197 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2198 LHSReg, LHSIsKill, CmpReg, true);
2199 ResultReg = createResultReg(RC);
2200 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2201 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002202 } else {
2203 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2204 CmpRHSReg, CmpRHSIsKill, CC);
2205 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2206 LHSReg, LHSIsKill);
2207 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2208 RHSReg, RHSIsKill);
2209 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2210 AndReg, /*IsKill=*/true);
2211 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002212 updateValueMap(I, ResultReg);
2213 return true;
2214}
2215
2216bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2217 // These are pseudo CMOV instructions and will be later expanded into control-
2218 // flow.
2219 unsigned Opc;
2220 switch (RetVT.SimpleTy) {
2221 default: return false;
2222 case MVT::i8: Opc = X86::CMOV_GR8; break;
2223 case MVT::i16: Opc = X86::CMOV_GR16; break;
2224 case MVT::i32: Opc = X86::CMOV_GR32; break;
2225 case MVT::f32: Opc = X86::CMOV_FR32; break;
2226 case MVT::f64: Opc = X86::CMOV_FR64; break;
2227 }
2228
2229 const Value *Cond = I->getOperand(0);
2230 X86::CondCode CC = X86::COND_NE;
2231
2232 // Optimize conditions coming from a compare if both instructions are in the
2233 // same basic block (values defined in other basic blocks may not have
2234 // initialized registers).
2235 const auto *CI = dyn_cast<CmpInst>(Cond);
2236 if (CI && (CI->getParent() == I->getParent())) {
2237 bool NeedSwap;
2238 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2239 if (CC > X86::LAST_VALID_COND)
2240 return false;
2241
2242 const Value *CmpLHS = CI->getOperand(0);
2243 const Value *CmpRHS = CI->getOperand(1);
2244
2245 if (NeedSwap)
2246 std::swap(CmpLHS, CmpRHS);
2247
Mehdi Amini44ede332015-07-09 02:09:04 +00002248 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002249 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2250 return false;
2251 } else {
2252 unsigned CondReg = getRegForValue(Cond);
2253 if (CondReg == 0)
2254 return false;
2255 bool CondIsKill = hasTrivialKill(Cond);
Guy Blank9ae797a2016-08-21 08:02:27 +00002256
2257 // In case OpReg is a K register, kortest against itself.
2258 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass)
2259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2260 TII.get(X86::KORTESTWrr))
2261 .addReg(CondReg, getKillRegState(CondIsKill))
2262 .addReg(CondReg);
2263 else
2264 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2265 .addReg(CondReg, getKillRegState(CondIsKill))
2266 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002267 }
2268
2269 const Value *LHS = I->getOperand(1);
2270 const Value *RHS = I->getOperand(2);
2271
2272 unsigned LHSReg = getRegForValue(LHS);
2273 bool LHSIsKill = hasTrivialKill(LHS);
2274
2275 unsigned RHSReg = getRegForValue(RHS);
2276 bool RHSIsKill = hasTrivialKill(RHS);
2277
2278 if (!LHSReg || !RHSReg)
2279 return false;
2280
2281 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2282
2283 unsigned ResultReg =
2284 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2285 updateValueMap(I, ResultReg);
2286 return true;
2287}
2288
2289bool X86FastISel::X86SelectSelect(const Instruction *I) {
2290 MVT RetVT;
2291 if (!isTypeLegal(I->getType(), RetVT))
2292 return false;
2293
2294 // Check if we can fold the select.
2295 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2296 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2297 const Value *Opnd = nullptr;
2298 switch (Predicate) {
2299 default: break;
2300 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2301 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2302 }
2303 // No need for a select anymore - this is an unconditional move.
2304 if (Opnd) {
2305 unsigned OpReg = getRegForValue(Opnd);
2306 if (OpReg == 0)
2307 return false;
2308 bool OpIsKill = hasTrivialKill(Opnd);
2309 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2310 unsigned ResultReg = createResultReg(RC);
2311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2312 TII.get(TargetOpcode::COPY), ResultReg)
2313 .addReg(OpReg, getKillRegState(OpIsKill));
2314 updateValueMap(I, ResultReg);
2315 return true;
2316 }
2317 }
2318
2319 // First try to use real conditional move instructions.
2320 if (X86FastEmitCMoveSelect(RetVT, I))
2321 return true;
2322
2323 // Try to use a sequence of SSE instructions to simulate a conditional move.
2324 if (X86FastEmitSSESelect(RetVT, I))
2325 return true;
2326
2327 // Fall-back to pseudo conditional move instructions, which will be later
2328 // converted to control-flow.
2329 if (X86FastEmitPseudoSelect(RetVT, I))
2330 return true;
2331
2332 return false;
2333}
2334
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002335bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002336 // The target-independent selection algorithm in FastISel already knows how
2337 // to select a SINT_TO_FP if the target is SSE but not AVX.
2338 // Early exit if the subtarget doesn't have AVX.
2339 if (!Subtarget->hasAVX())
2340 return false;
2341
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002342 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2343 return false;
2344
2345 // Select integer to float/double conversion.
2346 unsigned OpReg = getRegForValue(I->getOperand(0));
2347 if (OpReg == 0)
2348 return false;
2349
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002350 const TargetRegisterClass *RC = nullptr;
2351 unsigned Opcode;
2352
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002353 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002354 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002355 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002356 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002357 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002358 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002359 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002360 RC = &X86::FR32RegClass;
2361 } else
2362 return false;
2363
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002364 unsigned ImplicitDefReg = createResultReg(RC);
2365 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2366 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2367 unsigned ResultReg =
2368 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002369 updateValueMap(I, ResultReg);
2370 return true;
2371}
2372
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002373// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2374bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2375 unsigned TargetOpc,
2376 const TargetRegisterClass *RC) {
2377 assert((I->getOpcode() == Instruction::FPExt ||
2378 I->getOpcode() == Instruction::FPTrunc) &&
2379 "Instruction must be an FPExt or FPTrunc!");
2380
2381 unsigned OpReg = getRegForValue(I->getOperand(0));
2382 if (OpReg == 0)
2383 return false;
2384
2385 unsigned ResultReg = createResultReg(RC);
2386 MachineInstrBuilder MIB;
2387 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2388 ResultReg);
2389 if (Subtarget->hasAVX())
2390 MIB.addReg(OpReg);
2391 MIB.addReg(OpReg);
2392 updateValueMap(I, ResultReg);
2393 return true;
2394}
2395
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002396bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002397 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2398 I->getOperand(0)->getType()->isFloatTy()) {
2399 // fpext from float to double.
2400 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2401 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002402 }
2403
2404 return false;
2405}
2406
2407bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002408 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2409 I->getOperand(0)->getType()->isDoubleTy()) {
2410 // fptrunc from double to float.
2411 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2412 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002413 }
2414
2415 return false;
2416}
2417
2418bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002419 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2420 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002421
2422 // This code only handles truncation to byte.
2423 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2424 return false;
2425 if (!TLI.isTypeLegal(SrcVT))
2426 return false;
2427
2428 unsigned InputReg = getRegForValue(I->getOperand(0));
2429 if (!InputReg)
2430 // Unhandled operand. Halt "fast" selection and bail.
2431 return false;
2432
2433 if (SrcVT == MVT::i8) {
2434 // Truncate from i8 to i1; no code needed.
2435 updateValueMap(I, InputReg);
2436 return true;
2437 }
2438
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002439 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002440 if (!Subtarget->is64Bit()) {
2441 // If we're on x86-32; we can't extract an i8 from a general register.
2442 // First issue a copy to GR16_ABCD or GR32_ABCD.
2443 const TargetRegisterClass *CopyRC =
2444 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2445 unsigned CopyReg = createResultReg(CopyRC);
2446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2447 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2448 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002449 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002450 }
2451
2452 // Issue an extract_subreg.
2453 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002454 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002455 X86::sub_8bit);
2456 if (!ResultReg)
2457 return false;
2458
2459 updateValueMap(I, ResultReg);
2460 return true;
2461}
2462
2463bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2464 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2465}
2466
2467bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2468 X86AddressMode SrcAM, uint64_t Len) {
2469
2470 // Make sure we don't bloat code by inlining very large memcpy's.
2471 if (!IsMemcpySmall(Len))
2472 return false;
2473
2474 bool i64Legal = Subtarget->is64Bit();
2475
2476 // We don't care about alignment here since we just emit integer accesses.
2477 while (Len) {
2478 MVT VT;
2479 if (Len >= 8 && i64Legal)
2480 VT = MVT::i64;
2481 else if (Len >= 4)
2482 VT = MVT::i32;
2483 else if (Len >= 2)
2484 VT = MVT::i16;
2485 else
2486 VT = MVT::i8;
2487
2488 unsigned Reg;
2489 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2490 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2491 assert(RV && "Failed to emit load or store??");
2492
2493 unsigned Size = VT.getSizeInBits()/8;
2494 Len -= Size;
2495 DestAM.Disp += Size;
2496 SrcAM.Disp += Size;
2497 }
2498
2499 return true;
2500}
2501
2502bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2503 // FIXME: Handle more intrinsics.
2504 switch (II->getIntrinsicID()) {
2505 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002506 case Intrinsic::convert_from_fp16:
2507 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002508 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002509 return false;
2510
2511 const Value *Op = II->getArgOperand(0);
2512 unsigned InputReg = getRegForValue(Op);
2513 if (InputReg == 0)
2514 return false;
2515
2516 // F16C only allows converting from float to half and from half to float.
2517 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2518 if (IsFloatToHalf) {
2519 if (!Op->getType()->isFloatTy())
2520 return false;
2521 } else {
2522 if (!II->getType()->isFloatTy())
2523 return false;
2524 }
2525
2526 unsigned ResultReg = 0;
2527 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2528 if (IsFloatToHalf) {
2529 // 'InputReg' is implicitly promoted from register class FR32 to
2530 // register class VR128 by method 'constrainOperandRegClass' which is
2531 // directly called by 'fastEmitInst_ri'.
2532 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002533 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2534 // It's consistent with the other FP instructions, which are usually
2535 // controlled by MXCSR.
2536 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002537
2538 // Move the lower 32-bits of ResultReg to another register of class GR32.
2539 ResultReg = createResultReg(&X86::GR32RegClass);
2540 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2541 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2542 .addReg(InputReg, RegState::Kill);
2543
2544 // The result value is in the lower 16-bits of ResultReg.
2545 unsigned RegIdx = X86::sub_16bit;
2546 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2547 } else {
2548 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2549 // Explicitly sign-extend the input to 32-bit.
2550 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2551 /*Kill=*/false);
2552
2553 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2554 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2555 InputReg, /*Kill=*/true);
2556
2557 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2558
2559 // The result value is in the lower 32-bits of ResultReg.
2560 // Emit an explicit copy from register class VR128 to register class FR32.
2561 ResultReg = createResultReg(&X86::FR32RegClass);
2562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2563 TII.get(TargetOpcode::COPY), ResultReg)
2564 .addReg(InputReg, RegState::Kill);
2565 }
2566
2567 updateValueMap(II, ResultReg);
2568 return true;
2569 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002570 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002571 MachineFunction *MF = FuncInfo.MF;
2572 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2573 return false;
2574
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002575 Type *RetTy = II->getCalledFunction()->getReturnType();
2576
2577 MVT VT;
2578 if (!isTypeLegal(RetTy, VT))
2579 return false;
2580
2581 unsigned Opc;
2582 const TargetRegisterClass *RC = nullptr;
2583
2584 switch (VT.SimpleTy) {
2585 default: llvm_unreachable("Invalid result type for frameaddress.");
2586 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2587 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2588 }
2589
2590 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2591 // we get the wrong frame register.
Matthias Braun941a7052016-07-28 18:40:00 +00002592 MachineFrameInfo &MFI = MF->getFrameInfo();
2593 MFI.setFrameAddressIsTaken(true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002594
Eric Christophera1c535b2015-02-02 23:03:45 +00002595 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002596 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002597 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2598 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2599 "Invalid Frame Register!");
2600
2601 // Always make a copy of the frame register to to a vreg first, so that we
2602 // never directly reference the frame register (the TwoAddressInstruction-
2603 // Pass doesn't like that).
2604 unsigned SrcReg = createResultReg(RC);
2605 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2606 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2607
2608 // Now recursively load from the frame address.
2609 // movq (%rbp), %rax
2610 // movq (%rax), %rax
2611 // movq (%rax), %rax
2612 // ...
2613 unsigned DestReg;
2614 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2615 while (Depth--) {
2616 DestReg = createResultReg(RC);
2617 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2618 TII.get(Opc), DestReg), SrcReg);
2619 SrcReg = DestReg;
2620 }
2621
2622 updateValueMap(II, SrcReg);
2623 return true;
2624 }
2625 case Intrinsic::memcpy: {
2626 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2627 // Don't handle volatile or variable length memcpys.
2628 if (MCI->isVolatile())
2629 return false;
2630
2631 if (isa<ConstantInt>(MCI->getLength())) {
2632 // Small memcpy's are common enough that we want to do them
2633 // without a call if possible.
2634 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2635 if (IsMemcpySmall(Len)) {
2636 X86AddressMode DestAM, SrcAM;
2637 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2638 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2639 return false;
2640 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2641 return true;
2642 }
2643 }
2644
2645 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2646 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2647 return false;
2648
2649 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2650 return false;
2651
Pete Cooper67cf9a72015-11-19 05:56:52 +00002652 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002653 }
2654 case Intrinsic::memset: {
2655 const MemSetInst *MSI = cast<MemSetInst>(II);
2656
2657 if (MSI->isVolatile())
2658 return false;
2659
2660 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2661 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2662 return false;
2663
2664 if (MSI->getDestAddressSpace() > 255)
2665 return false;
2666
Pete Cooper67cf9a72015-11-19 05:56:52 +00002667 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002668 }
2669 case Intrinsic::stackprotector: {
2670 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002671 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002672
2673 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2674 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2675
2676 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2677
2678 // Grab the frame index.
2679 X86AddressMode AM;
2680 if (!X86SelectAddress(Slot, AM)) return false;
2681 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2682 return true;
2683 }
2684 case Intrinsic::dbg_declare: {
2685 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2686 X86AddressMode AM;
2687 assert(DI->getAddress() && "Null address should be checked earlier!");
2688 if (!X86SelectAddress(DI->getAddress(), AM))
2689 return false;
2690 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2691 // FIXME may need to add RegState::Debug to any registers produced,
2692 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002693 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2694 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002695 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2696 .addImm(0)
2697 .addMetadata(DI->getVariable())
2698 .addMetadata(DI->getExpression());
2699 return true;
2700 }
2701 case Intrinsic::trap: {
2702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2703 return true;
2704 }
2705 case Intrinsic::sqrt: {
2706 if (!Subtarget->hasSSE1())
2707 return false;
2708
2709 Type *RetTy = II->getCalledFunction()->getReturnType();
2710
2711 MVT VT;
2712 if (!isTypeLegal(RetTy, VT))
2713 return false;
2714
2715 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2716 // is not generated by FastISel yet.
2717 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002718 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002719 {X86::SQRTSSr, X86::VSQRTSSr},
2720 {X86::SQRTSDr, X86::VSQRTSDr}
2721 };
2722 bool HasAVX = Subtarget->hasAVX();
2723 unsigned Opc;
2724 const TargetRegisterClass *RC;
2725 switch (VT.SimpleTy) {
2726 default: return false;
2727 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2728 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2729 }
2730
2731 const Value *SrcVal = II->getArgOperand(0);
2732 unsigned SrcReg = getRegForValue(SrcVal);
2733
2734 if (SrcReg == 0)
2735 return false;
2736
2737 unsigned ImplicitDefReg = 0;
2738 if (HasAVX) {
2739 ImplicitDefReg = createResultReg(RC);
2740 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2741 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2742 }
2743
2744 unsigned ResultReg = createResultReg(RC);
2745 MachineInstrBuilder MIB;
2746 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2747 ResultReg);
2748
2749 if (ImplicitDefReg)
2750 MIB.addReg(ImplicitDefReg);
2751
2752 MIB.addReg(SrcReg);
2753
2754 updateValueMap(II, ResultReg);
2755 return true;
2756 }
2757 case Intrinsic::sadd_with_overflow:
2758 case Intrinsic::uadd_with_overflow:
2759 case Intrinsic::ssub_with_overflow:
2760 case Intrinsic::usub_with_overflow:
2761 case Intrinsic::smul_with_overflow:
2762 case Intrinsic::umul_with_overflow: {
2763 // This implements the basic lowering of the xalu with overflow intrinsics
2764 // into add/sub/mul followed by either seto or setb.
2765 const Function *Callee = II->getCalledFunction();
2766 auto *Ty = cast<StructType>(Callee->getReturnType());
2767 Type *RetTy = Ty->getTypeAtIndex(0U);
2768 Type *CondTy = Ty->getTypeAtIndex(1);
2769
2770 MVT VT;
2771 if (!isTypeLegal(RetTy, VT))
2772 return false;
2773
2774 if (VT < MVT::i8 || VT > MVT::i64)
2775 return false;
2776
2777 const Value *LHS = II->getArgOperand(0);
2778 const Value *RHS = II->getArgOperand(1);
2779
2780 // Canonicalize immediate to the RHS.
2781 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2782 isCommutativeIntrinsic(II))
2783 std::swap(LHS, RHS);
2784
2785 bool UseIncDec = false;
2786 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2787 UseIncDec = true;
2788
2789 unsigned BaseOpc, CondOpc;
2790 switch (II->getIntrinsicID()) {
2791 default: llvm_unreachable("Unexpected intrinsic!");
2792 case Intrinsic::sadd_with_overflow:
2793 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2794 CondOpc = X86::SETOr;
2795 break;
2796 case Intrinsic::uadd_with_overflow:
2797 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2798 case Intrinsic::ssub_with_overflow:
2799 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2800 CondOpc = X86::SETOr;
2801 break;
2802 case Intrinsic::usub_with_overflow:
2803 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2804 case Intrinsic::smul_with_overflow:
2805 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2806 case Intrinsic::umul_with_overflow:
2807 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2808 }
2809
2810 unsigned LHSReg = getRegForValue(LHS);
2811 if (LHSReg == 0)
2812 return false;
2813 bool LHSIsKill = hasTrivialKill(LHS);
2814
2815 unsigned ResultReg = 0;
2816 // Check if we have an immediate version.
2817 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002818 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002819 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2820 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2821 };
2822
2823 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2824 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2825 bool IsDec = BaseOpc == X86ISD::DEC;
2826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2827 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2828 .addReg(LHSReg, getKillRegState(LHSIsKill));
2829 } else
2830 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2831 CI->getZExtValue());
2832 }
2833
2834 unsigned RHSReg;
2835 bool RHSIsKill;
2836 if (!ResultReg) {
2837 RHSReg = getRegForValue(RHS);
2838 if (RHSReg == 0)
2839 return false;
2840 RHSIsKill = hasTrivialKill(RHS);
2841 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2842 RHSIsKill);
2843 }
2844
2845 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2846 // it manually.
2847 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002848 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002849 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002850 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002851 // First copy the first operand into RAX, which is an implicit input to
2852 // the X86::MUL*r instruction.
2853 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2854 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2855 .addReg(LHSReg, getKillRegState(LHSIsKill));
2856 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2857 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2858 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002859 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002860 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2861 if (VT == MVT::i8) {
2862 // Copy the first operand into AL, which is an implicit input to the
2863 // X86::IMUL8r instruction.
2864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2865 TII.get(TargetOpcode::COPY), X86::AL)
2866 .addReg(LHSReg, getKillRegState(LHSIsKill));
2867 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2868 RHSIsKill);
2869 } else
2870 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2871 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2872 RHSReg, RHSIsKill);
2873 }
2874
2875 if (!ResultReg)
2876 return false;
2877
2878 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2879 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2881 ResultReg2);
2882
2883 updateValueMap(II, ResultReg, 2);
2884 return true;
2885 }
2886 case Intrinsic::x86_sse_cvttss2si:
2887 case Intrinsic::x86_sse_cvttss2si64:
2888 case Intrinsic::x86_sse2_cvttsd2si:
2889 case Intrinsic::x86_sse2_cvttsd2si64: {
2890 bool IsInputDouble;
2891 switch (II->getIntrinsicID()) {
2892 default: llvm_unreachable("Unexpected intrinsic.");
2893 case Intrinsic::x86_sse_cvttss2si:
2894 case Intrinsic::x86_sse_cvttss2si64:
2895 if (!Subtarget->hasSSE1())
2896 return false;
2897 IsInputDouble = false;
2898 break;
2899 case Intrinsic::x86_sse2_cvttsd2si:
2900 case Intrinsic::x86_sse2_cvttsd2si64:
2901 if (!Subtarget->hasSSE2())
2902 return false;
2903 IsInputDouble = true;
2904 break;
2905 }
2906
2907 Type *RetTy = II->getCalledFunction()->getReturnType();
2908 MVT VT;
2909 if (!isTypeLegal(RetTy, VT))
2910 return false;
2911
Craig Topper66111882016-06-02 04:19:42 +00002912 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002913 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2914 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2915 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2916 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2917 };
2918 bool HasAVX = Subtarget->hasAVX();
2919 unsigned Opc;
2920 switch (VT.SimpleTy) {
2921 default: llvm_unreachable("Unexpected result type.");
2922 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2923 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2924 }
2925
2926 // Check if we can fold insertelement instructions into the convert.
2927 const Value *Op = II->getArgOperand(0);
2928 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2929 const Value *Index = IE->getOperand(2);
2930 if (!isa<ConstantInt>(Index))
2931 break;
2932 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2933
2934 if (Idx == 0) {
2935 Op = IE->getOperand(1);
2936 break;
2937 }
2938 Op = IE->getOperand(0);
2939 }
2940
2941 unsigned Reg = getRegForValue(Op);
2942 if (Reg == 0)
2943 return false;
2944
2945 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2947 .addReg(Reg);
2948
2949 updateValueMap(II, ResultReg);
2950 return true;
2951 }
2952 }
2953}
2954
2955bool X86FastISel::fastLowerArguments() {
2956 if (!FuncInfo.CanLowerReturn)
2957 return false;
2958
2959 const Function *F = FuncInfo.Fn;
2960 if (F->isVarArg())
2961 return false;
2962
2963 CallingConv::ID CC = F->getCallingConv();
2964 if (CC != CallingConv::C)
2965 return false;
2966
2967 if (Subtarget->isCallingConvWin64(CC))
2968 return false;
2969
2970 if (!Subtarget->is64Bit())
2971 return false;
2972
2973 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2974 unsigned GPRCnt = 0;
2975 unsigned FPRCnt = 0;
2976 unsigned Idx = 0;
2977 for (auto const &Arg : F->args()) {
2978 // The first argument is at index 1.
2979 ++Idx;
2980 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2981 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2982 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002983 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002984 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002985 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2986 return false;
2987
2988 Type *ArgTy = Arg.getType();
2989 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2990 return false;
2991
Mehdi Amini44ede332015-07-09 02:09:04 +00002992 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002993 if (!ArgVT.isSimple()) return false;
2994 switch (ArgVT.getSimpleVT().SimpleTy) {
2995 default: return false;
2996 case MVT::i32:
2997 case MVT::i64:
2998 ++GPRCnt;
2999 break;
3000 case MVT::f32:
3001 case MVT::f64:
3002 if (!Subtarget->hasSSE1())
3003 return false;
3004 ++FPRCnt;
3005 break;
3006 }
3007
3008 if (GPRCnt > 6)
3009 return false;
3010
3011 if (FPRCnt > 8)
3012 return false;
3013 }
3014
3015 static const MCPhysReg GPR32ArgRegs[] = {
3016 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3017 };
3018 static const MCPhysReg GPR64ArgRegs[] = {
3019 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3020 };
3021 static const MCPhysReg XMMArgRegs[] = {
3022 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3023 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3024 };
3025
3026 unsigned GPRIdx = 0;
3027 unsigned FPRIdx = 0;
3028 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003029 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003030 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3031 unsigned SrcReg;
3032 switch (VT.SimpleTy) {
3033 default: llvm_unreachable("Unexpected value type.");
3034 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3035 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003036 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003037 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3038 }
3039 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3040 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3041 // Without this, EmitLiveInCopies may eliminate the livein if its only
3042 // use is a bitcast (which isn't turned into an instruction).
3043 unsigned ResultReg = createResultReg(RC);
3044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3045 TII.get(TargetOpcode::COPY), ResultReg)
3046 .addReg(DstReg, getKillRegState(true));
3047 updateValueMap(&Arg, ResultReg);
3048 }
3049 return true;
3050}
3051
Nico Weberaf7e8462016-07-14 01:52:51 +00003052static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3053 CallingConv::ID CC,
3054 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003055 if (Subtarget->is64Bit())
3056 return 0;
3057 if (Subtarget->getTargetTriple().isOSMSVCRT())
3058 return 0;
3059 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3060 CC == CallingConv::HiPE)
3061 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003062
3063 if (CS)
3064 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00003065 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003066 return 0;
3067
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003068 return 4;
3069}
3070
3071bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3072 auto &OutVals = CLI.OutVals;
3073 auto &OutFlags = CLI.OutFlags;
3074 auto &OutRegs = CLI.OutRegs;
3075 auto &Ins = CLI.Ins;
3076 auto &InRegs = CLI.InRegs;
3077 CallingConv::ID CC = CLI.CallConv;
3078 bool &IsTailCall = CLI.IsTailCall;
3079 bool IsVarArg = CLI.IsVarArg;
3080 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003081 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003082
3083 bool Is64Bit = Subtarget->is64Bit();
3084 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3085
3086 // Handle only C, fastcc, and webkit_js calling conventions for now.
3087 switch (CC) {
3088 default: return false;
3089 case CallingConv::C:
3090 case CallingConv::Fast:
3091 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003092 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003093 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003094 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003095 case CallingConv::X86_ThisCall:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003096 case CallingConv::X86_64_Win64:
3097 case CallingConv::X86_64_SysV:
3098 break;
3099 }
3100
3101 // Allow SelectionDAG isel to handle tail calls.
3102 if (IsTailCall)
3103 return false;
3104
3105 // fastcc with -tailcallopt is intended to provide a guaranteed
3106 // tail call optimization. Fastisel doesn't know how to do that.
3107 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3108 return false;
3109
3110 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3111 // x86-32. Special handling for x86-64 is implemented.
3112 if (IsVarArg && IsWin64)
3113 return false;
3114
3115 // Don't know about inalloca yet.
3116 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3117 return false;
3118
Manman Ren57518142016-04-11 21:08:06 +00003119 for (auto Flag : CLI.OutFlags)
3120 if (Flag.isSwiftError())
3121 return false;
3122
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003123 SmallVector<MVT, 16> OutVTs;
3124 SmallVector<unsigned, 16> ArgRegs;
3125
3126 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3127 // instruction. This is safe because it is common to all FastISel supported
3128 // calling conventions on x86.
3129 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3130 Value *&Val = OutVals[i];
3131 ISD::ArgFlagsTy Flags = OutFlags[i];
3132 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3133 if (CI->getBitWidth() < 32) {
3134 if (Flags.isSExt())
3135 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3136 else
3137 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3138 }
3139 }
3140
3141 // Passing bools around ends up doing a trunc to i1 and passing it.
3142 // Codegen this as an argument + "and 1".
3143 MVT VT;
3144 auto *TI = dyn_cast<TruncInst>(Val);
3145 unsigned ResultReg;
3146 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3147 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3148 TI->hasOneUse()) {
3149 Value *PrevVal = TI->getOperand(0);
3150 ResultReg = getRegForValue(PrevVal);
3151
3152 if (!ResultReg)
3153 return false;
3154
3155 if (!isTypeLegal(PrevVal->getType(), VT))
3156 return false;
3157
3158 ResultReg =
3159 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3160 } else {
3161 if (!isTypeLegal(Val->getType(), VT))
3162 return false;
3163 ResultReg = getRegForValue(Val);
3164 }
3165
3166 if (!ResultReg)
3167 return false;
3168
3169 ArgRegs.push_back(ResultReg);
3170 OutVTs.push_back(VT);
3171 }
3172
3173 // Analyze operands of the call, assigning locations to each operand.
3174 SmallVector<CCValAssign, 16> ArgLocs;
3175 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3176
3177 // Allocate shadow area for Win64
3178 if (IsWin64)
3179 CCInfo.AllocateStack(32, 8);
3180
3181 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3182
3183 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003184 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003185
3186 // Issue CALLSEQ_START
3187 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003189 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003190
3191 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003192 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003193 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3194 CCValAssign const &VA = ArgLocs[i];
3195 const Value *ArgVal = OutVals[VA.getValNo()];
3196 MVT ArgVT = OutVTs[VA.getValNo()];
3197
3198 if (ArgVT == MVT::x86mmx)
3199 return false;
3200
3201 unsigned ArgReg = ArgRegs[VA.getValNo()];
3202
3203 // Promote the value if needed.
3204 switch (VA.getLocInfo()) {
3205 case CCValAssign::Full: break;
3206 case CCValAssign::SExt: {
3207 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3208 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003209
3210 if (ArgVT.SimpleTy == MVT::i1)
3211 return false;
3212
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003213 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3214 ArgVT, ArgReg);
3215 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3216 ArgVT = VA.getLocVT();
3217 break;
3218 }
3219 case CCValAssign::ZExt: {
3220 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3221 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003222
3223 // Handle zero-extension from i1 to i8, which is common.
3224 if (ArgVT.SimpleTy == MVT::i1) {
3225 // Set the high bits to zero.
3226 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3227 ArgVT = MVT::i8;
3228
3229 if (ArgReg == 0)
3230 return false;
3231 }
3232
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003233 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3234 ArgVT, ArgReg);
3235 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3236 ArgVT = VA.getLocVT();
3237 break;
3238 }
3239 case CCValAssign::AExt: {
3240 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3241 "Unexpected extend");
3242 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3243 ArgVT, ArgReg);
3244 if (!Emitted)
3245 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3246 ArgVT, ArgReg);
3247 if (!Emitted)
3248 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3249 ArgVT, ArgReg);
3250
3251 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3252 ArgVT = VA.getLocVT();
3253 break;
3254 }
3255 case CCValAssign::BCvt: {
3256 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3257 /*TODO: Kill=*/false);
3258 assert(ArgReg && "Failed to emit a bitcast!");
3259 ArgVT = VA.getLocVT();
3260 break;
3261 }
3262 case CCValAssign::VExt:
3263 // VExt has not been implemented, so this should be impossible to reach
3264 // for now. However, fallback to Selection DAG isel once implemented.
3265 return false;
3266 case CCValAssign::AExtUpper:
3267 case CCValAssign::SExtUpper:
3268 case CCValAssign::ZExtUpper:
3269 case CCValAssign::FPExt:
3270 llvm_unreachable("Unexpected loc info!");
3271 case CCValAssign::Indirect:
3272 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3273 // support this.
3274 return false;
3275 }
3276
3277 if (VA.isRegLoc()) {
3278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3279 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3280 OutRegs.push_back(VA.getLocReg());
3281 } else {
3282 assert(VA.isMemLoc());
3283
3284 // Don't emit stores for undef values.
3285 if (isa<UndefValue>(ArgVal))
3286 continue;
3287
3288 unsigned LocMemOffset = VA.getLocMemOffset();
3289 X86AddressMode AM;
3290 AM.Base.Reg = RegInfo->getStackRegister();
3291 AM.Disp = LocMemOffset;
3292 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3293 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3294 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003295 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3296 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003297 if (Flags.isByVal()) {
3298 X86AddressMode SrcAM;
3299 SrcAM.Base.Reg = ArgReg;
3300 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3301 return false;
3302 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3303 // If this is a really simple value, emit this with the Value* version
3304 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3305 // as it can cause us to reevaluate the argument.
3306 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3307 return false;
3308 } else {
3309 bool ValIsKill = hasTrivialKill(ArgVal);
3310 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3311 return false;
3312 }
3313 }
3314 }
3315
3316 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3317 // GOT pointer.
3318 if (Subtarget->isPICStyleGOT()) {
3319 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3321 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3322 }
3323
3324 if (Is64Bit && IsVarArg && !IsWin64) {
3325 // From AMD64 ABI document:
3326 // For calls that may call functions that use varargs or stdargs
3327 // (prototype-less calls or calls to functions containing ellipsis (...) in
3328 // the declaration) %al is used as hidden argument to specify the number
3329 // of SSE registers used. The contents of %al do not need to match exactly
3330 // the number of registers, but must be an ubound on the number of SSE
3331 // registers used and is in the range 0 - 8 inclusive.
3332
3333 // Count the number of XMM registers allocated.
3334 static const MCPhysReg XMMArgRegs[] = {
3335 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3336 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3337 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003338 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003339 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3340 && "SSE registers cannot be used when SSE is disabled");
3341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3342 X86::AL).addImm(NumXMMRegs);
3343 }
3344
3345 // Materialize callee address in a register. FIXME: GV address can be
3346 // handled with a CALLpcrel32 instead.
3347 X86AddressMode CalleeAM;
3348 if (!X86SelectCallAddress(Callee, CalleeAM))
3349 return false;
3350
3351 unsigned CalleeOp = 0;
3352 const GlobalValue *GV = nullptr;
3353 if (CalleeAM.GV != nullptr) {
3354 GV = CalleeAM.GV;
3355 } else if (CalleeAM.Base.Reg != 0) {
3356 CalleeOp = CalleeAM.Base.Reg;
3357 } else
3358 return false;
3359
3360 // Issue the call.
3361 MachineInstrBuilder MIB;
3362 if (CalleeOp) {
3363 // Register-indirect call.
3364 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3365 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3366 .addReg(CalleeOp);
3367 } else {
3368 // Direct call.
3369 assert(GV && "Not a direct call");
3370 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3371
3372 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003373 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003374 // Ignore NonLazyBind attribute in FastISel
3375 if (OpFlags == X86II::MO_GOTPCREL)
3376 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003377
3378 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003379 if (Symbol)
3380 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003381 else
3382 MIB.addGlobalAddress(GV, 0, OpFlags);
3383 }
3384
3385 // Add a register mask operand representing the call-preserved registers.
3386 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003387 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003388
3389 // Add an implicit use GOT pointer in EBX.
3390 if (Subtarget->isPICStyleGOT())
3391 MIB.addReg(X86::EBX, RegState::Implicit);
3392
3393 if (Is64Bit && IsVarArg && !IsWin64)
3394 MIB.addReg(X86::AL, RegState::Implicit);
3395
3396 // Add implicit physical register uses to the call.
3397 for (auto Reg : OutRegs)
3398 MIB.addReg(Reg, RegState::Implicit);
3399
3400 // Issue CALLSEQ_END
3401 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003402 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3403 TM.Options.GuaranteedTailCallOpt)
3404 ? NumBytes // Callee pops everything.
3405 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003406 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3408 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3409
3410 // Now handle call return values.
3411 SmallVector<CCValAssign, 16> RVLocs;
3412 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3413 CLI.RetTy->getContext());
3414 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3415
3416 // Copy all of the result registers out of their specified physreg.
3417 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3418 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3419 CCValAssign &VA = RVLocs[i];
3420 EVT CopyVT = VA.getValVT();
3421 unsigned CopyReg = ResultReg + i;
3422
3423 // If this is x86-64, and we disabled SSE, we can't return FP values
3424 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3425 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3426 report_fatal_error("SSE register return with SSE disabled");
3427 }
3428
3429 // If we prefer to use the value in xmm registers, copy it out as f80 and
3430 // use a truncate to move it from fp stack reg to xmm reg.
3431 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3432 isScalarFPTypeInSSEReg(VA.getValVT())) {
3433 CopyVT = MVT::f80;
3434 CopyReg = createResultReg(&X86::RFP80RegClass);
3435 }
3436
3437 // Copy out the result.
3438 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3439 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3440 InRegs.push_back(VA.getLocReg());
3441
3442 // Round the f80 to the right size, which also moves it to the appropriate
3443 // xmm register. This is accomplished by storing the f80 value in memory
3444 // and then loading it back.
3445 if (CopyVT != VA.getValVT()) {
3446 EVT ResVT = VA.getValVT();
3447 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3448 unsigned MemSize = ResVT.getSizeInBits()/8;
3449 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3450 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3451 TII.get(Opc)), FI)
3452 .addReg(CopyReg);
3453 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3454 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3455 TII.get(Opc), ResultReg + i), FI);
3456 }
3457 }
3458
3459 CLI.ResultReg = ResultReg;
3460 CLI.NumResultRegs = RVLocs.size();
3461 CLI.Call = MIB;
3462
3463 return true;
3464}
3465
3466bool
3467X86FastISel::fastSelectInstruction(const Instruction *I) {
3468 switch (I->getOpcode()) {
3469 default: break;
3470 case Instruction::Load:
3471 return X86SelectLoad(I);
3472 case Instruction::Store:
3473 return X86SelectStore(I);
3474 case Instruction::Ret:
3475 return X86SelectRet(I);
3476 case Instruction::ICmp:
3477 case Instruction::FCmp:
3478 return X86SelectCmp(I);
3479 case Instruction::ZExt:
3480 return X86SelectZExt(I);
3481 case Instruction::Br:
3482 return X86SelectBranch(I);
3483 case Instruction::LShr:
3484 case Instruction::AShr:
3485 case Instruction::Shl:
3486 return X86SelectShift(I);
3487 case Instruction::SDiv:
3488 case Instruction::UDiv:
3489 case Instruction::SRem:
3490 case Instruction::URem:
3491 return X86SelectDivRem(I);
3492 case Instruction::Select:
3493 return X86SelectSelect(I);
3494 case Instruction::Trunc:
3495 return X86SelectTrunc(I);
3496 case Instruction::FPExt:
3497 return X86SelectFPExt(I);
3498 case Instruction::FPTrunc:
3499 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003500 case Instruction::SIToFP:
3501 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003502 case Instruction::IntToPtr: // Deliberate fall-through.
3503 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003504 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3505 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003506 if (DstVT.bitsGT(SrcVT))
3507 return X86SelectZExt(I);
3508 if (DstVT.bitsLT(SrcVT))
3509 return X86SelectTrunc(I);
3510 unsigned Reg = getRegForValue(I->getOperand(0));
3511 if (Reg == 0) return false;
3512 updateValueMap(I, Reg);
3513 return true;
3514 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003515 case Instruction::BitCast: {
3516 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3517 if (!Subtarget->hasSSE2())
3518 return false;
3519
3520 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3521 EVT DstVT = TLI.getValueType(DL, I->getType());
3522
3523 if (!SrcVT.isSimple() || !DstVT.isSimple())
3524 return false;
3525
3526 if (!SrcVT.is128BitVector() &&
3527 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3528 return false;
3529
3530 unsigned Reg = getRegForValue(I->getOperand(0));
3531 if (Reg == 0)
3532 return false;
3533
3534 // No instruction is needed for conversion. Reuse the register used by
3535 // the fist operand.
3536 updateValueMap(I, Reg);
3537 return true;
3538 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003539 }
3540
3541 return false;
3542}
3543
3544unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3545 if (VT > MVT::i64)
3546 return 0;
3547
3548 uint64_t Imm = CI->getZExtValue();
3549 if (Imm == 0) {
3550 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3551 switch (VT.SimpleTy) {
3552 default: llvm_unreachable("Unexpected value type");
3553 case MVT::i1:
3554 case MVT::i8:
3555 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3556 X86::sub_8bit);
3557 case MVT::i16:
3558 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3559 X86::sub_16bit);
3560 case MVT::i32:
3561 return SrcReg;
3562 case MVT::i64: {
3563 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3564 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3565 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3566 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3567 return ResultReg;
3568 }
3569 }
3570 }
3571
3572 unsigned Opc = 0;
3573 switch (VT.SimpleTy) {
3574 default: llvm_unreachable("Unexpected value type");
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003575 case MVT::i1: VT = MVT::i8; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003576 case MVT::i8: Opc = X86::MOV8ri; break;
3577 case MVT::i16: Opc = X86::MOV16ri; break;
3578 case MVT::i32: Opc = X86::MOV32ri; break;
3579 case MVT::i64: {
3580 if (isUInt<32>(Imm))
3581 Opc = X86::MOV32ri;
3582 else if (isInt<32>(Imm))
3583 Opc = X86::MOV64ri32;
3584 else
3585 Opc = X86::MOV64ri;
3586 break;
3587 }
3588 }
3589 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3590 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3591 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3593 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3594 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3595 return ResultReg;
3596 }
3597 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3598}
3599
3600unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3601 if (CFP->isNullValue())
3602 return fastMaterializeFloatZero(CFP);
3603
3604 // Can't handle alternate code models yet.
3605 CodeModel::Model CM = TM.getCodeModel();
3606 if (CM != CodeModel::Small && CM != CodeModel::Large)
3607 return 0;
3608
3609 // Get opcode and regclass of the output for the given load instruction.
3610 unsigned Opc = 0;
3611 const TargetRegisterClass *RC = nullptr;
3612 switch (VT.SimpleTy) {
3613 default: return 0;
3614 case MVT::f32:
3615 if (X86ScalarSSEf32) {
3616 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3617 RC = &X86::FR32RegClass;
3618 } else {
3619 Opc = X86::LD_Fp32m;
3620 RC = &X86::RFP32RegClass;
3621 }
3622 break;
3623 case MVT::f64:
3624 if (X86ScalarSSEf64) {
3625 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3626 RC = &X86::FR64RegClass;
3627 } else {
3628 Opc = X86::LD_Fp64m;
3629 RC = &X86::RFP64RegClass;
3630 }
3631 break;
3632 case MVT::f80:
3633 // No f80 support yet.
3634 return 0;
3635 }
3636
3637 // MachineConstantPool wants an explicit alignment.
3638 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3639 if (Align == 0) {
3640 // Alignment of vector types. FIXME!
3641 Align = DL.getTypeAllocSize(CFP->getType());
3642 }
3643
3644 // x86-32 PIC requires a PIC base register for constant pools.
3645 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003646 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3647 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003648 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003649 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003650 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003651 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003652 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003653
3654 // Create the load from the constant pool.
3655 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3656 unsigned ResultReg = createResultReg(RC);
3657
3658 if (CM == CodeModel::Large) {
3659 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3660 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3661 AddrReg)
3662 .addConstantPoolIndex(CPI, 0, OpFlag);
3663 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3664 TII.get(Opc), ResultReg);
3665 addDirectMem(MIB, AddrReg);
3666 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003667 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3668 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003669 MIB->addMemOperand(*FuncInfo.MF, MMO);
3670 return ResultReg;
3671 }
3672
3673 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3674 TII.get(Opc), ResultReg),
3675 CPI, PICBase, OpFlag);
3676 return ResultReg;
3677}
3678
3679unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3680 // Can't handle alternate code models yet.
3681 if (TM.getCodeModel() != CodeModel::Small)
3682 return 0;
3683
3684 // Materialize addresses with LEA/MOV instructions.
3685 X86AddressMode AM;
3686 if (X86SelectAddress(GV, AM)) {
3687 // If the expression is just a basereg, then we're done, otherwise we need
3688 // to emit an LEA.
3689 if (AM.BaseType == X86AddressMode::RegBase &&
3690 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3691 return AM.Base.Reg;
3692
3693 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3694 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003695 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003696 // The displacement code could be more than 32 bits away so we need to use
3697 // an instruction with a 64 bit immediate
3698 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3699 ResultReg)
3700 .addGlobalAddress(GV);
3701 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003702 unsigned Opc =
3703 TLI.getPointerTy(DL) == MVT::i32
3704 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3705 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003706 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3707 TII.get(Opc), ResultReg), AM);
3708 }
3709 return ResultReg;
3710 }
3711 return 0;
3712}
3713
3714unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003715 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003716
3717 // Only handle simple types.
3718 if (!CEVT.isSimple())
3719 return 0;
3720 MVT VT = CEVT.getSimpleVT();
3721
3722 if (const auto *CI = dyn_cast<ConstantInt>(C))
3723 return X86MaterializeInt(CI, VT);
3724 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3725 return X86MaterializeFP(CFP, VT);
3726 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3727 return X86MaterializeGV(GV, VT);
3728
3729 return 0;
3730}
3731
3732unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3733 // Fail on dynamic allocas. At this point, getRegForValue has already
3734 // checked its CSE maps, so if we're here trying to handle a dynamic
3735 // alloca, we're not going to succeed. X86SelectAddress has a
3736 // check for dynamic allocas, because it's called directly from
3737 // various places, but targetMaterializeAlloca also needs a check
3738 // in order to avoid recursion between getRegForValue,
3739 // X86SelectAddrss, and targetMaterializeAlloca.
3740 if (!FuncInfo.StaticAllocaMap.count(C))
3741 return 0;
3742 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3743
3744 X86AddressMode AM;
3745 if (!X86SelectAddress(C, AM))
3746 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003747 unsigned Opc =
3748 TLI.getPointerTy(DL) == MVT::i32
3749 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3750 : X86::LEA64r;
3751 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003752 unsigned ResultReg = createResultReg(RC);
3753 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3754 TII.get(Opc), ResultReg), AM);
3755 return ResultReg;
3756}
3757
3758unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3759 MVT VT;
3760 if (!isTypeLegal(CF->getType(), VT))
3761 return 0;
3762
3763 // Get opcode and regclass for the given zero.
3764 unsigned Opc = 0;
3765 const TargetRegisterClass *RC = nullptr;
3766 switch (VT.SimpleTy) {
3767 default: return 0;
3768 case MVT::f32:
3769 if (X86ScalarSSEf32) {
3770 Opc = X86::FsFLD0SS;
3771 RC = &X86::FR32RegClass;
3772 } else {
3773 Opc = X86::LD_Fp032;
3774 RC = &X86::RFP32RegClass;
3775 }
3776 break;
3777 case MVT::f64:
3778 if (X86ScalarSSEf64) {
3779 Opc = X86::FsFLD0SD;
3780 RC = &X86::FR64RegClass;
3781 } else {
3782 Opc = X86::LD_Fp064;
3783 RC = &X86::RFP64RegClass;
3784 }
3785 break;
3786 case MVT::f80:
3787 // No f80 support yet.
3788 return 0;
3789 }
3790
3791 unsigned ResultReg = createResultReg(RC);
3792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3793 return ResultReg;
3794}
3795
3796
3797bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3798 const LoadInst *LI) {
3799 const Value *Ptr = LI->getPointerOperand();
3800 X86AddressMode AM;
3801 if (!X86SelectAddress(Ptr, AM))
3802 return false;
3803
3804 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3805
3806 unsigned Size = DL.getTypeAllocSize(LI->getType());
3807 unsigned Alignment = LI->getAlignment();
3808
3809 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3810 Alignment = DL.getABITypeAlignment(LI->getType());
3811
3812 SmallVector<MachineOperand, 8> AddrOps;
3813 AM.getFullAddress(AddrOps);
3814
Keno Fischere70b31f2015-06-08 20:09:58 +00003815 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003816 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003817 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003818 if (!Result)
3819 return false;
3820
Pete Cooperd31583d2015-05-06 21:37:19 +00003821 // The index register could be in the wrong register class. Unfortunately,
3822 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3823 // to just look at OpNo + the offset to the index reg. We actually need to
3824 // scan the instruction to find the index reg and see if its the correct reg
3825 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003826 unsigned OperandNo = 0;
3827 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3828 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3829 MachineOperand &MO = *I;
3830 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003831 continue;
3832 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003833 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003834 MO.getReg(), OperandNo);
3835 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003836 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003837 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003838 }
3839
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003840 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003841 MI->eraseFromParent();
3842 return true;
3843}
3844
3845
3846namespace llvm {
3847 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3848 const TargetLibraryInfo *libInfo) {
3849 return new X86FastISel(funcInfo, libInfo);
3850 }
3851}