blob: 697bd8aace76719fe9b3b16c223363bd16730067 [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) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000351 // Get opcode and regclass of the output for the given load instruction.
352 unsigned Opc = 0;
353 const TargetRegisterClass *RC = nullptr;
354 switch (VT.getSimpleVT().SimpleTy) {
355 default: return false;
356 case MVT::i1:
357 case MVT::i8:
358 Opc = X86::MOV8rm;
359 RC = &X86::GR8RegClass;
360 break;
361 case MVT::i16:
362 Opc = X86::MOV16rm;
363 RC = &X86::GR16RegClass;
364 break;
365 case MVT::i32:
366 Opc = X86::MOV32rm;
367 RC = &X86::GR32RegClass;
368 break;
369 case MVT::i64:
370 // Must be in x86-64 mode.
371 Opc = X86::MOV64rm;
372 RC = &X86::GR64RegClass;
373 break;
374 case MVT::f32:
375 if (X86ScalarSSEf32) {
376 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
377 RC = &X86::FR32RegClass;
378 } else {
379 Opc = X86::LD_Fp32m;
380 RC = &X86::RFP32RegClass;
381 }
382 break;
383 case MVT::f64:
384 if (X86ScalarSSEf64) {
385 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
386 RC = &X86::FR64RegClass;
387 } else {
388 Opc = X86::LD_Fp64m;
389 RC = &X86::RFP64RegClass;
390 }
391 break;
392 case MVT::f80:
393 // No f80 support yet.
394 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000395 case MVT::v4f32:
396 if (Alignment >= 16)
397 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
398 else
399 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
400 RC = &X86::VR128RegClass;
401 break;
402 case MVT::v2f64:
403 if (Alignment >= 16)
404 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
405 else
406 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
407 RC = &X86::VR128RegClass;
408 break;
409 case MVT::v4i32:
410 case MVT::v2i64:
411 case MVT::v8i16:
412 case MVT::v16i8:
413 if (Alignment >= 16)
414 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
415 else
416 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
417 RC = &X86::VR128RegClass;
418 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000419 }
420
421 ResultReg = createResultReg(RC);
422 MachineInstrBuilder MIB =
423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
424 addFullAddress(MIB, AM);
425 if (MMO)
426 MIB->addMemOperand(*FuncInfo.MF, MMO);
427 return true;
428}
429
430/// X86FastEmitStore - Emit a machine instruction to store a value Val of
431/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
432/// and a displacement offset, or a GlobalAddress,
433/// i.e. V. Return true if it is possible.
434bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000435 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000436 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000437 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000438 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000439 bool HasAVX = Subtarget->hasAVX();
440 bool IsNonTemporal = MMO && MMO->isNonTemporal();
441
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000442 // Get opcode and regclass of the output for the given store instruction.
443 unsigned Opc = 0;
444 switch (VT.getSimpleVT().SimpleTy) {
445 case MVT::f80: // No f80 support yet.
446 default: return false;
447 case MVT::i1: {
448 // Mask out all but lowest bit.
449 unsigned AndResult = createResultReg(&X86::GR8RegClass);
450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
451 TII.get(X86::AND8ri), AndResult)
452 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
453 ValReg = AndResult;
454 }
455 // FALLTHROUGH, handling i1 as i8.
456 case MVT::i8: Opc = X86::MOV8mr; break;
457 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000458 case MVT::i32:
459 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
460 break;
461 case MVT::i64:
462 // Must be in x86-64 mode.
463 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
464 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000465 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000466 if (X86ScalarSSEf32) {
467 if (IsNonTemporal && HasSSE4A)
468 Opc = X86::MOVNTSS;
469 else
470 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
471 } else
472 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000473 break;
474 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000475 if (X86ScalarSSEf32) {
476 if (IsNonTemporal && HasSSE4A)
477 Opc = X86::MOVNTSD;
478 else
479 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
480 } else
481 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000482 break;
483 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000484 if (Aligned) {
485 if (IsNonTemporal)
486 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
487 else
488 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
489 } else
490 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000491 break;
492 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000493 if (Aligned) {
494 if (IsNonTemporal)
495 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
496 else
497 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
498 } else
499 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000500 break;
501 case MVT::v4i32:
502 case MVT::v2i64:
503 case MVT::v8i16:
504 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000505 if (Aligned) {
506 if (IsNonTemporal)
507 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
508 else
509 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
510 } else
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000511 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
512 break;
513 }
514
515 MachineInstrBuilder MIB =
516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
517 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
518 if (MMO)
519 MIB->addMemOperand(*FuncInfo.MF, MMO);
520
521 return true;
522}
523
524bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000525 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000526 MachineMemOperand *MMO, bool Aligned) {
527 // Handle 'null' like i32/i64 0.
528 if (isa<ConstantPointerNull>(Val))
529 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
530
531 // If this is a store of a simple constant, fold the constant into the store.
532 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
533 unsigned Opc = 0;
534 bool Signed = true;
535 switch (VT.getSimpleVT().SimpleTy) {
536 default: break;
537 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
538 case MVT::i8: Opc = X86::MOV8mi; break;
539 case MVT::i16: Opc = X86::MOV16mi; break;
540 case MVT::i32: Opc = X86::MOV32mi; break;
541 case MVT::i64:
542 // Must be a 32-bit sign extended value.
543 if (isInt<32>(CI->getSExtValue()))
544 Opc = X86::MOV64mi32;
545 break;
546 }
547
548 if (Opc) {
549 MachineInstrBuilder MIB =
550 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
551 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
552 : CI->getZExtValue());
553 if (MMO)
554 MIB->addMemOperand(*FuncInfo.MF, MMO);
555 return true;
556 }
557 }
558
559 unsigned ValReg = getRegForValue(Val);
560 if (ValReg == 0)
561 return false;
562
563 bool ValKill = hasTrivialKill(Val);
564 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
565}
566
567/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
568/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
569/// ISD::SIGN_EXTEND).
570bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
571 unsigned Src, EVT SrcVT,
572 unsigned &ResultReg) {
573 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
574 Src, /*TODO: Kill=*/false);
575 if (RR == 0)
576 return false;
577
578 ResultReg = RR;
579 return true;
580}
581
582bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
583 // Handle constant address.
584 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
585 // Can't handle alternate code models yet.
586 if (TM.getCodeModel() != CodeModel::Small)
587 return false;
588
589 // Can't handle TLS yet.
590 if (GV->isThreadLocal())
591 return false;
592
593 // RIP-relative addresses can't have additional register operands, so if
594 // we've already folded stuff into the addressing mode, just force the
595 // global value into its own register, which we can use as the basereg.
596 if (!Subtarget->isPICStyleRIPRel() ||
597 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
598 // Okay, we've committed to selecting this global. Set up the address.
599 AM.GV = GV;
600
601 // Allow the subtarget to classify the global.
602 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
603
604 // If this reference is relative to the pic base, set it now.
605 if (isGlobalRelativeToPICBase(GVFlags)) {
606 // FIXME: How do we know Base.Reg is free??
607 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
608 }
609
610 // Unless the ABI requires an extra load, return a direct reference to
611 // the global.
612 if (!isGlobalStubReference(GVFlags)) {
613 if (Subtarget->isPICStyleRIPRel()) {
614 // Use rip-relative addressing if we can. Above we verified that the
615 // base and index registers are unused.
616 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
617 AM.Base.Reg = X86::RIP;
618 }
619 AM.GVOpFlags = GVFlags;
620 return true;
621 }
622
623 // Ok, we need to do a load from a stub. If we've already loaded from
624 // this stub, reuse the loaded pointer, otherwise emit the load now.
625 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
626 unsigned LoadReg;
627 if (I != LocalValueMap.end() && I->second != 0) {
628 LoadReg = I->second;
629 } else {
630 // Issue load from stub.
631 unsigned Opc = 0;
632 const TargetRegisterClass *RC = nullptr;
633 X86AddressMode StubAM;
634 StubAM.Base.Reg = AM.Base.Reg;
635 StubAM.GV = GV;
636 StubAM.GVOpFlags = GVFlags;
637
638 // Prepare for inserting code in the local-value area.
639 SavePoint SaveInsertPt = enterLocalValueArea();
640
Mehdi Amini44ede332015-07-09 02:09:04 +0000641 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000642 Opc = X86::MOV64rm;
643 RC = &X86::GR64RegClass;
644
645 if (Subtarget->isPICStyleRIPRel())
646 StubAM.Base.Reg = X86::RIP;
647 } else {
648 Opc = X86::MOV32rm;
649 RC = &X86::GR32RegClass;
650 }
651
652 LoadReg = createResultReg(RC);
653 MachineInstrBuilder LoadMI =
654 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
655 addFullAddress(LoadMI, StubAM);
656
657 // Ok, back to normal mode.
658 leaveLocalValueArea(SaveInsertPt);
659
660 // Prevent loading GV stub multiple times in same MBB.
661 LocalValueMap[V] = LoadReg;
662 }
663
664 // Now construct the final address. Note that the Disp, Scale,
665 // and Index values may already be set here.
666 AM.Base.Reg = LoadReg;
667 AM.GV = nullptr;
668 return true;
669 }
670 }
671
672 // If all else fails, try to materialize the value in a register.
673 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
674 if (AM.Base.Reg == 0) {
675 AM.Base.Reg = getRegForValue(V);
676 return AM.Base.Reg != 0;
677 }
678 if (AM.IndexReg == 0) {
679 assert(AM.Scale == 1 && "Scale with no index!");
680 AM.IndexReg = getRegForValue(V);
681 return AM.IndexReg != 0;
682 }
683 }
684
685 return false;
686}
687
688/// X86SelectAddress - Attempt to fill in an address from the given value.
689///
690bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
691 SmallVector<const Value *, 32> GEPs;
692redo_gep:
693 const User *U = nullptr;
694 unsigned Opcode = Instruction::UserOp1;
695 if (const Instruction *I = dyn_cast<Instruction>(V)) {
696 // Don't walk into other basic blocks; it's possible we haven't
697 // visited them yet, so the instructions may not yet be assigned
698 // virtual registers.
699 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
700 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
701 Opcode = I->getOpcode();
702 U = I;
703 }
704 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
705 Opcode = C->getOpcode();
706 U = C;
707 }
708
709 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
710 if (Ty->getAddressSpace() > 255)
711 // Fast instruction selection doesn't support the special
712 // address spaces.
713 return false;
714
715 switch (Opcode) {
716 default: break;
717 case Instruction::BitCast:
718 // Look past bitcasts.
719 return X86SelectAddress(U->getOperand(0), AM);
720
721 case Instruction::IntToPtr:
722 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000723 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
724 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000725 return X86SelectAddress(U->getOperand(0), AM);
726 break;
727
728 case Instruction::PtrToInt:
729 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000730 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000731 return X86SelectAddress(U->getOperand(0), AM);
732 break;
733
734 case Instruction::Alloca: {
735 // Do static allocas.
736 const AllocaInst *A = cast<AllocaInst>(V);
737 DenseMap<const AllocaInst *, int>::iterator SI =
738 FuncInfo.StaticAllocaMap.find(A);
739 if (SI != FuncInfo.StaticAllocaMap.end()) {
740 AM.BaseType = X86AddressMode::FrameIndexBase;
741 AM.Base.FrameIndex = SI->second;
742 return true;
743 }
744 break;
745 }
746
747 case Instruction::Add: {
748 // Adds of constants are common and easy enough.
749 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
750 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
751 // They have to fit in the 32-bit signed displacement field though.
752 if (isInt<32>(Disp)) {
753 AM.Disp = (uint32_t)Disp;
754 return X86SelectAddress(U->getOperand(0), AM);
755 }
756 }
757 break;
758 }
759
760 case Instruction::GetElementPtr: {
761 X86AddressMode SavedAM = AM;
762
763 // Pattern-match simple GEPs.
764 uint64_t Disp = (int32_t)AM.Disp;
765 unsigned IndexReg = AM.IndexReg;
766 unsigned Scale = AM.Scale;
767 gep_type_iterator GTI = gep_type_begin(U);
768 // Iterate through the indices, folding what we can. Constants can be
769 // folded, and one dynamic index can be handled, if the scale is supported.
770 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
771 i != e; ++i, ++GTI) {
772 const Value *Op = *i;
773 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
774 const StructLayout *SL = DL.getStructLayout(STy);
775 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
776 continue;
777 }
778
779 // A array/variable index is always of the form i*S where S is the
780 // constant scale size. See if we can push the scale into immediates.
781 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
782 for (;;) {
783 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
784 // Constant-offset addressing.
785 Disp += CI->getSExtValue() * S;
786 break;
787 }
788 if (canFoldAddIntoGEP(U, Op)) {
789 // A compatible add with a constant operand. Fold the constant.
790 ConstantInt *CI =
791 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
792 Disp += CI->getSExtValue() * S;
793 // Iterate on the other operand.
794 Op = cast<AddOperator>(Op)->getOperand(0);
795 continue;
796 }
797 if (IndexReg == 0 &&
798 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
799 (S == 1 || S == 2 || S == 4 || S == 8)) {
800 // Scaled-index addressing.
801 Scale = S;
802 IndexReg = getRegForGEPIndex(Op).first;
803 if (IndexReg == 0)
804 return false;
805 break;
806 }
807 // Unsupported.
808 goto unsupported_gep;
809 }
810 }
811
812 // Check for displacement overflow.
813 if (!isInt<32>(Disp))
814 break;
815
816 AM.IndexReg = IndexReg;
817 AM.Scale = Scale;
818 AM.Disp = (uint32_t)Disp;
819 GEPs.push_back(V);
820
821 if (const GetElementPtrInst *GEP =
822 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
823 // Ok, the GEP indices were covered by constant-offset and scaled-index
824 // addressing. Update the address state and move on to examining the base.
825 V = GEP;
826 goto redo_gep;
827 } else if (X86SelectAddress(U->getOperand(0), AM)) {
828 return true;
829 }
830
831 // If we couldn't merge the gep value into this addr mode, revert back to
832 // our address and just match the value instead of completely failing.
833 AM = SavedAM;
834
835 for (SmallVectorImpl<const Value *>::reverse_iterator
836 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
837 if (handleConstantAddresses(*I, AM))
838 return true;
839
840 return false;
841 unsupported_gep:
842 // Ok, the GEP indices weren't all covered.
843 break;
844 }
845 }
846
847 return handleConstantAddresses(V, AM);
848}
849
850/// X86SelectCallAddress - Attempt to fill in an address from the given value.
851///
852bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
853 const User *U = nullptr;
854 unsigned Opcode = Instruction::UserOp1;
855 const Instruction *I = dyn_cast<Instruction>(V);
856 // Record if the value is defined in the same basic block.
857 //
858 // This information is crucial to know whether or not folding an
859 // operand is valid.
860 // Indeed, FastISel generates or reuses a virtual register for all
861 // operands of all instructions it selects. Obviously, the definition and
862 // its uses must use the same virtual register otherwise the produced
863 // code is incorrect.
864 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
865 // registers for values that are alive across basic blocks. This ensures
866 // that the values are consistently set between across basic block, even
867 // if different instruction selection mechanisms are used (e.g., a mix of
868 // SDISel and FastISel).
869 // For values local to a basic block, the instruction selection process
870 // generates these virtual registers with whatever method is appropriate
871 // for its needs. In particular, FastISel and SDISel do not share the way
872 // local virtual registers are set.
873 // Therefore, this is impossible (or at least unsafe) to share values
874 // between basic blocks unless they use the same instruction selection
875 // method, which is not guarantee for X86.
876 // Moreover, things like hasOneUse could not be used accurately, if we
877 // allow to reference values across basic blocks whereas they are not
878 // alive across basic blocks initially.
879 bool InMBB = true;
880 if (I) {
881 Opcode = I->getOpcode();
882 U = I;
883 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
884 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
885 Opcode = C->getOpcode();
886 U = C;
887 }
888
889 switch (Opcode) {
890 default: break;
891 case Instruction::BitCast:
892 // Look past bitcasts if its operand is in the same BB.
893 if (InMBB)
894 return X86SelectCallAddress(U->getOperand(0), AM);
895 break;
896
897 case Instruction::IntToPtr:
898 // Look past no-op inttoptrs if its operand is in the same BB.
899 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +0000900 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
901 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000902 return X86SelectCallAddress(U->getOperand(0), AM);
903 break;
904
905 case Instruction::PtrToInt:
906 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +0000907 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000908 return X86SelectCallAddress(U->getOperand(0), AM);
909 break;
910 }
911
912 // Handle constant address.
913 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
914 // Can't handle alternate code models yet.
915 if (TM.getCodeModel() != CodeModel::Small)
916 return false;
917
918 // RIP-relative addresses can't have additional register operands.
919 if (Subtarget->isPICStyleRIPRel() &&
920 (AM.Base.Reg != 0 || AM.IndexReg != 0))
921 return false;
922
923 // Can't handle DLL Import.
924 if (GV->hasDLLImportStorageClass())
925 return false;
926
927 // Can't handle TLS.
928 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
929 if (GVar->isThreadLocal())
930 return false;
931
932 // Okay, we've committed to selecting this global. Set up the basic address.
933 AM.GV = GV;
934
935 // No ABI requires an extra load for anything other than DLLImport, which
936 // we rejected above. Return a direct reference to the global.
937 if (Subtarget->isPICStyleRIPRel()) {
938 // Use rip-relative addressing if we can. Above we verified that the
939 // base and index registers are unused.
940 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
941 AM.Base.Reg = X86::RIP;
942 } else if (Subtarget->isPICStyleStubPIC()) {
943 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
944 } else if (Subtarget->isPICStyleGOT()) {
945 AM.GVOpFlags = X86II::MO_GOTOFF;
946 }
947
948 return true;
949 }
950
951 // If all else fails, try to materialize the value in a register.
952 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
953 if (AM.Base.Reg == 0) {
954 AM.Base.Reg = getRegForValue(V);
955 return AM.Base.Reg != 0;
956 }
957 if (AM.IndexReg == 0) {
958 assert(AM.Scale == 1 && "Scale with no index!");
959 AM.IndexReg = getRegForValue(V);
960 return AM.IndexReg != 0;
961 }
962 }
963
964 return false;
965}
966
967
968/// X86SelectStore - Select and emit code to implement store instructions.
969bool X86FastISel::X86SelectStore(const Instruction *I) {
970 // Atomic stores need special handling.
971 const StoreInst *S = cast<StoreInst>(I);
972
973 if (S->isAtomic())
974 return false;
975
Manman Ren57518142016-04-11 21:08:06 +0000976 const Value *PtrV = I->getOperand(1);
977 if (TLI.supportSwiftError()) {
978 // Swifterror values can come from either a function parameter with
979 // swifterror attribute or an alloca with swifterror attribute.
980 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
981 if (Arg->hasSwiftErrorAttr())
982 return false;
983 }
984
985 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
986 if (Alloca->isSwiftError())
987 return false;
988 }
989 }
990
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000991 const Value *Val = S->getValueOperand();
992 const Value *Ptr = S->getPointerOperand();
993
994 MVT VT;
995 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
996 return false;
997
998 unsigned Alignment = S->getAlignment();
999 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1000 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1001 Alignment = ABIAlignment;
1002 bool Aligned = Alignment >= ABIAlignment;
1003
1004 X86AddressMode AM;
1005 if (!X86SelectAddress(Ptr, AM))
1006 return false;
1007
1008 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1009}
1010
1011/// X86SelectRet - Select and emit code to implement ret instructions.
1012bool X86FastISel::X86SelectRet(const Instruction *I) {
1013 const ReturnInst *Ret = cast<ReturnInst>(I);
1014 const Function &F = *I->getParent()->getParent();
1015 const X86MachineFunctionInfo *X86MFInfo =
1016 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1017
1018 if (!FuncInfo.CanLowerReturn)
1019 return false;
1020
Manman Ren57518142016-04-11 21:08:06 +00001021 if (TLI.supportSwiftError() &&
1022 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1023 return false;
1024
Manman Rened967f32016-01-12 01:08:46 +00001025 if (TLI.supportSplitCSR(FuncInfo.MF))
1026 return false;
1027
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001028 CallingConv::ID CC = F.getCallingConv();
1029 if (CC != CallingConv::C &&
1030 CC != CallingConv::Fast &&
1031 CC != CallingConv::X86_FastCall &&
1032 CC != CallingConv::X86_64_SysV)
1033 return false;
1034
1035 if (Subtarget->isCallingConvWin64(CC))
1036 return false;
1037
1038 // Don't handle popping bytes on return for now.
1039 if (X86MFInfo->getBytesToPopOnReturn() != 0)
1040 return false;
1041
1042 // fastcc with -tailcallopt is intended to provide a guaranteed
1043 // tail call optimization. Fastisel doesn't know how to do that.
1044 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1045 return false;
1046
1047 // Let SDISel handle vararg functions.
1048 if (F.isVarArg())
1049 return false;
1050
1051 // Build a list of return value registers.
1052 SmallVector<unsigned, 4> RetRegs;
1053
1054 if (Ret->getNumOperands() > 0) {
1055 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001056 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001057
1058 // Analyze operands of the call, assigning locations to each operand.
1059 SmallVector<CCValAssign, 16> ValLocs;
1060 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1061 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1062
1063 const Value *RV = Ret->getOperand(0);
1064 unsigned Reg = getRegForValue(RV);
1065 if (Reg == 0)
1066 return false;
1067
1068 // Only handle a single return value for now.
1069 if (ValLocs.size() != 1)
1070 return false;
1071
1072 CCValAssign &VA = ValLocs[0];
1073
1074 // Don't bother handling odd stuff for now.
1075 if (VA.getLocInfo() != CCValAssign::Full)
1076 return false;
1077 // Only handle register returns for now.
1078 if (!VA.isRegLoc())
1079 return false;
1080
1081 // The calling-convention tables for x87 returns don't tell
1082 // the whole story.
1083 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1084 return false;
1085
1086 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001087 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001088 EVT DstVT = VA.getValVT();
1089 // Special handling for extended integers.
1090 if (SrcVT != DstVT) {
1091 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1092 return false;
1093
1094 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1095 return false;
1096
1097 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1098
1099 if (SrcVT == MVT::i1) {
1100 if (Outs[0].Flags.isSExt())
1101 return false;
1102 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1103 SrcVT = MVT::i8;
1104 }
1105 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1106 ISD::SIGN_EXTEND;
1107 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1108 SrcReg, /*TODO: Kill=*/false);
1109 }
1110
1111 // Make the copy.
1112 unsigned DstReg = VA.getLocReg();
1113 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1114 // Avoid a cross-class copy. This is very unlikely.
1115 if (!SrcRC->contains(DstReg))
1116 return false;
1117 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1118 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1119
1120 // Add register to return instruction.
1121 RetRegs.push_back(VA.getLocReg());
1122 }
1123
Dimitry Andric227b9282016-01-03 17:22:03 +00001124 // All x86 ABIs require that for returning structs by value we copy
1125 // the sret argument into %rax/%eax (depending on ABI) for the return.
1126 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001127 // so now we copy the value out and into %rax/%eax.
1128 if (F.hasStructRetAttr()) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001129 unsigned Reg = X86MFInfo->getSRetReturnReg();
1130 assert(Reg &&
1131 "SRetReturnReg should have been set in LowerFormalArguments()!");
1132 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1133 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1134 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1135 RetRegs.push_back(RetReg);
1136 }
1137
1138 // Now emit the RET.
1139 MachineInstrBuilder MIB =
1140 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1141 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1142 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1143 MIB.addReg(RetRegs[i], RegState::Implicit);
1144 return true;
1145}
1146
1147/// X86SelectLoad - Select and emit code to implement load instructions.
1148///
1149bool X86FastISel::X86SelectLoad(const Instruction *I) {
1150 const LoadInst *LI = cast<LoadInst>(I);
1151
1152 // Atomic loads need special handling.
1153 if (LI->isAtomic())
1154 return false;
1155
Manman Ren57518142016-04-11 21:08:06 +00001156 const Value *SV = I->getOperand(0);
1157 if (TLI.supportSwiftError()) {
1158 // Swifterror values can come from either a function parameter with
1159 // swifterror attribute or an alloca with swifterror attribute.
1160 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1161 if (Arg->hasSwiftErrorAttr())
1162 return false;
1163 }
1164
1165 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1166 if (Alloca->isSwiftError())
1167 return false;
1168 }
1169 }
1170
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001171 MVT VT;
1172 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1173 return false;
1174
1175 const Value *Ptr = LI->getPointerOperand();
1176
1177 X86AddressMode AM;
1178 if (!X86SelectAddress(Ptr, AM))
1179 return false;
1180
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001181 unsigned Alignment = LI->getAlignment();
1182 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1183 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1184 Alignment = ABIAlignment;
1185
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001186 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001187 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1188 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001189 return false;
1190
1191 updateValueMap(I, ResultReg);
1192 return true;
1193}
1194
1195static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1196 bool HasAVX = Subtarget->hasAVX();
1197 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1198 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1199
1200 switch (VT.getSimpleVT().SimpleTy) {
1201 default: return 0;
1202 case MVT::i8: return X86::CMP8rr;
1203 case MVT::i16: return X86::CMP16rr;
1204 case MVT::i32: return X86::CMP32rr;
1205 case MVT::i64: return X86::CMP64rr;
1206 case MVT::f32:
1207 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1208 case MVT::f64:
1209 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1210 }
1211}
1212
Rafael Espindola19141f22015-03-16 14:05:49 +00001213/// If we have a comparison with RHS as the RHS of the comparison, return an
1214/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001215static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001216 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001217 switch (VT.getSimpleVT().SimpleTy) {
1218 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001219 default:
1220 return 0;
1221 case MVT::i8:
1222 return X86::CMP8ri;
1223 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001224 if (isInt<8>(Val))
1225 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001226 return X86::CMP16ri;
1227 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001228 if (isInt<8>(Val))
1229 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001230 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001231 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001232 if (isInt<8>(Val))
1233 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001234 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1235 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001236 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001237 return X86::CMP64ri32;
1238 return 0;
1239 }
1240}
1241
1242bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1243 EVT VT, DebugLoc CurDbgLoc) {
1244 unsigned Op0Reg = getRegForValue(Op0);
1245 if (Op0Reg == 0) return false;
1246
1247 // Handle 'null' like i32/i64 0.
1248 if (isa<ConstantPointerNull>(Op1))
1249 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1250
1251 // We have two options: compare with register or immediate. If the RHS of
1252 // the compare is an immediate that we can fold into this compare, use
1253 // CMPri, otherwise use CMPrr.
1254 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1255 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1257 .addReg(Op0Reg)
1258 .addImm(Op1C->getSExtValue());
1259 return true;
1260 }
1261 }
1262
1263 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1264 if (CompareOpc == 0) return false;
1265
1266 unsigned Op1Reg = getRegForValue(Op1);
1267 if (Op1Reg == 0) return false;
1268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1269 .addReg(Op0Reg)
1270 .addReg(Op1Reg);
1271
1272 return true;
1273}
1274
1275bool X86FastISel::X86SelectCmp(const Instruction *I) {
1276 const CmpInst *CI = cast<CmpInst>(I);
1277
1278 MVT VT;
1279 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1280 return false;
1281
1282 // Try to optimize or fold the cmp.
1283 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1284 unsigned ResultReg = 0;
1285 switch (Predicate) {
1286 default: break;
1287 case CmpInst::FCMP_FALSE: {
1288 ResultReg = createResultReg(&X86::GR32RegClass);
1289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1290 ResultReg);
1291 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1292 X86::sub_8bit);
1293 if (!ResultReg)
1294 return false;
1295 break;
1296 }
1297 case CmpInst::FCMP_TRUE: {
1298 ResultReg = createResultReg(&X86::GR8RegClass);
1299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1300 ResultReg).addImm(1);
1301 break;
1302 }
1303 }
1304
1305 if (ResultReg) {
1306 updateValueMap(I, ResultReg);
1307 return true;
1308 }
1309
1310 const Value *LHS = CI->getOperand(0);
1311 const Value *RHS = CI->getOperand(1);
1312
1313 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1314 // We don't have to materialize a zero constant for this case and can just use
1315 // %x again on the RHS.
1316 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1317 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1318 if (RHSC && RHSC->isNullValue())
1319 RHS = LHS;
1320 }
1321
1322 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1323 static unsigned SETFOpcTable[2][3] = {
1324 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1325 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1326 };
1327 unsigned *SETFOpc = nullptr;
1328 switch (Predicate) {
1329 default: break;
1330 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1331 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1332 }
1333
1334 ResultReg = createResultReg(&X86::GR8RegClass);
1335 if (SETFOpc) {
1336 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1337 return false;
1338
1339 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1340 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1342 FlagReg1);
1343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1344 FlagReg2);
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1346 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1347 updateValueMap(I, ResultReg);
1348 return true;
1349 }
1350
1351 X86::CondCode CC;
1352 bool SwapArgs;
1353 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1354 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1355 unsigned Opc = X86::getSETFromCond(CC);
1356
1357 if (SwapArgs)
1358 std::swap(LHS, RHS);
1359
1360 // Emit a compare of LHS/RHS.
1361 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1362 return false;
1363
1364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1365 updateValueMap(I, ResultReg);
1366 return true;
1367}
1368
1369bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001370 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001371 if (!TLI.isTypeLegal(DstVT))
1372 return false;
1373
1374 unsigned ResultReg = getRegForValue(I->getOperand(0));
1375 if (ResultReg == 0)
1376 return false;
1377
1378 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001379 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001380 if (SrcVT.SimpleTy == MVT::i1) {
1381 // Set the high bits to zero.
1382 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1383 SrcVT = MVT::i8;
1384
1385 if (ResultReg == 0)
1386 return false;
1387 }
1388
1389 if (DstVT == MVT::i64) {
1390 // Handle extension to 64-bits via sub-register shenanigans.
1391 unsigned MovInst;
1392
1393 switch (SrcVT.SimpleTy) {
1394 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1395 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1396 case MVT::i32: MovInst = X86::MOV32rr; break;
1397 default: llvm_unreachable("Unexpected zext to i64 source type");
1398 }
1399
1400 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1402 .addReg(ResultReg);
1403
1404 ResultReg = createResultReg(&X86::GR64RegClass);
1405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1406 ResultReg)
1407 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1408 } else if (DstVT != MVT::i8) {
1409 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1410 ResultReg, /*Kill=*/true);
1411 if (ResultReg == 0)
1412 return false;
1413 }
1414
1415 updateValueMap(I, ResultReg);
1416 return true;
1417}
1418
1419bool X86FastISel::X86SelectBranch(const Instruction *I) {
1420 // Unconditional branches are selected by tablegen-generated code.
1421 // Handle a conditional branch.
1422 const BranchInst *BI = cast<BranchInst>(I);
1423 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1424 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1425
1426 // Fold the common case of a conditional branch with a comparison
1427 // in the same block (values defined on other blocks may not have
1428 // initialized registers).
1429 X86::CondCode CC;
1430 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1431 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001432 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001433
1434 // Try to optimize or fold the cmp.
1435 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1436 switch (Predicate) {
1437 default: break;
1438 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1439 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1440 }
1441
1442 const Value *CmpLHS = CI->getOperand(0);
1443 const Value *CmpRHS = CI->getOperand(1);
1444
1445 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1446 // 0.0.
1447 // We don't have to materialize a zero constant for this case and can just
1448 // use %x again on the RHS.
1449 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1450 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1451 if (CmpRHSC && CmpRHSC->isNullValue())
1452 CmpRHS = CmpLHS;
1453 }
1454
1455 // Try to take advantage of fallthrough opportunities.
1456 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1457 std::swap(TrueMBB, FalseMBB);
1458 Predicate = CmpInst::getInversePredicate(Predicate);
1459 }
1460
1461 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1462 // code check. Instead two branch instructions are required to check all
1463 // the flags. First we change the predicate to a supported condition code,
1464 // which will be the first branch. Later one we will emit the second
1465 // branch.
1466 bool NeedExtraBranch = false;
1467 switch (Predicate) {
1468 default: break;
1469 case CmpInst::FCMP_OEQ:
1470 std::swap(TrueMBB, FalseMBB); // fall-through
1471 case CmpInst::FCMP_UNE:
1472 NeedExtraBranch = true;
1473 Predicate = CmpInst::FCMP_ONE;
1474 break;
1475 }
1476
1477 bool SwapArgs;
1478 unsigned BranchOpc;
1479 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1480 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1481
1482 BranchOpc = X86::GetCondBranchFromCond(CC);
1483 if (SwapArgs)
1484 std::swap(CmpLHS, CmpRHS);
1485
1486 // Emit a compare of the LHS and RHS, setting the flags.
1487 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1488 return false;
1489
1490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1491 .addMBB(TrueMBB);
1492
1493 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1494 // to UNE above).
1495 if (NeedExtraBranch) {
1496 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1497 .addMBB(TrueMBB);
1498 }
1499
Matthias Braun17af6072015-08-26 01:38:00 +00001500 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001501 return true;
1502 }
1503 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1504 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1505 // typically happen for _Bool and C++ bools.
1506 MVT SourceVT;
1507 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1508 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1509 unsigned TestOpc = 0;
1510 switch (SourceVT.SimpleTy) {
1511 default: break;
1512 case MVT::i8: TestOpc = X86::TEST8ri; break;
1513 case MVT::i16: TestOpc = X86::TEST16ri; break;
1514 case MVT::i32: TestOpc = X86::TEST32ri; break;
1515 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1516 }
1517 if (TestOpc) {
1518 unsigned OpReg = getRegForValue(TI->getOperand(0));
1519 if (OpReg == 0) return false;
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1521 .addReg(OpReg).addImm(1);
1522
1523 unsigned JmpOpc = X86::JNE_1;
1524 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1525 std::swap(TrueMBB, FalseMBB);
1526 JmpOpc = X86::JE_1;
1527 }
1528
1529 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1530 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001531
1532 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001533 return true;
1534 }
1535 }
1536 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1537 // Fake request the condition, otherwise the intrinsic might be completely
1538 // optimized away.
1539 unsigned TmpReg = getRegForValue(BI->getCondition());
1540 if (TmpReg == 0)
1541 return false;
1542
1543 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1544
1545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1546 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001547 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001548 return true;
1549 }
1550
1551 // Otherwise do a clumsy setcc and re-test it.
1552 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1553 // in an explicit cast, so make sure to handle that correctly.
1554 unsigned OpReg = getRegForValue(BI->getCondition());
1555 if (OpReg == 0) return false;
1556
1557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1558 .addReg(OpReg).addImm(1);
1559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1560 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001561 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001562 return true;
1563}
1564
1565bool X86FastISel::X86SelectShift(const Instruction *I) {
1566 unsigned CReg = 0, OpReg = 0;
1567 const TargetRegisterClass *RC = nullptr;
1568 if (I->getType()->isIntegerTy(8)) {
1569 CReg = X86::CL;
1570 RC = &X86::GR8RegClass;
1571 switch (I->getOpcode()) {
1572 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1573 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1574 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1575 default: return false;
1576 }
1577 } else if (I->getType()->isIntegerTy(16)) {
1578 CReg = X86::CX;
1579 RC = &X86::GR16RegClass;
1580 switch (I->getOpcode()) {
1581 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1582 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1583 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1584 default: return false;
1585 }
1586 } else if (I->getType()->isIntegerTy(32)) {
1587 CReg = X86::ECX;
1588 RC = &X86::GR32RegClass;
1589 switch (I->getOpcode()) {
1590 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1591 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1592 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1593 default: return false;
1594 }
1595 } else if (I->getType()->isIntegerTy(64)) {
1596 CReg = X86::RCX;
1597 RC = &X86::GR64RegClass;
1598 switch (I->getOpcode()) {
1599 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1600 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1601 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1602 default: return false;
1603 }
1604 } else {
1605 return false;
1606 }
1607
1608 MVT VT;
1609 if (!isTypeLegal(I->getType(), VT))
1610 return false;
1611
1612 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1613 if (Op0Reg == 0) return false;
1614
1615 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1616 if (Op1Reg == 0) return false;
1617 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1618 CReg).addReg(Op1Reg);
1619
1620 // The shift instruction uses X86::CL. If we defined a super-register
1621 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1622 if (CReg != X86::CL)
1623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1624 TII.get(TargetOpcode::KILL), X86::CL)
1625 .addReg(CReg, RegState::Kill);
1626
1627 unsigned ResultReg = createResultReg(RC);
1628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1629 .addReg(Op0Reg);
1630 updateValueMap(I, ResultReg);
1631 return true;
1632}
1633
1634bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1635 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1636 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1637 const static bool S = true; // IsSigned
1638 const static bool U = false; // !IsSigned
1639 const static unsigned Copy = TargetOpcode::COPY;
1640 // For the X86 DIV/IDIV instruction, in most cases the dividend
1641 // (numerator) must be in a specific register pair highreg:lowreg,
1642 // producing the quotient in lowreg and the remainder in highreg.
1643 // For most data types, to set up the instruction, the dividend is
1644 // copied into lowreg, and lowreg is sign-extended or zero-extended
1645 // into highreg. The exception is i8, where the dividend is defined
1646 // as a single register rather than a register pair, and we
1647 // therefore directly sign-extend or zero-extend the dividend into
1648 // lowreg, instead of copying, and ignore the highreg.
1649 const static struct DivRemEntry {
1650 // The following portion depends only on the data type.
1651 const TargetRegisterClass *RC;
1652 unsigned LowInReg; // low part of the register pair
1653 unsigned HighInReg; // high part of the register pair
1654 // The following portion depends on both the data type and the operation.
1655 struct DivRemResult {
1656 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1657 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1658 // highreg, or copying a zero into highreg.
1659 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1660 // zero/sign-extending into lowreg for i8.
1661 unsigned DivRemResultReg; // Register containing the desired result.
1662 bool IsOpSigned; // Whether to use signed or unsigned form.
1663 } ResultTable[NumOps];
1664 } OpTable[NumTypes] = {
1665 { &X86::GR8RegClass, X86::AX, 0, {
1666 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1667 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1668 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1669 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1670 }
1671 }, // i8
1672 { &X86::GR16RegClass, X86::AX, X86::DX, {
1673 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1674 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1675 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1676 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1677 }
1678 }, // i16
1679 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1680 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1681 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1682 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1683 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1684 }
1685 }, // i32
1686 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1687 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1688 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1689 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1690 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1691 }
1692 }, // i64
1693 };
1694
1695 MVT VT;
1696 if (!isTypeLegal(I->getType(), VT))
1697 return false;
1698
1699 unsigned TypeIndex, OpIndex;
1700 switch (VT.SimpleTy) {
1701 default: return false;
1702 case MVT::i8: TypeIndex = 0; break;
1703 case MVT::i16: TypeIndex = 1; break;
1704 case MVT::i32: TypeIndex = 2; break;
1705 case MVT::i64: TypeIndex = 3;
1706 if (!Subtarget->is64Bit())
1707 return false;
1708 break;
1709 }
1710
1711 switch (I->getOpcode()) {
1712 default: llvm_unreachable("Unexpected div/rem opcode");
1713 case Instruction::SDiv: OpIndex = 0; break;
1714 case Instruction::SRem: OpIndex = 1; break;
1715 case Instruction::UDiv: OpIndex = 2; break;
1716 case Instruction::URem: OpIndex = 3; break;
1717 }
1718
1719 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1720 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1721 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1722 if (Op0Reg == 0)
1723 return false;
1724 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1725 if (Op1Reg == 0)
1726 return false;
1727
1728 // Move op0 into low-order input register.
1729 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1730 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1731 // Zero-extend or sign-extend into high-order input register.
1732 if (OpEntry.OpSignExtend) {
1733 if (OpEntry.IsOpSigned)
1734 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1735 TII.get(OpEntry.OpSignExtend));
1736 else {
1737 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1738 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1739 TII.get(X86::MOV32r0), Zero32);
1740
1741 // Copy the zero into the appropriate sub/super/identical physical
1742 // register. Unfortunately the operations needed are not uniform enough
1743 // to fit neatly into the table above.
1744 if (VT.SimpleTy == MVT::i16) {
1745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1746 TII.get(Copy), TypeEntry.HighInReg)
1747 .addReg(Zero32, 0, X86::sub_16bit);
1748 } else if (VT.SimpleTy == MVT::i32) {
1749 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1750 TII.get(Copy), TypeEntry.HighInReg)
1751 .addReg(Zero32);
1752 } else if (VT.SimpleTy == MVT::i64) {
1753 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1754 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1755 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1756 }
1757 }
1758 }
1759 // Generate the DIV/IDIV instruction.
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1761 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1762 // For i8 remainder, we can't reference AH directly, as we'll end
1763 // up with bogus copies like %R9B = COPY %AH. Reference AX
1764 // instead to prevent AH references in a REX instruction.
1765 //
1766 // The current assumption of the fast register allocator is that isel
1767 // won't generate explicit references to the GPR8_NOREX registers. If
1768 // the allocator and/or the backend get enhanced to be more robust in
1769 // that regard, this can be, and should be, removed.
1770 unsigned ResultReg = 0;
1771 if ((I->getOpcode() == Instruction::SRem ||
1772 I->getOpcode() == Instruction::URem) &&
1773 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1774 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1775 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1776 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1777 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1778
1779 // Shift AX right by 8 bits instead of using AH.
1780 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1781 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1782
1783 // Now reference the 8-bit subreg of the result.
1784 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1785 /*Kill=*/true, X86::sub_8bit);
1786 }
1787 // Copy the result out of the physreg if we haven't already.
1788 if (!ResultReg) {
1789 ResultReg = createResultReg(TypeEntry.RC);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1791 .addReg(OpEntry.DivRemResultReg);
1792 }
1793 updateValueMap(I, ResultReg);
1794
1795 return true;
1796}
1797
1798/// \brief Emit a conditional move instruction (if the are supported) to lower
1799/// the select.
1800bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1801 // Check if the subtarget supports these instructions.
1802 if (!Subtarget->hasCMov())
1803 return false;
1804
1805 // FIXME: Add support for i8.
1806 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1807 return false;
1808
1809 const Value *Cond = I->getOperand(0);
1810 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1811 bool NeedTest = true;
1812 X86::CondCode CC = X86::COND_NE;
1813
1814 // Optimize conditions coming from a compare if both instructions are in the
1815 // same basic block (values defined in other basic blocks may not have
1816 // initialized registers).
1817 const auto *CI = dyn_cast<CmpInst>(Cond);
1818 if (CI && (CI->getParent() == I->getParent())) {
1819 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1820
1821 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1822 static unsigned SETFOpcTable[2][3] = {
1823 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1824 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1825 };
1826 unsigned *SETFOpc = nullptr;
1827 switch (Predicate) {
1828 default: break;
1829 case CmpInst::FCMP_OEQ:
1830 SETFOpc = &SETFOpcTable[0][0];
1831 Predicate = CmpInst::ICMP_NE;
1832 break;
1833 case CmpInst::FCMP_UNE:
1834 SETFOpc = &SETFOpcTable[1][0];
1835 Predicate = CmpInst::ICMP_NE;
1836 break;
1837 }
1838
1839 bool NeedSwap;
1840 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1841 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1842
1843 const Value *CmpLHS = CI->getOperand(0);
1844 const Value *CmpRHS = CI->getOperand(1);
1845 if (NeedSwap)
1846 std::swap(CmpLHS, CmpRHS);
1847
Mehdi Amini44ede332015-07-09 02:09:04 +00001848 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001849 // Emit a compare of the LHS and RHS, setting the flags.
1850 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1851 return false;
1852
1853 if (SETFOpc) {
1854 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1855 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1856 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1857 FlagReg1);
1858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1859 FlagReg2);
1860 auto const &II = TII.get(SETFOpc[2]);
1861 if (II.getNumDefs()) {
1862 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1863 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1864 .addReg(FlagReg2).addReg(FlagReg1);
1865 } else {
1866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1867 .addReg(FlagReg2).addReg(FlagReg1);
1868 }
1869 }
1870 NeedTest = false;
1871 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1872 // Fake request the condition, otherwise the intrinsic might be completely
1873 // optimized away.
1874 unsigned TmpReg = getRegForValue(Cond);
1875 if (TmpReg == 0)
1876 return false;
1877
1878 NeedTest = false;
1879 }
1880
1881 if (NeedTest) {
1882 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1883 // garbage. Indeed, only the less significant bit is supposed to be
1884 // accurate. If we read more than the lsb, we may see non-zero values
1885 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1886 // the select. This is achieved by performing TEST against 1.
1887 unsigned CondReg = getRegForValue(Cond);
1888 if (CondReg == 0)
1889 return false;
1890 bool CondIsKill = hasTrivialKill(Cond);
1891
1892 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1893 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1894 }
1895
1896 const Value *LHS = I->getOperand(1);
1897 const Value *RHS = I->getOperand(2);
1898
1899 unsigned RHSReg = getRegForValue(RHS);
1900 bool RHSIsKill = hasTrivialKill(RHS);
1901
1902 unsigned LHSReg = getRegForValue(LHS);
1903 bool LHSIsKill = hasTrivialKill(LHS);
1904
1905 if (!LHSReg || !RHSReg)
1906 return false;
1907
1908 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1909 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1910 LHSReg, LHSIsKill);
1911 updateValueMap(I, ResultReg);
1912 return true;
1913}
1914
Sanjay Patel302404b2015-03-05 21:46:54 +00001915/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001916///
1917/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1918/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00001919/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001920bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1921 // Optimize conditions coming from a compare if both instructions are in the
1922 // same basic block (values defined in other basic blocks may not have
1923 // initialized registers).
1924 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1925 if (!CI || (CI->getParent() != I->getParent()))
1926 return false;
1927
1928 if (I->getType() != CI->getOperand(0)->getType() ||
1929 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1930 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1931 return false;
1932
1933 const Value *CmpLHS = CI->getOperand(0);
1934 const Value *CmpRHS = CI->getOperand(1);
1935 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1936
1937 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1938 // We don't have to materialize a zero constant for this case and can just use
1939 // %x again on the RHS.
1940 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1941 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1942 if (CmpRHSC && CmpRHSC->isNullValue())
1943 CmpRHS = CmpLHS;
1944 }
1945
1946 unsigned CC;
1947 bool NeedSwap;
1948 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1949 if (CC > 7)
1950 return false;
1951
1952 if (NeedSwap)
1953 std::swap(CmpLHS, CmpRHS);
1954
Sanjay Patel302404b2015-03-05 21:46:54 +00001955 // Choose the SSE instruction sequence based on data type (float or double).
1956 static unsigned OpcTable[2][4] = {
1957 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1958 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001959 };
1960
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001961 unsigned *Opc = nullptr;
1962 switch (RetVT.SimpleTy) {
1963 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00001964 case MVT::f32: Opc = &OpcTable[0][0]; break;
1965 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001966 }
1967
1968 const Value *LHS = I->getOperand(1);
1969 const Value *RHS = I->getOperand(2);
1970
1971 unsigned LHSReg = getRegForValue(LHS);
1972 bool LHSIsKill = hasTrivialKill(LHS);
1973
1974 unsigned RHSReg = getRegForValue(RHS);
1975 bool RHSIsKill = hasTrivialKill(RHS);
1976
1977 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1978 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1979
1980 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1981 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1982
1983 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1984 return false;
1985
1986 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00001987 unsigned ResultReg;
1988
1989 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00001990 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
1991 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
1992
Sanjay Patel302404b2015-03-05 21:46:54 +00001993 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1994 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1995 // uses XMM0 as the selection register. That may need just as many
1996 // instructions as the AND/ANDN/OR sequence due to register moves, so
1997 // don't bother.
1998 unsigned CmpOpcode =
1999 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2000 unsigned BlendOpcode =
2001 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2002
Matthias Braun818c78d2015-08-31 18:25:11 +00002003 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002004 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002005 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2006 LHSReg, LHSIsKill, CmpReg, true);
2007 ResultReg = createResultReg(RC);
2008 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2009 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002010 } else {
2011 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2012 CmpRHSReg, CmpRHSIsKill, CC);
2013 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2014 LHSReg, LHSIsKill);
2015 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2016 RHSReg, RHSIsKill);
2017 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2018 AndReg, /*IsKill=*/true);
2019 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002020 updateValueMap(I, ResultReg);
2021 return true;
2022}
2023
2024bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2025 // These are pseudo CMOV instructions and will be later expanded into control-
2026 // flow.
2027 unsigned Opc;
2028 switch (RetVT.SimpleTy) {
2029 default: return false;
2030 case MVT::i8: Opc = X86::CMOV_GR8; break;
2031 case MVT::i16: Opc = X86::CMOV_GR16; break;
2032 case MVT::i32: Opc = X86::CMOV_GR32; break;
2033 case MVT::f32: Opc = X86::CMOV_FR32; break;
2034 case MVT::f64: Opc = X86::CMOV_FR64; break;
2035 }
2036
2037 const Value *Cond = I->getOperand(0);
2038 X86::CondCode CC = X86::COND_NE;
2039
2040 // Optimize conditions coming from a compare if both instructions are in the
2041 // same basic block (values defined in other basic blocks may not have
2042 // initialized registers).
2043 const auto *CI = dyn_cast<CmpInst>(Cond);
2044 if (CI && (CI->getParent() == I->getParent())) {
2045 bool NeedSwap;
2046 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2047 if (CC > X86::LAST_VALID_COND)
2048 return false;
2049
2050 const Value *CmpLHS = CI->getOperand(0);
2051 const Value *CmpRHS = CI->getOperand(1);
2052
2053 if (NeedSwap)
2054 std::swap(CmpLHS, CmpRHS);
2055
Mehdi Amini44ede332015-07-09 02:09:04 +00002056 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002057 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2058 return false;
2059 } else {
2060 unsigned CondReg = getRegForValue(Cond);
2061 if (CondReg == 0)
2062 return false;
2063 bool CondIsKill = hasTrivialKill(Cond);
2064 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2065 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2066 }
2067
2068 const Value *LHS = I->getOperand(1);
2069 const Value *RHS = I->getOperand(2);
2070
2071 unsigned LHSReg = getRegForValue(LHS);
2072 bool LHSIsKill = hasTrivialKill(LHS);
2073
2074 unsigned RHSReg = getRegForValue(RHS);
2075 bool RHSIsKill = hasTrivialKill(RHS);
2076
2077 if (!LHSReg || !RHSReg)
2078 return false;
2079
2080 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2081
2082 unsigned ResultReg =
2083 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2084 updateValueMap(I, ResultReg);
2085 return true;
2086}
2087
2088bool X86FastISel::X86SelectSelect(const Instruction *I) {
2089 MVT RetVT;
2090 if (!isTypeLegal(I->getType(), RetVT))
2091 return false;
2092
2093 // Check if we can fold the select.
2094 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2095 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2096 const Value *Opnd = nullptr;
2097 switch (Predicate) {
2098 default: break;
2099 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2100 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2101 }
2102 // No need for a select anymore - this is an unconditional move.
2103 if (Opnd) {
2104 unsigned OpReg = getRegForValue(Opnd);
2105 if (OpReg == 0)
2106 return false;
2107 bool OpIsKill = hasTrivialKill(Opnd);
2108 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2109 unsigned ResultReg = createResultReg(RC);
2110 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2111 TII.get(TargetOpcode::COPY), ResultReg)
2112 .addReg(OpReg, getKillRegState(OpIsKill));
2113 updateValueMap(I, ResultReg);
2114 return true;
2115 }
2116 }
2117
2118 // First try to use real conditional move instructions.
2119 if (X86FastEmitCMoveSelect(RetVT, I))
2120 return true;
2121
2122 // Try to use a sequence of SSE instructions to simulate a conditional move.
2123 if (X86FastEmitSSESelect(RetVT, I))
2124 return true;
2125
2126 // Fall-back to pseudo conditional move instructions, which will be later
2127 // converted to control-flow.
2128 if (X86FastEmitPseudoSelect(RetVT, I))
2129 return true;
2130
2131 return false;
2132}
2133
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002134bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002135 // The target-independent selection algorithm in FastISel already knows how
2136 // to select a SINT_TO_FP if the target is SSE but not AVX.
2137 // Early exit if the subtarget doesn't have AVX.
2138 if (!Subtarget->hasAVX())
2139 return false;
2140
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002141 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2142 return false;
2143
2144 // Select integer to float/double conversion.
2145 unsigned OpReg = getRegForValue(I->getOperand(0));
2146 if (OpReg == 0)
2147 return false;
2148
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002149 const TargetRegisterClass *RC = nullptr;
2150 unsigned Opcode;
2151
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002152 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002153 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002154 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002155 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002156 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002157 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002158 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002159 RC = &X86::FR32RegClass;
2160 } else
2161 return false;
2162
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002163 unsigned ImplicitDefReg = createResultReg(RC);
2164 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2165 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2166 unsigned ResultReg =
2167 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002168 updateValueMap(I, ResultReg);
2169 return true;
2170}
2171
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002172// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2173bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2174 unsigned TargetOpc,
2175 const TargetRegisterClass *RC) {
2176 assert((I->getOpcode() == Instruction::FPExt ||
2177 I->getOpcode() == Instruction::FPTrunc) &&
2178 "Instruction must be an FPExt or FPTrunc!");
2179
2180 unsigned OpReg = getRegForValue(I->getOperand(0));
2181 if (OpReg == 0)
2182 return false;
2183
2184 unsigned ResultReg = createResultReg(RC);
2185 MachineInstrBuilder MIB;
2186 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2187 ResultReg);
2188 if (Subtarget->hasAVX())
2189 MIB.addReg(OpReg);
2190 MIB.addReg(OpReg);
2191 updateValueMap(I, ResultReg);
2192 return true;
2193}
2194
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002195bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002196 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2197 I->getOperand(0)->getType()->isFloatTy()) {
2198 // fpext from float to double.
2199 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2200 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002201 }
2202
2203 return false;
2204}
2205
2206bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002207 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2208 I->getOperand(0)->getType()->isDoubleTy()) {
2209 // fptrunc from double to float.
2210 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2211 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002212 }
2213
2214 return false;
2215}
2216
2217bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002218 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2219 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002220
2221 // This code only handles truncation to byte.
2222 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2223 return false;
2224 if (!TLI.isTypeLegal(SrcVT))
2225 return false;
2226
2227 unsigned InputReg = getRegForValue(I->getOperand(0));
2228 if (!InputReg)
2229 // Unhandled operand. Halt "fast" selection and bail.
2230 return false;
2231
2232 if (SrcVT == MVT::i8) {
2233 // Truncate from i8 to i1; no code needed.
2234 updateValueMap(I, InputReg);
2235 return true;
2236 }
2237
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002238 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002239 if (!Subtarget->is64Bit()) {
2240 // If we're on x86-32; we can't extract an i8 from a general register.
2241 // First issue a copy to GR16_ABCD or GR32_ABCD.
2242 const TargetRegisterClass *CopyRC =
2243 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2244 unsigned CopyReg = createResultReg(CopyRC);
2245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2246 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2247 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002248 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002249 }
2250
2251 // Issue an extract_subreg.
2252 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002253 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002254 X86::sub_8bit);
2255 if (!ResultReg)
2256 return false;
2257
2258 updateValueMap(I, ResultReg);
2259 return true;
2260}
2261
2262bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2263 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2264}
2265
2266bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2267 X86AddressMode SrcAM, uint64_t Len) {
2268
2269 // Make sure we don't bloat code by inlining very large memcpy's.
2270 if (!IsMemcpySmall(Len))
2271 return false;
2272
2273 bool i64Legal = Subtarget->is64Bit();
2274
2275 // We don't care about alignment here since we just emit integer accesses.
2276 while (Len) {
2277 MVT VT;
2278 if (Len >= 8 && i64Legal)
2279 VT = MVT::i64;
2280 else if (Len >= 4)
2281 VT = MVT::i32;
2282 else if (Len >= 2)
2283 VT = MVT::i16;
2284 else
2285 VT = MVT::i8;
2286
2287 unsigned Reg;
2288 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2289 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2290 assert(RV && "Failed to emit load or store??");
2291
2292 unsigned Size = VT.getSizeInBits()/8;
2293 Len -= Size;
2294 DestAM.Disp += Size;
2295 SrcAM.Disp += Size;
2296 }
2297
2298 return true;
2299}
2300
2301bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2302 // FIXME: Handle more intrinsics.
2303 switch (II->getIntrinsicID()) {
2304 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002305 case Intrinsic::convert_from_fp16:
2306 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002307 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002308 return false;
2309
2310 const Value *Op = II->getArgOperand(0);
2311 unsigned InputReg = getRegForValue(Op);
2312 if (InputReg == 0)
2313 return false;
2314
2315 // F16C only allows converting from float to half and from half to float.
2316 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2317 if (IsFloatToHalf) {
2318 if (!Op->getType()->isFloatTy())
2319 return false;
2320 } else {
2321 if (!II->getType()->isFloatTy())
2322 return false;
2323 }
2324
2325 unsigned ResultReg = 0;
2326 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2327 if (IsFloatToHalf) {
2328 // 'InputReg' is implicitly promoted from register class FR32 to
2329 // register class VR128 by method 'constrainOperandRegClass' which is
2330 // directly called by 'fastEmitInst_ri'.
2331 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002332 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2333 // It's consistent with the other FP instructions, which are usually
2334 // controlled by MXCSR.
2335 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002336
2337 // Move the lower 32-bits of ResultReg to another register of class GR32.
2338 ResultReg = createResultReg(&X86::GR32RegClass);
2339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2340 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2341 .addReg(InputReg, RegState::Kill);
2342
2343 // The result value is in the lower 16-bits of ResultReg.
2344 unsigned RegIdx = X86::sub_16bit;
2345 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2346 } else {
2347 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2348 // Explicitly sign-extend the input to 32-bit.
2349 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2350 /*Kill=*/false);
2351
2352 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2353 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2354 InputReg, /*Kill=*/true);
2355
2356 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2357
2358 // The result value is in the lower 32-bits of ResultReg.
2359 // Emit an explicit copy from register class VR128 to register class FR32.
2360 ResultReg = createResultReg(&X86::FR32RegClass);
2361 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2362 TII.get(TargetOpcode::COPY), ResultReg)
2363 .addReg(InputReg, RegState::Kill);
2364 }
2365
2366 updateValueMap(II, ResultReg);
2367 return true;
2368 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002369 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002370 MachineFunction *MF = FuncInfo.MF;
2371 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2372 return false;
2373
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002374 Type *RetTy = II->getCalledFunction()->getReturnType();
2375
2376 MVT VT;
2377 if (!isTypeLegal(RetTy, VT))
2378 return false;
2379
2380 unsigned Opc;
2381 const TargetRegisterClass *RC = nullptr;
2382
2383 switch (VT.SimpleTy) {
2384 default: llvm_unreachable("Invalid result type for frameaddress.");
2385 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2386 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2387 }
2388
2389 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2390 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002391 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002392 MFI->setFrameAddressIsTaken(true);
2393
Eric Christophera1c535b2015-02-02 23:03:45 +00002394 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002395 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002396 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2397 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2398 "Invalid Frame Register!");
2399
2400 // Always make a copy of the frame register to to a vreg first, so that we
2401 // never directly reference the frame register (the TwoAddressInstruction-
2402 // Pass doesn't like that).
2403 unsigned SrcReg = createResultReg(RC);
2404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2405 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2406
2407 // Now recursively load from the frame address.
2408 // movq (%rbp), %rax
2409 // movq (%rax), %rax
2410 // movq (%rax), %rax
2411 // ...
2412 unsigned DestReg;
2413 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2414 while (Depth--) {
2415 DestReg = createResultReg(RC);
2416 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2417 TII.get(Opc), DestReg), SrcReg);
2418 SrcReg = DestReg;
2419 }
2420
2421 updateValueMap(II, SrcReg);
2422 return true;
2423 }
2424 case Intrinsic::memcpy: {
2425 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2426 // Don't handle volatile or variable length memcpys.
2427 if (MCI->isVolatile())
2428 return false;
2429
2430 if (isa<ConstantInt>(MCI->getLength())) {
2431 // Small memcpy's are common enough that we want to do them
2432 // without a call if possible.
2433 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2434 if (IsMemcpySmall(Len)) {
2435 X86AddressMode DestAM, SrcAM;
2436 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2437 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2438 return false;
2439 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2440 return true;
2441 }
2442 }
2443
2444 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2445 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2446 return false;
2447
2448 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2449 return false;
2450
Pete Cooper67cf9a72015-11-19 05:56:52 +00002451 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002452 }
2453 case Intrinsic::memset: {
2454 const MemSetInst *MSI = cast<MemSetInst>(II);
2455
2456 if (MSI->isVolatile())
2457 return false;
2458
2459 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2460 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2461 return false;
2462
2463 if (MSI->getDestAddressSpace() > 255)
2464 return false;
2465
Pete Cooper67cf9a72015-11-19 05:56:52 +00002466 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002467 }
2468 case Intrinsic::stackprotector: {
2469 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002470 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002471
2472 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2473 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2474
2475 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2476
2477 // Grab the frame index.
2478 X86AddressMode AM;
2479 if (!X86SelectAddress(Slot, AM)) return false;
2480 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2481 return true;
2482 }
2483 case Intrinsic::dbg_declare: {
2484 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2485 X86AddressMode AM;
2486 assert(DI->getAddress() && "Null address should be checked earlier!");
2487 if (!X86SelectAddress(DI->getAddress(), AM))
2488 return false;
2489 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2490 // FIXME may need to add RegState::Debug to any registers produced,
2491 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002492 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2493 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002494 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2495 .addImm(0)
2496 .addMetadata(DI->getVariable())
2497 .addMetadata(DI->getExpression());
2498 return true;
2499 }
2500 case Intrinsic::trap: {
2501 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2502 return true;
2503 }
2504 case Intrinsic::sqrt: {
2505 if (!Subtarget->hasSSE1())
2506 return false;
2507
2508 Type *RetTy = II->getCalledFunction()->getReturnType();
2509
2510 MVT VT;
2511 if (!isTypeLegal(RetTy, VT))
2512 return false;
2513
2514 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2515 // is not generated by FastISel yet.
2516 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002517 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002518 {X86::SQRTSSr, X86::VSQRTSSr},
2519 {X86::SQRTSDr, X86::VSQRTSDr}
2520 };
2521 bool HasAVX = Subtarget->hasAVX();
2522 unsigned Opc;
2523 const TargetRegisterClass *RC;
2524 switch (VT.SimpleTy) {
2525 default: return false;
2526 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2527 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2528 }
2529
2530 const Value *SrcVal = II->getArgOperand(0);
2531 unsigned SrcReg = getRegForValue(SrcVal);
2532
2533 if (SrcReg == 0)
2534 return false;
2535
2536 unsigned ImplicitDefReg = 0;
2537 if (HasAVX) {
2538 ImplicitDefReg = createResultReg(RC);
2539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2540 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2541 }
2542
2543 unsigned ResultReg = createResultReg(RC);
2544 MachineInstrBuilder MIB;
2545 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2546 ResultReg);
2547
2548 if (ImplicitDefReg)
2549 MIB.addReg(ImplicitDefReg);
2550
2551 MIB.addReg(SrcReg);
2552
2553 updateValueMap(II, ResultReg);
2554 return true;
2555 }
2556 case Intrinsic::sadd_with_overflow:
2557 case Intrinsic::uadd_with_overflow:
2558 case Intrinsic::ssub_with_overflow:
2559 case Intrinsic::usub_with_overflow:
2560 case Intrinsic::smul_with_overflow:
2561 case Intrinsic::umul_with_overflow: {
2562 // This implements the basic lowering of the xalu with overflow intrinsics
2563 // into add/sub/mul followed by either seto or setb.
2564 const Function *Callee = II->getCalledFunction();
2565 auto *Ty = cast<StructType>(Callee->getReturnType());
2566 Type *RetTy = Ty->getTypeAtIndex(0U);
2567 Type *CondTy = Ty->getTypeAtIndex(1);
2568
2569 MVT VT;
2570 if (!isTypeLegal(RetTy, VT))
2571 return false;
2572
2573 if (VT < MVT::i8 || VT > MVT::i64)
2574 return false;
2575
2576 const Value *LHS = II->getArgOperand(0);
2577 const Value *RHS = II->getArgOperand(1);
2578
2579 // Canonicalize immediate to the RHS.
2580 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2581 isCommutativeIntrinsic(II))
2582 std::swap(LHS, RHS);
2583
2584 bool UseIncDec = false;
2585 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2586 UseIncDec = true;
2587
2588 unsigned BaseOpc, CondOpc;
2589 switch (II->getIntrinsicID()) {
2590 default: llvm_unreachable("Unexpected intrinsic!");
2591 case Intrinsic::sadd_with_overflow:
2592 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2593 CondOpc = X86::SETOr;
2594 break;
2595 case Intrinsic::uadd_with_overflow:
2596 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2597 case Intrinsic::ssub_with_overflow:
2598 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2599 CondOpc = X86::SETOr;
2600 break;
2601 case Intrinsic::usub_with_overflow:
2602 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2603 case Intrinsic::smul_with_overflow:
2604 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2605 case Intrinsic::umul_with_overflow:
2606 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2607 }
2608
2609 unsigned LHSReg = getRegForValue(LHS);
2610 if (LHSReg == 0)
2611 return false;
2612 bool LHSIsKill = hasTrivialKill(LHS);
2613
2614 unsigned ResultReg = 0;
2615 // Check if we have an immediate version.
2616 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2617 static const unsigned Opc[2][4] = {
2618 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2619 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2620 };
2621
2622 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2623 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2624 bool IsDec = BaseOpc == X86ISD::DEC;
2625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2626 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2627 .addReg(LHSReg, getKillRegState(LHSIsKill));
2628 } else
2629 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2630 CI->getZExtValue());
2631 }
2632
2633 unsigned RHSReg;
2634 bool RHSIsKill;
2635 if (!ResultReg) {
2636 RHSReg = getRegForValue(RHS);
2637 if (RHSReg == 0)
2638 return false;
2639 RHSIsKill = hasTrivialKill(RHS);
2640 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2641 RHSIsKill);
2642 }
2643
2644 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2645 // it manually.
2646 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002647 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002648 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002649 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002650 // First copy the first operand into RAX, which is an implicit input to
2651 // the X86::MUL*r instruction.
2652 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2653 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2654 .addReg(LHSReg, getKillRegState(LHSIsKill));
2655 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2656 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2657 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002658 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002659 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2660 if (VT == MVT::i8) {
2661 // Copy the first operand into AL, which is an implicit input to the
2662 // X86::IMUL8r instruction.
2663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2664 TII.get(TargetOpcode::COPY), X86::AL)
2665 .addReg(LHSReg, getKillRegState(LHSIsKill));
2666 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2667 RHSIsKill);
2668 } else
2669 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2670 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2671 RHSReg, RHSIsKill);
2672 }
2673
2674 if (!ResultReg)
2675 return false;
2676
2677 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2678 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2680 ResultReg2);
2681
2682 updateValueMap(II, ResultReg, 2);
2683 return true;
2684 }
2685 case Intrinsic::x86_sse_cvttss2si:
2686 case Intrinsic::x86_sse_cvttss2si64:
2687 case Intrinsic::x86_sse2_cvttsd2si:
2688 case Intrinsic::x86_sse2_cvttsd2si64: {
2689 bool IsInputDouble;
2690 switch (II->getIntrinsicID()) {
2691 default: llvm_unreachable("Unexpected intrinsic.");
2692 case Intrinsic::x86_sse_cvttss2si:
2693 case Intrinsic::x86_sse_cvttss2si64:
2694 if (!Subtarget->hasSSE1())
2695 return false;
2696 IsInputDouble = false;
2697 break;
2698 case Intrinsic::x86_sse2_cvttsd2si:
2699 case Intrinsic::x86_sse2_cvttsd2si64:
2700 if (!Subtarget->hasSSE2())
2701 return false;
2702 IsInputDouble = true;
2703 break;
2704 }
2705
2706 Type *RetTy = II->getCalledFunction()->getReturnType();
2707 MVT VT;
2708 if (!isTypeLegal(RetTy, VT))
2709 return false;
2710
2711 static const unsigned CvtOpc[2][2][2] = {
2712 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2713 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2714 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2715 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2716 };
2717 bool HasAVX = Subtarget->hasAVX();
2718 unsigned Opc;
2719 switch (VT.SimpleTy) {
2720 default: llvm_unreachable("Unexpected result type.");
2721 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2722 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2723 }
2724
2725 // Check if we can fold insertelement instructions into the convert.
2726 const Value *Op = II->getArgOperand(0);
2727 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2728 const Value *Index = IE->getOperand(2);
2729 if (!isa<ConstantInt>(Index))
2730 break;
2731 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2732
2733 if (Idx == 0) {
2734 Op = IE->getOperand(1);
2735 break;
2736 }
2737 Op = IE->getOperand(0);
2738 }
2739
2740 unsigned Reg = getRegForValue(Op);
2741 if (Reg == 0)
2742 return false;
2743
2744 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2746 .addReg(Reg);
2747
2748 updateValueMap(II, ResultReg);
2749 return true;
2750 }
2751 }
2752}
2753
2754bool X86FastISel::fastLowerArguments() {
2755 if (!FuncInfo.CanLowerReturn)
2756 return false;
2757
2758 const Function *F = FuncInfo.Fn;
2759 if (F->isVarArg())
2760 return false;
2761
2762 CallingConv::ID CC = F->getCallingConv();
2763 if (CC != CallingConv::C)
2764 return false;
2765
2766 if (Subtarget->isCallingConvWin64(CC))
2767 return false;
2768
2769 if (!Subtarget->is64Bit())
2770 return false;
2771
2772 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2773 unsigned GPRCnt = 0;
2774 unsigned FPRCnt = 0;
2775 unsigned Idx = 0;
2776 for (auto const &Arg : F->args()) {
2777 // The first argument is at index 1.
2778 ++Idx;
2779 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2780 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2781 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002782 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002783 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002784 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2785 return false;
2786
2787 Type *ArgTy = Arg.getType();
2788 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2789 return false;
2790
Mehdi Amini44ede332015-07-09 02:09:04 +00002791 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002792 if (!ArgVT.isSimple()) return false;
2793 switch (ArgVT.getSimpleVT().SimpleTy) {
2794 default: return false;
2795 case MVT::i32:
2796 case MVT::i64:
2797 ++GPRCnt;
2798 break;
2799 case MVT::f32:
2800 case MVT::f64:
2801 if (!Subtarget->hasSSE1())
2802 return false;
2803 ++FPRCnt;
2804 break;
2805 }
2806
2807 if (GPRCnt > 6)
2808 return false;
2809
2810 if (FPRCnt > 8)
2811 return false;
2812 }
2813
2814 static const MCPhysReg GPR32ArgRegs[] = {
2815 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2816 };
2817 static const MCPhysReg GPR64ArgRegs[] = {
2818 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2819 };
2820 static const MCPhysReg XMMArgRegs[] = {
2821 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2822 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2823 };
2824
2825 unsigned GPRIdx = 0;
2826 unsigned FPRIdx = 0;
2827 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002828 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002829 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2830 unsigned SrcReg;
2831 switch (VT.SimpleTy) {
2832 default: llvm_unreachable("Unexpected value type.");
2833 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2834 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2835 case MVT::f32: // fall-through
2836 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2837 }
2838 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2839 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2840 // Without this, EmitLiveInCopies may eliminate the livein if its only
2841 // use is a bitcast (which isn't turned into an instruction).
2842 unsigned ResultReg = createResultReg(RC);
2843 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2844 TII.get(TargetOpcode::COPY), ResultReg)
2845 .addReg(DstReg, getKillRegState(true));
2846 updateValueMap(&Arg, ResultReg);
2847 }
2848 return true;
2849}
2850
2851static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2852 CallingConv::ID CC,
2853 ImmutableCallSite *CS) {
2854 if (Subtarget->is64Bit())
2855 return 0;
2856 if (Subtarget->getTargetTriple().isOSMSVCRT())
2857 return 0;
2858 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2859 CC == CallingConv::HiPE)
2860 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002861
2862 if (CS)
2863 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00002864 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002865 return 0;
2866
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002867 return 4;
2868}
2869
2870bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2871 auto &OutVals = CLI.OutVals;
2872 auto &OutFlags = CLI.OutFlags;
2873 auto &OutRegs = CLI.OutRegs;
2874 auto &Ins = CLI.Ins;
2875 auto &InRegs = CLI.InRegs;
2876 CallingConv::ID CC = CLI.CallConv;
2877 bool &IsTailCall = CLI.IsTailCall;
2878 bool IsVarArg = CLI.IsVarArg;
2879 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00002880 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002881
2882 bool Is64Bit = Subtarget->is64Bit();
2883 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2884
2885 // Handle only C, fastcc, and webkit_js calling conventions for now.
2886 switch (CC) {
2887 default: return false;
2888 case CallingConv::C:
2889 case CallingConv::Fast:
2890 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00002891 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002892 case CallingConv::X86_FastCall:
2893 case CallingConv::X86_64_Win64:
2894 case CallingConv::X86_64_SysV:
2895 break;
2896 }
2897
2898 // Allow SelectionDAG isel to handle tail calls.
2899 if (IsTailCall)
2900 return false;
2901
2902 // fastcc with -tailcallopt is intended to provide a guaranteed
2903 // tail call optimization. Fastisel doesn't know how to do that.
2904 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2905 return false;
2906
2907 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2908 // x86-32. Special handling for x86-64 is implemented.
2909 if (IsVarArg && IsWin64)
2910 return false;
2911
2912 // Don't know about inalloca yet.
2913 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2914 return false;
2915
Manman Ren57518142016-04-11 21:08:06 +00002916 for (auto Flag : CLI.OutFlags)
2917 if (Flag.isSwiftError())
2918 return false;
2919
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002920 // Fast-isel doesn't know about callee-pop yet.
2921 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2922 TM.Options.GuaranteedTailCallOpt))
2923 return false;
2924
2925 SmallVector<MVT, 16> OutVTs;
2926 SmallVector<unsigned, 16> ArgRegs;
2927
2928 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2929 // instruction. This is safe because it is common to all FastISel supported
2930 // calling conventions on x86.
2931 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2932 Value *&Val = OutVals[i];
2933 ISD::ArgFlagsTy Flags = OutFlags[i];
2934 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2935 if (CI->getBitWidth() < 32) {
2936 if (Flags.isSExt())
2937 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2938 else
2939 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2940 }
2941 }
2942
2943 // Passing bools around ends up doing a trunc to i1 and passing it.
2944 // Codegen this as an argument + "and 1".
2945 MVT VT;
2946 auto *TI = dyn_cast<TruncInst>(Val);
2947 unsigned ResultReg;
2948 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2949 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2950 TI->hasOneUse()) {
2951 Value *PrevVal = TI->getOperand(0);
2952 ResultReg = getRegForValue(PrevVal);
2953
2954 if (!ResultReg)
2955 return false;
2956
2957 if (!isTypeLegal(PrevVal->getType(), VT))
2958 return false;
2959
2960 ResultReg =
2961 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2962 } else {
2963 if (!isTypeLegal(Val->getType(), VT))
2964 return false;
2965 ResultReg = getRegForValue(Val);
2966 }
2967
2968 if (!ResultReg)
2969 return false;
2970
2971 ArgRegs.push_back(ResultReg);
2972 OutVTs.push_back(VT);
2973 }
2974
2975 // Analyze operands of the call, assigning locations to each operand.
2976 SmallVector<CCValAssign, 16> ArgLocs;
2977 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2978
2979 // Allocate shadow area for Win64
2980 if (IsWin64)
2981 CCInfo.AllocateStack(32, 8);
2982
2983 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2984
2985 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00002986 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002987
2988 // Issue CALLSEQ_START
2989 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002991 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002992
2993 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00002994 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002995 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2996 CCValAssign const &VA = ArgLocs[i];
2997 const Value *ArgVal = OutVals[VA.getValNo()];
2998 MVT ArgVT = OutVTs[VA.getValNo()];
2999
3000 if (ArgVT == MVT::x86mmx)
3001 return false;
3002
3003 unsigned ArgReg = ArgRegs[VA.getValNo()];
3004
3005 // Promote the value if needed.
3006 switch (VA.getLocInfo()) {
3007 case CCValAssign::Full: break;
3008 case CCValAssign::SExt: {
3009 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3010 "Unexpected extend");
3011 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3012 ArgVT, ArgReg);
3013 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3014 ArgVT = VA.getLocVT();
3015 break;
3016 }
3017 case CCValAssign::ZExt: {
3018 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3019 "Unexpected extend");
3020 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3021 ArgVT, ArgReg);
3022 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3023 ArgVT = VA.getLocVT();
3024 break;
3025 }
3026 case CCValAssign::AExt: {
3027 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3028 "Unexpected extend");
3029 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3030 ArgVT, ArgReg);
3031 if (!Emitted)
3032 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3033 ArgVT, ArgReg);
3034 if (!Emitted)
3035 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3036 ArgVT, ArgReg);
3037
3038 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3039 ArgVT = VA.getLocVT();
3040 break;
3041 }
3042 case CCValAssign::BCvt: {
3043 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3044 /*TODO: Kill=*/false);
3045 assert(ArgReg && "Failed to emit a bitcast!");
3046 ArgVT = VA.getLocVT();
3047 break;
3048 }
3049 case CCValAssign::VExt:
3050 // VExt has not been implemented, so this should be impossible to reach
3051 // for now. However, fallback to Selection DAG isel once implemented.
3052 return false;
3053 case CCValAssign::AExtUpper:
3054 case CCValAssign::SExtUpper:
3055 case CCValAssign::ZExtUpper:
3056 case CCValAssign::FPExt:
3057 llvm_unreachable("Unexpected loc info!");
3058 case CCValAssign::Indirect:
3059 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3060 // support this.
3061 return false;
3062 }
3063
3064 if (VA.isRegLoc()) {
3065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3066 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3067 OutRegs.push_back(VA.getLocReg());
3068 } else {
3069 assert(VA.isMemLoc());
3070
3071 // Don't emit stores for undef values.
3072 if (isa<UndefValue>(ArgVal))
3073 continue;
3074
3075 unsigned LocMemOffset = VA.getLocMemOffset();
3076 X86AddressMode AM;
3077 AM.Base.Reg = RegInfo->getStackRegister();
3078 AM.Disp = LocMemOffset;
3079 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3080 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3081 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003082 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3083 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003084 if (Flags.isByVal()) {
3085 X86AddressMode SrcAM;
3086 SrcAM.Base.Reg = ArgReg;
3087 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3088 return false;
3089 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3090 // If this is a really simple value, emit this with the Value* version
3091 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3092 // as it can cause us to reevaluate the argument.
3093 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3094 return false;
3095 } else {
3096 bool ValIsKill = hasTrivialKill(ArgVal);
3097 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3098 return false;
3099 }
3100 }
3101 }
3102
3103 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3104 // GOT pointer.
3105 if (Subtarget->isPICStyleGOT()) {
3106 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3108 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3109 }
3110
3111 if (Is64Bit && IsVarArg && !IsWin64) {
3112 // From AMD64 ABI document:
3113 // For calls that may call functions that use varargs or stdargs
3114 // (prototype-less calls or calls to functions containing ellipsis (...) in
3115 // the declaration) %al is used as hidden argument to specify the number
3116 // of SSE registers used. The contents of %al do not need to match exactly
3117 // the number of registers, but must be an ubound on the number of SSE
3118 // registers used and is in the range 0 - 8 inclusive.
3119
3120 // Count the number of XMM registers allocated.
3121 static const MCPhysReg XMMArgRegs[] = {
3122 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3123 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3124 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003125 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003126 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3127 && "SSE registers cannot be used when SSE is disabled");
3128 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3129 X86::AL).addImm(NumXMMRegs);
3130 }
3131
3132 // Materialize callee address in a register. FIXME: GV address can be
3133 // handled with a CALLpcrel32 instead.
3134 X86AddressMode CalleeAM;
3135 if (!X86SelectCallAddress(Callee, CalleeAM))
3136 return false;
3137
3138 unsigned CalleeOp = 0;
3139 const GlobalValue *GV = nullptr;
3140 if (CalleeAM.GV != nullptr) {
3141 GV = CalleeAM.GV;
3142 } else if (CalleeAM.Base.Reg != 0) {
3143 CalleeOp = CalleeAM.Base.Reg;
3144 } else
3145 return false;
3146
3147 // Issue the call.
3148 MachineInstrBuilder MIB;
3149 if (CalleeOp) {
3150 // Register-indirect call.
3151 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3152 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3153 .addReg(CalleeOp);
3154 } else {
3155 // Direct call.
3156 assert(GV && "Not a direct call");
3157 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3158
3159 // See if we need any target-specific flags on the GV operand.
Asaf Badouh89406d12016-04-20 08:32:57 +00003160 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV, TM);
3161 // Ignore NonLazyBind attribute in FastISel
3162 if (OpFlags == X86II::MO_GOTPCREL)
3163 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003164
3165 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003166 if (Symbol)
3167 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003168 else
3169 MIB.addGlobalAddress(GV, 0, OpFlags);
3170 }
3171
3172 // Add a register mask operand representing the call-preserved registers.
3173 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003174 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003175
3176 // Add an implicit use GOT pointer in EBX.
3177 if (Subtarget->isPICStyleGOT())
3178 MIB.addReg(X86::EBX, RegState::Implicit);
3179
3180 if (Is64Bit && IsVarArg && !IsWin64)
3181 MIB.addReg(X86::AL, RegState::Implicit);
3182
3183 // Add implicit physical register uses to the call.
3184 for (auto Reg : OutRegs)
3185 MIB.addReg(Reg, RegState::Implicit);
3186
3187 // Issue CALLSEQ_END
3188 unsigned NumBytesForCalleeToPop =
3189 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3190 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3191 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3192 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3193
3194 // Now handle call return values.
3195 SmallVector<CCValAssign, 16> RVLocs;
3196 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3197 CLI.RetTy->getContext());
3198 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3199
3200 // Copy all of the result registers out of their specified physreg.
3201 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3202 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3203 CCValAssign &VA = RVLocs[i];
3204 EVT CopyVT = VA.getValVT();
3205 unsigned CopyReg = ResultReg + i;
3206
3207 // If this is x86-64, and we disabled SSE, we can't return FP values
3208 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3209 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3210 report_fatal_error("SSE register return with SSE disabled");
3211 }
3212
3213 // If we prefer to use the value in xmm registers, copy it out as f80 and
3214 // use a truncate to move it from fp stack reg to xmm reg.
3215 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3216 isScalarFPTypeInSSEReg(VA.getValVT())) {
3217 CopyVT = MVT::f80;
3218 CopyReg = createResultReg(&X86::RFP80RegClass);
3219 }
3220
3221 // Copy out the result.
3222 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3223 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3224 InRegs.push_back(VA.getLocReg());
3225
3226 // Round the f80 to the right size, which also moves it to the appropriate
3227 // xmm register. This is accomplished by storing the f80 value in memory
3228 // and then loading it back.
3229 if (CopyVT != VA.getValVT()) {
3230 EVT ResVT = VA.getValVT();
3231 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3232 unsigned MemSize = ResVT.getSizeInBits()/8;
3233 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3234 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3235 TII.get(Opc)), FI)
3236 .addReg(CopyReg);
3237 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3238 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3239 TII.get(Opc), ResultReg + i), FI);
3240 }
3241 }
3242
3243 CLI.ResultReg = ResultReg;
3244 CLI.NumResultRegs = RVLocs.size();
3245 CLI.Call = MIB;
3246
3247 return true;
3248}
3249
3250bool
3251X86FastISel::fastSelectInstruction(const Instruction *I) {
3252 switch (I->getOpcode()) {
3253 default: break;
3254 case Instruction::Load:
3255 return X86SelectLoad(I);
3256 case Instruction::Store:
3257 return X86SelectStore(I);
3258 case Instruction::Ret:
3259 return X86SelectRet(I);
3260 case Instruction::ICmp:
3261 case Instruction::FCmp:
3262 return X86SelectCmp(I);
3263 case Instruction::ZExt:
3264 return X86SelectZExt(I);
3265 case Instruction::Br:
3266 return X86SelectBranch(I);
3267 case Instruction::LShr:
3268 case Instruction::AShr:
3269 case Instruction::Shl:
3270 return X86SelectShift(I);
3271 case Instruction::SDiv:
3272 case Instruction::UDiv:
3273 case Instruction::SRem:
3274 case Instruction::URem:
3275 return X86SelectDivRem(I);
3276 case Instruction::Select:
3277 return X86SelectSelect(I);
3278 case Instruction::Trunc:
3279 return X86SelectTrunc(I);
3280 case Instruction::FPExt:
3281 return X86SelectFPExt(I);
3282 case Instruction::FPTrunc:
3283 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003284 case Instruction::SIToFP:
3285 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003286 case Instruction::IntToPtr: // Deliberate fall-through.
3287 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003288 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3289 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003290 if (DstVT.bitsGT(SrcVT))
3291 return X86SelectZExt(I);
3292 if (DstVT.bitsLT(SrcVT))
3293 return X86SelectTrunc(I);
3294 unsigned Reg = getRegForValue(I->getOperand(0));
3295 if (Reg == 0) return false;
3296 updateValueMap(I, Reg);
3297 return true;
3298 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003299 case Instruction::BitCast: {
3300 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3301 if (!Subtarget->hasSSE2())
3302 return false;
3303
3304 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3305 EVT DstVT = TLI.getValueType(DL, I->getType());
3306
3307 if (!SrcVT.isSimple() || !DstVT.isSimple())
3308 return false;
3309
3310 if (!SrcVT.is128BitVector() &&
3311 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3312 return false;
3313
3314 unsigned Reg = getRegForValue(I->getOperand(0));
3315 if (Reg == 0)
3316 return false;
3317
3318 // No instruction is needed for conversion. Reuse the register used by
3319 // the fist operand.
3320 updateValueMap(I, Reg);
3321 return true;
3322 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003323 }
3324
3325 return false;
3326}
3327
3328unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3329 if (VT > MVT::i64)
3330 return 0;
3331
3332 uint64_t Imm = CI->getZExtValue();
3333 if (Imm == 0) {
3334 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3335 switch (VT.SimpleTy) {
3336 default: llvm_unreachable("Unexpected value type");
3337 case MVT::i1:
3338 case MVT::i8:
3339 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3340 X86::sub_8bit);
3341 case MVT::i16:
3342 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3343 X86::sub_16bit);
3344 case MVT::i32:
3345 return SrcReg;
3346 case MVT::i64: {
3347 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3348 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3349 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3350 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3351 return ResultReg;
3352 }
3353 }
3354 }
3355
3356 unsigned Opc = 0;
3357 switch (VT.SimpleTy) {
3358 default: llvm_unreachable("Unexpected value type");
3359 case MVT::i1: VT = MVT::i8; // fall-through
3360 case MVT::i8: Opc = X86::MOV8ri; break;
3361 case MVT::i16: Opc = X86::MOV16ri; break;
3362 case MVT::i32: Opc = X86::MOV32ri; break;
3363 case MVT::i64: {
3364 if (isUInt<32>(Imm))
3365 Opc = X86::MOV32ri;
3366 else if (isInt<32>(Imm))
3367 Opc = X86::MOV64ri32;
3368 else
3369 Opc = X86::MOV64ri;
3370 break;
3371 }
3372 }
3373 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3374 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3375 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3377 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3378 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3379 return ResultReg;
3380 }
3381 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3382}
3383
3384unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3385 if (CFP->isNullValue())
3386 return fastMaterializeFloatZero(CFP);
3387
3388 // Can't handle alternate code models yet.
3389 CodeModel::Model CM = TM.getCodeModel();
3390 if (CM != CodeModel::Small && CM != CodeModel::Large)
3391 return 0;
3392
3393 // Get opcode and regclass of the output for the given load instruction.
3394 unsigned Opc = 0;
3395 const TargetRegisterClass *RC = nullptr;
3396 switch (VT.SimpleTy) {
3397 default: return 0;
3398 case MVT::f32:
3399 if (X86ScalarSSEf32) {
3400 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3401 RC = &X86::FR32RegClass;
3402 } else {
3403 Opc = X86::LD_Fp32m;
3404 RC = &X86::RFP32RegClass;
3405 }
3406 break;
3407 case MVT::f64:
3408 if (X86ScalarSSEf64) {
3409 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3410 RC = &X86::FR64RegClass;
3411 } else {
3412 Opc = X86::LD_Fp64m;
3413 RC = &X86::RFP64RegClass;
3414 }
3415 break;
3416 case MVT::f80:
3417 // No f80 support yet.
3418 return 0;
3419 }
3420
3421 // MachineConstantPool wants an explicit alignment.
3422 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3423 if (Align == 0) {
3424 // Alignment of vector types. FIXME!
3425 Align = DL.getTypeAllocSize(CFP->getType());
3426 }
3427
3428 // x86-32 PIC requires a PIC base register for constant pools.
3429 unsigned PICBase = 0;
3430 unsigned char OpFlag = 0;
3431 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3432 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3433 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3434 } else if (Subtarget->isPICStyleGOT()) {
3435 OpFlag = X86II::MO_GOTOFF;
3436 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3437 } else if (Subtarget->isPICStyleRIPRel() &&
3438 TM.getCodeModel() == CodeModel::Small) {
3439 PICBase = X86::RIP;
3440 }
3441
3442 // Create the load from the constant pool.
3443 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3444 unsigned ResultReg = createResultReg(RC);
3445
3446 if (CM == CodeModel::Large) {
3447 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3449 AddrReg)
3450 .addConstantPoolIndex(CPI, 0, OpFlag);
3451 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3452 TII.get(Opc), ResultReg);
3453 addDirectMem(MIB, AddrReg);
3454 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003455 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3456 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003457 MIB->addMemOperand(*FuncInfo.MF, MMO);
3458 return ResultReg;
3459 }
3460
3461 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3462 TII.get(Opc), ResultReg),
3463 CPI, PICBase, OpFlag);
3464 return ResultReg;
3465}
3466
3467unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3468 // Can't handle alternate code models yet.
3469 if (TM.getCodeModel() != CodeModel::Small)
3470 return 0;
3471
3472 // Materialize addresses with LEA/MOV instructions.
3473 X86AddressMode AM;
3474 if (X86SelectAddress(GV, AM)) {
3475 // If the expression is just a basereg, then we're done, otherwise we need
3476 // to emit an LEA.
3477 if (AM.BaseType == X86AddressMode::RegBase &&
3478 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3479 return AM.Base.Reg;
3480
3481 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3482 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003483 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003484 // The displacement code could be more than 32 bits away so we need to use
3485 // an instruction with a 64 bit immediate
3486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3487 ResultReg)
3488 .addGlobalAddress(GV);
3489 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003490 unsigned Opc =
3491 TLI.getPointerTy(DL) == MVT::i32
3492 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3493 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003494 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3495 TII.get(Opc), ResultReg), AM);
3496 }
3497 return ResultReg;
3498 }
3499 return 0;
3500}
3501
3502unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003503 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003504
3505 // Only handle simple types.
3506 if (!CEVT.isSimple())
3507 return 0;
3508 MVT VT = CEVT.getSimpleVT();
3509
3510 if (const auto *CI = dyn_cast<ConstantInt>(C))
3511 return X86MaterializeInt(CI, VT);
3512 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3513 return X86MaterializeFP(CFP, VT);
3514 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3515 return X86MaterializeGV(GV, VT);
3516
3517 return 0;
3518}
3519
3520unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3521 // Fail on dynamic allocas. At this point, getRegForValue has already
3522 // checked its CSE maps, so if we're here trying to handle a dynamic
3523 // alloca, we're not going to succeed. X86SelectAddress has a
3524 // check for dynamic allocas, because it's called directly from
3525 // various places, but targetMaterializeAlloca also needs a check
3526 // in order to avoid recursion between getRegForValue,
3527 // X86SelectAddrss, and targetMaterializeAlloca.
3528 if (!FuncInfo.StaticAllocaMap.count(C))
3529 return 0;
3530 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3531
3532 X86AddressMode AM;
3533 if (!X86SelectAddress(C, AM))
3534 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003535 unsigned Opc =
3536 TLI.getPointerTy(DL) == MVT::i32
3537 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3538 : X86::LEA64r;
3539 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003540 unsigned ResultReg = createResultReg(RC);
3541 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3542 TII.get(Opc), ResultReg), AM);
3543 return ResultReg;
3544}
3545
3546unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3547 MVT VT;
3548 if (!isTypeLegal(CF->getType(), VT))
3549 return 0;
3550
3551 // Get opcode and regclass for the given zero.
3552 unsigned Opc = 0;
3553 const TargetRegisterClass *RC = nullptr;
3554 switch (VT.SimpleTy) {
3555 default: return 0;
3556 case MVT::f32:
3557 if (X86ScalarSSEf32) {
3558 Opc = X86::FsFLD0SS;
3559 RC = &X86::FR32RegClass;
3560 } else {
3561 Opc = X86::LD_Fp032;
3562 RC = &X86::RFP32RegClass;
3563 }
3564 break;
3565 case MVT::f64:
3566 if (X86ScalarSSEf64) {
3567 Opc = X86::FsFLD0SD;
3568 RC = &X86::FR64RegClass;
3569 } else {
3570 Opc = X86::LD_Fp064;
3571 RC = &X86::RFP64RegClass;
3572 }
3573 break;
3574 case MVT::f80:
3575 // No f80 support yet.
3576 return 0;
3577 }
3578
3579 unsigned ResultReg = createResultReg(RC);
3580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3581 return ResultReg;
3582}
3583
3584
3585bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3586 const LoadInst *LI) {
3587 const Value *Ptr = LI->getPointerOperand();
3588 X86AddressMode AM;
3589 if (!X86SelectAddress(Ptr, AM))
3590 return false;
3591
3592 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3593
3594 unsigned Size = DL.getTypeAllocSize(LI->getType());
3595 unsigned Alignment = LI->getAlignment();
3596
3597 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3598 Alignment = DL.getABITypeAlignment(LI->getType());
3599
3600 SmallVector<MachineOperand, 8> AddrOps;
3601 AM.getFullAddress(AddrOps);
3602
Keno Fischere70b31f2015-06-08 20:09:58 +00003603 MachineInstr *Result = XII.foldMemoryOperandImpl(
3604 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3605 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003606 if (!Result)
3607 return false;
3608
Pete Cooperd31583d2015-05-06 21:37:19 +00003609 // The index register could be in the wrong register class. Unfortunately,
3610 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3611 // to just look at OpNo + the offset to the index reg. We actually need to
3612 // scan the instruction to find the index reg and see if its the correct reg
3613 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003614 unsigned OperandNo = 0;
3615 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3616 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3617 MachineOperand &MO = *I;
3618 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003619 continue;
3620 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003621 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003622 MO.getReg(), OperandNo);
3623 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003624 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003625 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003626 }
3627
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003628 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003629 MI->eraseFromParent();
3630 return true;
3631}
3632
3633
3634namespace llvm {
3635 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3636 const TargetLibraryInfo *libInfo) {
3637 return new X86FastISel(funcInfo, libInfo);
3638 }
3639}