blob: 53ad1e9000033e2d92cac686cec4d17a2ad986c8 [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"
25#include "llvm/CodeGen/Analysis.h"
26#include "llvm/CodeGen/FastISel.h"
27#include "llvm/CodeGen/FunctionLoweringInfo.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/IR/CallSite.h"
32#include "llvm/IR/CallingConv.h"
Reid Kleckner28865802016-04-14 18:29:59 +000033#include "llvm/IR/DebugInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000034#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/GetElementPtrTypeIterator.h"
36#include "llvm/IR/GlobalAlias.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Operator.h"
David Majnemerca194852015-02-10 22:00:34 +000041#include "llvm/MC/MCAsmInfo.h"
Rafael Espindolace4c2bc2015-06-23 12:21:54 +000042#include "llvm/MC/MCSymbol.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000043#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Target/TargetOptions.h"
45using namespace llvm;
46
47namespace {
48
49class X86FastISel final : public FastISel {
50 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
51 /// make the right decision when generating code for different targets.
52 const X86Subtarget *Subtarget;
53
54 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
55 /// floating point ops.
56 /// When SSE is available, use it for f32 operations.
57 /// When SSE2 is available, use it for f64 operations.
58 bool X86ScalarSSEf64;
59 bool X86ScalarSSEf32;
60
61public:
62 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
63 const TargetLibraryInfo *libInfo)
Eric Christophera1c535b2015-02-02 23:03:45 +000064 : FastISel(funcInfo, libInfo) {
65 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000066 X86ScalarSSEf64 = Subtarget->hasSSE2();
67 X86ScalarSSEf32 = Subtarget->hasSSE1();
68 }
69
70 bool fastSelectInstruction(const Instruction *I) override;
71
72 /// \brief The specified machine instr operand is a vreg, and that
73 /// vreg is being provided by the specified load instruction. If possible,
74 /// try to fold the load as an operand to the instruction, returning true if
75 /// possible.
76 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
77 const LoadInst *LI) override;
78
79 bool fastLowerArguments() override;
80 bool fastLowerCall(CallLoweringInfo &CLI) override;
81 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
82
83#include "X86GenFastISel.inc"
84
85private:
Benjamin Kramerbdc49562016-06-12 15:39:02 +000086 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
87 const DebugLoc &DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000088
Pete Cooperd0dae3e2015-05-05 23:41:53 +000089 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000090 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000091
Pete Cooperd0dae3e2015-05-05 23:41:53 +000092 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000093 MachineMemOperand *MMO = nullptr, bool Aligned = false);
94 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000095 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000096 MachineMemOperand *MMO = nullptr, bool Aligned = false);
97
98 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
99 unsigned &ResultReg);
100
101 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
102 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
103
104 bool X86SelectLoad(const Instruction *I);
105
106 bool X86SelectStore(const Instruction *I);
107
108 bool X86SelectRet(const Instruction *I);
109
110 bool X86SelectCmp(const Instruction *I);
111
112 bool X86SelectZExt(const Instruction *I);
113
114 bool X86SelectBranch(const Instruction *I);
115
116 bool X86SelectShift(const Instruction *I);
117
118 bool X86SelectDivRem(const Instruction *I);
119
120 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
121
122 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
123
124 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
125
126 bool X86SelectSelect(const Instruction *I);
127
128 bool X86SelectTrunc(const Instruction *I);
129
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000130 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
131 const TargetRegisterClass *RC);
132
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000133 bool X86SelectFPExt(const Instruction *I);
134 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000135 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000136
137 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000138 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000139 }
140 const X86TargetMachine *getTargetMachine() const {
141 return static_cast<const X86TargetMachine *>(&TM);
142 }
143
144 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
145
146 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
147 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
148 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
149 unsigned fastMaterializeConstant(const Constant *C) override;
150
151 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
152
153 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
154
155 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
156 /// computed in an SSE register, not on the X87 floating point stack.
157 bool isScalarFPTypeInSSEReg(EVT VT) const {
158 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
159 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
160 }
161
162 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
163
164 bool IsMemcpySmall(uint64_t Len);
165
166 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
167 X86AddressMode SrcAM, uint64_t Len);
168
169 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
170 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000171
172 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
173 X86AddressMode &AM);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000174};
175
176} // end anonymous namespace.
177
178static std::pair<X86::CondCode, bool>
179getX86ConditionCode(CmpInst::Predicate Predicate) {
180 X86::CondCode CC = X86::COND_INVALID;
181 bool NeedSwap = false;
182 switch (Predicate) {
183 default: break;
184 // Floating-point Predicates
185 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
186 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
187 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
188 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
189 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
190 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
191 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
192 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
193 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
194 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
195 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
196 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
197 case CmpInst::FCMP_OEQ: // fall-through
198 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
199
200 // Integer Predicates
201 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
202 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
203 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
204 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
205 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
206 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
207 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
208 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
209 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
210 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
211 }
212
213 return std::make_pair(CC, NeedSwap);
214}
215
216static std::pair<unsigned, bool>
217getX86SSEConditionCode(CmpInst::Predicate Predicate) {
218 unsigned CC;
219 bool NeedSwap = false;
220
221 // SSE Condition code mapping:
222 // 0 - EQ
223 // 1 - LT
224 // 2 - LE
225 // 3 - UNORD
226 // 4 - NEQ
227 // 5 - NLT
228 // 6 - NLE
229 // 7 - ORD
230 switch (Predicate) {
231 default: llvm_unreachable("Unexpected predicate");
232 case CmpInst::FCMP_OEQ: CC = 0; break;
233 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
234 case CmpInst::FCMP_OLT: CC = 1; break;
235 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
236 case CmpInst::FCMP_OLE: CC = 2; break;
237 case CmpInst::FCMP_UNO: CC = 3; break;
238 case CmpInst::FCMP_UNE: CC = 4; break;
239 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
240 case CmpInst::FCMP_UGE: CC = 5; break;
241 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
242 case CmpInst::FCMP_UGT: CC = 6; break;
243 case CmpInst::FCMP_ORD: CC = 7; break;
244 case CmpInst::FCMP_UEQ:
245 case CmpInst::FCMP_ONE: CC = 8; break;
246 }
247
248 return std::make_pair(CC, NeedSwap);
249}
250
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000251/// \brief Adds a complex addressing mode to the given machine instr builder.
252/// Note, this will constrain the index register. If its not possible to
253/// constrain the given index register, then a new one will be created. The
254/// IndexReg field of the addressing mode will be updated to match in this case.
255const MachineInstrBuilder &
256X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
257 X86AddressMode &AM) {
258 // First constrain the index register. It needs to be a GR64_NOSP.
259 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
260 MIB->getNumOperands() +
261 X86::AddrIndexReg);
262 return ::addFullAddress(MIB, AM);
263}
264
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000265/// \brief Check if it is possible to fold the condition from the XALU intrinsic
266/// into the user. The condition code will only be updated on success.
267bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
268 const Value *Cond) {
269 if (!isa<ExtractValueInst>(Cond))
270 return false;
271
272 const auto *EV = cast<ExtractValueInst>(Cond);
273 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
274 return false;
275
276 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
277 MVT RetVT;
278 const Function *Callee = II->getCalledFunction();
279 Type *RetTy =
280 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
281 if (!isTypeLegal(RetTy, RetVT))
282 return false;
283
284 if (RetVT != MVT::i32 && RetVT != MVT::i64)
285 return false;
286
287 X86::CondCode TmpCC;
288 switch (II->getIntrinsicID()) {
289 default: return false;
290 case Intrinsic::sadd_with_overflow:
291 case Intrinsic::ssub_with_overflow:
292 case Intrinsic::smul_with_overflow:
293 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
294 case Intrinsic::uadd_with_overflow:
295 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
296 }
297
298 // Check if both instructions are in the same basic block.
299 if (II->getParent() != I->getParent())
300 return false;
301
302 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000303 BasicBlock::const_iterator Start(I);
304 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000305 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
306 // We only expect extractvalue instructions between the intrinsic and the
307 // instruction to be selected.
308 if (!isa<ExtractValueInst>(Itr))
309 return false;
310
311 // Check that the extractvalue operand comes from the intrinsic.
312 const auto *EVI = cast<ExtractValueInst>(Itr);
313 if (EVI->getAggregateOperand() != II)
314 return false;
315 }
316
317 CC = TmpCC;
318 return true;
319}
320
321bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000322 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000323 if (evt == MVT::Other || !evt.isSimple())
324 // Unhandled type. Halt "fast" selection and bail.
325 return false;
326
327 VT = evt.getSimpleVT();
328 // For now, require SSE/SSE2 for performing floating-point operations,
329 // since x87 requires additional work.
330 if (VT == MVT::f64 && !X86ScalarSSEf64)
331 return false;
332 if (VT == MVT::f32 && !X86ScalarSSEf32)
333 return false;
334 // Similarly, no f80 support yet.
335 if (VT == MVT::f80)
336 return false;
337 // We only handle legal types. For example, on x86-32 the instruction
338 // selector contains all of the 64-bit instructions from x86-64,
339 // under the assumption that i64 won't be used if the target doesn't
340 // support it.
341 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
342}
343
344#include "X86GenCallingConv.inc"
345
346/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
347/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
348/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000349bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000350 MachineMemOperand *MMO, unsigned &ResultReg,
351 unsigned Alignment) {
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000352 bool HasSSE41 = Subtarget->hasSSE41();
Craig Topperca9c0802016-06-02 04:19:45 +0000353 bool HasAVX = Subtarget->hasAVX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000354 bool HasAVX2 = Subtarget->hasAVX2();
355 bool IsNonTemporal = MMO && MMO->isNonTemporal();
356
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000357 // Get opcode and regclass of the output for the given load instruction.
358 unsigned Opc = 0;
359 const TargetRegisterClass *RC = nullptr;
360 switch (VT.getSimpleVT().SimpleTy) {
361 default: return false;
362 case MVT::i1:
363 case MVT::i8:
364 Opc = X86::MOV8rm;
365 RC = &X86::GR8RegClass;
366 break;
367 case MVT::i16:
368 Opc = X86::MOV16rm;
369 RC = &X86::GR16RegClass;
370 break;
371 case MVT::i32:
372 Opc = X86::MOV32rm;
373 RC = &X86::GR32RegClass;
374 break;
375 case MVT::i64:
376 // Must be in x86-64 mode.
377 Opc = X86::MOV64rm;
378 RC = &X86::GR64RegClass;
379 break;
380 case MVT::f32:
381 if (X86ScalarSSEf32) {
Craig Topperca9c0802016-06-02 04:19:45 +0000382 Opc = HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000383 RC = &X86::FR32RegClass;
384 } else {
385 Opc = X86::LD_Fp32m;
386 RC = &X86::RFP32RegClass;
387 }
388 break;
389 case MVT::f64:
390 if (X86ScalarSSEf64) {
Craig Topperca9c0802016-06-02 04:19:45 +0000391 Opc = HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000392 RC = &X86::FR64RegClass;
393 } else {
394 Opc = X86::LD_Fp64m;
395 RC = &X86::RFP64RegClass;
396 }
397 break;
398 case MVT::f80:
399 // No f80 support yet.
400 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000401 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000402 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
403 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
404 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000405 Opc = HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000406 else
Craig Topperca9c0802016-06-02 04:19:45 +0000407 Opc = HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000408 RC = &X86::VR128RegClass;
409 break;
410 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000411 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
412 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
413 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000414 Opc = HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000415 else
Craig Topperca9c0802016-06-02 04:19:45 +0000416 Opc = HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000417 RC = &X86::VR128RegClass;
418 break;
419 case MVT::v4i32:
420 case MVT::v2i64:
421 case MVT::v8i16:
422 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000423 if (IsNonTemporal && Alignment >= 16)
424 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
425 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000426 Opc = HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000427 else
Craig Topperca9c0802016-06-02 04:19:45 +0000428 Opc = HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000429 RC = &X86::VR128RegClass;
430 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000431 case MVT::v8f32:
432 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000433 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
434 Opc = X86::VMOVNTDQAYrm;
435 else
436 Opc = (Alignment >= 32) ? X86::VMOVAPSYrm : X86::VMOVUPSYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000437 RC = &X86::VR256RegClass;
438 break;
439 case MVT::v4f64:
440 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000441 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
442 Opc = X86::VMOVNTDQAYrm;
443 else
444 Opc = (Alignment >= 32) ? X86::VMOVAPDYrm : X86::VMOVUPDYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000445 RC = &X86::VR256RegClass;
446 break;
447 case MVT::v8i32:
448 case MVT::v4i64:
449 case MVT::v16i16:
450 case MVT::v32i8:
451 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000452 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
453 Opc = X86::VMOVNTDQAYrm;
454 else
455 Opc = (Alignment >= 32) ? X86::VMOVDQAYrm : X86::VMOVDQUYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000456 RC = &X86::VR256RegClass;
457 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000458 case MVT::v16f32:
459 assert(Subtarget->hasAVX512());
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000460 if (IsNonTemporal && Alignment >= 64)
461 Opc = X86::VMOVNTDQAZrm;
462 else
463 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000464 RC = &X86::VR512RegClass;
465 break;
466 case MVT::v8f64:
467 assert(Subtarget->hasAVX512());
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000468 if (IsNonTemporal && Alignment >= 64)
469 Opc = X86::VMOVNTDQAZrm;
470 else
471 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000472 RC = &X86::VR512RegClass;
473 break;
474 case MVT::v8i64:
475 case MVT::v16i32:
476 case MVT::v32i16:
477 case MVT::v64i8:
478 assert(Subtarget->hasAVX512());
479 // Note: There are a lot more choices based on type with AVX-512, but
480 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000481 if (IsNonTemporal && Alignment >= 64)
482 Opc = X86::VMOVNTDQAZrm;
483 else
484 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000485 RC = &X86::VR512RegClass;
486 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000487 }
488
489 ResultReg = createResultReg(RC);
490 MachineInstrBuilder MIB =
491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
492 addFullAddress(MIB, AM);
493 if (MMO)
494 MIB->addMemOperand(*FuncInfo.MF, MMO);
495 return true;
496}
497
498/// X86FastEmitStore - Emit a machine instruction to store a value Val of
499/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
500/// and a displacement offset, or a GlobalAddress,
501/// i.e. V. Return true if it is possible.
502bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000503 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000504 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000505 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000506 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000507 bool HasAVX = Subtarget->hasAVX();
508 bool IsNonTemporal = MMO && MMO->isNonTemporal();
509
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000510 // Get opcode and regclass of the output for the given store instruction.
511 unsigned Opc = 0;
512 switch (VT.getSimpleVT().SimpleTy) {
513 case MVT::f80: // No f80 support yet.
514 default: return false;
515 case MVT::i1: {
516 // Mask out all but lowest bit.
517 unsigned AndResult = createResultReg(&X86::GR8RegClass);
518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
519 TII.get(X86::AND8ri), AndResult)
520 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
521 ValReg = AndResult;
522 }
523 // FALLTHROUGH, handling i1 as i8.
524 case MVT::i8: Opc = X86::MOV8mr; break;
525 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000526 case MVT::i32:
527 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
528 break;
529 case MVT::i64:
530 // Must be in x86-64 mode.
531 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
532 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000533 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000534 if (X86ScalarSSEf32) {
535 if (IsNonTemporal && HasSSE4A)
536 Opc = X86::MOVNTSS;
537 else
538 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
539 } else
540 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000541 break;
542 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000543 if (X86ScalarSSEf32) {
544 if (IsNonTemporal && HasSSE4A)
545 Opc = X86::MOVNTSD;
546 else
547 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
548 } else
549 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000550 break;
551 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000552 if (Aligned) {
553 if (IsNonTemporal)
554 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
555 else
556 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
557 } else
558 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000559 break;
560 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000561 if (Aligned) {
562 if (IsNonTemporal)
563 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
564 else
565 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
566 } else
567 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000568 break;
569 case MVT::v4i32:
570 case MVT::v2i64:
571 case MVT::v8i16:
572 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000573 if (Aligned) {
574 if (IsNonTemporal)
575 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
576 else
577 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
578 } else
Craig Topperca9c0802016-06-02 04:19:45 +0000579 Opc = HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
580 break;
581 case MVT::v8f32:
582 assert(HasAVX);
583 if (Aligned)
584 Opc = IsNonTemporal ? X86::VMOVNTPSYmr : X86::VMOVAPSYmr;
585 else
586 Opc = X86::VMOVUPSYmr;
587 break;
588 case MVT::v4f64:
589 assert(HasAVX);
590 if (Aligned) {
591 Opc = IsNonTemporal ? X86::VMOVNTPDYmr : X86::VMOVAPDYmr;
592 } else
593 Opc = X86::VMOVUPDYmr;
594 break;
595 case MVT::v8i32:
596 case MVT::v4i64:
597 case MVT::v16i16:
598 case MVT::v32i8:
599 assert(HasAVX);
600 if (Aligned)
601 Opc = IsNonTemporal ? X86::VMOVNTDQYmr : X86::VMOVDQAYmr;
602 else
603 Opc = X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000604 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000605 case MVT::v16f32:
606 assert(Subtarget->hasAVX512());
607 if (Aligned)
608 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
609 else
610 Opc = X86::VMOVUPSZmr;
611 break;
612 case MVT::v8f64:
613 assert(Subtarget->hasAVX512());
614 if (Aligned) {
615 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
616 } else
617 Opc = X86::VMOVUPDZmr;
618 break;
619 case MVT::v8i64:
620 case MVT::v16i32:
621 case MVT::v32i16:
622 case MVT::v64i8:
623 assert(Subtarget->hasAVX512());
624 // Note: There are a lot more choices based on type with AVX-512, but
625 // there's really no advantage when the store isn't masked.
626 if (Aligned)
627 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
628 else
629 Opc = X86::VMOVDQU64Zmr;
630 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000631 }
632
Quentin Colombetbf200682016-04-27 22:33:42 +0000633 const MCInstrDesc &Desc = TII.get(Opc);
634 // Some of the instructions in the previous switch use FR128 instead
635 // of FR32 for ValReg. Make sure the register we feed the instruction
636 // matches its register class constraints.
637 // Note: This is fine to do a copy from FR32 to FR128, this is the
638 // same registers behind the scene and actually why it did not trigger
639 // any bugs before.
640 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000641 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000642 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000643 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
644 if (MMO)
645 MIB->addMemOperand(*FuncInfo.MF, MMO);
646
647 return true;
648}
649
650bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000651 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000652 MachineMemOperand *MMO, bool Aligned) {
653 // Handle 'null' like i32/i64 0.
654 if (isa<ConstantPointerNull>(Val))
655 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
656
657 // If this is a store of a simple constant, fold the constant into the store.
658 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
659 unsigned Opc = 0;
660 bool Signed = true;
661 switch (VT.getSimpleVT().SimpleTy) {
662 default: break;
663 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
664 case MVT::i8: Opc = X86::MOV8mi; break;
665 case MVT::i16: Opc = X86::MOV16mi; break;
666 case MVT::i32: Opc = X86::MOV32mi; break;
667 case MVT::i64:
668 // Must be a 32-bit sign extended value.
669 if (isInt<32>(CI->getSExtValue()))
670 Opc = X86::MOV64mi32;
671 break;
672 }
673
674 if (Opc) {
675 MachineInstrBuilder MIB =
676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
677 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
678 : CI->getZExtValue());
679 if (MMO)
680 MIB->addMemOperand(*FuncInfo.MF, MMO);
681 return true;
682 }
683 }
684
685 unsigned ValReg = getRegForValue(Val);
686 if (ValReg == 0)
687 return false;
688
689 bool ValKill = hasTrivialKill(Val);
690 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
691}
692
693/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
694/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
695/// ISD::SIGN_EXTEND).
696bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
697 unsigned Src, EVT SrcVT,
698 unsigned &ResultReg) {
699 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
700 Src, /*TODO: Kill=*/false);
701 if (RR == 0)
702 return false;
703
704 ResultReg = RR;
705 return true;
706}
707
708bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
709 // Handle constant address.
710 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
711 // Can't handle alternate code models yet.
712 if (TM.getCodeModel() != CodeModel::Small)
713 return false;
714
715 // Can't handle TLS yet.
716 if (GV->isThreadLocal())
717 return false;
718
719 // RIP-relative addresses can't have additional register operands, so if
720 // we've already folded stuff into the addressing mode, just force the
721 // global value into its own register, which we can use as the basereg.
722 if (!Subtarget->isPICStyleRIPRel() ||
723 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
724 // Okay, we've committed to selecting this global. Set up the address.
725 AM.GV = GV;
726
727 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000728 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000729
730 // If this reference is relative to the pic base, set it now.
731 if (isGlobalRelativeToPICBase(GVFlags)) {
732 // FIXME: How do we know Base.Reg is free??
733 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
734 }
735
736 // Unless the ABI requires an extra load, return a direct reference to
737 // the global.
738 if (!isGlobalStubReference(GVFlags)) {
739 if (Subtarget->isPICStyleRIPRel()) {
740 // Use rip-relative addressing if we can. Above we verified that the
741 // base and index registers are unused.
742 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
743 AM.Base.Reg = X86::RIP;
744 }
745 AM.GVOpFlags = GVFlags;
746 return true;
747 }
748
749 // Ok, we need to do a load from a stub. If we've already loaded from
750 // this stub, reuse the loaded pointer, otherwise emit the load now.
751 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
752 unsigned LoadReg;
753 if (I != LocalValueMap.end() && I->second != 0) {
754 LoadReg = I->second;
755 } else {
756 // Issue load from stub.
757 unsigned Opc = 0;
758 const TargetRegisterClass *RC = nullptr;
759 X86AddressMode StubAM;
760 StubAM.Base.Reg = AM.Base.Reg;
761 StubAM.GV = GV;
762 StubAM.GVOpFlags = GVFlags;
763
764 // Prepare for inserting code in the local-value area.
765 SavePoint SaveInsertPt = enterLocalValueArea();
766
Mehdi Amini44ede332015-07-09 02:09:04 +0000767 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000768 Opc = X86::MOV64rm;
769 RC = &X86::GR64RegClass;
770
771 if (Subtarget->isPICStyleRIPRel())
772 StubAM.Base.Reg = X86::RIP;
773 } else {
774 Opc = X86::MOV32rm;
775 RC = &X86::GR32RegClass;
776 }
777
778 LoadReg = createResultReg(RC);
779 MachineInstrBuilder LoadMI =
780 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
781 addFullAddress(LoadMI, StubAM);
782
783 // Ok, back to normal mode.
784 leaveLocalValueArea(SaveInsertPt);
785
786 // Prevent loading GV stub multiple times in same MBB.
787 LocalValueMap[V] = LoadReg;
788 }
789
790 // Now construct the final address. Note that the Disp, Scale,
791 // and Index values may already be set here.
792 AM.Base.Reg = LoadReg;
793 AM.GV = nullptr;
794 return true;
795 }
796 }
797
798 // If all else fails, try to materialize the value in a register.
799 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
800 if (AM.Base.Reg == 0) {
801 AM.Base.Reg = getRegForValue(V);
802 return AM.Base.Reg != 0;
803 }
804 if (AM.IndexReg == 0) {
805 assert(AM.Scale == 1 && "Scale with no index!");
806 AM.IndexReg = getRegForValue(V);
807 return AM.IndexReg != 0;
808 }
809 }
810
811 return false;
812}
813
814/// X86SelectAddress - Attempt to fill in an address from the given value.
815///
816bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
817 SmallVector<const Value *, 32> GEPs;
818redo_gep:
819 const User *U = nullptr;
820 unsigned Opcode = Instruction::UserOp1;
821 if (const Instruction *I = dyn_cast<Instruction>(V)) {
822 // Don't walk into other basic blocks; it's possible we haven't
823 // visited them yet, so the instructions may not yet be assigned
824 // virtual registers.
825 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
826 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
827 Opcode = I->getOpcode();
828 U = I;
829 }
830 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
831 Opcode = C->getOpcode();
832 U = C;
833 }
834
835 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
836 if (Ty->getAddressSpace() > 255)
837 // Fast instruction selection doesn't support the special
838 // address spaces.
839 return false;
840
841 switch (Opcode) {
842 default: break;
843 case Instruction::BitCast:
844 // Look past bitcasts.
845 return X86SelectAddress(U->getOperand(0), AM);
846
847 case Instruction::IntToPtr:
848 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000849 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
850 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000851 return X86SelectAddress(U->getOperand(0), AM);
852 break;
853
854 case Instruction::PtrToInt:
855 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000856 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000857 return X86SelectAddress(U->getOperand(0), AM);
858 break;
859
860 case Instruction::Alloca: {
861 // Do static allocas.
862 const AllocaInst *A = cast<AllocaInst>(V);
863 DenseMap<const AllocaInst *, int>::iterator SI =
864 FuncInfo.StaticAllocaMap.find(A);
865 if (SI != FuncInfo.StaticAllocaMap.end()) {
866 AM.BaseType = X86AddressMode::FrameIndexBase;
867 AM.Base.FrameIndex = SI->second;
868 return true;
869 }
870 break;
871 }
872
873 case Instruction::Add: {
874 // Adds of constants are common and easy enough.
875 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
876 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
877 // They have to fit in the 32-bit signed displacement field though.
878 if (isInt<32>(Disp)) {
879 AM.Disp = (uint32_t)Disp;
880 return X86SelectAddress(U->getOperand(0), AM);
881 }
882 }
883 break;
884 }
885
886 case Instruction::GetElementPtr: {
887 X86AddressMode SavedAM = AM;
888
889 // Pattern-match simple GEPs.
890 uint64_t Disp = (int32_t)AM.Disp;
891 unsigned IndexReg = AM.IndexReg;
892 unsigned Scale = AM.Scale;
893 gep_type_iterator GTI = gep_type_begin(U);
894 // Iterate through the indices, folding what we can. Constants can be
895 // folded, and one dynamic index can be handled, if the scale is supported.
896 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
897 i != e; ++i, ++GTI) {
898 const Value *Op = *i;
899 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
900 const StructLayout *SL = DL.getStructLayout(STy);
901 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
902 continue;
903 }
904
905 // A array/variable index is always of the form i*S where S is the
906 // constant scale size. See if we can push the scale into immediates.
907 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
908 for (;;) {
909 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
910 // Constant-offset addressing.
911 Disp += CI->getSExtValue() * S;
912 break;
913 }
914 if (canFoldAddIntoGEP(U, Op)) {
915 // A compatible add with a constant operand. Fold the constant.
916 ConstantInt *CI =
917 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
918 Disp += CI->getSExtValue() * S;
919 // Iterate on the other operand.
920 Op = cast<AddOperator>(Op)->getOperand(0);
921 continue;
922 }
923 if (IndexReg == 0 &&
924 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
925 (S == 1 || S == 2 || S == 4 || S == 8)) {
926 // Scaled-index addressing.
927 Scale = S;
928 IndexReg = getRegForGEPIndex(Op).first;
929 if (IndexReg == 0)
930 return false;
931 break;
932 }
933 // Unsupported.
934 goto unsupported_gep;
935 }
936 }
937
938 // Check for displacement overflow.
939 if (!isInt<32>(Disp))
940 break;
941
942 AM.IndexReg = IndexReg;
943 AM.Scale = Scale;
944 AM.Disp = (uint32_t)Disp;
945 GEPs.push_back(V);
946
947 if (const GetElementPtrInst *GEP =
948 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
949 // Ok, the GEP indices were covered by constant-offset and scaled-index
950 // addressing. Update the address state and move on to examining the base.
951 V = GEP;
952 goto redo_gep;
953 } else if (X86SelectAddress(U->getOperand(0), AM)) {
954 return true;
955 }
956
957 // If we couldn't merge the gep value into this addr mode, revert back to
958 // our address and just match the value instead of completely failing.
959 AM = SavedAM;
960
961 for (SmallVectorImpl<const Value *>::reverse_iterator
962 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
963 if (handleConstantAddresses(*I, AM))
964 return true;
965
966 return false;
967 unsupported_gep:
968 // Ok, the GEP indices weren't all covered.
969 break;
970 }
971 }
972
973 return handleConstantAddresses(V, AM);
974}
975
976/// X86SelectCallAddress - Attempt to fill in an address from the given value.
977///
978bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
979 const User *U = nullptr;
980 unsigned Opcode = Instruction::UserOp1;
981 const Instruction *I = dyn_cast<Instruction>(V);
982 // Record if the value is defined in the same basic block.
983 //
984 // This information is crucial to know whether or not folding an
985 // operand is valid.
986 // Indeed, FastISel generates or reuses a virtual register for all
987 // operands of all instructions it selects. Obviously, the definition and
988 // its uses must use the same virtual register otherwise the produced
989 // code is incorrect.
990 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
991 // registers for values that are alive across basic blocks. This ensures
992 // that the values are consistently set between across basic block, even
993 // if different instruction selection mechanisms are used (e.g., a mix of
994 // SDISel and FastISel).
995 // For values local to a basic block, the instruction selection process
996 // generates these virtual registers with whatever method is appropriate
997 // for its needs. In particular, FastISel and SDISel do not share the way
998 // local virtual registers are set.
999 // Therefore, this is impossible (or at least unsafe) to share values
1000 // between basic blocks unless they use the same instruction selection
1001 // method, which is not guarantee for X86.
1002 // Moreover, things like hasOneUse could not be used accurately, if we
1003 // allow to reference values across basic blocks whereas they are not
1004 // alive across basic blocks initially.
1005 bool InMBB = true;
1006 if (I) {
1007 Opcode = I->getOpcode();
1008 U = I;
1009 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1010 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1011 Opcode = C->getOpcode();
1012 U = C;
1013 }
1014
1015 switch (Opcode) {
1016 default: break;
1017 case Instruction::BitCast:
1018 // Look past bitcasts if its operand is in the same BB.
1019 if (InMBB)
1020 return X86SelectCallAddress(U->getOperand(0), AM);
1021 break;
1022
1023 case Instruction::IntToPtr:
1024 // Look past no-op inttoptrs if its operand is in the same BB.
1025 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001026 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1027 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001028 return X86SelectCallAddress(U->getOperand(0), AM);
1029 break;
1030
1031 case Instruction::PtrToInt:
1032 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001033 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001034 return X86SelectCallAddress(U->getOperand(0), AM);
1035 break;
1036 }
1037
1038 // Handle constant address.
1039 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1040 // Can't handle alternate code models yet.
1041 if (TM.getCodeModel() != CodeModel::Small)
1042 return false;
1043
1044 // RIP-relative addresses can't have additional register operands.
1045 if (Subtarget->isPICStyleRIPRel() &&
1046 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1047 return false;
1048
1049 // Can't handle DLL Import.
1050 if (GV->hasDLLImportStorageClass())
1051 return false;
1052
1053 // Can't handle TLS.
1054 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1055 if (GVar->isThreadLocal())
1056 return false;
1057
1058 // Okay, we've committed to selecting this global. Set up the basic address.
1059 AM.GV = GV;
1060
1061 // No ABI requires an extra load for anything other than DLLImport, which
1062 // we rejected above. Return a direct reference to the global.
1063 if (Subtarget->isPICStyleRIPRel()) {
1064 // Use rip-relative addressing if we can. Above we verified that the
1065 // base and index registers are unused.
1066 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1067 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001068 } else {
1069 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001070 }
1071
1072 return true;
1073 }
1074
1075 // If all else fails, try to materialize the value in a register.
1076 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1077 if (AM.Base.Reg == 0) {
1078 AM.Base.Reg = getRegForValue(V);
1079 return AM.Base.Reg != 0;
1080 }
1081 if (AM.IndexReg == 0) {
1082 assert(AM.Scale == 1 && "Scale with no index!");
1083 AM.IndexReg = getRegForValue(V);
1084 return AM.IndexReg != 0;
1085 }
1086 }
1087
1088 return false;
1089}
1090
1091
1092/// X86SelectStore - Select and emit code to implement store instructions.
1093bool X86FastISel::X86SelectStore(const Instruction *I) {
1094 // Atomic stores need special handling.
1095 const StoreInst *S = cast<StoreInst>(I);
1096
1097 if (S->isAtomic())
1098 return false;
1099
Manman Ren57518142016-04-11 21:08:06 +00001100 const Value *PtrV = I->getOperand(1);
1101 if (TLI.supportSwiftError()) {
1102 // Swifterror values can come from either a function parameter with
1103 // swifterror attribute or an alloca with swifterror attribute.
1104 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1105 if (Arg->hasSwiftErrorAttr())
1106 return false;
1107 }
1108
1109 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1110 if (Alloca->isSwiftError())
1111 return false;
1112 }
1113 }
1114
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001115 const Value *Val = S->getValueOperand();
1116 const Value *Ptr = S->getPointerOperand();
1117
1118 MVT VT;
1119 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1120 return false;
1121
1122 unsigned Alignment = S->getAlignment();
1123 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1124 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1125 Alignment = ABIAlignment;
1126 bool Aligned = Alignment >= ABIAlignment;
1127
1128 X86AddressMode AM;
1129 if (!X86SelectAddress(Ptr, AM))
1130 return false;
1131
1132 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1133}
1134
1135/// X86SelectRet - Select and emit code to implement ret instructions.
1136bool X86FastISel::X86SelectRet(const Instruction *I) {
1137 const ReturnInst *Ret = cast<ReturnInst>(I);
1138 const Function &F = *I->getParent()->getParent();
1139 const X86MachineFunctionInfo *X86MFInfo =
1140 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1141
1142 if (!FuncInfo.CanLowerReturn)
1143 return false;
1144
Manman Ren57518142016-04-11 21:08:06 +00001145 if (TLI.supportSwiftError() &&
1146 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1147 return false;
1148
Manman Rened967f32016-01-12 01:08:46 +00001149 if (TLI.supportSplitCSR(FuncInfo.MF))
1150 return false;
1151
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001152 CallingConv::ID CC = F.getCallingConv();
1153 if (CC != CallingConv::C &&
1154 CC != CallingConv::Fast &&
1155 CC != CallingConv::X86_FastCall &&
1156 CC != CallingConv::X86_64_SysV)
1157 return false;
1158
1159 if (Subtarget->isCallingConvWin64(CC))
1160 return false;
1161
1162 // Don't handle popping bytes on return for now.
1163 if (X86MFInfo->getBytesToPopOnReturn() != 0)
1164 return false;
1165
1166 // fastcc with -tailcallopt is intended to provide a guaranteed
1167 // tail call optimization. Fastisel doesn't know how to do that.
1168 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1169 return false;
1170
1171 // Let SDISel handle vararg functions.
1172 if (F.isVarArg())
1173 return false;
1174
1175 // Build a list of return value registers.
1176 SmallVector<unsigned, 4> RetRegs;
1177
1178 if (Ret->getNumOperands() > 0) {
1179 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001180 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001181
1182 // Analyze operands of the call, assigning locations to each operand.
1183 SmallVector<CCValAssign, 16> ValLocs;
1184 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1185 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1186
1187 const Value *RV = Ret->getOperand(0);
1188 unsigned Reg = getRegForValue(RV);
1189 if (Reg == 0)
1190 return false;
1191
1192 // Only handle a single return value for now.
1193 if (ValLocs.size() != 1)
1194 return false;
1195
1196 CCValAssign &VA = ValLocs[0];
1197
1198 // Don't bother handling odd stuff for now.
1199 if (VA.getLocInfo() != CCValAssign::Full)
1200 return false;
1201 // Only handle register returns for now.
1202 if (!VA.isRegLoc())
1203 return false;
1204
1205 // The calling-convention tables for x87 returns don't tell
1206 // the whole story.
1207 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1208 return false;
1209
1210 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001211 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001212 EVT DstVT = VA.getValVT();
1213 // Special handling for extended integers.
1214 if (SrcVT != DstVT) {
1215 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1216 return false;
1217
1218 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1219 return false;
1220
1221 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1222
1223 if (SrcVT == MVT::i1) {
1224 if (Outs[0].Flags.isSExt())
1225 return false;
1226 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1227 SrcVT = MVT::i8;
1228 }
1229 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1230 ISD::SIGN_EXTEND;
1231 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1232 SrcReg, /*TODO: Kill=*/false);
1233 }
1234
1235 // Make the copy.
1236 unsigned DstReg = VA.getLocReg();
1237 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1238 // Avoid a cross-class copy. This is very unlikely.
1239 if (!SrcRC->contains(DstReg))
1240 return false;
1241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1242 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1243
1244 // Add register to return instruction.
1245 RetRegs.push_back(VA.getLocReg());
1246 }
1247
Manman Ren1c3f65a2016-04-26 18:08:06 +00001248 // Swift calling convention does not require we copy the sret argument
1249 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1250
Dimitry Andric227b9282016-01-03 17:22:03 +00001251 // All x86 ABIs require that for returning structs by value we copy
1252 // the sret argument into %rax/%eax (depending on ABI) for the return.
1253 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001254 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001255 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001256 unsigned Reg = X86MFInfo->getSRetReturnReg();
1257 assert(Reg &&
1258 "SRetReturnReg should have been set in LowerFormalArguments()!");
1259 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1260 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1261 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1262 RetRegs.push_back(RetReg);
1263 }
1264
1265 // Now emit the RET.
1266 MachineInstrBuilder MIB =
1267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1268 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1269 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1270 MIB.addReg(RetRegs[i], RegState::Implicit);
1271 return true;
1272}
1273
1274/// X86SelectLoad - Select and emit code to implement load instructions.
1275///
1276bool X86FastISel::X86SelectLoad(const Instruction *I) {
1277 const LoadInst *LI = cast<LoadInst>(I);
1278
1279 // Atomic loads need special handling.
1280 if (LI->isAtomic())
1281 return false;
1282
Manman Ren57518142016-04-11 21:08:06 +00001283 const Value *SV = I->getOperand(0);
1284 if (TLI.supportSwiftError()) {
1285 // Swifterror values can come from either a function parameter with
1286 // swifterror attribute or an alloca with swifterror attribute.
1287 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1288 if (Arg->hasSwiftErrorAttr())
1289 return false;
1290 }
1291
1292 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1293 if (Alloca->isSwiftError())
1294 return false;
1295 }
1296 }
1297
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001298 MVT VT;
1299 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1300 return false;
1301
1302 const Value *Ptr = LI->getPointerOperand();
1303
1304 X86AddressMode AM;
1305 if (!X86SelectAddress(Ptr, AM))
1306 return false;
1307
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001308 unsigned Alignment = LI->getAlignment();
1309 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1310 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1311 Alignment = ABIAlignment;
1312
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001313 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001314 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1315 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001316 return false;
1317
1318 updateValueMap(I, ResultReg);
1319 return true;
1320}
1321
1322static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1323 bool HasAVX = Subtarget->hasAVX();
1324 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1325 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1326
1327 switch (VT.getSimpleVT().SimpleTy) {
1328 default: return 0;
1329 case MVT::i8: return X86::CMP8rr;
1330 case MVT::i16: return X86::CMP16rr;
1331 case MVT::i32: return X86::CMP32rr;
1332 case MVT::i64: return X86::CMP64rr;
1333 case MVT::f32:
1334 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1335 case MVT::f64:
1336 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1337 }
1338}
1339
Rafael Espindola19141f22015-03-16 14:05:49 +00001340/// If we have a comparison with RHS as the RHS of the comparison, return an
1341/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001342static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001343 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001344 switch (VT.getSimpleVT().SimpleTy) {
1345 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001346 default:
1347 return 0;
1348 case MVT::i8:
1349 return X86::CMP8ri;
1350 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001351 if (isInt<8>(Val))
1352 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001353 return X86::CMP16ri;
1354 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001355 if (isInt<8>(Val))
1356 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001357 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001358 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001359 if (isInt<8>(Val))
1360 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001361 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1362 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001363 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001364 return X86::CMP64ri32;
1365 return 0;
1366 }
1367}
1368
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001369bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1370 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001371 unsigned Op0Reg = getRegForValue(Op0);
1372 if (Op0Reg == 0) return false;
1373
1374 // Handle 'null' like i32/i64 0.
1375 if (isa<ConstantPointerNull>(Op1))
1376 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1377
1378 // We have two options: compare with register or immediate. If the RHS of
1379 // the compare is an immediate that we can fold into this compare, use
1380 // CMPri, otherwise use CMPrr.
1381 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1382 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1383 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1384 .addReg(Op0Reg)
1385 .addImm(Op1C->getSExtValue());
1386 return true;
1387 }
1388 }
1389
1390 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1391 if (CompareOpc == 0) return false;
1392
1393 unsigned Op1Reg = getRegForValue(Op1);
1394 if (Op1Reg == 0) return false;
1395 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1396 .addReg(Op0Reg)
1397 .addReg(Op1Reg);
1398
1399 return true;
1400}
1401
1402bool X86FastISel::X86SelectCmp(const Instruction *I) {
1403 const CmpInst *CI = cast<CmpInst>(I);
1404
1405 MVT VT;
1406 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1407 return false;
1408
1409 // Try to optimize or fold the cmp.
1410 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1411 unsigned ResultReg = 0;
1412 switch (Predicate) {
1413 default: break;
1414 case CmpInst::FCMP_FALSE: {
1415 ResultReg = createResultReg(&X86::GR32RegClass);
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1417 ResultReg);
1418 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1419 X86::sub_8bit);
1420 if (!ResultReg)
1421 return false;
1422 break;
1423 }
1424 case CmpInst::FCMP_TRUE: {
1425 ResultReg = createResultReg(&X86::GR8RegClass);
1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1427 ResultReg).addImm(1);
1428 break;
1429 }
1430 }
1431
1432 if (ResultReg) {
1433 updateValueMap(I, ResultReg);
1434 return true;
1435 }
1436
1437 const Value *LHS = CI->getOperand(0);
1438 const Value *RHS = CI->getOperand(1);
1439
1440 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1441 // We don't have to materialize a zero constant for this case and can just use
1442 // %x again on the RHS.
1443 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1444 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1445 if (RHSC && RHSC->isNullValue())
1446 RHS = LHS;
1447 }
1448
1449 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1450 static unsigned SETFOpcTable[2][3] = {
1451 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1452 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1453 };
1454 unsigned *SETFOpc = nullptr;
1455 switch (Predicate) {
1456 default: break;
1457 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1458 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1459 }
1460
1461 ResultReg = createResultReg(&X86::GR8RegClass);
1462 if (SETFOpc) {
1463 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1464 return false;
1465
1466 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1467 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1469 FlagReg1);
1470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1471 FlagReg2);
1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1473 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1474 updateValueMap(I, ResultReg);
1475 return true;
1476 }
1477
1478 X86::CondCode CC;
1479 bool SwapArgs;
1480 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1481 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1482 unsigned Opc = X86::getSETFromCond(CC);
1483
1484 if (SwapArgs)
1485 std::swap(LHS, RHS);
1486
1487 // Emit a compare of LHS/RHS.
1488 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1489 return false;
1490
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1492 updateValueMap(I, ResultReg);
1493 return true;
1494}
1495
1496bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001497 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001498 if (!TLI.isTypeLegal(DstVT))
1499 return false;
1500
1501 unsigned ResultReg = getRegForValue(I->getOperand(0));
1502 if (ResultReg == 0)
1503 return false;
1504
1505 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001506 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001507 if (SrcVT.SimpleTy == MVT::i1) {
1508 // Set the high bits to zero.
1509 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1510 SrcVT = MVT::i8;
1511
1512 if (ResultReg == 0)
1513 return false;
1514 }
1515
1516 if (DstVT == MVT::i64) {
1517 // Handle extension to 64-bits via sub-register shenanigans.
1518 unsigned MovInst;
1519
1520 switch (SrcVT.SimpleTy) {
1521 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1522 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1523 case MVT::i32: MovInst = X86::MOV32rr; break;
1524 default: llvm_unreachable("Unexpected zext to i64 source type");
1525 }
1526
1527 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1528 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1529 .addReg(ResultReg);
1530
1531 ResultReg = createResultReg(&X86::GR64RegClass);
1532 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1533 ResultReg)
1534 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1535 } else if (DstVT != MVT::i8) {
1536 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1537 ResultReg, /*Kill=*/true);
1538 if (ResultReg == 0)
1539 return false;
1540 }
1541
1542 updateValueMap(I, ResultReg);
1543 return true;
1544}
1545
1546bool X86FastISel::X86SelectBranch(const Instruction *I) {
1547 // Unconditional branches are selected by tablegen-generated code.
1548 // Handle a conditional branch.
1549 const BranchInst *BI = cast<BranchInst>(I);
1550 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1551 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1552
1553 // Fold the common case of a conditional branch with a comparison
1554 // in the same block (values defined on other blocks may not have
1555 // initialized registers).
1556 X86::CondCode CC;
1557 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1558 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001559 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001560
1561 // Try to optimize or fold the cmp.
1562 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1563 switch (Predicate) {
1564 default: break;
1565 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1566 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1567 }
1568
1569 const Value *CmpLHS = CI->getOperand(0);
1570 const Value *CmpRHS = CI->getOperand(1);
1571
1572 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1573 // 0.0.
1574 // We don't have to materialize a zero constant for this case and can just
1575 // use %x again on the RHS.
1576 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1577 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1578 if (CmpRHSC && CmpRHSC->isNullValue())
1579 CmpRHS = CmpLHS;
1580 }
1581
1582 // Try to take advantage of fallthrough opportunities.
1583 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1584 std::swap(TrueMBB, FalseMBB);
1585 Predicate = CmpInst::getInversePredicate(Predicate);
1586 }
1587
1588 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1589 // code check. Instead two branch instructions are required to check all
1590 // the flags. First we change the predicate to a supported condition code,
1591 // which will be the first branch. Later one we will emit the second
1592 // branch.
1593 bool NeedExtraBranch = false;
1594 switch (Predicate) {
1595 default: break;
1596 case CmpInst::FCMP_OEQ:
1597 std::swap(TrueMBB, FalseMBB); // fall-through
1598 case CmpInst::FCMP_UNE:
1599 NeedExtraBranch = true;
1600 Predicate = CmpInst::FCMP_ONE;
1601 break;
1602 }
1603
1604 bool SwapArgs;
1605 unsigned BranchOpc;
1606 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1607 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1608
1609 BranchOpc = X86::GetCondBranchFromCond(CC);
1610 if (SwapArgs)
1611 std::swap(CmpLHS, CmpRHS);
1612
1613 // Emit a compare of the LHS and RHS, setting the flags.
1614 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1615 return false;
1616
1617 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1618 .addMBB(TrueMBB);
1619
1620 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1621 // to UNE above).
1622 if (NeedExtraBranch) {
1623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1624 .addMBB(TrueMBB);
1625 }
1626
Matthias Braun17af6072015-08-26 01:38:00 +00001627 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001628 return true;
1629 }
1630 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1631 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1632 // typically happen for _Bool and C++ bools.
1633 MVT SourceVT;
1634 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1635 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1636 unsigned TestOpc = 0;
1637 switch (SourceVT.SimpleTy) {
1638 default: break;
1639 case MVT::i8: TestOpc = X86::TEST8ri; break;
1640 case MVT::i16: TestOpc = X86::TEST16ri; break;
1641 case MVT::i32: TestOpc = X86::TEST32ri; break;
1642 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1643 }
1644 if (TestOpc) {
1645 unsigned OpReg = getRegForValue(TI->getOperand(0));
1646 if (OpReg == 0) return false;
1647 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1648 .addReg(OpReg).addImm(1);
1649
1650 unsigned JmpOpc = X86::JNE_1;
1651 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1652 std::swap(TrueMBB, FalseMBB);
1653 JmpOpc = X86::JE_1;
1654 }
1655
1656 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1657 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001658
1659 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001660 return true;
1661 }
1662 }
1663 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1664 // Fake request the condition, otherwise the intrinsic might be completely
1665 // optimized away.
1666 unsigned TmpReg = getRegForValue(BI->getCondition());
1667 if (TmpReg == 0)
1668 return false;
1669
1670 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1671
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1673 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001674 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001675 return true;
1676 }
1677
1678 // Otherwise do a clumsy setcc and re-test it.
1679 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1680 // in an explicit cast, so make sure to handle that correctly.
1681 unsigned OpReg = getRegForValue(BI->getCondition());
1682 if (OpReg == 0) return false;
1683
1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1685 .addReg(OpReg).addImm(1);
1686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1687 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001688 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001689 return true;
1690}
1691
1692bool X86FastISel::X86SelectShift(const Instruction *I) {
1693 unsigned CReg = 0, OpReg = 0;
1694 const TargetRegisterClass *RC = nullptr;
1695 if (I->getType()->isIntegerTy(8)) {
1696 CReg = X86::CL;
1697 RC = &X86::GR8RegClass;
1698 switch (I->getOpcode()) {
1699 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1700 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1701 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1702 default: return false;
1703 }
1704 } else if (I->getType()->isIntegerTy(16)) {
1705 CReg = X86::CX;
1706 RC = &X86::GR16RegClass;
1707 switch (I->getOpcode()) {
1708 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1709 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1710 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1711 default: return false;
1712 }
1713 } else if (I->getType()->isIntegerTy(32)) {
1714 CReg = X86::ECX;
1715 RC = &X86::GR32RegClass;
1716 switch (I->getOpcode()) {
1717 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1718 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1719 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1720 default: return false;
1721 }
1722 } else if (I->getType()->isIntegerTy(64)) {
1723 CReg = X86::RCX;
1724 RC = &X86::GR64RegClass;
1725 switch (I->getOpcode()) {
1726 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1727 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1728 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1729 default: return false;
1730 }
1731 } else {
1732 return false;
1733 }
1734
1735 MVT VT;
1736 if (!isTypeLegal(I->getType(), VT))
1737 return false;
1738
1739 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1740 if (Op0Reg == 0) return false;
1741
1742 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1743 if (Op1Reg == 0) return false;
1744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1745 CReg).addReg(Op1Reg);
1746
1747 // The shift instruction uses X86::CL. If we defined a super-register
1748 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1749 if (CReg != X86::CL)
1750 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1751 TII.get(TargetOpcode::KILL), X86::CL)
1752 .addReg(CReg, RegState::Kill);
1753
1754 unsigned ResultReg = createResultReg(RC);
1755 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1756 .addReg(Op0Reg);
1757 updateValueMap(I, ResultReg);
1758 return true;
1759}
1760
1761bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1762 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1763 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1764 const static bool S = true; // IsSigned
1765 const static bool U = false; // !IsSigned
1766 const static unsigned Copy = TargetOpcode::COPY;
1767 // For the X86 DIV/IDIV instruction, in most cases the dividend
1768 // (numerator) must be in a specific register pair highreg:lowreg,
1769 // producing the quotient in lowreg and the remainder in highreg.
1770 // For most data types, to set up the instruction, the dividend is
1771 // copied into lowreg, and lowreg is sign-extended or zero-extended
1772 // into highreg. The exception is i8, where the dividend is defined
1773 // as a single register rather than a register pair, and we
1774 // therefore directly sign-extend or zero-extend the dividend into
1775 // lowreg, instead of copying, and ignore the highreg.
1776 const static struct DivRemEntry {
1777 // The following portion depends only on the data type.
1778 const TargetRegisterClass *RC;
1779 unsigned LowInReg; // low part of the register pair
1780 unsigned HighInReg; // high part of the register pair
1781 // The following portion depends on both the data type and the operation.
1782 struct DivRemResult {
1783 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1784 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1785 // highreg, or copying a zero into highreg.
1786 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1787 // zero/sign-extending into lowreg for i8.
1788 unsigned DivRemResultReg; // Register containing the desired result.
1789 bool IsOpSigned; // Whether to use signed or unsigned form.
1790 } ResultTable[NumOps];
1791 } OpTable[NumTypes] = {
1792 { &X86::GR8RegClass, X86::AX, 0, {
1793 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1794 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1795 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1796 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1797 }
1798 }, // i8
1799 { &X86::GR16RegClass, X86::AX, X86::DX, {
1800 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1801 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1802 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1803 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1804 }
1805 }, // i16
1806 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1807 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1808 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1809 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1810 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1811 }
1812 }, // i32
1813 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1814 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1815 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1816 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1817 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1818 }
1819 }, // i64
1820 };
1821
1822 MVT VT;
1823 if (!isTypeLegal(I->getType(), VT))
1824 return false;
1825
1826 unsigned TypeIndex, OpIndex;
1827 switch (VT.SimpleTy) {
1828 default: return false;
1829 case MVT::i8: TypeIndex = 0; break;
1830 case MVT::i16: TypeIndex = 1; break;
1831 case MVT::i32: TypeIndex = 2; break;
1832 case MVT::i64: TypeIndex = 3;
1833 if (!Subtarget->is64Bit())
1834 return false;
1835 break;
1836 }
1837
1838 switch (I->getOpcode()) {
1839 default: llvm_unreachable("Unexpected div/rem opcode");
1840 case Instruction::SDiv: OpIndex = 0; break;
1841 case Instruction::SRem: OpIndex = 1; break;
1842 case Instruction::UDiv: OpIndex = 2; break;
1843 case Instruction::URem: OpIndex = 3; break;
1844 }
1845
1846 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1847 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1848 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1849 if (Op0Reg == 0)
1850 return false;
1851 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1852 if (Op1Reg == 0)
1853 return false;
1854
1855 // Move op0 into low-order input register.
1856 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1857 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1858 // Zero-extend or sign-extend into high-order input register.
1859 if (OpEntry.OpSignExtend) {
1860 if (OpEntry.IsOpSigned)
1861 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1862 TII.get(OpEntry.OpSignExtend));
1863 else {
1864 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1866 TII.get(X86::MOV32r0), Zero32);
1867
1868 // Copy the zero into the appropriate sub/super/identical physical
1869 // register. Unfortunately the operations needed are not uniform enough
1870 // to fit neatly into the table above.
1871 if (VT.SimpleTy == MVT::i16) {
1872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1873 TII.get(Copy), TypeEntry.HighInReg)
1874 .addReg(Zero32, 0, X86::sub_16bit);
1875 } else if (VT.SimpleTy == MVT::i32) {
1876 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1877 TII.get(Copy), TypeEntry.HighInReg)
1878 .addReg(Zero32);
1879 } else if (VT.SimpleTy == MVT::i64) {
1880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1881 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1882 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1883 }
1884 }
1885 }
1886 // Generate the DIV/IDIV instruction.
1887 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1888 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1889 // For i8 remainder, we can't reference AH directly, as we'll end
1890 // up with bogus copies like %R9B = COPY %AH. Reference AX
1891 // instead to prevent AH references in a REX instruction.
1892 //
1893 // The current assumption of the fast register allocator is that isel
1894 // won't generate explicit references to the GPR8_NOREX registers. If
1895 // the allocator and/or the backend get enhanced to be more robust in
1896 // that regard, this can be, and should be, removed.
1897 unsigned ResultReg = 0;
1898 if ((I->getOpcode() == Instruction::SRem ||
1899 I->getOpcode() == Instruction::URem) &&
1900 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1901 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1902 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1903 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1904 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1905
1906 // Shift AX right by 8 bits instead of using AH.
1907 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1908 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1909
1910 // Now reference the 8-bit subreg of the result.
1911 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1912 /*Kill=*/true, X86::sub_8bit);
1913 }
1914 // Copy the result out of the physreg if we haven't already.
1915 if (!ResultReg) {
1916 ResultReg = createResultReg(TypeEntry.RC);
1917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1918 .addReg(OpEntry.DivRemResultReg);
1919 }
1920 updateValueMap(I, ResultReg);
1921
1922 return true;
1923}
1924
1925/// \brief Emit a conditional move instruction (if the are supported) to lower
1926/// the select.
1927bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1928 // Check if the subtarget supports these instructions.
1929 if (!Subtarget->hasCMov())
1930 return false;
1931
1932 // FIXME: Add support for i8.
1933 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1934 return false;
1935
1936 const Value *Cond = I->getOperand(0);
1937 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1938 bool NeedTest = true;
1939 X86::CondCode CC = X86::COND_NE;
1940
1941 // Optimize conditions coming from a compare if both instructions are in the
1942 // same basic block (values defined in other basic blocks may not have
1943 // initialized registers).
1944 const auto *CI = dyn_cast<CmpInst>(Cond);
1945 if (CI && (CI->getParent() == I->getParent())) {
1946 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1947
1948 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1949 static unsigned SETFOpcTable[2][3] = {
1950 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1951 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1952 };
1953 unsigned *SETFOpc = nullptr;
1954 switch (Predicate) {
1955 default: break;
1956 case CmpInst::FCMP_OEQ:
1957 SETFOpc = &SETFOpcTable[0][0];
1958 Predicate = CmpInst::ICMP_NE;
1959 break;
1960 case CmpInst::FCMP_UNE:
1961 SETFOpc = &SETFOpcTable[1][0];
1962 Predicate = CmpInst::ICMP_NE;
1963 break;
1964 }
1965
1966 bool NeedSwap;
1967 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1968 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1969
1970 const Value *CmpLHS = CI->getOperand(0);
1971 const Value *CmpRHS = CI->getOperand(1);
1972 if (NeedSwap)
1973 std::swap(CmpLHS, CmpRHS);
1974
Mehdi Amini44ede332015-07-09 02:09:04 +00001975 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001976 // Emit a compare of the LHS and RHS, setting the flags.
1977 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1978 return false;
1979
1980 if (SETFOpc) {
1981 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1982 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1984 FlagReg1);
1985 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1986 FlagReg2);
1987 auto const &II = TII.get(SETFOpc[2]);
1988 if (II.getNumDefs()) {
1989 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1991 .addReg(FlagReg2).addReg(FlagReg1);
1992 } else {
1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1994 .addReg(FlagReg2).addReg(FlagReg1);
1995 }
1996 }
1997 NeedTest = false;
1998 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1999 // Fake request the condition, otherwise the intrinsic might be completely
2000 // optimized away.
2001 unsigned TmpReg = getRegForValue(Cond);
2002 if (TmpReg == 0)
2003 return false;
2004
2005 NeedTest = false;
2006 }
2007
2008 if (NeedTest) {
2009 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2010 // garbage. Indeed, only the less significant bit is supposed to be
2011 // accurate. If we read more than the lsb, we may see non-zero values
2012 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2013 // the select. This is achieved by performing TEST against 1.
2014 unsigned CondReg = getRegForValue(Cond);
2015 if (CondReg == 0)
2016 return false;
2017 bool CondIsKill = hasTrivialKill(Cond);
2018
2019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2020 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2021 }
2022
2023 const Value *LHS = I->getOperand(1);
2024 const Value *RHS = I->getOperand(2);
2025
2026 unsigned RHSReg = getRegForValue(RHS);
2027 bool RHSIsKill = hasTrivialKill(RHS);
2028
2029 unsigned LHSReg = getRegForValue(LHS);
2030 bool LHSIsKill = hasTrivialKill(LHS);
2031
2032 if (!LHSReg || !RHSReg)
2033 return false;
2034
2035 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2036 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2037 LHSReg, LHSIsKill);
2038 updateValueMap(I, ResultReg);
2039 return true;
2040}
2041
Sanjay Patel302404b2015-03-05 21:46:54 +00002042/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002043///
2044/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2045/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002046/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002047bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2048 // Optimize conditions coming from a compare if both instructions are in the
2049 // same basic block (values defined in other basic blocks may not have
2050 // initialized registers).
2051 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2052 if (!CI || (CI->getParent() != I->getParent()))
2053 return false;
2054
2055 if (I->getType() != CI->getOperand(0)->getType() ||
2056 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2057 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2058 return false;
2059
2060 const Value *CmpLHS = CI->getOperand(0);
2061 const Value *CmpRHS = CI->getOperand(1);
2062 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2063
2064 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2065 // We don't have to materialize a zero constant for this case and can just use
2066 // %x again on the RHS.
2067 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2068 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2069 if (CmpRHSC && CmpRHSC->isNullValue())
2070 CmpRHS = CmpLHS;
2071 }
2072
2073 unsigned CC;
2074 bool NeedSwap;
2075 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2076 if (CC > 7)
2077 return false;
2078
2079 if (NeedSwap)
2080 std::swap(CmpLHS, CmpRHS);
2081
Sanjay Patel302404b2015-03-05 21:46:54 +00002082 // Choose the SSE instruction sequence based on data type (float or double).
2083 static unsigned OpcTable[2][4] = {
2084 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2085 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002086 };
2087
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002088 unsigned *Opc = nullptr;
2089 switch (RetVT.SimpleTy) {
2090 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002091 case MVT::f32: Opc = &OpcTable[0][0]; break;
2092 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002093 }
2094
2095 const Value *LHS = I->getOperand(1);
2096 const Value *RHS = I->getOperand(2);
2097
2098 unsigned LHSReg = getRegForValue(LHS);
2099 bool LHSIsKill = hasTrivialKill(LHS);
2100
2101 unsigned RHSReg = getRegForValue(RHS);
2102 bool RHSIsKill = hasTrivialKill(RHS);
2103
2104 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2105 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2106
2107 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2108 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2109
2110 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2111 return false;
2112
2113 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002114 unsigned ResultReg;
2115
2116 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002117 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2118 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2119
Sanjay Patel302404b2015-03-05 21:46:54 +00002120 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2121 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2122 // uses XMM0 as the selection register. That may need just as many
2123 // instructions as the AND/ANDN/OR sequence due to register moves, so
2124 // don't bother.
2125 unsigned CmpOpcode =
2126 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2127 unsigned BlendOpcode =
2128 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2129
Matthias Braun818c78d2015-08-31 18:25:11 +00002130 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002131 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002132 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2133 LHSReg, LHSIsKill, CmpReg, true);
2134 ResultReg = createResultReg(RC);
2135 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2136 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002137 } else {
2138 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2139 CmpRHSReg, CmpRHSIsKill, CC);
2140 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2141 LHSReg, LHSIsKill);
2142 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2143 RHSReg, RHSIsKill);
2144 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2145 AndReg, /*IsKill=*/true);
2146 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002147 updateValueMap(I, ResultReg);
2148 return true;
2149}
2150
2151bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2152 // These are pseudo CMOV instructions and will be later expanded into control-
2153 // flow.
2154 unsigned Opc;
2155 switch (RetVT.SimpleTy) {
2156 default: return false;
2157 case MVT::i8: Opc = X86::CMOV_GR8; break;
2158 case MVT::i16: Opc = X86::CMOV_GR16; break;
2159 case MVT::i32: Opc = X86::CMOV_GR32; break;
2160 case MVT::f32: Opc = X86::CMOV_FR32; break;
2161 case MVT::f64: Opc = X86::CMOV_FR64; break;
2162 }
2163
2164 const Value *Cond = I->getOperand(0);
2165 X86::CondCode CC = X86::COND_NE;
2166
2167 // Optimize conditions coming from a compare if both instructions are in the
2168 // same basic block (values defined in other basic blocks may not have
2169 // initialized registers).
2170 const auto *CI = dyn_cast<CmpInst>(Cond);
2171 if (CI && (CI->getParent() == I->getParent())) {
2172 bool NeedSwap;
2173 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2174 if (CC > X86::LAST_VALID_COND)
2175 return false;
2176
2177 const Value *CmpLHS = CI->getOperand(0);
2178 const Value *CmpRHS = CI->getOperand(1);
2179
2180 if (NeedSwap)
2181 std::swap(CmpLHS, CmpRHS);
2182
Mehdi Amini44ede332015-07-09 02:09:04 +00002183 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002184 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2185 return false;
2186 } else {
2187 unsigned CondReg = getRegForValue(Cond);
2188 if (CondReg == 0)
2189 return false;
2190 bool CondIsKill = hasTrivialKill(Cond);
2191 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2192 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2193 }
2194
2195 const Value *LHS = I->getOperand(1);
2196 const Value *RHS = I->getOperand(2);
2197
2198 unsigned LHSReg = getRegForValue(LHS);
2199 bool LHSIsKill = hasTrivialKill(LHS);
2200
2201 unsigned RHSReg = getRegForValue(RHS);
2202 bool RHSIsKill = hasTrivialKill(RHS);
2203
2204 if (!LHSReg || !RHSReg)
2205 return false;
2206
2207 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2208
2209 unsigned ResultReg =
2210 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2211 updateValueMap(I, ResultReg);
2212 return true;
2213}
2214
2215bool X86FastISel::X86SelectSelect(const Instruction *I) {
2216 MVT RetVT;
2217 if (!isTypeLegal(I->getType(), RetVT))
2218 return false;
2219
2220 // Check if we can fold the select.
2221 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2222 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2223 const Value *Opnd = nullptr;
2224 switch (Predicate) {
2225 default: break;
2226 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2227 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2228 }
2229 // No need for a select anymore - this is an unconditional move.
2230 if (Opnd) {
2231 unsigned OpReg = getRegForValue(Opnd);
2232 if (OpReg == 0)
2233 return false;
2234 bool OpIsKill = hasTrivialKill(Opnd);
2235 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2236 unsigned ResultReg = createResultReg(RC);
2237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2238 TII.get(TargetOpcode::COPY), ResultReg)
2239 .addReg(OpReg, getKillRegState(OpIsKill));
2240 updateValueMap(I, ResultReg);
2241 return true;
2242 }
2243 }
2244
2245 // First try to use real conditional move instructions.
2246 if (X86FastEmitCMoveSelect(RetVT, I))
2247 return true;
2248
2249 // Try to use a sequence of SSE instructions to simulate a conditional move.
2250 if (X86FastEmitSSESelect(RetVT, I))
2251 return true;
2252
2253 // Fall-back to pseudo conditional move instructions, which will be later
2254 // converted to control-flow.
2255 if (X86FastEmitPseudoSelect(RetVT, I))
2256 return true;
2257
2258 return false;
2259}
2260
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002261bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002262 // The target-independent selection algorithm in FastISel already knows how
2263 // to select a SINT_TO_FP if the target is SSE but not AVX.
2264 // Early exit if the subtarget doesn't have AVX.
2265 if (!Subtarget->hasAVX())
2266 return false;
2267
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002268 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2269 return false;
2270
2271 // Select integer to float/double conversion.
2272 unsigned OpReg = getRegForValue(I->getOperand(0));
2273 if (OpReg == 0)
2274 return false;
2275
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002276 const TargetRegisterClass *RC = nullptr;
2277 unsigned Opcode;
2278
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002279 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002280 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002281 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002282 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002283 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002284 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002285 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002286 RC = &X86::FR32RegClass;
2287 } else
2288 return false;
2289
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002290 unsigned ImplicitDefReg = createResultReg(RC);
2291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2292 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2293 unsigned ResultReg =
2294 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002295 updateValueMap(I, ResultReg);
2296 return true;
2297}
2298
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002299// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2300bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2301 unsigned TargetOpc,
2302 const TargetRegisterClass *RC) {
2303 assert((I->getOpcode() == Instruction::FPExt ||
2304 I->getOpcode() == Instruction::FPTrunc) &&
2305 "Instruction must be an FPExt or FPTrunc!");
2306
2307 unsigned OpReg = getRegForValue(I->getOperand(0));
2308 if (OpReg == 0)
2309 return false;
2310
2311 unsigned ResultReg = createResultReg(RC);
2312 MachineInstrBuilder MIB;
2313 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2314 ResultReg);
2315 if (Subtarget->hasAVX())
2316 MIB.addReg(OpReg);
2317 MIB.addReg(OpReg);
2318 updateValueMap(I, ResultReg);
2319 return true;
2320}
2321
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002322bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002323 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2324 I->getOperand(0)->getType()->isFloatTy()) {
2325 // fpext from float to double.
2326 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2327 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002328 }
2329
2330 return false;
2331}
2332
2333bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002334 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2335 I->getOperand(0)->getType()->isDoubleTy()) {
2336 // fptrunc from double to float.
2337 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2338 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002339 }
2340
2341 return false;
2342}
2343
2344bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002345 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2346 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002347
2348 // This code only handles truncation to byte.
2349 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2350 return false;
2351 if (!TLI.isTypeLegal(SrcVT))
2352 return false;
2353
2354 unsigned InputReg = getRegForValue(I->getOperand(0));
2355 if (!InputReg)
2356 // Unhandled operand. Halt "fast" selection and bail.
2357 return false;
2358
2359 if (SrcVT == MVT::i8) {
2360 // Truncate from i8 to i1; no code needed.
2361 updateValueMap(I, InputReg);
2362 return true;
2363 }
2364
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002365 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002366 if (!Subtarget->is64Bit()) {
2367 // If we're on x86-32; we can't extract an i8 from a general register.
2368 // First issue a copy to GR16_ABCD or GR32_ABCD.
2369 const TargetRegisterClass *CopyRC =
2370 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2371 unsigned CopyReg = createResultReg(CopyRC);
2372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2373 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2374 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002375 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002376 }
2377
2378 // Issue an extract_subreg.
2379 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002380 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002381 X86::sub_8bit);
2382 if (!ResultReg)
2383 return false;
2384
2385 updateValueMap(I, ResultReg);
2386 return true;
2387}
2388
2389bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2390 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2391}
2392
2393bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2394 X86AddressMode SrcAM, uint64_t Len) {
2395
2396 // Make sure we don't bloat code by inlining very large memcpy's.
2397 if (!IsMemcpySmall(Len))
2398 return false;
2399
2400 bool i64Legal = Subtarget->is64Bit();
2401
2402 // We don't care about alignment here since we just emit integer accesses.
2403 while (Len) {
2404 MVT VT;
2405 if (Len >= 8 && i64Legal)
2406 VT = MVT::i64;
2407 else if (Len >= 4)
2408 VT = MVT::i32;
2409 else if (Len >= 2)
2410 VT = MVT::i16;
2411 else
2412 VT = MVT::i8;
2413
2414 unsigned Reg;
2415 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2416 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2417 assert(RV && "Failed to emit load or store??");
2418
2419 unsigned Size = VT.getSizeInBits()/8;
2420 Len -= Size;
2421 DestAM.Disp += Size;
2422 SrcAM.Disp += Size;
2423 }
2424
2425 return true;
2426}
2427
2428bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2429 // FIXME: Handle more intrinsics.
2430 switch (II->getIntrinsicID()) {
2431 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002432 case Intrinsic::convert_from_fp16:
2433 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002434 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002435 return false;
2436
2437 const Value *Op = II->getArgOperand(0);
2438 unsigned InputReg = getRegForValue(Op);
2439 if (InputReg == 0)
2440 return false;
2441
2442 // F16C only allows converting from float to half and from half to float.
2443 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2444 if (IsFloatToHalf) {
2445 if (!Op->getType()->isFloatTy())
2446 return false;
2447 } else {
2448 if (!II->getType()->isFloatTy())
2449 return false;
2450 }
2451
2452 unsigned ResultReg = 0;
2453 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2454 if (IsFloatToHalf) {
2455 // 'InputReg' is implicitly promoted from register class FR32 to
2456 // register class VR128 by method 'constrainOperandRegClass' which is
2457 // directly called by 'fastEmitInst_ri'.
2458 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002459 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2460 // It's consistent with the other FP instructions, which are usually
2461 // controlled by MXCSR.
2462 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002463
2464 // Move the lower 32-bits of ResultReg to another register of class GR32.
2465 ResultReg = createResultReg(&X86::GR32RegClass);
2466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2467 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2468 .addReg(InputReg, RegState::Kill);
2469
2470 // The result value is in the lower 16-bits of ResultReg.
2471 unsigned RegIdx = X86::sub_16bit;
2472 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2473 } else {
2474 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2475 // Explicitly sign-extend the input to 32-bit.
2476 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2477 /*Kill=*/false);
2478
2479 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2480 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2481 InputReg, /*Kill=*/true);
2482
2483 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2484
2485 // The result value is in the lower 32-bits of ResultReg.
2486 // Emit an explicit copy from register class VR128 to register class FR32.
2487 ResultReg = createResultReg(&X86::FR32RegClass);
2488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2489 TII.get(TargetOpcode::COPY), ResultReg)
2490 .addReg(InputReg, RegState::Kill);
2491 }
2492
2493 updateValueMap(II, ResultReg);
2494 return true;
2495 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002496 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002497 MachineFunction *MF = FuncInfo.MF;
2498 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2499 return false;
2500
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002501 Type *RetTy = II->getCalledFunction()->getReturnType();
2502
2503 MVT VT;
2504 if (!isTypeLegal(RetTy, VT))
2505 return false;
2506
2507 unsigned Opc;
2508 const TargetRegisterClass *RC = nullptr;
2509
2510 switch (VT.SimpleTy) {
2511 default: llvm_unreachable("Invalid result type for frameaddress.");
2512 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2513 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2514 }
2515
2516 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2517 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002518 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002519 MFI->setFrameAddressIsTaken(true);
2520
Eric Christophera1c535b2015-02-02 23:03:45 +00002521 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002522 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002523 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2524 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2525 "Invalid Frame Register!");
2526
2527 // Always make a copy of the frame register to to a vreg first, so that we
2528 // never directly reference the frame register (the TwoAddressInstruction-
2529 // Pass doesn't like that).
2530 unsigned SrcReg = createResultReg(RC);
2531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2532 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2533
2534 // Now recursively load from the frame address.
2535 // movq (%rbp), %rax
2536 // movq (%rax), %rax
2537 // movq (%rax), %rax
2538 // ...
2539 unsigned DestReg;
2540 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2541 while (Depth--) {
2542 DestReg = createResultReg(RC);
2543 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2544 TII.get(Opc), DestReg), SrcReg);
2545 SrcReg = DestReg;
2546 }
2547
2548 updateValueMap(II, SrcReg);
2549 return true;
2550 }
2551 case Intrinsic::memcpy: {
2552 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2553 // Don't handle volatile or variable length memcpys.
2554 if (MCI->isVolatile())
2555 return false;
2556
2557 if (isa<ConstantInt>(MCI->getLength())) {
2558 // Small memcpy's are common enough that we want to do them
2559 // without a call if possible.
2560 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2561 if (IsMemcpySmall(Len)) {
2562 X86AddressMode DestAM, SrcAM;
2563 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2564 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2565 return false;
2566 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2567 return true;
2568 }
2569 }
2570
2571 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2572 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2573 return false;
2574
2575 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2576 return false;
2577
Pete Cooper67cf9a72015-11-19 05:56:52 +00002578 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002579 }
2580 case Intrinsic::memset: {
2581 const MemSetInst *MSI = cast<MemSetInst>(II);
2582
2583 if (MSI->isVolatile())
2584 return false;
2585
2586 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2587 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2588 return false;
2589
2590 if (MSI->getDestAddressSpace() > 255)
2591 return false;
2592
Pete Cooper67cf9a72015-11-19 05:56:52 +00002593 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002594 }
2595 case Intrinsic::stackprotector: {
2596 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002597 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002598
2599 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2600 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2601
2602 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2603
2604 // Grab the frame index.
2605 X86AddressMode AM;
2606 if (!X86SelectAddress(Slot, AM)) return false;
2607 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2608 return true;
2609 }
2610 case Intrinsic::dbg_declare: {
2611 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2612 X86AddressMode AM;
2613 assert(DI->getAddress() && "Null address should be checked earlier!");
2614 if (!X86SelectAddress(DI->getAddress(), AM))
2615 return false;
2616 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2617 // FIXME may need to add RegState::Debug to any registers produced,
2618 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002619 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2620 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002621 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2622 .addImm(0)
2623 .addMetadata(DI->getVariable())
2624 .addMetadata(DI->getExpression());
2625 return true;
2626 }
2627 case Intrinsic::trap: {
2628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2629 return true;
2630 }
2631 case Intrinsic::sqrt: {
2632 if (!Subtarget->hasSSE1())
2633 return false;
2634
2635 Type *RetTy = II->getCalledFunction()->getReturnType();
2636
2637 MVT VT;
2638 if (!isTypeLegal(RetTy, VT))
2639 return false;
2640
2641 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2642 // is not generated by FastISel yet.
2643 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002644 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002645 {X86::SQRTSSr, X86::VSQRTSSr},
2646 {X86::SQRTSDr, X86::VSQRTSDr}
2647 };
2648 bool HasAVX = Subtarget->hasAVX();
2649 unsigned Opc;
2650 const TargetRegisterClass *RC;
2651 switch (VT.SimpleTy) {
2652 default: return false;
2653 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2654 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2655 }
2656
2657 const Value *SrcVal = II->getArgOperand(0);
2658 unsigned SrcReg = getRegForValue(SrcVal);
2659
2660 if (SrcReg == 0)
2661 return false;
2662
2663 unsigned ImplicitDefReg = 0;
2664 if (HasAVX) {
2665 ImplicitDefReg = createResultReg(RC);
2666 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2667 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2668 }
2669
2670 unsigned ResultReg = createResultReg(RC);
2671 MachineInstrBuilder MIB;
2672 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2673 ResultReg);
2674
2675 if (ImplicitDefReg)
2676 MIB.addReg(ImplicitDefReg);
2677
2678 MIB.addReg(SrcReg);
2679
2680 updateValueMap(II, ResultReg);
2681 return true;
2682 }
2683 case Intrinsic::sadd_with_overflow:
2684 case Intrinsic::uadd_with_overflow:
2685 case Intrinsic::ssub_with_overflow:
2686 case Intrinsic::usub_with_overflow:
2687 case Intrinsic::smul_with_overflow:
2688 case Intrinsic::umul_with_overflow: {
2689 // This implements the basic lowering of the xalu with overflow intrinsics
2690 // into add/sub/mul followed by either seto or setb.
2691 const Function *Callee = II->getCalledFunction();
2692 auto *Ty = cast<StructType>(Callee->getReturnType());
2693 Type *RetTy = Ty->getTypeAtIndex(0U);
2694 Type *CondTy = Ty->getTypeAtIndex(1);
2695
2696 MVT VT;
2697 if (!isTypeLegal(RetTy, VT))
2698 return false;
2699
2700 if (VT < MVT::i8 || VT > MVT::i64)
2701 return false;
2702
2703 const Value *LHS = II->getArgOperand(0);
2704 const Value *RHS = II->getArgOperand(1);
2705
2706 // Canonicalize immediate to the RHS.
2707 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2708 isCommutativeIntrinsic(II))
2709 std::swap(LHS, RHS);
2710
2711 bool UseIncDec = false;
2712 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2713 UseIncDec = true;
2714
2715 unsigned BaseOpc, CondOpc;
2716 switch (II->getIntrinsicID()) {
2717 default: llvm_unreachable("Unexpected intrinsic!");
2718 case Intrinsic::sadd_with_overflow:
2719 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2720 CondOpc = X86::SETOr;
2721 break;
2722 case Intrinsic::uadd_with_overflow:
2723 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2724 case Intrinsic::ssub_with_overflow:
2725 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2726 CondOpc = X86::SETOr;
2727 break;
2728 case Intrinsic::usub_with_overflow:
2729 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2730 case Intrinsic::smul_with_overflow:
2731 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2732 case Intrinsic::umul_with_overflow:
2733 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2734 }
2735
2736 unsigned LHSReg = getRegForValue(LHS);
2737 if (LHSReg == 0)
2738 return false;
2739 bool LHSIsKill = hasTrivialKill(LHS);
2740
2741 unsigned ResultReg = 0;
2742 // Check if we have an immediate version.
2743 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002744 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002745 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2746 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2747 };
2748
2749 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2750 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2751 bool IsDec = BaseOpc == X86ISD::DEC;
2752 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2753 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2754 .addReg(LHSReg, getKillRegState(LHSIsKill));
2755 } else
2756 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2757 CI->getZExtValue());
2758 }
2759
2760 unsigned RHSReg;
2761 bool RHSIsKill;
2762 if (!ResultReg) {
2763 RHSReg = getRegForValue(RHS);
2764 if (RHSReg == 0)
2765 return false;
2766 RHSIsKill = hasTrivialKill(RHS);
2767 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2768 RHSIsKill);
2769 }
2770
2771 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2772 // it manually.
2773 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002774 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002775 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002776 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002777 // First copy the first operand into RAX, which is an implicit input to
2778 // the X86::MUL*r instruction.
2779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2780 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2781 .addReg(LHSReg, getKillRegState(LHSIsKill));
2782 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2783 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2784 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002785 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002786 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2787 if (VT == MVT::i8) {
2788 // Copy the first operand into AL, which is an implicit input to the
2789 // X86::IMUL8r instruction.
2790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2791 TII.get(TargetOpcode::COPY), X86::AL)
2792 .addReg(LHSReg, getKillRegState(LHSIsKill));
2793 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2794 RHSIsKill);
2795 } else
2796 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2797 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2798 RHSReg, RHSIsKill);
2799 }
2800
2801 if (!ResultReg)
2802 return false;
2803
2804 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2805 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2806 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2807 ResultReg2);
2808
2809 updateValueMap(II, ResultReg, 2);
2810 return true;
2811 }
2812 case Intrinsic::x86_sse_cvttss2si:
2813 case Intrinsic::x86_sse_cvttss2si64:
2814 case Intrinsic::x86_sse2_cvttsd2si:
2815 case Intrinsic::x86_sse2_cvttsd2si64: {
2816 bool IsInputDouble;
2817 switch (II->getIntrinsicID()) {
2818 default: llvm_unreachable("Unexpected intrinsic.");
2819 case Intrinsic::x86_sse_cvttss2si:
2820 case Intrinsic::x86_sse_cvttss2si64:
2821 if (!Subtarget->hasSSE1())
2822 return false;
2823 IsInputDouble = false;
2824 break;
2825 case Intrinsic::x86_sse2_cvttsd2si:
2826 case Intrinsic::x86_sse2_cvttsd2si64:
2827 if (!Subtarget->hasSSE2())
2828 return false;
2829 IsInputDouble = true;
2830 break;
2831 }
2832
2833 Type *RetTy = II->getCalledFunction()->getReturnType();
2834 MVT VT;
2835 if (!isTypeLegal(RetTy, VT))
2836 return false;
2837
Craig Topper66111882016-06-02 04:19:42 +00002838 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002839 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2840 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2841 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2842 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2843 };
2844 bool HasAVX = Subtarget->hasAVX();
2845 unsigned Opc;
2846 switch (VT.SimpleTy) {
2847 default: llvm_unreachable("Unexpected result type.");
2848 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2849 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2850 }
2851
2852 // Check if we can fold insertelement instructions into the convert.
2853 const Value *Op = II->getArgOperand(0);
2854 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2855 const Value *Index = IE->getOperand(2);
2856 if (!isa<ConstantInt>(Index))
2857 break;
2858 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2859
2860 if (Idx == 0) {
2861 Op = IE->getOperand(1);
2862 break;
2863 }
2864 Op = IE->getOperand(0);
2865 }
2866
2867 unsigned Reg = getRegForValue(Op);
2868 if (Reg == 0)
2869 return false;
2870
2871 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2873 .addReg(Reg);
2874
2875 updateValueMap(II, ResultReg);
2876 return true;
2877 }
2878 }
2879}
2880
2881bool X86FastISel::fastLowerArguments() {
2882 if (!FuncInfo.CanLowerReturn)
2883 return false;
2884
2885 const Function *F = FuncInfo.Fn;
2886 if (F->isVarArg())
2887 return false;
2888
2889 CallingConv::ID CC = F->getCallingConv();
2890 if (CC != CallingConv::C)
2891 return false;
2892
2893 if (Subtarget->isCallingConvWin64(CC))
2894 return false;
2895
2896 if (!Subtarget->is64Bit())
2897 return false;
2898
2899 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2900 unsigned GPRCnt = 0;
2901 unsigned FPRCnt = 0;
2902 unsigned Idx = 0;
2903 for (auto const &Arg : F->args()) {
2904 // The first argument is at index 1.
2905 ++Idx;
2906 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2907 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2908 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002909 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002910 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002911 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2912 return false;
2913
2914 Type *ArgTy = Arg.getType();
2915 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2916 return false;
2917
Mehdi Amini44ede332015-07-09 02:09:04 +00002918 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002919 if (!ArgVT.isSimple()) return false;
2920 switch (ArgVT.getSimpleVT().SimpleTy) {
2921 default: return false;
2922 case MVT::i32:
2923 case MVT::i64:
2924 ++GPRCnt;
2925 break;
2926 case MVT::f32:
2927 case MVT::f64:
2928 if (!Subtarget->hasSSE1())
2929 return false;
2930 ++FPRCnt;
2931 break;
2932 }
2933
2934 if (GPRCnt > 6)
2935 return false;
2936
2937 if (FPRCnt > 8)
2938 return false;
2939 }
2940
2941 static const MCPhysReg GPR32ArgRegs[] = {
2942 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2943 };
2944 static const MCPhysReg GPR64ArgRegs[] = {
2945 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2946 };
2947 static const MCPhysReg XMMArgRegs[] = {
2948 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2949 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2950 };
2951
2952 unsigned GPRIdx = 0;
2953 unsigned FPRIdx = 0;
2954 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002955 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002956 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2957 unsigned SrcReg;
2958 switch (VT.SimpleTy) {
2959 default: llvm_unreachable("Unexpected value type.");
2960 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2961 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2962 case MVT::f32: // fall-through
2963 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2964 }
2965 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2966 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2967 // Without this, EmitLiveInCopies may eliminate the livein if its only
2968 // use is a bitcast (which isn't turned into an instruction).
2969 unsigned ResultReg = createResultReg(RC);
2970 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2971 TII.get(TargetOpcode::COPY), ResultReg)
2972 .addReg(DstReg, getKillRegState(true));
2973 updateValueMap(&Arg, ResultReg);
2974 }
2975 return true;
2976}
2977
2978static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2979 CallingConv::ID CC,
2980 ImmutableCallSite *CS) {
2981 if (Subtarget->is64Bit())
2982 return 0;
2983 if (Subtarget->getTargetTriple().isOSMSVCRT())
2984 return 0;
2985 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2986 CC == CallingConv::HiPE)
2987 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002988
2989 if (CS)
2990 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00002991 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002992 return 0;
2993
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002994 return 4;
2995}
2996
2997bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2998 auto &OutVals = CLI.OutVals;
2999 auto &OutFlags = CLI.OutFlags;
3000 auto &OutRegs = CLI.OutRegs;
3001 auto &Ins = CLI.Ins;
3002 auto &InRegs = CLI.InRegs;
3003 CallingConv::ID CC = CLI.CallConv;
3004 bool &IsTailCall = CLI.IsTailCall;
3005 bool IsVarArg = CLI.IsVarArg;
3006 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003007 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003008
3009 bool Is64Bit = Subtarget->is64Bit();
3010 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3011
3012 // Handle only C, fastcc, and webkit_js calling conventions for now.
3013 switch (CC) {
3014 default: return false;
3015 case CallingConv::C:
3016 case CallingConv::Fast:
3017 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003018 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003019 case CallingConv::X86_FastCall:
3020 case CallingConv::X86_64_Win64:
3021 case CallingConv::X86_64_SysV:
3022 break;
3023 }
3024
3025 // Allow SelectionDAG isel to handle tail calls.
3026 if (IsTailCall)
3027 return false;
3028
3029 // fastcc with -tailcallopt is intended to provide a guaranteed
3030 // tail call optimization. Fastisel doesn't know how to do that.
3031 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3032 return false;
3033
3034 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3035 // x86-32. Special handling for x86-64 is implemented.
3036 if (IsVarArg && IsWin64)
3037 return false;
3038
3039 // Don't know about inalloca yet.
3040 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3041 return false;
3042
Manman Ren57518142016-04-11 21:08:06 +00003043 for (auto Flag : CLI.OutFlags)
3044 if (Flag.isSwiftError())
3045 return false;
3046
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003047 // Fast-isel doesn't know about callee-pop yet.
3048 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3049 TM.Options.GuaranteedTailCallOpt))
3050 return false;
3051
3052 SmallVector<MVT, 16> OutVTs;
3053 SmallVector<unsigned, 16> ArgRegs;
3054
3055 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3056 // instruction. This is safe because it is common to all FastISel supported
3057 // calling conventions on x86.
3058 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3059 Value *&Val = OutVals[i];
3060 ISD::ArgFlagsTy Flags = OutFlags[i];
3061 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3062 if (CI->getBitWidth() < 32) {
3063 if (Flags.isSExt())
3064 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3065 else
3066 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3067 }
3068 }
3069
3070 // Passing bools around ends up doing a trunc to i1 and passing it.
3071 // Codegen this as an argument + "and 1".
3072 MVT VT;
3073 auto *TI = dyn_cast<TruncInst>(Val);
3074 unsigned ResultReg;
3075 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3076 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3077 TI->hasOneUse()) {
3078 Value *PrevVal = TI->getOperand(0);
3079 ResultReg = getRegForValue(PrevVal);
3080
3081 if (!ResultReg)
3082 return false;
3083
3084 if (!isTypeLegal(PrevVal->getType(), VT))
3085 return false;
3086
3087 ResultReg =
3088 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3089 } else {
3090 if (!isTypeLegal(Val->getType(), VT))
3091 return false;
3092 ResultReg = getRegForValue(Val);
3093 }
3094
3095 if (!ResultReg)
3096 return false;
3097
3098 ArgRegs.push_back(ResultReg);
3099 OutVTs.push_back(VT);
3100 }
3101
3102 // Analyze operands of the call, assigning locations to each operand.
3103 SmallVector<CCValAssign, 16> ArgLocs;
3104 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3105
3106 // Allocate shadow area for Win64
3107 if (IsWin64)
3108 CCInfo.AllocateStack(32, 8);
3109
3110 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3111
3112 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003113 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003114
3115 // Issue CALLSEQ_START
3116 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3117 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003118 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003119
3120 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003121 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003122 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3123 CCValAssign const &VA = ArgLocs[i];
3124 const Value *ArgVal = OutVals[VA.getValNo()];
3125 MVT ArgVT = OutVTs[VA.getValNo()];
3126
3127 if (ArgVT == MVT::x86mmx)
3128 return false;
3129
3130 unsigned ArgReg = ArgRegs[VA.getValNo()];
3131
3132 // Promote the value if needed.
3133 switch (VA.getLocInfo()) {
3134 case CCValAssign::Full: break;
3135 case CCValAssign::SExt: {
3136 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3137 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003138
3139 if (ArgVT.SimpleTy == MVT::i1)
3140 return false;
3141
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003142 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3143 ArgVT, ArgReg);
3144 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3145 ArgVT = VA.getLocVT();
3146 break;
3147 }
3148 case CCValAssign::ZExt: {
3149 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3150 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003151
3152 // Handle zero-extension from i1 to i8, which is common.
3153 if (ArgVT.SimpleTy == MVT::i1) {
3154 // Set the high bits to zero.
3155 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3156 ArgVT = MVT::i8;
3157
3158 if (ArgReg == 0)
3159 return false;
3160 }
3161
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003162 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3163 ArgVT, ArgReg);
3164 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3165 ArgVT = VA.getLocVT();
3166 break;
3167 }
3168 case CCValAssign::AExt: {
3169 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3170 "Unexpected extend");
3171 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3172 ArgVT, ArgReg);
3173 if (!Emitted)
3174 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3175 ArgVT, ArgReg);
3176 if (!Emitted)
3177 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3178 ArgVT, ArgReg);
3179
3180 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3181 ArgVT = VA.getLocVT();
3182 break;
3183 }
3184 case CCValAssign::BCvt: {
3185 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3186 /*TODO: Kill=*/false);
3187 assert(ArgReg && "Failed to emit a bitcast!");
3188 ArgVT = VA.getLocVT();
3189 break;
3190 }
3191 case CCValAssign::VExt:
3192 // VExt has not been implemented, so this should be impossible to reach
3193 // for now. However, fallback to Selection DAG isel once implemented.
3194 return false;
3195 case CCValAssign::AExtUpper:
3196 case CCValAssign::SExtUpper:
3197 case CCValAssign::ZExtUpper:
3198 case CCValAssign::FPExt:
3199 llvm_unreachable("Unexpected loc info!");
3200 case CCValAssign::Indirect:
3201 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3202 // support this.
3203 return false;
3204 }
3205
3206 if (VA.isRegLoc()) {
3207 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3208 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3209 OutRegs.push_back(VA.getLocReg());
3210 } else {
3211 assert(VA.isMemLoc());
3212
3213 // Don't emit stores for undef values.
3214 if (isa<UndefValue>(ArgVal))
3215 continue;
3216
3217 unsigned LocMemOffset = VA.getLocMemOffset();
3218 X86AddressMode AM;
3219 AM.Base.Reg = RegInfo->getStackRegister();
3220 AM.Disp = LocMemOffset;
3221 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3222 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3223 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003224 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3225 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003226 if (Flags.isByVal()) {
3227 X86AddressMode SrcAM;
3228 SrcAM.Base.Reg = ArgReg;
3229 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3230 return false;
3231 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3232 // If this is a really simple value, emit this with the Value* version
3233 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3234 // as it can cause us to reevaluate the argument.
3235 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3236 return false;
3237 } else {
3238 bool ValIsKill = hasTrivialKill(ArgVal);
3239 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3240 return false;
3241 }
3242 }
3243 }
3244
3245 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3246 // GOT pointer.
3247 if (Subtarget->isPICStyleGOT()) {
3248 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3250 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3251 }
3252
3253 if (Is64Bit && IsVarArg && !IsWin64) {
3254 // From AMD64 ABI document:
3255 // For calls that may call functions that use varargs or stdargs
3256 // (prototype-less calls or calls to functions containing ellipsis (...) in
3257 // the declaration) %al is used as hidden argument to specify the number
3258 // of SSE registers used. The contents of %al do not need to match exactly
3259 // the number of registers, but must be an ubound on the number of SSE
3260 // registers used and is in the range 0 - 8 inclusive.
3261
3262 // Count the number of XMM registers allocated.
3263 static const MCPhysReg XMMArgRegs[] = {
3264 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3265 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3266 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003267 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003268 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3269 && "SSE registers cannot be used when SSE is disabled");
3270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3271 X86::AL).addImm(NumXMMRegs);
3272 }
3273
3274 // Materialize callee address in a register. FIXME: GV address can be
3275 // handled with a CALLpcrel32 instead.
3276 X86AddressMode CalleeAM;
3277 if (!X86SelectCallAddress(Callee, CalleeAM))
3278 return false;
3279
3280 unsigned CalleeOp = 0;
3281 const GlobalValue *GV = nullptr;
3282 if (CalleeAM.GV != nullptr) {
3283 GV = CalleeAM.GV;
3284 } else if (CalleeAM.Base.Reg != 0) {
3285 CalleeOp = CalleeAM.Base.Reg;
3286 } else
3287 return false;
3288
3289 // Issue the call.
3290 MachineInstrBuilder MIB;
3291 if (CalleeOp) {
3292 // Register-indirect call.
3293 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3294 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3295 .addReg(CalleeOp);
3296 } else {
3297 // Direct call.
3298 assert(GV && "Not a direct call");
3299 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3300
3301 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003302 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003303 // Ignore NonLazyBind attribute in FastISel
3304 if (OpFlags == X86II::MO_GOTPCREL)
3305 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003306
3307 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003308 if (Symbol)
3309 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003310 else
3311 MIB.addGlobalAddress(GV, 0, OpFlags);
3312 }
3313
3314 // Add a register mask operand representing the call-preserved registers.
3315 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003316 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003317
3318 // Add an implicit use GOT pointer in EBX.
3319 if (Subtarget->isPICStyleGOT())
3320 MIB.addReg(X86::EBX, RegState::Implicit);
3321
3322 if (Is64Bit && IsVarArg && !IsWin64)
3323 MIB.addReg(X86::AL, RegState::Implicit);
3324
3325 // Add implicit physical register uses to the call.
3326 for (auto Reg : OutRegs)
3327 MIB.addReg(Reg, RegState::Implicit);
3328
3329 // Issue CALLSEQ_END
3330 unsigned NumBytesForCalleeToPop =
3331 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3332 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3334 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3335
3336 // Now handle call return values.
3337 SmallVector<CCValAssign, 16> RVLocs;
3338 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3339 CLI.RetTy->getContext());
3340 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3341
3342 // Copy all of the result registers out of their specified physreg.
3343 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3344 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3345 CCValAssign &VA = RVLocs[i];
3346 EVT CopyVT = VA.getValVT();
3347 unsigned CopyReg = ResultReg + i;
3348
3349 // If this is x86-64, and we disabled SSE, we can't return FP values
3350 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3351 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3352 report_fatal_error("SSE register return with SSE disabled");
3353 }
3354
3355 // If we prefer to use the value in xmm registers, copy it out as f80 and
3356 // use a truncate to move it from fp stack reg to xmm reg.
3357 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3358 isScalarFPTypeInSSEReg(VA.getValVT())) {
3359 CopyVT = MVT::f80;
3360 CopyReg = createResultReg(&X86::RFP80RegClass);
3361 }
3362
3363 // Copy out the result.
3364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3365 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3366 InRegs.push_back(VA.getLocReg());
3367
3368 // Round the f80 to the right size, which also moves it to the appropriate
3369 // xmm register. This is accomplished by storing the f80 value in memory
3370 // and then loading it back.
3371 if (CopyVT != VA.getValVT()) {
3372 EVT ResVT = VA.getValVT();
3373 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3374 unsigned MemSize = ResVT.getSizeInBits()/8;
3375 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3376 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3377 TII.get(Opc)), FI)
3378 .addReg(CopyReg);
3379 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3380 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3381 TII.get(Opc), ResultReg + i), FI);
3382 }
3383 }
3384
3385 CLI.ResultReg = ResultReg;
3386 CLI.NumResultRegs = RVLocs.size();
3387 CLI.Call = MIB;
3388
3389 return true;
3390}
3391
3392bool
3393X86FastISel::fastSelectInstruction(const Instruction *I) {
3394 switch (I->getOpcode()) {
3395 default: break;
3396 case Instruction::Load:
3397 return X86SelectLoad(I);
3398 case Instruction::Store:
3399 return X86SelectStore(I);
3400 case Instruction::Ret:
3401 return X86SelectRet(I);
3402 case Instruction::ICmp:
3403 case Instruction::FCmp:
3404 return X86SelectCmp(I);
3405 case Instruction::ZExt:
3406 return X86SelectZExt(I);
3407 case Instruction::Br:
3408 return X86SelectBranch(I);
3409 case Instruction::LShr:
3410 case Instruction::AShr:
3411 case Instruction::Shl:
3412 return X86SelectShift(I);
3413 case Instruction::SDiv:
3414 case Instruction::UDiv:
3415 case Instruction::SRem:
3416 case Instruction::URem:
3417 return X86SelectDivRem(I);
3418 case Instruction::Select:
3419 return X86SelectSelect(I);
3420 case Instruction::Trunc:
3421 return X86SelectTrunc(I);
3422 case Instruction::FPExt:
3423 return X86SelectFPExt(I);
3424 case Instruction::FPTrunc:
3425 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003426 case Instruction::SIToFP:
3427 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003428 case Instruction::IntToPtr: // Deliberate fall-through.
3429 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003430 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3431 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003432 if (DstVT.bitsGT(SrcVT))
3433 return X86SelectZExt(I);
3434 if (DstVT.bitsLT(SrcVT))
3435 return X86SelectTrunc(I);
3436 unsigned Reg = getRegForValue(I->getOperand(0));
3437 if (Reg == 0) return false;
3438 updateValueMap(I, Reg);
3439 return true;
3440 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003441 case Instruction::BitCast: {
3442 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3443 if (!Subtarget->hasSSE2())
3444 return false;
3445
3446 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3447 EVT DstVT = TLI.getValueType(DL, I->getType());
3448
3449 if (!SrcVT.isSimple() || !DstVT.isSimple())
3450 return false;
3451
3452 if (!SrcVT.is128BitVector() &&
3453 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3454 return false;
3455
3456 unsigned Reg = getRegForValue(I->getOperand(0));
3457 if (Reg == 0)
3458 return false;
3459
3460 // No instruction is needed for conversion. Reuse the register used by
3461 // the fist operand.
3462 updateValueMap(I, Reg);
3463 return true;
3464 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003465 }
3466
3467 return false;
3468}
3469
3470unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3471 if (VT > MVT::i64)
3472 return 0;
3473
3474 uint64_t Imm = CI->getZExtValue();
3475 if (Imm == 0) {
3476 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3477 switch (VT.SimpleTy) {
3478 default: llvm_unreachable("Unexpected value type");
3479 case MVT::i1:
3480 case MVT::i8:
3481 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3482 X86::sub_8bit);
3483 case MVT::i16:
3484 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3485 X86::sub_16bit);
3486 case MVT::i32:
3487 return SrcReg;
3488 case MVT::i64: {
3489 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3491 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3492 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3493 return ResultReg;
3494 }
3495 }
3496 }
3497
3498 unsigned Opc = 0;
3499 switch (VT.SimpleTy) {
3500 default: llvm_unreachable("Unexpected value type");
3501 case MVT::i1: VT = MVT::i8; // fall-through
3502 case MVT::i8: Opc = X86::MOV8ri; break;
3503 case MVT::i16: Opc = X86::MOV16ri; break;
3504 case MVT::i32: Opc = X86::MOV32ri; break;
3505 case MVT::i64: {
3506 if (isUInt<32>(Imm))
3507 Opc = X86::MOV32ri;
3508 else if (isInt<32>(Imm))
3509 Opc = X86::MOV64ri32;
3510 else
3511 Opc = X86::MOV64ri;
3512 break;
3513 }
3514 }
3515 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3516 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3517 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3519 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3520 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3521 return ResultReg;
3522 }
3523 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3524}
3525
3526unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3527 if (CFP->isNullValue())
3528 return fastMaterializeFloatZero(CFP);
3529
3530 // Can't handle alternate code models yet.
3531 CodeModel::Model CM = TM.getCodeModel();
3532 if (CM != CodeModel::Small && CM != CodeModel::Large)
3533 return 0;
3534
3535 // Get opcode and regclass of the output for the given load instruction.
3536 unsigned Opc = 0;
3537 const TargetRegisterClass *RC = nullptr;
3538 switch (VT.SimpleTy) {
3539 default: return 0;
3540 case MVT::f32:
3541 if (X86ScalarSSEf32) {
3542 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3543 RC = &X86::FR32RegClass;
3544 } else {
3545 Opc = X86::LD_Fp32m;
3546 RC = &X86::RFP32RegClass;
3547 }
3548 break;
3549 case MVT::f64:
3550 if (X86ScalarSSEf64) {
3551 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3552 RC = &X86::FR64RegClass;
3553 } else {
3554 Opc = X86::LD_Fp64m;
3555 RC = &X86::RFP64RegClass;
3556 }
3557 break;
3558 case MVT::f80:
3559 // No f80 support yet.
3560 return 0;
3561 }
3562
3563 // MachineConstantPool wants an explicit alignment.
3564 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3565 if (Align == 0) {
3566 // Alignment of vector types. FIXME!
3567 Align = DL.getTypeAllocSize(CFP->getType());
3568 }
3569
3570 // x86-32 PIC requires a PIC base register for constant pools.
3571 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003572 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3573 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003574 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003575 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003576 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003577 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003578 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003579
3580 // Create the load from the constant pool.
3581 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3582 unsigned ResultReg = createResultReg(RC);
3583
3584 if (CM == CodeModel::Large) {
3585 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3586 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3587 AddrReg)
3588 .addConstantPoolIndex(CPI, 0, OpFlag);
3589 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3590 TII.get(Opc), ResultReg);
3591 addDirectMem(MIB, AddrReg);
3592 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003593 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3594 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003595 MIB->addMemOperand(*FuncInfo.MF, MMO);
3596 return ResultReg;
3597 }
3598
3599 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3600 TII.get(Opc), ResultReg),
3601 CPI, PICBase, OpFlag);
3602 return ResultReg;
3603}
3604
3605unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3606 // Can't handle alternate code models yet.
3607 if (TM.getCodeModel() != CodeModel::Small)
3608 return 0;
3609
3610 // Materialize addresses with LEA/MOV instructions.
3611 X86AddressMode AM;
3612 if (X86SelectAddress(GV, AM)) {
3613 // If the expression is just a basereg, then we're done, otherwise we need
3614 // to emit an LEA.
3615 if (AM.BaseType == X86AddressMode::RegBase &&
3616 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3617 return AM.Base.Reg;
3618
3619 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3620 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003621 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003622 // The displacement code could be more than 32 bits away so we need to use
3623 // an instruction with a 64 bit immediate
3624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3625 ResultReg)
3626 .addGlobalAddress(GV);
3627 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003628 unsigned Opc =
3629 TLI.getPointerTy(DL) == MVT::i32
3630 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3631 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003632 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3633 TII.get(Opc), ResultReg), AM);
3634 }
3635 return ResultReg;
3636 }
3637 return 0;
3638}
3639
3640unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003641 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003642
3643 // Only handle simple types.
3644 if (!CEVT.isSimple())
3645 return 0;
3646 MVT VT = CEVT.getSimpleVT();
3647
3648 if (const auto *CI = dyn_cast<ConstantInt>(C))
3649 return X86MaterializeInt(CI, VT);
3650 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3651 return X86MaterializeFP(CFP, VT);
3652 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3653 return X86MaterializeGV(GV, VT);
3654
3655 return 0;
3656}
3657
3658unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3659 // Fail on dynamic allocas. At this point, getRegForValue has already
3660 // checked its CSE maps, so if we're here trying to handle a dynamic
3661 // alloca, we're not going to succeed. X86SelectAddress has a
3662 // check for dynamic allocas, because it's called directly from
3663 // various places, but targetMaterializeAlloca also needs a check
3664 // in order to avoid recursion between getRegForValue,
3665 // X86SelectAddrss, and targetMaterializeAlloca.
3666 if (!FuncInfo.StaticAllocaMap.count(C))
3667 return 0;
3668 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3669
3670 X86AddressMode AM;
3671 if (!X86SelectAddress(C, AM))
3672 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003673 unsigned Opc =
3674 TLI.getPointerTy(DL) == MVT::i32
3675 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3676 : X86::LEA64r;
3677 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003678 unsigned ResultReg = createResultReg(RC);
3679 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3680 TII.get(Opc), ResultReg), AM);
3681 return ResultReg;
3682}
3683
3684unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3685 MVT VT;
3686 if (!isTypeLegal(CF->getType(), VT))
3687 return 0;
3688
3689 // Get opcode and regclass for the given zero.
3690 unsigned Opc = 0;
3691 const TargetRegisterClass *RC = nullptr;
3692 switch (VT.SimpleTy) {
3693 default: return 0;
3694 case MVT::f32:
3695 if (X86ScalarSSEf32) {
3696 Opc = X86::FsFLD0SS;
3697 RC = &X86::FR32RegClass;
3698 } else {
3699 Opc = X86::LD_Fp032;
3700 RC = &X86::RFP32RegClass;
3701 }
3702 break;
3703 case MVT::f64:
3704 if (X86ScalarSSEf64) {
3705 Opc = X86::FsFLD0SD;
3706 RC = &X86::FR64RegClass;
3707 } else {
3708 Opc = X86::LD_Fp064;
3709 RC = &X86::RFP64RegClass;
3710 }
3711 break;
3712 case MVT::f80:
3713 // No f80 support yet.
3714 return 0;
3715 }
3716
3717 unsigned ResultReg = createResultReg(RC);
3718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3719 return ResultReg;
3720}
3721
3722
3723bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3724 const LoadInst *LI) {
3725 const Value *Ptr = LI->getPointerOperand();
3726 X86AddressMode AM;
3727 if (!X86SelectAddress(Ptr, AM))
3728 return false;
3729
3730 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3731
3732 unsigned Size = DL.getTypeAllocSize(LI->getType());
3733 unsigned Alignment = LI->getAlignment();
3734
3735 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3736 Alignment = DL.getABITypeAlignment(LI->getType());
3737
3738 SmallVector<MachineOperand, 8> AddrOps;
3739 AM.getFullAddress(AddrOps);
3740
Keno Fischere70b31f2015-06-08 20:09:58 +00003741 MachineInstr *Result = XII.foldMemoryOperandImpl(
3742 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3743 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003744 if (!Result)
3745 return false;
3746
Pete Cooperd31583d2015-05-06 21:37:19 +00003747 // The index register could be in the wrong register class. Unfortunately,
3748 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3749 // to just look at OpNo + the offset to the index reg. We actually need to
3750 // scan the instruction to find the index reg and see if its the correct reg
3751 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003752 unsigned OperandNo = 0;
3753 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3754 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3755 MachineOperand &MO = *I;
3756 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003757 continue;
3758 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003759 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003760 MO.getReg(), OperandNo);
3761 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003762 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003763 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003764 }
3765
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003766 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003767 MI->eraseFromParent();
3768 return true;
3769}
3770
3771
3772namespace llvm {
3773 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3774 const TargetLibraryInfo *libInfo) {
3775 return new X86FastISel(funcInfo, libInfo);
3776 }
3777}