Bug Summary

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