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