Bug Summary

File:lib/Target/X86/X86FastISel.cpp
Warning:line 2471, column 5
1st function call argument is an uninitialized value

Annotated Source Code

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