Bug Summary

File:lib/Target/X86/X86ISelDAGToDAG.cpp
Warning:line 574, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name X86ISelDAGToDAG.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86 -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp -faddrsig
1//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a DAG pattern matching instruction selector for X86,
10// converting from a legalized dag to a X86 dag.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
15#include "X86MachineFunctionInfo.h"
16#include "X86RegisterInfo.h"
17#include "X86Subtarget.h"
18#include "X86TargetMachine.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/SelectionDAGISel.h"
23#include "llvm/Config/llvm-config.h"
24#include "llvm/IR/ConstantRange.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/KnownBits.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
36#include <stdint.h>
37using namespace llvm;
38
39#define DEBUG_TYPE"x86-isel" "x86-isel"
40
41STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor")static llvm::Statistic NumLoadMoved = {"x86-isel", "NumLoadMoved"
, "Number of loads moved below TokenFactor", {0}, {false}}
;
42
43static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
44 cl::desc("Enable setting constant bits to reduce size of mask immediates"),
45 cl::Hidden);
46
47//===----------------------------------------------------------------------===//
48// Pattern Matcher Implementation
49//===----------------------------------------------------------------------===//
50
51namespace {
52 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
53 /// numbers for the leaves of the matched tree.
54 struct X86ISelAddressMode {
55 enum {
56 RegBase,
57 FrameIndexBase
58 } BaseType;
59
60 // This is really a union, discriminated by BaseType!
61 SDValue Base_Reg;
62 int Base_FrameIndex;
63
64 unsigned Scale;
65 SDValue IndexReg;
66 int32_t Disp;
67 SDValue Segment;
68 const GlobalValue *GV;
69 const Constant *CP;
70 const BlockAddress *BlockAddr;
71 const char *ES;
72 MCSymbol *MCSym;
73 int JT;
74 unsigned Align; // CP alignment.
75 unsigned char SymbolFlags; // X86II::MO_*
76 bool NegateIndex = false;
77
78 X86ISelAddressMode()
79 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
80 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
81 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
82
83 bool hasSymbolicDisplacement() const {
84 return GV != nullptr || CP != nullptr || ES != nullptr ||
85 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
86 }
87
88 bool hasBaseOrIndexReg() const {
89 return BaseType == FrameIndexBase ||
90 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
91 }
92
93 /// Return true if this addressing mode is already RIP-relative.
94 bool isRIPRelative() const {
95 if (BaseType != RegBase) return false;
96 if (RegisterSDNode *RegNode =
97 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
98 return RegNode->getReg() == X86::RIP;
99 return false;
100 }
101
102 void setBaseReg(SDValue Reg) {
103 BaseType = RegBase;
104 Base_Reg = Reg;
105 }
106
107#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
108 void dump(SelectionDAG *DAG = nullptr) {
109 dbgs() << "X86ISelAddressMode " << this << '\n';
110 dbgs() << "Base_Reg ";
111 if (Base_Reg.getNode())
112 Base_Reg.getNode()->dump(DAG);
113 else
114 dbgs() << "nul\n";
115 if (BaseType == FrameIndexBase)
116 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
117 dbgs() << " Scale " << Scale << '\n'
118 << "IndexReg ";
119 if (NegateIndex)
120 dbgs() << "negate ";
121 if (IndexReg.getNode())
122 IndexReg.getNode()->dump(DAG);
123 else
124 dbgs() << "nul\n";
125 dbgs() << " Disp " << Disp << '\n'
126 << "GV ";
127 if (GV)
128 GV->dump();
129 else
130 dbgs() << "nul";
131 dbgs() << " CP ";
132 if (CP)
133 CP->dump();
134 else
135 dbgs() << "nul";
136 dbgs() << '\n'
137 << "ES ";
138 if (ES)
139 dbgs() << ES;
140 else
141 dbgs() << "nul";
142 dbgs() << " MCSym ";
143 if (MCSym)
144 dbgs() << MCSym;
145 else
146 dbgs() << "nul";
147 dbgs() << " JT" << JT << " Align" << Align << '\n';
148 }
149#endif
150 };
151}
152
153namespace {
154 //===--------------------------------------------------------------------===//
155 /// ISel - X86-specific code to select X86 machine instructions for
156 /// SelectionDAG operations.
157 ///
158 class X86DAGToDAGISel final : public SelectionDAGISel {
159 /// Keep a pointer to the X86Subtarget around so that we can
160 /// make the right decision when generating code for different targets.
161 const X86Subtarget *Subtarget;
162
163 /// If true, selector should try to optimize for code size instead of
164 /// performance.
165 bool OptForSize;
166
167 /// If true, selector should try to optimize for minimum code size.
168 bool OptForMinSize;
169
170 /// Disable direct TLS access through segment registers.
171 bool IndirectTlsSegRefs;
172
173 public:
174 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
175 : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr), OptForSize(false),
176 OptForMinSize(false), IndirectTlsSegRefs(false) {}
177
178 StringRef getPassName() const override {
179 return "X86 DAG->DAG Instruction Selection";
180 }
181
182 bool runOnMachineFunction(MachineFunction &MF) override {
183 // Reset the subtarget each time through.
184 Subtarget = &MF.getSubtarget<X86Subtarget>();
185 IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
186 "indirect-tls-seg-refs");
187
188 // OptFor[Min]Size are used in pattern predicates that isel is matching.
189 OptForSize = MF.getFunction().hasOptSize();
190 OptForMinSize = MF.getFunction().hasMinSize();
191 assert((!OptForMinSize || OptForSize) &&(((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize"
) ? static_cast<void> (0) : __assert_fail ("(!OptForMinSize || OptForSize) && \"OptForMinSize implies OptForSize\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 192, __PRETTY_FUNCTION__))
192 "OptForMinSize implies OptForSize")(((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize"
) ? static_cast<void> (0) : __assert_fail ("(!OptForMinSize || OptForSize) && \"OptForMinSize implies OptForSize\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 192, __PRETTY_FUNCTION__))
;
193
194 SelectionDAGISel::runOnMachineFunction(MF);
195 return true;
196 }
197
198 void EmitFunctionEntryCode() override;
199
200 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
201
202 void PreprocessISelDAG() override;
203 void PostprocessISelDAG() override;
204
205// Include the pieces autogenerated from the target description.
206#include "X86GenDAGISel.inc"
207
208 private:
209 void Select(SDNode *N) override;
210
211 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
212 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
213 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
214 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
215 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
216 bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
217 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
218 unsigned Depth);
219 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
220 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
221 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 SDValue &Segment);
223 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
224 SDValue &Scale, SDValue &Index, SDValue &Disp,
225 SDValue &Segment);
226 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
227 bool selectLEAAddr(SDValue N, SDValue &Base,
228 SDValue &Scale, SDValue &Index, SDValue &Disp,
229 SDValue &Segment);
230 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
231 SDValue &Scale, SDValue &Index, SDValue &Disp,
232 SDValue &Segment);
233 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
234 SDValue &Scale, SDValue &Index, SDValue &Disp,
235 SDValue &Segment);
236 bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
237 SDValue &Base, SDValue &Scale,
238 SDValue &Index, SDValue &Disp,
239 SDValue &Segment,
240 SDValue &NodeWithChain);
241 bool selectRelocImm(SDValue N, SDValue &Op);
242
243 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
244 SDValue &Base, SDValue &Scale,
245 SDValue &Index, SDValue &Disp,
246 SDValue &Segment);
247
248 // Convenience method where P is also root.
249 bool tryFoldLoad(SDNode *P, SDValue N,
250 SDValue &Base, SDValue &Scale,
251 SDValue &Index, SDValue &Disp,
252 SDValue &Segment) {
253 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
254 }
255
256 /// Implement addressing mode selection for inline asm expressions.
257 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
258 unsigned ConstraintID,
259 std::vector<SDValue> &OutOps) override;
260
261 void emitSpecialCodeForMain();
262
263 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
264 MVT VT, SDValue &Base, SDValue &Scale,
265 SDValue &Index, SDValue &Disp,
266 SDValue &Segment) {
267 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
268 Base = CurDAG->getTargetFrameIndex(
269 AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
270 else if (AM.Base_Reg.getNode())
271 Base = AM.Base_Reg;
272 else
273 Base = CurDAG->getRegister(0, VT);
274
275 Scale = getI8Imm(AM.Scale, DL);
276
277 // Negate the index if needed.
278 if (AM.NegateIndex) {
279 unsigned NegOpc = VT == MVT::i64 ? X86::NEG64r : X86::NEG32r;
280 SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
281 AM.IndexReg), 0);
282 AM.IndexReg = Neg;
283 }
284
285 if (AM.IndexReg.getNode())
286 Index = AM.IndexReg;
287 else
288 Index = CurDAG->getRegister(0, VT);
289
290 // These are 32-bit even in 64-bit mode since RIP-relative offset
291 // is 32-bit.
292 if (AM.GV)
293 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
294 MVT::i32, AM.Disp,
295 AM.SymbolFlags);
296 else if (AM.CP)
297 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
298 AM.Align, AM.Disp, AM.SymbolFlags);
299 else if (AM.ES) {
300 assert(!AM.Disp && "Non-zero displacement is ignored with ES.")((!AM.Disp && "Non-zero displacement is ignored with ES."
) ? static_cast<void> (0) : __assert_fail ("!AM.Disp && \"Non-zero displacement is ignored with ES.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 300, __PRETTY_FUNCTION__))
;
301 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
302 } else if (AM.MCSym) {
303 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.")((!AM.Disp && "Non-zero displacement is ignored with MCSym."
) ? static_cast<void> (0) : __assert_fail ("!AM.Disp && \"Non-zero displacement is ignored with MCSym.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 303, __PRETTY_FUNCTION__))
;
304 assert(AM.SymbolFlags == 0 && "oo")((AM.SymbolFlags == 0 && "oo") ? static_cast<void>
(0) : __assert_fail ("AM.SymbolFlags == 0 && \"oo\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 304, __PRETTY_FUNCTION__))
;
305 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
306 } else if (AM.JT != -1) {
307 assert(!AM.Disp && "Non-zero displacement is ignored with JT.")((!AM.Disp && "Non-zero displacement is ignored with JT."
) ? static_cast<void> (0) : __assert_fail ("!AM.Disp && \"Non-zero displacement is ignored with JT.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 307, __PRETTY_FUNCTION__))
;
308 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
309 } else if (AM.BlockAddr)
310 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
311 AM.SymbolFlags);
312 else
313 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
314
315 if (AM.Segment.getNode())
316 Segment = AM.Segment;
317 else
318 Segment = CurDAG->getRegister(0, MVT::i16);
319 }
320
321 // Utility function to determine whether we should avoid selecting
322 // immediate forms of instructions for better code size or not.
323 // At a high level, we'd like to avoid such instructions when
324 // we have similar constants used within the same basic block
325 // that can be kept in a register.
326 //
327 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
328 uint32_t UseCount = 0;
329
330 // Do not want to hoist if we're not optimizing for size.
331 // TODO: We'd like to remove this restriction.
332 // See the comment in X86InstrInfo.td for more info.
333 if (!OptForSize)
334 return false;
335
336 // Walk all the users of the immediate.
337 for (SDNode::use_iterator UI = N->use_begin(),
338 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
339
340 SDNode *User = *UI;
341
342 // This user is already selected. Count it as a legitimate use and
343 // move on.
344 if (User->isMachineOpcode()) {
345 UseCount++;
346 continue;
347 }
348
349 // We want to count stores of immediates as real uses.
350 if (User->getOpcode() == ISD::STORE &&
351 User->getOperand(1).getNode() == N) {
352 UseCount++;
353 continue;
354 }
355
356 // We don't currently match users that have > 2 operands (except
357 // for stores, which are handled above)
358 // Those instruction won't match in ISEL, for now, and would
359 // be counted incorrectly.
360 // This may change in the future as we add additional instruction
361 // types.
362 if (User->getNumOperands() != 2)
363 continue;
364
365 // Immediates that are used for offsets as part of stack
366 // manipulation should be left alone. These are typically
367 // used to indicate SP offsets for argument passing and
368 // will get pulled into stores/pushes (implicitly).
369 if (User->getOpcode() == X86ISD::ADD ||
370 User->getOpcode() == ISD::ADD ||
371 User->getOpcode() == X86ISD::SUB ||
372 User->getOpcode() == ISD::SUB) {
373
374 // Find the other operand of the add/sub.
375 SDValue OtherOp = User->getOperand(0);
376 if (OtherOp.getNode() == N)
377 OtherOp = User->getOperand(1);
378
379 // Don't count if the other operand is SP.
380 RegisterSDNode *RegNode;
381 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
382 (RegNode = dyn_cast_or_null<RegisterSDNode>(
383 OtherOp->getOperand(1).getNode())))
384 if ((RegNode->getReg() == X86::ESP) ||
385 (RegNode->getReg() == X86::RSP))
386 continue;
387 }
388
389 // ... otherwise, count this and move on.
390 UseCount++;
391 }
392
393 // If we have more than 1 use, then recommend for hoisting.
394 return (UseCount > 1);
395 }
396
397 /// Return a target constant with the specified value of type i8.
398 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
399 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
400 }
401
402 /// Return a target constant with the specified value, of type i32.
403 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
404 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
405 }
406
407 /// Return a target constant with the specified value, of type i64.
408 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
409 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
410 }
411
412 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
413 const SDLoc &DL) {
414 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width")(((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width"
) ? static_cast<void> (0) : __assert_fail ("(VecWidth == 128 || VecWidth == 256) && \"Unexpected vector width\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 414, __PRETTY_FUNCTION__))
;
415 uint64_t Index = N->getConstantOperandVal(1);
416 MVT VecVT = N->getOperand(0).getSimpleValueType();
417 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
418 }
419
420 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
421 const SDLoc &DL) {
422 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width")(((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width"
) ? static_cast<void> (0) : __assert_fail ("(VecWidth == 128 || VecWidth == 256) && \"Unexpected vector width\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 uint64_t Index = N->getConstantOperandVal(2);
424 MVT VecVT = N->getSimpleValueType(0);
425 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
426 }
427
428 // Helper to detect unneeded and instructions on shift amounts. Called
429 // from PatFrags in tablegen.
430 bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
431 assert(N->getOpcode() == ISD::AND && "Unexpected opcode")((N->getOpcode() == ISD::AND && "Unexpected opcode"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::AND && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 431, __PRETTY_FUNCTION__))
;
432 const APInt &Val = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
433
434 if (Val.countTrailingOnes() >= Width)
435 return true;
436
437 APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
438 return Mask.countTrailingOnes() >= Width;
439 }
440
441 /// Return an SDNode that returns the value of the global base register.
442 /// Output instructions required to initialize the global base register,
443 /// if necessary.
444 SDNode *getGlobalBaseReg();
445
446 /// Return a reference to the TargetMachine, casted to the target-specific
447 /// type.
448 const X86TargetMachine &getTargetMachine() const {
449 return static_cast<const X86TargetMachine &>(TM);
450 }
451
452 /// Return a reference to the TargetInstrInfo, casted to the target-specific
453 /// type.
454 const X86InstrInfo *getInstrInfo() const {
455 return Subtarget->getInstrInfo();
456 }
457
458 /// Address-mode matching performs shift-of-and to and-of-shift
459 /// reassociation in order to expose more scaled addressing
460 /// opportunities.
461 bool ComplexPatternFuncMutatesDAG() const override {
462 return true;
463 }
464
465 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
466
467 /// Returns whether this is a relocatable immediate in the range
468 /// [-2^Width .. 2^Width-1].
469 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
470 if (auto *CN = dyn_cast<ConstantSDNode>(N))
471 return isInt<Width>(CN->getSExtValue());
472 return isSExtAbsoluteSymbolRef(Width, N);
473 }
474
475 // Indicates we should prefer to use a non-temporal load for this load.
476 bool useNonTemporalLoad(LoadSDNode *N) const {
477 if (!N->isNonTemporal())
478 return false;
479
480 unsigned StoreSize = N->getMemoryVT().getStoreSize();
481
482 if (N->getAlignment() < StoreSize)
483 return false;
484
485 switch (StoreSize) {
486 default: llvm_unreachable("Unsupported store size")::llvm::llvm_unreachable_internal("Unsupported store size", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 486)
;
487 case 4:
488 case 8:
489 return false;
490 case 16:
491 return Subtarget->hasSSE41();
492 case 32:
493 return Subtarget->hasAVX2();
494 case 64:
495 return Subtarget->hasAVX512();
496 }
497 }
498
499 bool foldLoadStoreIntoMemOperand(SDNode *Node);
500 MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
501 bool matchBitExtract(SDNode *Node);
502 bool shrinkAndImmediate(SDNode *N);
503 bool isMaskZeroExtended(SDNode *N) const;
504 bool tryShiftAmountMod(SDNode *N);
505 bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
506
507 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
508 const SDLoc &dl, MVT VT, SDNode *Node);
509 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
510 const SDLoc &dl, MVT VT, SDNode *Node,
511 SDValue &InFlag);
512
513 bool tryOptimizeRem8Extend(SDNode *N);
514
515 bool onlyUsesZeroFlag(SDValue Flags) const;
516 bool hasNoSignFlagUses(SDValue Flags) const;
517 bool hasNoCarryFlagUses(SDValue Flags) const;
518 };
519}
520
521
522// Returns true if this masked compare can be implemented legally with this
523// type.
524static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
525 unsigned Opcode = N->getOpcode();
526 if (Opcode == X86ISD::CMPM || Opcode == ISD::SETCC ||
527 Opcode == X86ISD::CMPM_SAE || Opcode == X86ISD::VFPCLASS) {
528 // We can get 256-bit 8 element types here without VLX being enabled. When
529 // this happens we will use 512-bit operations and the mask will not be
530 // zero extended.
531 EVT OpVT = N->getOperand(0).getValueType();
532 if (OpVT.is256BitVector() || OpVT.is128BitVector())
533 return Subtarget->hasVLX();
534
535 return true;
536 }
537 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
538 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
539 Opcode == X86ISD::FSETCCM_SAE)
540 return true;
541
542 return false;
543}
544
545// Returns true if we can assume the writer of the mask has zero extended it
546// for us.
547bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
548 // If this is an AND, check if we have a compare on either side. As long as
549 // one side guarantees the mask is zero extended, the AND will preserve those
550 // zeros.
551 if (N->getOpcode() == ISD::AND)
552 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
553 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
554
555 return isLegalMaskCompare(N, Subtarget);
556}
557
558bool
559X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
560 if (OptLevel == CodeGenOpt::None) return false;
29
Assuming the condition is false
30
Taking false branch
561
562 if (!N.hasOneUse())
31
Assuming the condition is false
32
Taking false branch
563 return false;
564
565 if (N.getOpcode() != ISD::LOAD)
33
Assuming the condition is false
34
Taking false branch
566 return true;
567
568 // Don't fold non-temporal loads if we have an instruction for them.
569 if (useNonTemporalLoad(cast<LoadSDNode>(N)))
35
Taking false branch
570 return false;
571
572 // If N is a load, do additional profitability checks.
573 if (U == Root) {
36
Assuming 'U' is equal to 'Root'
37
Taking true branch
574 switch (U->getOpcode()) {
38
Called C++ object pointer is null
575 default: break;
576 case X86ISD::ADD:
577 case X86ISD::ADC:
578 case X86ISD::SUB:
579 case X86ISD::SBB:
580 case X86ISD::AND:
581 case X86ISD::XOR:
582 case X86ISD::OR:
583 case ISD::ADD:
584 case ISD::ADDCARRY:
585 case ISD::AND:
586 case ISD::OR:
587 case ISD::XOR: {
588 SDValue Op1 = U->getOperand(1);
589
590 // If the other operand is a 8-bit immediate we should fold the immediate
591 // instead. This reduces code size.
592 // e.g.
593 // movl 4(%esp), %eax
594 // addl $4, %eax
595 // vs.
596 // movl $4, %eax
597 // addl 4(%esp), %eax
598 // The former is 2 bytes shorter. In case where the increment is 1, then
599 // the saving can be 4 bytes (by using incl %eax).
600 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
601 if (Imm->getAPIntValue().isSignedIntN(8))
602 return false;
603
604 // If this is a 64-bit AND with an immediate that fits in 32-bits,
605 // prefer using the smaller and over folding the load. This is needed to
606 // make sure immediates created by shrinkAndImmediate are always folded.
607 // Ideally we would narrow the load during DAG combine and get the
608 // best of both worlds.
609 if (U->getOpcode() == ISD::AND &&
610 Imm->getAPIntValue().getBitWidth() == 64 &&
611 Imm->getAPIntValue().isIntN(32))
612 return false;
613
614 // If this really a zext_inreg that can be represented with a movzx
615 // instruction, prefer that.
616 // TODO: We could shrink the load and fold if it is non-volatile.
617 if (U->getOpcode() == ISD::AND &&
618 (Imm->getAPIntValue() == UINT8_MAX(255) ||
619 Imm->getAPIntValue() == UINT16_MAX(65535) ||
620 Imm->getAPIntValue() == UINT32_MAX(4294967295U)))
621 return false;
622
623 // ADD/SUB with can negate the immediate and use the opposite operation
624 // to fit 128 into a sign extended 8 bit immediate.
625 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
626 (-Imm->getAPIntValue()).isSignedIntN(8))
627 return false;
628 }
629
630 // If the other operand is a TLS address, we should fold it instead.
631 // This produces
632 // movl %gs:0, %eax
633 // leal i@NTPOFF(%eax), %eax
634 // instead of
635 // movl $i@NTPOFF, %eax
636 // addl %gs:0, %eax
637 // if the block also has an access to a second TLS address this will save
638 // a load.
639 // FIXME: This is probably also true for non-TLS addresses.
640 if (Op1.getOpcode() == X86ISD::Wrapper) {
641 SDValue Val = Op1.getOperand(0);
642 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
643 return false;
644 }
645
646 // Don't fold load if this matches the BTS/BTR/BTC patterns.
647 // BTS: (or X, (shl 1, n))
648 // BTR: (and X, (rotl -2, n))
649 // BTC: (xor X, (shl 1, n))
650 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
651 if (U->getOperand(0).getOpcode() == ISD::SHL &&
652 isOneConstant(U->getOperand(0).getOperand(0)))
653 return false;
654
655 if (U->getOperand(1).getOpcode() == ISD::SHL &&
656 isOneConstant(U->getOperand(1).getOperand(0)))
657 return false;
658 }
659 if (U->getOpcode() == ISD::AND) {
660 SDValue U0 = U->getOperand(0);
661 SDValue U1 = U->getOperand(1);
662 if (U0.getOpcode() == ISD::ROTL) {
663 auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
664 if (C && C->getSExtValue() == -2)
665 return false;
666 }
667
668 if (U1.getOpcode() == ISD::ROTL) {
669 auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
670 if (C && C->getSExtValue() == -2)
671 return false;
672 }
673 }
674
675 break;
676 }
677 case ISD::SHL:
678 case ISD::SRA:
679 case ISD::SRL:
680 // Don't fold a load into a shift by immediate. The BMI2 instructions
681 // support folding a load, but not an immediate. The legacy instructions
682 // support folding an immediate, but can't fold a load. Folding an
683 // immediate is preferable to folding a load.
684 if (isa<ConstantSDNode>(U->getOperand(1)))
685 return false;
686
687 break;
688 }
689 }
690
691 // Prevent folding a load if this can implemented with an insert_subreg or
692 // a move that implicitly zeroes.
693 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
694 isNullConstant(Root->getOperand(2)) &&
695 (Root->getOperand(0).isUndef() ||
696 ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
697 return false;
698
699 return true;
700}
701
702/// Replace the original chain operand of the call with
703/// load's chain operand and move load below the call's chain operand.
704static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
705 SDValue Call, SDValue OrigChain) {
706 SmallVector<SDValue, 8> Ops;
707 SDValue Chain = OrigChain.getOperand(0);
708 if (Chain.getNode() == Load.getNode())
709 Ops.push_back(Load.getOperand(0));
710 else {
711 assert(Chain.getOpcode() == ISD::TokenFactor &&((Chain.getOpcode() == ISD::TokenFactor && "Unexpected chain operand"
) ? static_cast<void> (0) : __assert_fail ("Chain.getOpcode() == ISD::TokenFactor && \"Unexpected chain operand\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 712, __PRETTY_FUNCTION__))
712 "Unexpected chain operand")((Chain.getOpcode() == ISD::TokenFactor && "Unexpected chain operand"
) ? static_cast<void> (0) : __assert_fail ("Chain.getOpcode() == ISD::TokenFactor && \"Unexpected chain operand\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 712, __PRETTY_FUNCTION__))
;
713 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
714 if (Chain.getOperand(i).getNode() == Load.getNode())
715 Ops.push_back(Load.getOperand(0));
716 else
717 Ops.push_back(Chain.getOperand(i));
718 SDValue NewChain =
719 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
720 Ops.clear();
721 Ops.push_back(NewChain);
722 }
723 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
724 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
725 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
726 Load.getOperand(1), Load.getOperand(2));
727
728 Ops.clear();
729 Ops.push_back(SDValue(Load.getNode(), 1));
730 Ops.append(Call->op_begin() + 1, Call->op_end());
731 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
732}
733
734/// Return true if call address is a load and it can be
735/// moved below CALLSEQ_START and the chains leading up to the call.
736/// Return the CALLSEQ_START by reference as a second output.
737/// In the case of a tail call, there isn't a callseq node between the call
738/// chain and the load.
739static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
740 // The transformation is somewhat dangerous if the call's chain was glued to
741 // the call. After MoveBelowOrigChain the load is moved between the call and
742 // the chain, this can create a cycle if the load is not folded. So it is
743 // *really* important that we are sure the load will be folded.
744 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
745 return false;
746 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
747 if (!LD ||
748 LD->isVolatile() ||
749 LD->getAddressingMode() != ISD::UNINDEXED ||
750 LD->getExtensionType() != ISD::NON_EXTLOAD)
751 return false;
752
753 // Now let's find the callseq_start.
754 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
755 if (!Chain.hasOneUse())
756 return false;
757 Chain = Chain.getOperand(0);
758 }
759
760 if (!Chain.getNumOperands())
761 return false;
762 // Since we are not checking for AA here, conservatively abort if the chain
763 // writes to memory. It's not safe to move the callee (a load) across a store.
764 if (isa<MemSDNode>(Chain.getNode()) &&
765 cast<MemSDNode>(Chain.getNode())->writeMem())
766 return false;
767 if (Chain.getOperand(0).getNode() == Callee.getNode())
768 return true;
769 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
770 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
771 Callee.getValue(1).hasOneUse())
772 return true;
773 return false;
774}
775
776void X86DAGToDAGISel::PreprocessISelDAG() {
777 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
778 E = CurDAG->allnodes_end(); I != E; ) {
779 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
780
781 // If this is a target specific AND node with no flag usages, turn it back
782 // into ISD::AND to enable test instruction matching.
783 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
784 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
785 N->getOperand(0), N->getOperand(1));
786 --I;
787 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
788 ++I;
789 CurDAG->DeleteNode(N);
790 continue;
791 }
792
793 switch (N->getOpcode()) {
794 case ISD::SHL:
795 case ISD::SRA:
796 case ISD::SRL: {
797 // Replace vector shifts with their X86 specific equivalent so we don't
798 // need 2 sets of patterns.
799 if (!N->getValueType(0).isVector())
800 break;
801
802 unsigned NewOpc;
803 switch (N->getOpcode()) {
804 default: llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 804)
;
805 case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
806 case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
807 case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
808 }
809 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
810 N->getOperand(0), N->getOperand(1));
811 --I;
812 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
813 ++I;
814 CurDAG->DeleteNode(N);
815 continue;
816 }
817 case ISD::FCEIL:
818 case ISD::FFLOOR:
819 case ISD::FTRUNC:
820 case ISD::FNEARBYINT:
821 case ISD::FRINT: {
822 // Replace vector rounding with their X86 specific equivalent so we don't
823 // need 2 sets of patterns.
824 if (!N->getValueType(0).isVector())
825 break;
826
827 unsigned Imm;
828 switch (N->getOpcode()) {
829 default: llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 829)
;
830 case ISD::FCEIL: Imm = 0xA; break;
831 case ISD::FFLOOR: Imm = 0x9; break;
832 case ISD::FTRUNC: Imm = 0xB; break;
833 case ISD::FNEARBYINT: Imm = 0xC; break;
834 case ISD::FRINT: Imm = 0x4; break;
835 }
836 SDLoc dl(N);
837 SDValue Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl,
838 N->getValueType(0),
839 N->getOperand(0),
840 CurDAG->getConstant(Imm, dl, MVT::i8));
841 --I;
842 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
843 ++I;
844 CurDAG->DeleteNode(N);
845 continue;
846 }
847 }
848
849 if (OptLevel != CodeGenOpt::None &&
850 // Only do this when the target can fold the load into the call or
851 // jmp.
852 !Subtarget->useRetpolineIndirectCalls() &&
853 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
854 (N->getOpcode() == X86ISD::TC_RETURN &&
855 (Subtarget->is64Bit() ||
856 !getTargetMachine().isPositionIndependent())))) {
857 /// Also try moving call address load from outside callseq_start to just
858 /// before the call to allow it to be folded.
859 ///
860 /// [Load chain]
861 /// ^
862 /// |
863 /// [Load]
864 /// ^ ^
865 /// | |
866 /// / \--
867 /// / |
868 ///[CALLSEQ_START] |
869 /// ^ |
870 /// | |
871 /// [LOAD/C2Reg] |
872 /// | |
873 /// \ /
874 /// \ /
875 /// [CALL]
876 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
877 SDValue Chain = N->getOperand(0);
878 SDValue Load = N->getOperand(1);
879 if (!isCalleeLoad(Load, Chain, HasCallSeq))
880 continue;
881 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
882 ++NumLoadMoved;
883 continue;
884 }
885
886 // Lower fpround and fpextend nodes that target the FP stack to be store and
887 // load to the stack. This is a gross hack. We would like to simply mark
888 // these as being illegal, but when we do that, legalize produces these when
889 // it expands calls, then expands these in the same legalize pass. We would
890 // like dag combine to be able to hack on these between the call expansion
891 // and the node legalization. As such this pass basically does "really
892 // late" legalization of these inline with the X86 isel pass.
893 // FIXME: This should only happen when not compiled with -O0.
894 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
895 continue;
896
897 MVT SrcVT = N->getOperand(0).getSimpleValueType();
898 MVT DstVT = N->getSimpleValueType(0);
899
900 // If any of the sources are vectors, no fp stack involved.
901 if (SrcVT.isVector() || DstVT.isVector())
902 continue;
903
904 // If the source and destination are SSE registers, then this is a legal
905 // conversion that should not be lowered.
906 const X86TargetLowering *X86Lowering =
907 static_cast<const X86TargetLowering *>(TLI);
908 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
909 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
910 if (SrcIsSSE && DstIsSSE)
911 continue;
912
913 if (!SrcIsSSE && !DstIsSSE) {
914 // If this is an FPStack extension, it is a noop.
915 if (N->getOpcode() == ISD::FP_EXTEND)
916 continue;
917 // If this is a value-preserving FPStack truncation, it is a noop.
918 if (N->getConstantOperandVal(1))
919 continue;
920 }
921
922 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
923 // FPStack has extload and truncstore. SSE can fold direct loads into other
924 // operations. Based on this, decide what we want to do.
925 MVT MemVT;
926 if (N->getOpcode() == ISD::FP_ROUND)
927 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
928 else
929 MemVT = SrcIsSSE ? SrcVT : DstVT;
930
931 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
932 SDLoc dl(N);
933
934 // FIXME: optimize the case where the src/dest is a load or store?
935 SDValue Store =
936 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
937 MemTmp, MachinePointerInfo(), MemVT);
938 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
939 MachinePointerInfo(), MemVT);
940
941 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
942 // extload we created. This will cause general havok on the dag because
943 // anything below the conversion could be folded into other existing nodes.
944 // To avoid invalidating 'I', back it up to the convert node.
945 --I;
946 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
947
948 // Now that we did that, the node is dead. Increment the iterator to the
949 // next node to process, then delete N.
950 ++I;
951 CurDAG->DeleteNode(N);
952 }
953
954 // The load+call transform above can leave some dead nodes in the graph. Make
955 // sure we remove them. Its possible some of the other transforms do to so
956 // just remove dead nodes unconditionally.
957 CurDAG->RemoveDeadNodes();
958}
959
960// Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
961bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
962 unsigned Opc = N->getMachineOpcode();
963 if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
964 Opc != X86::MOVSX64rr8)
965 return false;
966
967 SDValue N0 = N->getOperand(0);
968
969 // We need to be extracting the lower bit of an extend.
970 if (!N0.isMachineOpcode() ||
971 N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
972 N0.getConstantOperandVal(1) != X86::sub_8bit)
973 return false;
974
975 // We're looking for either a movsx or movzx to match the original opcode.
976 unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
977 : X86::MOVSX32rr8_NOREX;
978 SDValue N00 = N0.getOperand(0);
979 if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
980 return false;
981
982 if (Opc == X86::MOVSX64rr8) {
983 // If we had a sign extend from 8 to 64 bits. We still need to go from 32
984 // to 64.
985 MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
986 MVT::i64, N00);
987 ReplaceUses(N, Extend);
988 } else {
989 // Ok we can drop this extend and just use the original extend.
990 ReplaceUses(N, N00.getNode());
991 }
992
993 return true;
994}
995
996void X86DAGToDAGISel::PostprocessISelDAG() {
997 // Skip peepholes at -O0.
998 if (TM.getOptLevel() == CodeGenOpt::None)
999 return;
1000
1001 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
1002
1003 bool MadeChange = false;
1004 while (Position != CurDAG->allnodes_begin()) {
1005 SDNode *N = &*--Position;
1006 // Skip dead nodes and any non-machine opcodes.
1007 if (N->use_empty() || !N->isMachineOpcode())
1008 continue;
1009
1010 if (tryOptimizeRem8Extend(N)) {
1011 MadeChange = true;
1012 continue;
1013 }
1014
1015 // Look for a TESTrr+ANDrr pattern where both operands of the test are
1016 // the same. Rewrite to remove the AND.
1017 unsigned Opc = N->getMachineOpcode();
1018 if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr ||
1019 Opc == X86::TEST32rr || Opc == X86::TEST64rr) &&
1020 N->getOperand(0) == N->getOperand(1) &&
1021 N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1022 N->getOperand(0).isMachineOpcode()) {
1023 SDValue And = N->getOperand(0);
1024 unsigned N0Opc = And.getMachineOpcode();
1025 if (N0Opc == X86::AND8rr || N0Opc == X86::AND16rr ||
1026 N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) {
1027 MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N),
1028 MVT::i32,
1029 And.getOperand(0),
1030 And.getOperand(1));
1031 ReplaceUses(N, Test);
1032 MadeChange = true;
1033 continue;
1034 }
1035 if (N0Opc == X86::AND8rm || N0Opc == X86::AND16rm ||
1036 N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) {
1037 unsigned NewOpc;
1038 switch (N0Opc) {
1039 case X86::AND8rm: NewOpc = X86::TEST8mr; break;
1040 case X86::AND16rm: NewOpc = X86::TEST16mr; break;
1041 case X86::AND32rm: NewOpc = X86::TEST32mr; break;
1042 case X86::AND64rm: NewOpc = X86::TEST64mr; break;
1043 }
1044
1045 // Need to swap the memory and register operand.
1046 SDValue Ops[] = { And.getOperand(1),
1047 And.getOperand(2),
1048 And.getOperand(3),
1049 And.getOperand(4),
1050 And.getOperand(5),
1051 And.getOperand(0),
1052 And.getOperand(6) /* Chain */ };
1053 MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1054 MVT::i32, MVT::Other, Ops);
1055 ReplaceUses(N, Test);
1056 MadeChange = true;
1057 continue;
1058 }
1059 }
1060
1061 // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
1062 // used. We're doing this late so we can prefer to fold the AND into masked
1063 // comparisons. Doing that can be better for the live range of the mask
1064 // register.
1065 if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr ||
1066 Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) &&
1067 N->getOperand(0) == N->getOperand(1) &&
1068 N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1069 N->getOperand(0).isMachineOpcode() &&
1070 onlyUsesZeroFlag(SDValue(N, 0))) {
1071 SDValue And = N->getOperand(0);
1072 unsigned N0Opc = And.getMachineOpcode();
1073 // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
1074 // KAND instructions and KTEST use the same ISA feature.
1075 if (N0Opc == X86::KANDBrr ||
1076 (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) ||
1077 N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) {
1078 unsigned NewOpc;
1079 switch (Opc) {
1080 default: llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1080)
;
1081 case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break;
1082 case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break;
1083 case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break;
1084 case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break;
1085 }
1086 MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1087 MVT::i32,
1088 And.getOperand(0),
1089 And.getOperand(1));
1090 ReplaceUses(N, KTest);
1091 MadeChange = true;
1092 continue;
1093 }
1094 }
1095
1096 // Attempt to remove vectors moves that were inserted to zero upper bits.
1097 if (Opc != TargetOpcode::SUBREG_TO_REG)
1098 continue;
1099
1100 unsigned SubRegIdx = N->getConstantOperandVal(2);
1101 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
1102 continue;
1103
1104 SDValue Move = N->getOperand(1);
1105 if (!Move.isMachineOpcode())
1106 continue;
1107
1108 // Make sure its one of the move opcodes we recognize.
1109 switch (Move.getMachineOpcode()) {
1110 default:
1111 continue;
1112 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
1113 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
1114 case X86::VMOVDQArr: case X86::VMOVDQUrr:
1115 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
1116 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
1117 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
1118 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
1119 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
1120 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
1121 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
1122 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
1123 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
1124 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
1125 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
1126 break;
1127 }
1128
1129 SDValue In = Move.getOperand(0);
1130 if (!In.isMachineOpcode() ||
1131 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1132 continue;
1133
1134 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1135 // the SHA instructions which use a legacy encoding.
1136 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1137 if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
1138 (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
1139 (TSFlags & X86II::EncodingMask) != X86II::XOP)
1140 continue;
1141
1142 // Producing instruction is another vector instruction. We can drop the
1143 // move.
1144 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
1145 MadeChange = true;
1146 }
1147
1148 if (MadeChange)
1149 CurDAG->RemoveDeadNodes();
1150}
1151
1152
1153/// Emit any code that needs to be executed only in the main function.
1154void X86DAGToDAGISel::emitSpecialCodeForMain() {
1155 if (Subtarget->isTargetCygMing()) {
1156 TargetLowering::ArgListTy Args;
1157 auto &DL = CurDAG->getDataLayout();
1158
1159 TargetLowering::CallLoweringInfo CLI(*CurDAG);
1160 CLI.setChain(CurDAG->getRoot())
1161 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1162 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1163 std::move(Args));
1164 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1165 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1166 CurDAG->setRoot(Result.second);
1167 }
1168}
1169
1170void X86DAGToDAGISel::EmitFunctionEntryCode() {
1171 // If this is main, emit special code for main.
1172 const Function &F = MF->getFunction();
1173 if (F.hasExternalLinkage() && F.getName() == "main")
1174 emitSpecialCodeForMain();
1175}
1176
1177static bool isDispSafeForFrameIndex(int64_t Val) {
1178 // On 64-bit platforms, we can run into an issue where a frame index
1179 // includes a displacement that, when added to the explicit displacement,
1180 // will overflow the displacement field. Assuming that the frame index
1181 // displacement fits into a 31-bit integer (which is only slightly more
1182 // aggressive than the current fundamental assumption that it fits into
1183 // a 32-bit integer), a 31-bit disp should always be safe.
1184 return isInt<31>(Val);
1185}
1186
1187bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1188 X86ISelAddressMode &AM) {
1189 // If there's no offset to fold, we don't need to do any work.
1190 if (Offset == 0)
1191 return false;
1192
1193 // Cannot combine ExternalSymbol displacements with integer offsets.
1194 if (AM.ES || AM.MCSym)
1195 return true;
1196
1197 int64_t Val = AM.Disp + Offset;
1198 CodeModel::Model M = TM.getCodeModel();
1199 if (Subtarget->is64Bit()) {
1200 if (!X86::isOffsetSuitableForCodeModel(Val, M,
1201 AM.hasSymbolicDisplacement()))
1202 return true;
1203 // In addition to the checks required for a register base, check that
1204 // we do not try to use an unsafe Disp with a frame index.
1205 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1206 !isDispSafeForFrameIndex(Val))
1207 return true;
1208 }
1209 AM.Disp = Val;
1210 return false;
1211
1212}
1213
1214bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
1215 SDValue Address = N->getOperand(1);
1216
1217 // load gs:0 -> GS segment register.
1218 // load fs:0 -> FS segment register.
1219 //
1220 // This optimization is valid because the GNU TLS model defines that
1221 // gs:0 (or fs:0 on X86-64) contains its own address.
1222 // For more information see http://people.redhat.com/drepper/tls.pdf
1223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
1224 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
1225 !IndirectTlsSegRefs &&
1226 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1227 Subtarget->isTargetFuchsia()))
1228 switch (N->getPointerInfo().getAddrSpace()) {
1229 case 256:
1230 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1231 return false;
1232 case 257:
1233 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1234 return false;
1235 // Address space 258 is not handled here, because it is not used to
1236 // address TLS areas.
1237 }
1238
1239 return true;
1240}
1241
1242/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1243/// mode. These wrap things that will resolve down into a symbol reference.
1244/// If no match is possible, this returns true, otherwise it returns false.
1245bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1246 // If the addressing mode already has a symbol as the displacement, we can
1247 // never match another symbol.
1248 if (AM.hasSymbolicDisplacement())
1249 return true;
1250
1251 bool IsRIPRelTLS = false;
1252 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1253 if (IsRIPRel) {
1254 SDValue Val = N.getOperand(0);
1255 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
1256 IsRIPRelTLS = true;
1257 }
1258
1259 // We can't use an addressing mode in the 64-bit large code model.
1260 // Global TLS addressing is an exception. In the medium code model,
1261 // we use can use a mode when RIP wrappers are present.
1262 // That signifies access to globals that are known to be "near",
1263 // such as the GOT itself.
1264 CodeModel::Model M = TM.getCodeModel();
1265 if (Subtarget->is64Bit() &&
1266 ((M == CodeModel::Large && !IsRIPRelTLS) ||
1267 (M == CodeModel::Medium && !IsRIPRel)))
1268 return true;
1269
1270 // Base and index reg must be 0 in order to use %rip as base.
1271 if (IsRIPRel && AM.hasBaseOrIndexReg())
1272 return true;
1273
1274 // Make a local copy in case we can't do this fold.
1275 X86ISelAddressMode Backup = AM;
1276
1277 int64_t Offset = 0;
1278 SDValue N0 = N.getOperand(0);
1279 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1280 AM.GV = G->getGlobal();
1281 AM.SymbolFlags = G->getTargetFlags();
1282 Offset = G->getOffset();
1283 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1284 AM.CP = CP->getConstVal();
1285 AM.Align = CP->getAlignment();
1286 AM.SymbolFlags = CP->getTargetFlags();
1287 Offset = CP->getOffset();
1288 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1289 AM.ES = S->getSymbol();
1290 AM.SymbolFlags = S->getTargetFlags();
1291 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1292 AM.MCSym = S->getMCSymbol();
1293 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1294 AM.JT = J->getIndex();
1295 AM.SymbolFlags = J->getTargetFlags();
1296 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1297 AM.BlockAddr = BA->getBlockAddress();
1298 AM.SymbolFlags = BA->getTargetFlags();
1299 Offset = BA->getOffset();
1300 } else
1301 llvm_unreachable("Unhandled symbol reference node.")::llvm::llvm_unreachable_internal("Unhandled symbol reference node."
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1301)
;
1302
1303 if (foldOffsetIntoAddress(Offset, AM)) {
1304 AM = Backup;
1305 return true;
1306 }
1307
1308 if (IsRIPRel)
1309 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
1310
1311 // Commit the changes now that we know this fold is safe.
1312 return false;
1313}
1314
1315/// Add the specified node to the specified addressing mode, returning true if
1316/// it cannot be done. This just pattern matches for the addressing mode.
1317bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1318 if (matchAddressRecursively(N, AM, 0))
1319 return true;
1320
1321 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1322 // a smaller encoding and avoids a scaled-index.
1323 if (AM.Scale == 2 &&
1324 AM.BaseType == X86ISelAddressMode::RegBase &&
1325 AM.Base_Reg.getNode() == nullptr) {
1326 AM.Base_Reg = AM.IndexReg;
1327 AM.Scale = 1;
1328 }
1329
1330 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1331 // because it has a smaller encoding.
1332 // TODO: Which other code models can use this?
1333 switch (TM.getCodeModel()) {
1334 default: break;
1335 case CodeModel::Small:
1336 case CodeModel::Kernel:
1337 if (Subtarget->is64Bit() &&
1338 AM.Scale == 1 &&
1339 AM.BaseType == X86ISelAddressMode::RegBase &&
1340 AM.Base_Reg.getNode() == nullptr &&
1341 AM.IndexReg.getNode() == nullptr &&
1342 AM.SymbolFlags == X86II::MO_NO_FLAG &&
1343 AM.hasSymbolicDisplacement())
1344 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
1345 break;
1346 }
1347
1348 return false;
1349}
1350
1351bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
1352 unsigned Depth) {
1353 // Add an artificial use to this node so that we can keep track of
1354 // it if it gets CSE'd with a different node.
1355 HandleSDNode Handle(N);
1356
1357 X86ISelAddressMode Backup = AM;
1358 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1359 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1360 return false;
1361 AM = Backup;
1362
1363 // Try again after commuting the operands.
1364 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1365 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1366 return false;
1367 AM = Backup;
1368
1369 // If we couldn't fold both operands into the address at the same time,
1370 // see if we can just put each operand into a register and fold at least
1371 // the add.
1372 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1373 !AM.Base_Reg.getNode() &&
1374 !AM.IndexReg.getNode()) {
1375 N = Handle.getValue();
1376 AM.Base_Reg = N.getOperand(0);
1377 AM.IndexReg = N.getOperand(1);
1378 AM.Scale = 1;
1379 return false;
1380 }
1381 N = Handle.getValue();
1382 return true;
1383}
1384
1385// Insert a node into the DAG at least before the Pos node's position. This
1386// will reposition the node as needed, and will assign it a node ID that is <=
1387// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1388// IDs! The selection DAG must no longer depend on their uniqueness when this
1389// is used.
1390static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
1391 if (N->getNodeId() == -1 ||
1392 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1393 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1394 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1395 // Mark Node as invalid for pruning as after this it may be a successor to a
1396 // selected node but otherwise be in the same position of Pos.
1397 // Conservatively mark it with the same -abs(Id) to assure node id
1398 // invariant is preserved.
1399 N->setNodeId(Pos->getNodeId());
1400 SelectionDAGISel::InvalidateNodeId(N.getNode());
1401 }
1402}
1403
1404// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1405// safe. This allows us to convert the shift and and into an h-register
1406// extract and a scaled index. Returns false if the simplification is
1407// performed.
1408static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1409 uint64_t Mask,
1410 SDValue Shift, SDValue X,
1411 X86ISelAddressMode &AM) {
1412 if (Shift.getOpcode() != ISD::SRL ||
1413 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1414 !Shift.hasOneUse())
1415 return true;
1416
1417 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1418 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1419 Mask != (0xffu << ScaleLog))
1420 return true;
1421
1422 MVT VT = N.getSimpleValueType();
1423 SDLoc DL(N);
1424 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1425 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1426 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1427 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1428 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1429 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1430
1431 // Insert the new nodes into the topological ordering. We must do this in
1432 // a valid topological ordering as nothing is going to go back and re-sort
1433 // these nodes. We continually insert before 'N' in sequence as this is
1434 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1435 // hierarchy left to express.
1436 insertDAGNode(DAG, N, Eight);
1437 insertDAGNode(DAG, N, Srl);
1438 insertDAGNode(DAG, N, NewMask);
1439 insertDAGNode(DAG, N, And);
1440 insertDAGNode(DAG, N, ShlCount);
1441 insertDAGNode(DAG, N, Shl);
1442 DAG.ReplaceAllUsesWith(N, Shl);
1443 DAG.RemoveDeadNode(N.getNode());
1444 AM.IndexReg = And;
1445 AM.Scale = (1 << ScaleLog);
1446 return false;
1447}
1448
1449// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1450// allows us to fold the shift into this addressing mode. Returns false if the
1451// transform succeeded.
1452static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1453 X86ISelAddressMode &AM) {
1454 SDValue Shift = N.getOperand(0);
1455
1456 // Use a signed mask so that shifting right will insert sign bits. These
1457 // bits will be removed when we shift the result left so it doesn't matter
1458 // what we use. This might allow a smaller immediate encoding.
1459 int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
1460
1461 // If we have an any_extend feeding the AND, look through it to see if there
1462 // is a shift behind it. But only if the AND doesn't use the extended bits.
1463 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
1464 bool FoundAnyExtend = false;
1465 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
1466 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
1467 isUInt<32>(Mask)) {
1468 FoundAnyExtend = true;
1469 Shift = Shift.getOperand(0);
1470 }
1471
1472 if (Shift.getOpcode() != ISD::SHL ||
1473 !isa<ConstantSDNode>(Shift.getOperand(1)))
1474 return true;
1475
1476 SDValue X = Shift.getOperand(0);
1477
1478 // Not likely to be profitable if either the AND or SHIFT node has more
1479 // than one use (unless all uses are for address computation). Besides,
1480 // isel mechanism requires their node ids to be reused.
1481 if (!N.hasOneUse() || !Shift.hasOneUse())
1482 return true;
1483
1484 // Verify that the shift amount is something we can fold.
1485 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1486 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1487 return true;
1488
1489 MVT VT = N.getSimpleValueType();
1490 SDLoc DL(N);
1491 if (FoundAnyExtend) {
1492 SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
1493 insertDAGNode(DAG, N, NewX);
1494 X = NewX;
1495 }
1496
1497 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
1498 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1499 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1500
1501 // Insert the new nodes into the topological ordering. We must do this in
1502 // a valid topological ordering as nothing is going to go back and re-sort
1503 // these nodes. We continually insert before 'N' in sequence as this is
1504 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1505 // hierarchy left to express.
1506 insertDAGNode(DAG, N, NewMask);
1507 insertDAGNode(DAG, N, NewAnd);
1508 insertDAGNode(DAG, N, NewShift);
1509 DAG.ReplaceAllUsesWith(N, NewShift);
1510 DAG.RemoveDeadNode(N.getNode());
1511
1512 AM.Scale = 1 << ShiftAmt;
1513 AM.IndexReg = NewAnd;
1514 return false;
1515}
1516
1517// Implement some heroics to detect shifts of masked values where the mask can
1518// be replaced by extending the shift and undoing that in the addressing mode
1519// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1520// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1521// the addressing mode. This results in code such as:
1522//
1523// int f(short *y, int *lookup_table) {
1524// ...
1525// return *y + lookup_table[*y >> 11];
1526// }
1527//
1528// Turning into:
1529// movzwl (%rdi), %eax
1530// movl %eax, %ecx
1531// shrl $11, %ecx
1532// addl (%rsi,%rcx,4), %eax
1533//
1534// Instead of:
1535// movzwl (%rdi), %eax
1536// movl %eax, %ecx
1537// shrl $9, %ecx
1538// andl $124, %rcx
1539// addl (%rsi,%rcx), %eax
1540//
1541// Note that this function assumes the mask is provided as a mask *after* the
1542// value is shifted. The input chain may or may not match that, but computing
1543// such a mask is trivial.
1544static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1545 uint64_t Mask,
1546 SDValue Shift, SDValue X,
1547 X86ISelAddressMode &AM) {
1548 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1549 !isa<ConstantSDNode>(Shift.getOperand(1)))
1550 return true;
1551
1552 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1553 unsigned MaskLZ = countLeadingZeros(Mask);
1554 unsigned MaskTZ = countTrailingZeros(Mask);
1555
1556 // The amount of shift we're trying to fit into the addressing mode is taken
1557 // from the trailing zeros of the mask.
1558 unsigned AMShiftAmt = MaskTZ;
1559
1560 // There is nothing we can do here unless the mask is removing some bits.
1561 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1562 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1563
1564 // We also need to ensure that mask is a continuous run of bits.
1565 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1566
1567 // Scale the leading zero count down based on the actual size of the value.
1568 // Also scale it down based on the size of the shift.
1569 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1570 if (MaskLZ < ScaleDown)
1571 return true;
1572 MaskLZ -= ScaleDown;
1573
1574 // The final check is to ensure that any masked out high bits of X are
1575 // already known to be zero. Otherwise, the mask has a semantic impact
1576 // other than masking out a couple of low bits. Unfortunately, because of
1577 // the mask, zero extensions will be removed from operands in some cases.
1578 // This code works extra hard to look through extensions because we can
1579 // replace them with zero extensions cheaply if necessary.
1580 bool ReplacingAnyExtend = false;
1581 if (X.getOpcode() == ISD::ANY_EXTEND) {
1582 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1583 X.getOperand(0).getSimpleValueType().getSizeInBits();
1584 // Assume that we'll replace the any-extend with a zero-extend, and
1585 // narrow the search to the extended value.
1586 X = X.getOperand(0);
1587 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1588 ReplacingAnyExtend = true;
1589 }
1590 APInt MaskedHighBits =
1591 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1592 KnownBits Known = DAG.computeKnownBits(X);
1593 if (MaskedHighBits != Known.Zero) return true;
1594
1595 // We've identified a pattern that can be transformed into a single shift
1596 // and an addressing mode. Make it so.
1597 MVT VT = N.getSimpleValueType();
1598 if (ReplacingAnyExtend) {
1599 assert(X.getValueType() != VT)((X.getValueType() != VT) ? static_cast<void> (0) : __assert_fail
("X.getValueType() != VT", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1599, __PRETTY_FUNCTION__))
;
1600 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1601 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1602 insertDAGNode(DAG, N, NewX);
1603 X = NewX;
1604 }
1605 SDLoc DL(N);
1606 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1607 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1608 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1609 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1610
1611 // Insert the new nodes into the topological ordering. We must do this in
1612 // a valid topological ordering as nothing is going to go back and re-sort
1613 // these nodes. We continually insert before 'N' in sequence as this is
1614 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1615 // hierarchy left to express.
1616 insertDAGNode(DAG, N, NewSRLAmt);
1617 insertDAGNode(DAG, N, NewSRL);
1618 insertDAGNode(DAG, N, NewSHLAmt);
1619 insertDAGNode(DAG, N, NewSHL);
1620 DAG.ReplaceAllUsesWith(N, NewSHL);
1621 DAG.RemoveDeadNode(N.getNode());
1622
1623 AM.Scale = 1 << AMShiftAmt;
1624 AM.IndexReg = NewSRL;
1625 return false;
1626}
1627
1628// Transform "(X >> SHIFT) & (MASK << C1)" to
1629// "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
1630// matched to a BEXTR later. Returns false if the simplification is performed.
1631static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
1632 uint64_t Mask,
1633 SDValue Shift, SDValue X,
1634 X86ISelAddressMode &AM,
1635 const X86Subtarget &Subtarget) {
1636 if (Shift.getOpcode() != ISD::SRL ||
1637 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1638 !Shift.hasOneUse() || !N.hasOneUse())
1639 return true;
1640
1641 // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
1642 if (!Subtarget.hasTBM() &&
1643 !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
1644 return true;
1645
1646 // We need to ensure that mask is a continuous run of bits.
1647 if (!isShiftedMask_64(Mask)) return true;
1648
1649 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1650
1651 // The amount of shift we're trying to fit into the addressing mode is taken
1652 // from the trailing zeros of the mask.
1653 unsigned AMShiftAmt = countTrailingZeros(Mask);
1654
1655 // There is nothing we can do here unless the mask is removing some bits.
1656 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1657 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1658
1659 MVT VT = N.getSimpleValueType();
1660 SDLoc DL(N);
1661 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1662 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1663 SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
1664 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
1665 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1666 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
1667
1668 // Insert the new nodes into the topological ordering. We must do this in
1669 // a valid topological ordering as nothing is going to go back and re-sort
1670 // these nodes. We continually insert before 'N' in sequence as this is
1671 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1672 // hierarchy left to express.
1673 insertDAGNode(DAG, N, NewSRLAmt);
1674 insertDAGNode(DAG, N, NewSRL);
1675 insertDAGNode(DAG, N, NewMask);
1676 insertDAGNode(DAG, N, NewAnd);
1677 insertDAGNode(DAG, N, NewSHLAmt);
1678 insertDAGNode(DAG, N, NewSHL);
1679 DAG.ReplaceAllUsesWith(N, NewSHL);
1680 DAG.RemoveDeadNode(N.getNode());
1681
1682 AM.Scale = 1 << AMShiftAmt;
1683 AM.IndexReg = NewAnd;
1684 return false;
1685}
1686
1687bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1688 unsigned Depth) {
1689 SDLoc dl(N);
1690 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { { dbgs() << "MatchAddress: "; AM.dump(CurDAG
); }; } } while (false)
1691 dbgs() << "MatchAddress: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { { dbgs() << "MatchAddress: "; AM.dump(CurDAG
); }; } } while (false)
1692 AM.dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { { dbgs() << "MatchAddress: "; AM.dump(CurDAG
); }; } } while (false)
1693 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { { dbgs() << "MatchAddress: "; AM.dump(CurDAG
); }; } } while (false)
;
1694 // Limit recursion.
1695 if (Depth > 5)
1696 return matchAddressBase(N, AM);
1697
1698 // If this is already a %rip relative address, we can only merge immediates
1699 // into it. Instead of handling this in every case, we handle it here.
1700 // RIP relative addressing: %rip + 32-bit displacement!
1701 if (AM.isRIPRelative()) {
1702 // FIXME: JumpTable and ExternalSymbol address currently don't like
1703 // displacements. It isn't very important, but this should be fixed for
1704 // consistency.
1705 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1706 return true;
1707
1708 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1709 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1710 return false;
1711 return true;
1712 }
1713
1714 switch (N.getOpcode()) {
1715 default: break;
1716 case ISD::LOCAL_RECOVER: {
1717 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1718 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1719 // Use the symbol and don't prefix it.
1720 AM.MCSym = ESNode->getMCSymbol();
1721 return false;
1722 }
1723 break;
1724 }
1725 case ISD::Constant: {
1726 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1727 if (!foldOffsetIntoAddress(Val, AM))
1728 return false;
1729 break;
1730 }
1731
1732 case X86ISD::Wrapper:
1733 case X86ISD::WrapperRIP:
1734 if (!matchWrapper(N, AM))
1735 return false;
1736 break;
1737
1738 case ISD::LOAD:
1739 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1740 return false;
1741 break;
1742
1743 case ISD::FrameIndex:
1744 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1745 AM.Base_Reg.getNode() == nullptr &&
1746 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1747 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1748 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1749 return false;
1750 }
1751 break;
1752
1753 case ISD::SHL:
1754 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1755 break;
1756
1757 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1758 unsigned Val = CN->getZExtValue();
1759 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1760 // that the base operand remains free for further matching. If
1761 // the base doesn't end up getting used, a post-processing step
1762 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1763 if (Val == 1 || Val == 2 || Val == 3) {
1764 AM.Scale = 1 << Val;
1765 SDValue ShVal = N.getOperand(0);
1766
1767 // Okay, we know that we have a scale by now. However, if the scaled
1768 // value is an add of something and a constant, we can fold the
1769 // constant into the disp field here.
1770 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1771 AM.IndexReg = ShVal.getOperand(0);
1772 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1773 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1774 if (!foldOffsetIntoAddress(Disp, AM))
1775 return false;
1776 }
1777
1778 AM.IndexReg = ShVal;
1779 return false;
1780 }
1781 }
1782 break;
1783
1784 case ISD::SRL: {
1785 // Scale must not be used already.
1786 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1787
1788 // We only handle up to 64-bit values here as those are what matter for
1789 // addressing mode optimizations.
1790 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&((N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"
) ? static_cast<void> (0) : __assert_fail ("N.getSimpleValueType().getSizeInBits() <= 64 && \"Unexpected value size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1791, __PRETTY_FUNCTION__))
1791 "Unexpected value size!")((N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"
) ? static_cast<void> (0) : __assert_fail ("N.getSimpleValueType().getSizeInBits() <= 64 && \"Unexpected value size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1791, __PRETTY_FUNCTION__))
;
1792
1793 SDValue And = N.getOperand(0);
1794 if (And.getOpcode() != ISD::AND) break;
1795 SDValue X = And.getOperand(0);
1796
1797 // The mask used for the transform is expected to be post-shift, but we
1798 // found the shift first so just apply the shift to the mask before passing
1799 // it down.
1800 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1801 !isa<ConstantSDNode>(And.getOperand(1)))
1802 break;
1803 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1804
1805 // Try to fold the mask and shift into the scale, and return false if we
1806 // succeed.
1807 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1808 return false;
1809 break;
1810 }
1811
1812 case ISD::SMUL_LOHI:
1813 case ISD::UMUL_LOHI:
1814 // A mul_lohi where we need the low part can be folded as a plain multiply.
1815 if (N.getResNo() != 0) break;
1816 LLVM_FALLTHROUGH[[clang::fallthrough]];
1817 case ISD::MUL:
1818 case X86ISD::MUL_IMM:
1819 // X*[3,5,9] -> X+X*[2,4,8]
1820 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1821 AM.Base_Reg.getNode() == nullptr &&
1822 AM.IndexReg.getNode() == nullptr) {
1823 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1824 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1825 CN->getZExtValue() == 9) {
1826 AM.Scale = unsigned(CN->getZExtValue())-1;
1827
1828 SDValue MulVal = N.getOperand(0);
1829 SDValue Reg;
1830
1831 // Okay, we know that we have a scale by now. However, if the scaled
1832 // value is an add of something and a constant, we can fold the
1833 // constant into the disp field here.
1834 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1835 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1836 Reg = MulVal.getOperand(0);
1837 ConstantSDNode *AddVal =
1838 cast<ConstantSDNode>(MulVal.getOperand(1));
1839 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1840 if (foldOffsetIntoAddress(Disp, AM))
1841 Reg = N.getOperand(0);
1842 } else {
1843 Reg = N.getOperand(0);
1844 }
1845
1846 AM.IndexReg = AM.Base_Reg = Reg;
1847 return false;
1848 }
1849 }
1850 break;
1851
1852 case ISD::SUB: {
1853 // Given A-B, if A can be completely folded into the address and
1854 // the index field with the index field unused, use -B as the index.
1855 // This is a win if a has multiple parts that can be folded into
1856 // the address. Also, this saves a mov if the base register has
1857 // other uses, since it avoids a two-address sub instruction, however
1858 // it costs an additional mov if the index register has other uses.
1859
1860 // Add an artificial use to this node so that we can keep track of
1861 // it if it gets CSE'd with a different node.
1862 HandleSDNode Handle(N);
1863
1864 // Test if the LHS of the sub can be folded.
1865 X86ISelAddressMode Backup = AM;
1866 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1867 N = Handle.getValue();
1868 AM = Backup;
1869 break;
1870 }
1871 N = Handle.getValue();
1872 // Test if the index field is free for use.
1873 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1874 AM = Backup;
1875 break;
1876 }
1877
1878 int Cost = 0;
1879 SDValue RHS = N.getOperand(1);
1880 // If the RHS involves a register with multiple uses, this
1881 // transformation incurs an extra mov, due to the neg instruction
1882 // clobbering its operand.
1883 if (!RHS.getNode()->hasOneUse() ||
1884 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1885 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1886 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1887 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1888 RHS.getOperand(0).getValueType() == MVT::i32))
1889 ++Cost;
1890 // If the base is a register with multiple uses, this
1891 // transformation may save a mov.
1892 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1893 !AM.Base_Reg.getNode()->hasOneUse()) ||
1894 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1895 --Cost;
1896 // If the folded LHS was interesting, this transformation saves
1897 // address arithmetic.
1898 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1899 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1900 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1901 --Cost;
1902 // If it doesn't look like it may be an overall win, don't do it.
1903 if (Cost >= 0) {
1904 AM = Backup;
1905 break;
1906 }
1907
1908 // Ok, the transformation is legal and appears profitable. Go for it.
1909 // Negation will be emitted later to avoid creating dangling nodes if this
1910 // was an unprofitable LEA.
1911 AM.IndexReg = RHS;
1912 AM.NegateIndex = true;
1913 AM.Scale = 1;
1914 return false;
1915 }
1916
1917 case ISD::ADD:
1918 if (!matchAdd(N, AM, Depth))
1919 return false;
1920 break;
1921
1922 case ISD::OR:
1923 // We want to look through a transform in InstCombine and DAGCombiner that
1924 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1925 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1926 // An 'lea' can then be used to match the shift (multiply) and add:
1927 // and $1, %esi
1928 // lea (%rsi, %rdi, 8), %rax
1929 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1930 !matchAdd(N, AM, Depth))
1931 return false;
1932 break;
1933
1934 case ISD::AND: {
1935 // Perform some heroic transforms on an and of a constant-count shift
1936 // with a constant to enable use of the scaled offset field.
1937
1938 // Scale must not be used already.
1939 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1940
1941 // We only handle up to 64-bit values here as those are what matter for
1942 // addressing mode optimizations.
1943 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&((N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"
) ? static_cast<void> (0) : __assert_fail ("N.getSimpleValueType().getSizeInBits() <= 64 && \"Unexpected value size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1944, __PRETTY_FUNCTION__))
1944 "Unexpected value size!")((N.getSimpleValueType().getSizeInBits() <= 64 && "Unexpected value size!"
) ? static_cast<void> (0) : __assert_fail ("N.getSimpleValueType().getSizeInBits() <= 64 && \"Unexpected value size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 1944, __PRETTY_FUNCTION__))
;
1945
1946 if (!isa<ConstantSDNode>(N.getOperand(1)))
1947 break;
1948
1949 if (N.getOperand(0).getOpcode() == ISD::SRL) {
1950 SDValue Shift = N.getOperand(0);
1951 SDValue X = Shift.getOperand(0);
1952
1953 uint64_t Mask = N.getConstantOperandVal(1);
1954
1955 // Try to fold the mask and shift into an extract and scale.
1956 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1957 return false;
1958
1959 // Try to fold the mask and shift directly into the scale.
1960 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1961 return false;
1962
1963 // Try to fold the mask and shift into BEXTR and scale.
1964 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
1965 return false;
1966 }
1967
1968 // Try to swap the mask and shift to place shifts which can be done as
1969 // a scale on the outside of the mask.
1970 if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
1971 return false;
1972
1973 break;
1974 }
1975 case ISD::ZERO_EXTEND: {
1976 // Try to widen a zexted shift left to the same size as its use, so we can
1977 // match the shift as a scale factor.
1978 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1979 break;
1980 if (N.getOperand(0).getOpcode() != ISD::SHL || !N.getOperand(0).hasOneUse())
1981 break;
1982
1983 // Give up if the shift is not a valid scale factor [1,2,3].
1984 SDValue Shl = N.getOperand(0);
1985 auto *ShAmtC = dyn_cast<ConstantSDNode>(Shl.getOperand(1));
1986 if (!ShAmtC || ShAmtC->getZExtValue() > 3)
1987 break;
1988
1989 // The narrow shift must only shift out zero bits (it must be 'nuw').
1990 // That makes it safe to widen to the destination type.
1991 APInt HighZeros = APInt::getHighBitsSet(Shl.getValueSizeInBits(),
1992 ShAmtC->getZExtValue());
1993 if (!CurDAG->MaskedValueIsZero(Shl.getOperand(0), HighZeros))
1994 break;
1995
1996 // zext (shl nuw i8 %x, C) to i32 --> shl (zext i8 %x to i32), (zext C)
1997 MVT VT = N.getSimpleValueType();
1998 SDLoc DL(N);
1999 SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Shl.getOperand(0));
2000 SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, Shl.getOperand(1));
2001
2002 // Convert the shift to scale factor.
2003 AM.Scale = 1 << ShAmtC->getZExtValue();
2004 AM.IndexReg = Zext;
2005
2006 insertDAGNode(*CurDAG, N, Zext);
2007 insertDAGNode(*CurDAG, N, NewShl);
2008 CurDAG->ReplaceAllUsesWith(N, NewShl);
2009 CurDAG->RemoveDeadNode(N.getNode());
2010 return false;
2011 }
2012 }
2013
2014 return matchAddressBase(N, AM);
2015}
2016
2017/// Helper for MatchAddress. Add the specified node to the
2018/// specified addressing mode without any further recursion.
2019bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
2020 // Is the base register already occupied?
2021 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
2022 // If so, check to see if the scale index register is set.
2023 if (!AM.IndexReg.getNode()) {
2024 AM.IndexReg = N;
2025 AM.Scale = 1;
2026 return false;
2027 }
2028
2029 // Otherwise, we cannot select it.
2030 return true;
2031 }
2032
2033 // Default, generate it as a register.
2034 AM.BaseType = X86ISelAddressMode::RegBase;
2035 AM.Base_Reg = N;
2036 return false;
2037}
2038
2039/// Helper for selectVectorAddr. Handles things that can be folded into a
2040/// gather scatter address. The index register and scale should have already
2041/// been handled.
2042bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
2043 // TODO: Support other operations.
2044 switch (N.getOpcode()) {
2045 case ISD::Constant: {
2046 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2047 if (!foldOffsetIntoAddress(Val, AM))
2048 return false;
2049 break;
2050 }
2051 case X86ISD::Wrapper:
2052 if (!matchWrapper(N, AM))
2053 return false;
2054 break;
2055 }
2056
2057 return matchAddressBase(N, AM);
2058}
2059
2060bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
2061 SDValue &Scale, SDValue &Index,
2062 SDValue &Disp, SDValue &Segment) {
2063 X86ISelAddressMode AM;
2064 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
2065 AM.IndexReg = Mgs->getIndex();
2066 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
2067
2068 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
2069 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
2070 if (AddrSpace == 256)
2071 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2072 if (AddrSpace == 257)
2073 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2074 if (AddrSpace == 258)
2075 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2076
2077 SDLoc DL(N);
2078 MVT VT = N.getSimpleValueType();
2079
2080 // Try to match into the base and displacement fields.
2081 if (matchVectorAddress(N, AM))
2082 return false;
2083
2084 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2085 return true;
2086}
2087
2088/// Returns true if it is able to pattern match an addressing mode.
2089/// It returns the operands which make up the maximal addressing mode it can
2090/// match by reference.
2091///
2092/// Parent is the parent node of the addr operand that is being matched. It
2093/// is always a load, store, atomic node, or null. It is only null when
2094/// checking memory operands for inline asm nodes.
2095bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
2096 SDValue &Scale, SDValue &Index,
2097 SDValue &Disp, SDValue &Segment) {
2098 X86ISelAddressMode AM;
2099
2100 if (Parent &&
2101 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
2102 // that are not a MemSDNode, and thus don't have proper addrspace info.
2103 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
2104 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
2105 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
2106 Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
2107 Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
2108 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
2109 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
2110 unsigned AddrSpace =
2111 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
2112 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
2113 if (AddrSpace == 256)
2114 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2115 if (AddrSpace == 257)
2116 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2117 if (AddrSpace == 258)
2118 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2119 }
2120
2121 // Save the DL and VT before calling matchAddress, it can invalidate N.
2122 SDLoc DL(N);
2123 MVT VT = N.getSimpleValueType();
2124
2125 if (matchAddress(N, AM))
2126 return false;
2127
2128 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2129 return true;
2130}
2131
2132// We can only fold a load if all nodes between it and the root node have a
2133// single use. If there are additional uses, we could end up duplicating the
2134// load.
2135static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
2136 while (User != Root) {
2137 if (!User->hasOneUse())
2138 return false;
2139 User = *User->use_begin();
2140 }
2141
2142 return true;
2143}
2144
2145/// Match a scalar SSE load. In particular, we want to match a load whose top
2146/// elements are either undef or zeros. The load flavor is derived from the
2147/// type of N, which is either v4f32 or v2f64.
2148///
2149/// We also return:
2150/// PatternChainNode: this is the matched node that has a chain input and
2151/// output.
2152bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
2153 SDValue N, SDValue &Base,
2154 SDValue &Scale, SDValue &Index,
2155 SDValue &Disp, SDValue &Segment,
2156 SDValue &PatternNodeWithChain) {
2157 if (!hasSingleUsesFromRoot(Root, Parent))
2158 return false;
2159
2160 // We can allow a full vector load here since narrowing a load is ok.
2161 if (ISD::isNON_EXTLoad(N.getNode())) {
2162 PatternNodeWithChain = N;
2163 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2164 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
2165 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2166 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2167 Segment);
2168 }
2169 }
2170
2171 // We can also match the special zero extended load opcode.
2172 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
2173 PatternNodeWithChain = N;
2174 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2175 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
2176 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
2177 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
2178 Segment);
2179 }
2180 }
2181
2182 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
2183 // once. Otherwise the load might get duplicated and the chain output of the
2184 // duplicate load will not be observed by all dependencies.
2185 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
2186 PatternNodeWithChain = N.getOperand(0);
2187 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
2188 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2189 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
2190 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2191 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2192 Segment);
2193 }
2194 }
2195
2196 // Also handle the case where we explicitly require zeros in the top
2197 // elements. This is a vector shuffle from the zero vector.
2198 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
2199 // Check to see if the top elements are all zeros (or bitcast of zeros).
2200 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
2201 N.getOperand(0).getNode()->hasOneUse()) {
2202 PatternNodeWithChain = N.getOperand(0).getOperand(0);
2203 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
2204 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2205 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
2206 // Okay, this is a zero extending load. Fold it.
2207 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2208 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2209 Segment);
2210 }
2211 }
2212
2213 return false;
2214}
2215
2216
2217bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
2218 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2219 uint64_t ImmVal = CN->getZExtValue();
2220 if (!isUInt<32>(ImmVal))
2221 return false;
2222
2223 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
2224 return true;
2225 }
2226
2227 // In static codegen with small code model, we can get the address of a label
2228 // into a register with 'movl'
2229 if (N->getOpcode() != X86ISD::Wrapper)
2230 return false;
2231
2232 N = N.getOperand(0);
2233
2234 // At least GNU as does not accept 'movl' for TPOFF relocations.
2235 // FIXME: We could use 'movl' when we know we are targeting MC.
2236 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
2237 return false;
2238
2239 Imm = N;
2240 if (N->getOpcode() != ISD::TargetGlobalAddress)
2241 return TM.getCodeModel() == CodeModel::Small;
2242
2243 Optional<ConstantRange> CR =
2244 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
2245 if (!CR)
2246 return TM.getCodeModel() == CodeModel::Small;
2247
2248 return CR->getUnsignedMax().ult(1ull << 32);
2249}
2250
2251bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
2252 SDValue &Scale, SDValue &Index,
2253 SDValue &Disp, SDValue &Segment) {
2254 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
2255 SDLoc DL(N);
2256
2257 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
2258 return false;
2259
2260 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
2261 if (RN && RN->getReg() == 0)
2262 Base = CurDAG->getRegister(0, MVT::i64);
2263 else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {
2264 // Base could already be %rip, particularly in the x32 ABI.
2265 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2266 MVT::i64), 0);
2267 Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2268 Base);
2269 }
2270
2271 RN = dyn_cast<RegisterSDNode>(Index);
2272 if (RN && RN->getReg() == 0)
2273 Index = CurDAG->getRegister(0, MVT::i64);
2274 else {
2275 assert(Index.getValueType() == MVT::i32 &&((Index.getValueType() == MVT::i32 && "Expect to be extending 32-bit registers for use in LEA"
) ? static_cast<void> (0) : __assert_fail ("Index.getValueType() == MVT::i32 && \"Expect to be extending 32-bit registers for use in LEA\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2276, __PRETTY_FUNCTION__))
2276 "Expect to be extending 32-bit registers for use in LEA")((Index.getValueType() == MVT::i32 && "Expect to be extending 32-bit registers for use in LEA"
) ? static_cast<void> (0) : __assert_fail ("Index.getValueType() == MVT::i32 && \"Expect to be extending 32-bit registers for use in LEA\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2276, __PRETTY_FUNCTION__))
;
2277 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2278 MVT::i64), 0);
2279 Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2280 Index);
2281 }
2282
2283 return true;
2284}
2285
2286/// Calls SelectAddr and determines if the maximal addressing
2287/// mode it matches can be cost effectively emitted as an LEA instruction.
2288bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
2289 SDValue &Base, SDValue &Scale,
2290 SDValue &Index, SDValue &Disp,
2291 SDValue &Segment) {
2292 X86ISelAddressMode AM;
2293
2294 // Save the DL and VT before calling matchAddress, it can invalidate N.
2295 SDLoc DL(N);
2296 MVT VT = N.getSimpleValueType();
2297
2298 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2299 // segments.
2300 SDValue Copy = AM.Segment;
2301 SDValue T = CurDAG->getRegister(0, MVT::i32);
2302 AM.Segment = T;
2303 if (matchAddress(N, AM))
2304 return false;
2305 assert (T == AM.Segment)((T == AM.Segment) ? static_cast<void> (0) : __assert_fail
("T == AM.Segment", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2305, __PRETTY_FUNCTION__))
;
2306 AM.Segment = Copy;
2307
2308 unsigned Complexity = 0;
2309 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
2310 Complexity = 1;
2311 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2312 Complexity = 4;
2313
2314 if (AM.IndexReg.getNode())
2315 Complexity++;
2316
2317 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2318 // a simple shift.
2319 if (AM.Scale > 1)
2320 Complexity++;
2321
2322 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
2323 // to a LEA. This is determined with some experimentation but is by no means
2324 // optimal (especially for code size consideration). LEA is nice because of
2325 // its three-address nature. Tweak the cost function again when we can run
2326 // convertToThreeAddress() at register allocation time.
2327 if (AM.hasSymbolicDisplacement()) {
2328 // For X86-64, always use LEA to materialize RIP-relative addresses.
2329 if (Subtarget->is64Bit())
2330 Complexity = 4;
2331 else
2332 Complexity += 2;
2333 }
2334
2335 if (AM.Disp)
2336 Complexity++;
2337
2338 // If it isn't worth using an LEA, reject it.
2339 if (Complexity <= 2)
2340 return false;
2341
2342 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2343 return true;
2344}
2345
2346/// This is only run on TargetGlobalTLSAddress nodes.
2347bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
2348 SDValue &Scale, SDValue &Index,
2349 SDValue &Disp, SDValue &Segment) {
2350 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress)((N.getOpcode() == ISD::TargetGlobalTLSAddress) ? static_cast
<void> (0) : __assert_fail ("N.getOpcode() == ISD::TargetGlobalTLSAddress"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2350, __PRETTY_FUNCTION__))
;
2351 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
2352
2353 X86ISelAddressMode AM;
2354 AM.GV = GA->getGlobal();
2355 AM.Disp += GA->getOffset();
2356 AM.SymbolFlags = GA->getTargetFlags();
2357
2358 MVT VT = N.getSimpleValueType();
2359 if (VT == MVT::i32) {
2360 AM.Scale = 1;
2361 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
2362 }
2363
2364 getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
2365 return true;
2366}
2367
2368bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2369 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2370 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
2371 N.getValueType());
2372 return true;
2373 }
2374
2375 // Keep track of the original value type and whether this value was
2376 // truncated. If we see a truncation from pointer type to VT that truncates
2377 // bits that are known to be zero, we can use a narrow reference.
2378 EVT VT = N.getValueType();
2379 bool WasTruncated = false;
2380 if (N.getOpcode() == ISD::TRUNCATE) {
2381 WasTruncated = true;
2382 N = N.getOperand(0);
2383 }
2384
2385 if (N.getOpcode() != X86ISD::Wrapper)
2386 return false;
2387
2388 // We can only use non-GlobalValues as immediates if they were not truncated,
2389 // as we do not have any range information. If we have a GlobalValue and the
2390 // address was not truncated, we can select it as an operand directly.
2391 unsigned Opc = N.getOperand(0)->getOpcode();
2392 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2393 Op = N.getOperand(0);
2394 // We can only select the operand directly if we didn't have to look past a
2395 // truncate.
2396 return !WasTruncated;
2397 }
2398
2399 // Check that the global's range fits into VT.
2400 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2401 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2402 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2403 return false;
2404
2405 // Okay, we can use a narrow reference.
2406 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2407 GA->getOffset(), GA->getTargetFlags());
2408 return true;
2409}
2410
2411bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2412 SDValue &Base, SDValue &Scale,
2413 SDValue &Index, SDValue &Disp,
2414 SDValue &Segment) {
2415 if (!ISD::isNON_EXTLoad(N.getNode()) ||
2416 !IsProfitableToFold(N, P, Root) ||
27
Passing null pointer value via 2nd parameter 'U'
28
Calling 'X86DAGToDAGISel::IsProfitableToFold'
2417 !IsLegalToFold(N, P, Root, OptLevel))
2418 return false;
2419
2420 return selectAddr(N.getNode(),
2421 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2422}
2423
2424/// Return an SDNode that returns the value of the global base register.
2425/// Output instructions required to initialize the global base register,
2426/// if necessary.
2427SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
2428 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
2429 auto &DL = MF->getDataLayout();
2430 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
2431}
2432
2433bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2434 if (N->getOpcode() == ISD::TRUNCATE)
2435 N = N->getOperand(0).getNode();
2436 if (N->getOpcode() != X86ISD::Wrapper)
2437 return false;
2438
2439 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2440 if (!GA)
2441 return false;
2442
2443 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2444 return CR && CR->getSignedMin().sge(-1ull << Width) &&
2445 CR->getSignedMax().slt(1ull << Width);
2446}
2447
2448static X86::CondCode getCondFromNode(SDNode *N) {
2449 assert(N->isMachineOpcode() && "Unexpected node")((N->isMachineOpcode() && "Unexpected node") ? static_cast
<void> (0) : __assert_fail ("N->isMachineOpcode() && \"Unexpected node\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2449, __PRETTY_FUNCTION__))
;
2450 X86::CondCode CC = X86::COND_INVALID;
2451 unsigned Opc = N->getMachineOpcode();
2452 if (Opc == X86::JCC_1)
2453 CC = static_cast<X86::CondCode>(N->getConstantOperandVal(1));
2454 else if (Opc == X86::SETCCr)
2455 CC = static_cast<X86::CondCode>(N->getConstantOperandVal(0));
2456 else if (Opc == X86::SETCCm)
2457 CC = static_cast<X86::CondCode>(N->getConstantOperandVal(5));
2458 else if (Opc == X86::CMOV16rr || Opc == X86::CMOV32rr ||
2459 Opc == X86::CMOV64rr)
2460 CC = static_cast<X86::CondCode>(N->getConstantOperandVal(2));
2461 else if (Opc == X86::CMOV16rm || Opc == X86::CMOV32rm ||
2462 Opc == X86::CMOV64rm)
2463 CC = static_cast<X86::CondCode>(N->getConstantOperandVal(6));
2464
2465 return CC;
2466}
2467
2468/// Test whether the given X86ISD::CMP node has any users that use a flag
2469/// other than ZF.
2470bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
2471 // Examine each user of the node.
2472 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2473 UI != UE; ++UI) {
2474 // Only check things that use the flags.
2475 if (UI.getUse().getResNo() != Flags.getResNo())
2476 continue;
2477 // Only examine CopyToReg uses that copy to EFLAGS.
2478 if (UI->getOpcode() != ISD::CopyToReg ||
2479 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2480 return false;
2481 // Examine each user of the CopyToReg use.
2482 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2483 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2484 // Only examine the Flag result.
2485 if (FlagUI.getUse().getResNo() != 1) continue;
2486 // Anything unusual: assume conservatively.
2487 if (!FlagUI->isMachineOpcode()) return false;
2488 // Examine the condition code of the user.
2489 X86::CondCode CC = getCondFromNode(*FlagUI);
2490
2491 switch (CC) {
2492 // Comparisons which only use the zero flag.
2493 case X86::COND_E: case X86::COND_NE:
2494 continue;
2495 // Anything else: assume conservatively.
2496 default:
2497 return false;
2498 }
2499 }
2500 }
2501 return true;
2502}
2503
2504/// Test whether the given X86ISD::CMP node has any uses which require the SF
2505/// flag to be accurate.
2506bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
2507 // Examine each user of the node.
2508 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2509 UI != UE; ++UI) {
2510 // Only check things that use the flags.
2511 if (UI.getUse().getResNo() != Flags.getResNo())
2512 continue;
2513 // Only examine CopyToReg uses that copy to EFLAGS.
2514 if (UI->getOpcode() != ISD::CopyToReg ||
2515 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2516 return false;
2517 // Examine each user of the CopyToReg use.
2518 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2519 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2520 // Only examine the Flag result.
2521 if (FlagUI.getUse().getResNo() != 1) continue;
2522 // Anything unusual: assume conservatively.
2523 if (!FlagUI->isMachineOpcode()) return false;
2524 // Examine the condition code of the user.
2525 X86::CondCode CC = getCondFromNode(*FlagUI);
2526
2527 switch (CC) {
2528 // Comparisons which don't examine the SF flag.
2529 case X86::COND_A: case X86::COND_AE:
2530 case X86::COND_B: case X86::COND_BE:
2531 case X86::COND_E: case X86::COND_NE:
2532 case X86::COND_O: case X86::COND_NO:
2533 case X86::COND_P: case X86::COND_NP:
2534 continue;
2535 // Anything else: assume conservatively.
2536 default:
2537 return false;
2538 }
2539 }
2540 }
2541 return true;
2542}
2543
2544static bool mayUseCarryFlag(X86::CondCode CC) {
2545 switch (CC) {
2546 // Comparisons which don't examine the CF flag.
2547 case X86::COND_O: case X86::COND_NO:
2548 case X86::COND_E: case X86::COND_NE:
2549 case X86::COND_S: case X86::COND_NS:
2550 case X86::COND_P: case X86::COND_NP:
2551 case X86::COND_L: case X86::COND_GE:
2552 case X86::COND_G: case X86::COND_LE:
2553 return false;
2554 // Anything else: assume conservatively.
2555 default:
2556 return true;
2557 }
2558}
2559
2560/// Test whether the given node which sets flags has any uses which require the
2561/// CF flag to be accurate.
2562 bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
2563 // Examine each user of the node.
2564 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2565 UI != UE; ++UI) {
2566 // Only check things that use the flags.
2567 if (UI.getUse().getResNo() != Flags.getResNo())
2568 continue;
2569
2570 unsigned UIOpc = UI->getOpcode();
2571
2572 if (UIOpc == ISD::CopyToReg) {
2573 // Only examine CopyToReg uses that copy to EFLAGS.
2574 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2575 return false;
2576 // Examine each user of the CopyToReg use.
2577 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2578 FlagUI != FlagUE; ++FlagUI) {
2579 // Only examine the Flag result.
2580 if (FlagUI.getUse().getResNo() != 1)
2581 continue;
2582 // Anything unusual: assume conservatively.
2583 if (!FlagUI->isMachineOpcode())
2584 return false;
2585 // Examine the condition code of the user.
2586 X86::CondCode CC = getCondFromNode(*FlagUI);
2587
2588 if (mayUseCarryFlag(CC))
2589 return false;
2590 }
2591
2592 // This CopyToReg is ok. Move on to the next user.
2593 continue;
2594 }
2595
2596 // This might be an unselected node. So look for the pre-isel opcodes that
2597 // use flags.
2598 unsigned CCOpNo;
2599 switch (UIOpc) {
2600 default:
2601 // Something unusual. Be conservative.
2602 return false;
2603 case X86ISD::SETCC: CCOpNo = 0; break;
2604 case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
2605 case X86ISD::CMOV: CCOpNo = 2; break;
2606 case X86ISD::BRCOND: CCOpNo = 2; break;
2607 }
2608
2609 X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
2610 if (mayUseCarryFlag(CC))
2611 return false;
2612 }
2613 return true;
2614}
2615
2616/// Check whether or not the chain ending in StoreNode is suitable for doing
2617/// the {load; op; store} to modify transformation.
2618static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2619 SDValue StoredVal, SelectionDAG *CurDAG,
2620 unsigned LoadOpNo,
2621 LoadSDNode *&LoadNode,
2622 SDValue &InputChain) {
2623 // Is the stored value result 0 of the operation?
2624 if (StoredVal.getResNo() != 0) return false;
2625
2626 // Are there other uses of the operation other than the store?
2627 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2628
2629 // Is the store non-extending and non-indexed?
2630 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2631 return false;
2632
2633 SDValue Load = StoredVal->getOperand(LoadOpNo);
2634 // Is the stored value a non-extending and non-indexed load?
2635 if (!ISD::isNormalLoad(Load.getNode())) return false;
2636
2637 // Return LoadNode by reference.
2638 LoadNode = cast<LoadSDNode>(Load);
2639
2640 // Is store the only read of the loaded value?
2641 if (!Load.hasOneUse())
2642 return false;
2643
2644 // Is the address of the store the same as the load?
2645 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2646 LoadNode->getOffset() != StoreNode->getOffset())
2647 return false;
2648
2649 bool FoundLoad = false;
2650 SmallVector<SDValue, 4> ChainOps;
2651 SmallVector<const SDNode *, 4> LoopWorklist;
2652 SmallPtrSet<const SDNode *, 16> Visited;
2653 const unsigned int Max = 1024;
2654
2655 // Visualization of Load-Op-Store fusion:
2656 // -------------------------
2657 // Legend:
2658 // *-lines = Chain operand dependencies.
2659 // |-lines = Normal operand dependencies.
2660 // Dependencies flow down and right. n-suffix references multiple nodes.
2661 //
2662 // C Xn C
2663 // * * *
2664 // * * *
2665 // Xn A-LD Yn TF Yn
2666 // * * \ | * |
2667 // * * \ | * |
2668 // * * \ | => A--LD_OP_ST
2669 // * * \| \
2670 // TF OP \
2671 // * | \ Zn
2672 // * | \
2673 // A-ST Zn
2674 //
2675
2676 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2677 // #2: Yn -> LD
2678 // #3: ST -> Zn
2679
2680 // Ensure the transform is safe by checking for the dual
2681 // dependencies to make sure we do not induce a loop.
2682
2683 // As LD is a predecessor to both OP and ST we can do this by checking:
2684 // a). if LD is a predecessor to a member of Xn or Yn.
2685 // b). if a Zn is a predecessor to ST.
2686
2687 // However, (b) can only occur through being a chain predecessor to
2688 // ST, which is the same as Zn being a member or predecessor of Xn,
2689 // which is a subset of LD being a predecessor of Xn. So it's
2690 // subsumed by check (a).
2691
2692 SDValue Chain = StoreNode->getChain();
2693
2694 // Gather X elements in ChainOps.
2695 if (Chain == Load.getValue(1)) {
2696 FoundLoad = true;
2697 ChainOps.push_back(Load.getOperand(0));
2698 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2699 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2700 SDValue Op = Chain.getOperand(i);
2701 if (Op == Load.getValue(1)) {
2702 FoundLoad = true;
2703 // Drop Load, but keep its chain. No cycle check necessary.
2704 ChainOps.push_back(Load.getOperand(0));
2705 continue;
2706 }
2707 LoopWorklist.push_back(Op.getNode());
2708 ChainOps.push_back(Op);
2709 }
2710 }
2711
2712 if (!FoundLoad)
2713 return false;
2714
2715 // Worklist is currently Xn. Add Yn to worklist.
2716 for (SDValue Op : StoredVal->ops())
2717 if (Op.getNode() != LoadNode)
2718 LoopWorklist.push_back(Op.getNode());
2719
2720 // Check (a) if Load is a predecessor to Xn + Yn
2721 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2722 true))
2723 return false;
2724
2725 InputChain =
2726 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
2727 return true;
2728}
2729
2730// Change a chain of {load; op; store} of the same value into a simple op
2731// through memory of that value, if the uses of the modified value and its
2732// address are suitable.
2733//
2734// The tablegen pattern memory operand pattern is currently not able to match
2735// the case where the EFLAGS on the original operation are used.
2736//
2737// To move this to tablegen, we'll need to improve tablegen to allow flags to
2738// be transferred from a node in the pattern to the result node, probably with
2739// a new keyword. For example, we have this
2740// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2741// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2742// (implicit EFLAGS)]>;
2743// but maybe need something like this
2744// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2745// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2746// (transferrable EFLAGS)]>;
2747//
2748// Until then, we manually fold these and instruction select the operation
2749// here.
2750bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2751 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2752 SDValue StoredVal = StoreNode->getOperand(1);
2753 unsigned Opc = StoredVal->getOpcode();
2754
2755 // Before we try to select anything, make sure this is memory operand size
2756 // and opcode we can handle. Note that this must match the code below that
2757 // actually lowers the opcodes.
2758 EVT MemVT = StoreNode->getMemoryVT();
2759 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2760 MemVT != MVT::i8)
2761 return false;
2762
2763 bool IsCommutable = false;
2764 bool IsNegate = false;
2765 switch (Opc) {
2766 default:
2767 return false;
2768 case X86ISD::SUB:
2769 IsNegate = isNullConstant(StoredVal.getOperand(0));
2770 break;
2771 case X86ISD::SBB:
2772 break;
2773 case X86ISD::ADD:
2774 case X86ISD::ADC:
2775 case X86ISD::AND:
2776 case X86ISD::OR:
2777 case X86ISD::XOR:
2778 IsCommutable = true;
2779 break;
2780 }
2781
2782 unsigned LoadOpNo = IsNegate ? 1 : 0;
2783 LoadSDNode *LoadNode = nullptr;
2784 SDValue InputChain;
2785 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2786 LoadNode, InputChain)) {
2787 if (!IsCommutable)
2788 return false;
2789
2790 // This operation is commutable, try the other operand.
2791 LoadOpNo = 1;
2792 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2793 LoadNode, InputChain))
2794 return false;
2795 }
2796
2797 SDValue Base, Scale, Index, Disp, Segment;
2798 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2799 Segment))
2800 return false;
2801
2802 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
2803 unsigned Opc8) {
2804 switch (MemVT.getSimpleVT().SimpleTy) {
2805 case MVT::i64:
2806 return Opc64;
2807 case MVT::i32:
2808 return Opc32;
2809 case MVT::i16:
2810 return Opc16;
2811 case MVT::i8:
2812 return Opc8;
2813 default:
2814 llvm_unreachable("Invalid size!")::llvm::llvm_unreachable_internal("Invalid size!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2814)
;
2815 }
2816 };
2817
2818 MachineSDNode *Result;
2819 switch (Opc) {
2820 case X86ISD::SUB:
2821 // Handle negate.
2822 if (IsNegate) {
2823 unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
2824 X86::NEG8m);
2825 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2826 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
2827 MVT::Other, Ops);
2828 break;
2829 }
2830 LLVM_FALLTHROUGH[[clang::fallthrough]];
2831 case X86ISD::ADD:
2832 // Try to match inc/dec.
2833 if (!Subtarget->slowIncDec() || OptForSize) {
2834 bool IsOne = isOneConstant(StoredVal.getOperand(1));
2835 bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
2836 // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
2837 if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
2838 unsigned NewOpc =
2839 ((Opc == X86ISD::ADD) == IsOne)
2840 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2841 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
2842 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2843 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
2844 MVT::Other, Ops);
2845 break;
2846 }
2847 }
2848 LLVM_FALLTHROUGH[[clang::fallthrough]];
2849 case X86ISD::ADC:
2850 case X86ISD::SBB:
2851 case X86ISD::AND:
2852 case X86ISD::OR:
2853 case X86ISD::XOR: {
2854 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2855 switch (Opc) {
2856 case X86ISD::ADD:
2857 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2858 X86::ADD8mr);
2859 case X86ISD::ADC:
2860 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2861 X86::ADC8mr);
2862 case X86ISD::SUB:
2863 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2864 X86::SUB8mr);
2865 case X86ISD::SBB:
2866 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2867 X86::SBB8mr);
2868 case X86ISD::AND:
2869 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2870 X86::AND8mr);
2871 case X86ISD::OR:
2872 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2873 case X86ISD::XOR:
2874 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2875 X86::XOR8mr);
2876 default:
2877 llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2877)
;
2878 }
2879 };
2880 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2881 switch (Opc) {
2882 case X86ISD::ADD:
2883 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
2884 case X86ISD::ADC:
2885 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
2886 case X86ISD::SUB:
2887 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
2888 case X86ISD::SBB:
2889 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
2890 case X86ISD::AND:
2891 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
2892 case X86ISD::OR:
2893 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
2894 case X86ISD::XOR:
2895 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
2896 default:
2897 llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2897)
;
2898 }
2899 };
2900 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2901 switch (Opc) {
2902 case X86ISD::ADD:
2903 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2904 X86::ADD8mi);
2905 case X86ISD::ADC:
2906 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2907 X86::ADC8mi);
2908 case X86ISD::SUB:
2909 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2910 X86::SUB8mi);
2911 case X86ISD::SBB:
2912 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2913 X86::SBB8mi);
2914 case X86ISD::AND:
2915 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2916 X86::AND8mi);
2917 case X86ISD::OR:
2918 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2919 X86::OR8mi);
2920 case X86ISD::XOR:
2921 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2922 X86::XOR8mi);
2923 default:
2924 llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2924)
;
2925 }
2926 };
2927
2928 unsigned NewOpc = SelectRegOpcode(Opc);
2929 SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
2930
2931 // See if the operand is a constant that we can fold into an immediate
2932 // operand.
2933 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2934 int64_t OperandV = OperandC->getSExtValue();
2935
2936 // Check if we can shrink the operand enough to fit in an immediate (or
2937 // fit into a smaller immediate) by negating it and switching the
2938 // operation.
2939 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2940 ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
2941 (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
2942 isInt<32>(-OperandV))) &&
2943 hasNoCarryFlagUses(StoredVal.getValue(1))) {
2944 OperandV = -OperandV;
2945 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2946 }
2947
2948 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2949 // the larger immediate operand.
2950 if (MemVT != MVT::i8 && isInt<8>(OperandV)) {
2951 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2952 NewOpc = SelectImm8Opcode(Opc);
2953 } else if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
2954 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2955 NewOpc = SelectImmOpcode(Opc);
2956 }
2957 }
2958
2959 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2960 SDValue CopyTo =
2961 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2962 StoredVal.getOperand(2), SDValue());
2963
2964 const SDValue Ops[] = {Base, Scale, Index, Disp,
2965 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2966 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2967 Ops);
2968 } else {
2969 const SDValue Ops[] = {Base, Scale, Index, Disp,
2970 Segment, Operand, InputChain};
2971 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2972 Ops);
2973 }
2974 break;
2975 }
2976 default:
2977 llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 2977)
;
2978 }
2979
2980 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
2981 LoadNode->getMemOperand()};
2982 CurDAG->setNodeMemRefs(Result, MemOps);
2983
2984 // Update Load Chain uses as well.
2985 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
2986 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2987 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2988 CurDAG->RemoveDeadNode(Node);
2989 return true;
2990}
2991
2992// See if this is an X & Mask that we can match to BEXTR/BZHI.
2993// Where Mask is one of the following patterns:
2994// a) x & (1 << nbits) - 1
2995// b) x & ~(-1 << nbits)
2996// c) x & (-1 >> (32 - y))
2997// d) x << (32 - y) >> (32 - y)
2998bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
2999 assert((((Node->getOpcode() == ISD::AND || Node->getOpcode() ==
ISD::SRL) && "Should be either an and-mask, or right-shift after clearing high bits."
) ? static_cast<void> (0) : __assert_fail ("(Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) && \"Should be either an and-mask, or right-shift after clearing high bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3001, __PRETTY_FUNCTION__))
3000 (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&(((Node->getOpcode() == ISD::AND || Node->getOpcode() ==
ISD::SRL) && "Should be either an and-mask, or right-shift after clearing high bits."
) ? static_cast<void> (0) : __assert_fail ("(Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) && \"Should be either an and-mask, or right-shift after clearing high bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3001, __PRETTY_FUNCTION__))
3001 "Should be either an and-mask, or right-shift after clearing high bits.")(((Node->getOpcode() == ISD::AND || Node->getOpcode() ==
ISD::SRL) && "Should be either an and-mask, or right-shift after clearing high bits."
) ? static_cast<void> (0) : __assert_fail ("(Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) && \"Should be either an and-mask, or right-shift after clearing high bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3001, __PRETTY_FUNCTION__))
;
3002
3003 // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
3004 if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
3005 return false;
3006
3007 MVT NVT = Node->getSimpleValueType(0);
3008
3009 // Only supported for 32 and 64 bits.
3010 if (NVT != MVT::i32 && NVT != MVT::i64)
3011 return false;
3012
3013 unsigned Size = NVT.getSizeInBits();
3014
3015 SDValue NBits;
3016
3017 // If we have BMI2's BZHI, we are ok with muti-use patterns.
3018 // Else, if we only have BMI1's BEXTR, we require one-use.
3019 const bool CanHaveExtraUses = Subtarget->hasBMI2();
3020 auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) {
3021 return CanHaveExtraUses ||
3022 Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
3023 };
3024 auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); };
3025 auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); };
3026
3027 // a) x & ((1 << nbits) + (-1))
3028 auto matchPatternA = [&checkOneUse, &NBits](SDValue Mask) -> bool {
3029 // Match `add`. Must only have one use!
3030 if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
3031 return false;
3032 // We should be adding all-ones constant (i.e. subtracting one.)
3033 if (!isAllOnesConstant(Mask->getOperand(1)))
3034 return false;
3035 // Match `1 << nbits`. Must only have one use!
3036 SDValue M0 = Mask->getOperand(0);
3037 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3038 return false;
3039 if (!isOneConstant(M0->getOperand(0)))
3040 return false;
3041 NBits = M0->getOperand(1);
3042 return true;
3043 };
3044
3045 // b) x & ~(-1 << nbits)
3046 auto matchPatternB = [&checkOneUse, &NBits](SDValue Mask) -> bool {
3047 // Match `~()`. Must only have one use!
3048 if (!isBitwiseNot(Mask) || !checkOneUse(Mask))
3049 return false;
3050 // Match `-1 << nbits`. Must only have one use!
3051 SDValue M0 = Mask->getOperand(0);
3052 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3053 return false;
3054 if (!isAllOnesConstant(M0->getOperand(0)))
3055 return false;
3056 NBits = M0->getOperand(1);
3057 return true;
3058 };
3059
3060 // Match potentially-truncated (bitwidth - y)
3061 auto matchShiftAmt = [checkOneUse, Size, &NBits](SDValue ShiftAmt) {
3062 // Skip over a truncate of the shift amount.
3063 if (ShiftAmt.getOpcode() == ISD::TRUNCATE) {
3064 ShiftAmt = ShiftAmt.getOperand(0);
3065 // The trunc should have been the only user of the real shift amount.
3066 if (!checkOneUse(ShiftAmt))
3067 return false;
3068 }
3069 // Match the shift amount as: (bitwidth - y). It should go away, too.
3070 if (ShiftAmt.getOpcode() != ISD::SUB)
3071 return false;
3072 auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0));
3073 if (!V0 || V0->getZExtValue() != Size)
3074 return false;
3075 NBits = ShiftAmt.getOperand(1);
3076 return true;
3077 };
3078
3079 // c) x & (-1 >> (32 - y))
3080 auto matchPatternC = [&checkOneUse, matchShiftAmt](SDValue Mask) -> bool {
3081 // Match `l>>`. Must only have one use!
3082 if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
3083 return false;
3084 // We should be shifting all-ones constant.
3085 if (!isAllOnesConstant(Mask.getOperand(0)))
3086 return false;
3087 SDValue M1 = Mask.getOperand(1);
3088 // The shift amount should not be used externally.
3089 if (!checkOneUse(M1))
3090 return false;
3091 return matchShiftAmt(M1);
3092 };
3093
3094 SDValue X;
3095
3096 // d) x << (32 - y) >> (32 - y)
3097 auto matchPatternD = [&checkOneUse, &checkTwoUse, matchShiftAmt,
3098 &X](SDNode *Node) -> bool {
3099 if (Node->getOpcode() != ISD::SRL)
3100 return false;
3101 SDValue N0 = Node->getOperand(0);
3102 if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0))
3103 return false;
3104 SDValue N1 = Node->getOperand(1);
3105 SDValue N01 = N0->getOperand(1);
3106 // Both of the shifts must be by the exact same value.
3107 // There should not be any uses of the shift amount outside of the pattern.
3108 if (N1 != N01 || !checkTwoUse(N1))
3109 return false;
3110 if (!matchShiftAmt(N1))
3111 return false;
3112 X = N0->getOperand(0);
3113 return true;
3114 };
3115
3116 auto matchLowBitMask = [&matchPatternA, &matchPatternB,
3117 &matchPatternC](SDValue Mask) -> bool {
3118 // FIXME: pattern c.
3119 return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
3120 };
3121
3122 if (Node->getOpcode() == ISD::AND) {
3123 X = Node->getOperand(0);
3124 SDValue Mask = Node->getOperand(1);
3125
3126 if (matchLowBitMask(Mask)) {
3127 // Great.
3128 } else {
3129 std::swap(X, Mask);
3130 if (!matchLowBitMask(Mask))
3131 return false;
3132 }
3133 } else if (!matchPatternD(Node))
3134 return false;
3135
3136 SDLoc DL(Node);
3137
3138 // If we do *NOT* have BMI2, let's find out if the if the 'X' is *logically*
3139 // shifted (potentially with one-use trunc inbetween),
3140 // and if so look past one-use truncation.
3141 MVT XVT = NVT;
3142 if (!Subtarget->hasBMI2() && X.getOpcode() == ISD::TRUNCATE &&
3143 X.hasOneUse() && X.getOperand(0).getOpcode() == ISD::SRL) {
3144 assert(NVT == MVT::i32 && "Expected target valuetype to be i32")((NVT == MVT::i32 && "Expected target valuetype to be i32"
) ? static_cast<void> (0) : __assert_fail ("NVT == MVT::i32 && \"Expected target valuetype to be i32\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3144, __PRETTY_FUNCTION__))
;
3145 X = X.getOperand(0);
3146 XVT = X.getSimpleValueType();
3147 assert(XVT == MVT::i64 && "Expected truncation from i64")((XVT == MVT::i64 && "Expected truncation from i64") ?
static_cast<void> (0) : __assert_fail ("XVT == MVT::i64 && \"Expected truncation from i64\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3147, __PRETTY_FUNCTION__))
;
3148 }
3149
3150 // Truncate the shift amount.
3151 NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
3152 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3153
3154 // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
3155 // All the other bits are undefined, we do not care about them.
3156 SDValue ImplDef = SDValue(
3157 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
3158 insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
3159 NBits = CurDAG->getTargetInsertSubreg(X86::sub_8bit, DL, MVT::i32, ImplDef,
3160 NBits);
3161 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3162
3163 if (Subtarget->hasBMI2()) {
3164 // Great, just emit the the BZHI..
3165 if (XVT != MVT::i32) {
3166 // But have to place the bit count into the wide-enough register first.
3167 NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, NBits);
3168 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3169 }
3170
3171 SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, XVT, X, NBits);
3172 ReplaceNode(Node, Extract.getNode());
3173 SelectCode(Extract.getNode());
3174 return true;
3175 }
3176
3177 // Else, emitting BEXTR requires one more step.
3178 // The 'control' of BEXTR has the pattern of:
3179 // [15...8 bit][ 7...0 bit] location
3180 // [ bit count][ shift] name
3181 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
3182
3183 // Shift NBits left by 8 bits, thus producing 'control'.
3184 // This makes the low 8 bits to be zero.
3185 SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
3186 SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
3187 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3188
3189 // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
3190 if (X.getOpcode() == ISD::SRL) {
3191 SDValue ShiftAmt = X.getOperand(1);
3192 X = X.getOperand(0);
3193
3194 assert(ShiftAmt.getValueType() == MVT::i8 &&((ShiftAmt.getValueType() == MVT::i8 && "Expected shift amount to be i8"
) ? static_cast<void> (0) : __assert_fail ("ShiftAmt.getValueType() == MVT::i8 && \"Expected shift amount to be i8\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3195, __PRETTY_FUNCTION__))
3195 "Expected shift amount to be i8")((ShiftAmt.getValueType() == MVT::i8 && "Expected shift amount to be i8"
) ? static_cast<void> (0) : __assert_fail ("ShiftAmt.getValueType() == MVT::i8 && \"Expected shift amount to be i8\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3195, __PRETTY_FUNCTION__))
;
3196
3197 // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
3198 // We could zext to i16 in some form, but we intentionally don't do that.
3199 SDValue OrigShiftAmt = ShiftAmt;
3200 ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
3201 insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
3202
3203 // And now 'or' these low 8 bits of shift amount into the 'control'.
3204 Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
3205 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3206 }
3207
3208 // But have to place the 'control' into the wide-enough register first.
3209 if (XVT != MVT::i32) {
3210 Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
3211 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3212 }
3213
3214 // And finally, form the BEXTR itself.
3215 SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
3216
3217 // The 'X' was originally truncated. Do that now.
3218 if (XVT != NVT) {
3219 insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
3220 Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
3221 }
3222
3223 ReplaceNode(Node, Extract.getNode());
3224 SelectCode(Extract.getNode());
3225
3226 return true;
3227}
3228
3229// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
3230MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
3231 MVT NVT = Node->getSimpleValueType(0);
3232 SDLoc dl(Node);
3233
3234 SDValue N0 = Node->getOperand(0);
3235 SDValue N1 = Node->getOperand(1);
3236
3237 // If we have TBM we can use an immediate for the control. If we have BMI
3238 // we should only do this if the BEXTR instruction is implemented well.
3239 // Otherwise moving the control into a register makes this more costly.
3240 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
3241 // hoisting the move immediate would make it worthwhile with a less optimal
3242 // BEXTR?
3243 if (!Subtarget->hasTBM() &&
3244 !(Subtarget->hasBMI() && Subtarget->hasFastBEXTR()))
3245 return nullptr;
3246
3247 // Must have a shift right.
3248 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
3249 return nullptr;
3250
3251 // Shift can't have additional users.
3252 if (!N0->hasOneUse())
3253 return nullptr;
3254
3255 // Only supported for 32 and 64 bits.
3256 if (NVT != MVT::i32 && NVT != MVT::i64)
3257 return nullptr;
3258
3259 // Shift amount and RHS of and must be constant.
3260 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
3261 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3262 if (!MaskCst || !ShiftCst)
3263 return nullptr;
3264
3265 // And RHS must be a mask.
3266 uint64_t Mask = MaskCst->getZExtValue();
3267 if (!isMask_64(Mask))
3268 return nullptr;
3269
3270 uint64_t Shift = ShiftCst->getZExtValue();
3271 uint64_t MaskSize = countPopulation(Mask);
3272
3273 // Don't interfere with something that can be handled by extracting AH.
3274 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
3275 if (Shift == 8 && MaskSize == 8)
3276 return nullptr;
3277
3278 // Make sure we are only using bits that were in the original value, not
3279 // shifted in.
3280 if (Shift + MaskSize > NVT.getSizeInBits())
3281 return nullptr;
3282
3283 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
3284 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
3285 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
3286
3287 // BMI requires the immediate to placed in a register.
3288 if (!Subtarget->hasTBM()) {
3289 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
3290 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
3291 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3292 New = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, New), 0);
3293 }
3294
3295 MachineSDNode *NewNode;
3296 SDValue Input = N0->getOperand(0);
3297 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3298 if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3299 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
3300 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
3301 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3302 // Update the chain.
3303 ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
3304 // Record the mem-refs
3305 CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
3306 } else {
3307 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, New);
3308 }
3309
3310 return NewNode;
3311}
3312
3313// Emit a PCMISTR(I/M) instruction.
3314MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
3315 bool MayFoldLoad, const SDLoc &dl,
3316 MVT VT, SDNode *Node) {
3317 SDValue N0 = Node->getOperand(0);
3318 SDValue N1 = Node->getOperand(1);
3319 SDValue Imm = Node->getOperand(2);
3320 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3321 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3322
3323 // Try to fold a load. No need to check alignment.
3324 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3325 if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3326 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3327 N1.getOperand(0) };
3328 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
3329 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3330 // Update the chain.
3331 ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
3332 // Record the mem-refs
3333 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3334 return CNode;
3335 }
3336
3337 SDValue Ops[] = { N0, N1, Imm };
3338 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3339 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3340 return CNode;
3341}
3342
3343// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3344// to emit a second instruction after this one. This is needed since we have two
3345// copyToReg nodes glued before this and we need to continue that glue through.
3346MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3347 bool MayFoldLoad, const SDLoc &dl,
3348 MVT VT, SDNode *Node,
3349 SDValue &InFlag) {
3350 SDValue N0 = Node->getOperand(0);
3351 SDValue N2 = Node->getOperand(2);
3352 SDValue Imm = Node->getOperand(4);
3353 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3354 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3355
3356 // Try to fold a load. No need to check alignment.
3357 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3358 if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3359 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3360 N2.getOperand(0), InFlag };
3361 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3362 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3363 InFlag = SDValue(CNode, 3);
3364 // Update the chain.
3365 ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
3366 // Record the mem-refs
3367 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
3368 return CNode;
3369 }
3370
3371 SDValue Ops[] = { N0, N2, Imm, InFlag };
3372 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3373 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3374 InFlag = SDValue(CNode, 2);
3375 return CNode;
3376}
3377
3378bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3379 EVT VT = N->getValueType(0);
3380
3381 // Only handle scalar shifts.
3382 if (VT.isVector())
3383 return false;
3384
3385 // Narrower shifts only mask to 5 bits in hardware.
3386 unsigned Size = VT == MVT::i64 ? 64 : 32;
3387
3388 SDValue OrigShiftAmt = N->getOperand(1);
3389 SDValue ShiftAmt = OrigShiftAmt;
3390 SDLoc DL(N);
3391
3392 // Skip over a truncate of the shift amount.
3393 if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
3394 ShiftAmt = ShiftAmt->getOperand(0);
3395
3396 // This function is called after X86DAGToDAGISel::matchBitExtract(),
3397 // so we are not afraid that we might mess up BZHI/BEXTR pattern.
3398
3399 SDValue NewShiftAmt;
3400 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
3401 SDValue Add0 = ShiftAmt->getOperand(0);
3402 SDValue Add1 = ShiftAmt->getOperand(1);
3403 // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
3404 // to avoid the ADD/SUB.
3405 if (isa<ConstantSDNode>(Add1) &&
3406 cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
3407 NewShiftAmt = Add0;
3408 // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
3409 // generate a NEG instead of a SUB of a constant.
3410 } else if (ShiftAmt->getOpcode() == ISD::SUB &&
3411 isa<ConstantSDNode>(Add0) &&
3412 cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
3413 cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
3414 // Insert a negate op.
3415 // TODO: This isn't guaranteed to replace the sub if there is a logic cone
3416 // that uses it that's not a shift.
3417 EVT SubVT = ShiftAmt.getValueType();
3418 SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
3419 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
3420 NewShiftAmt = Neg;
3421
3422 // Insert these operands into a valid topological order so they can
3423 // get selected independently.
3424 insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
3425 insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
3426 } else
3427 return false;
3428 } else
3429 return false;
3430
3431 if (NewShiftAmt.getValueType() != MVT::i8) {
3432 // Need to truncate the shift amount.
3433 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
3434 // Add to a correct topological ordering.
3435 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3436 }
3437
3438 // Insert a new mask to keep the shift amount legal. This should be removed
3439 // by isel patterns.
3440 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
3441 CurDAG->getConstant(Size - 1, DL, MVT::i8));
3442 // Place in a correct topological ordering.
3443 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3444
3445 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
3446 NewShiftAmt);
3447 if (UpdatedNode != N) {
3448 // If we found an existing node, we should replace ourselves with that node
3449 // and wait for it to be selected after its other users.
3450 ReplaceNode(N, UpdatedNode);
3451 return true;
3452 }
3453
3454 // If the original shift amount is now dead, delete it so that we don't run
3455 // it through isel.
3456 if (OrigShiftAmt.getNode()->use_empty())
3457 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
3458
3459 // Now that we've optimized the shift amount, defer to normal isel to get
3460 // load folding and legacy vs BMI2 selection without repeating it here.
3461 SelectCode(N);
3462 return true;
3463}
3464
3465/// If the high bits of an 'and' operand are known zero, try setting the
3466/// high bits of an 'and' constant operand to produce a smaller encoding by
3467/// creating a small, sign-extended negative immediate rather than a large
3468/// positive one. This reverses a transform in SimplifyDemandedBits that
3469/// shrinks mask constants by clearing bits. There is also a possibility that
3470/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
3471/// case, just replace the 'and'. Return 'true' if the node is replaced.
3472bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
3473 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
3474 // have immediate operands.
3475 MVT VT = And->getSimpleValueType(0);
3476 if (VT != MVT::i32 && VT != MVT::i64)
3477 return false;
3478
3479 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
3480 if (!And1C)
3481 return false;
3482
3483 // Bail out if the mask constant is already negative. It's can't shrink more.
3484 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
3485 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
3486 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
3487 // are negative too.
3488 APInt MaskVal = And1C->getAPIntValue();
3489 unsigned MaskLZ = MaskVal.countLeadingZeros();
3490 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
3491 return false;
3492
3493 // Don't extend into the upper 32 bits of a 64 bit mask.
3494 if (VT == MVT::i64 && MaskLZ >= 32) {
3495 MaskLZ -= 32;
3496 MaskVal = MaskVal.trunc(32);
3497 }
3498
3499 SDValue And0 = And->getOperand(0);
3500 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
3501 APInt NegMaskVal = MaskVal | HighZeros;
3502
3503 // If a negative constant would not allow a smaller encoding, there's no need
3504 // to continue. Only change the constant when we know it's a win.
3505 unsigned MinWidth = NegMaskVal.getMinSignedBits();
3506 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
3507 return false;
3508
3509 // Extend masks if we truncated above.
3510 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
3511 NegMaskVal = NegMaskVal.zext(64);
3512 HighZeros = HighZeros.zext(64);
3513 }
3514
3515 // The variable operand must be all zeros in the top bits to allow using the
3516 // new, negative constant as the mask.
3517 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
3518 return false;
3519
3520 // Check if the mask is -1. In that case, this is an unnecessary instruction
3521 // that escaped earlier analysis.
3522 if (NegMaskVal.isAllOnesValue()) {
3523 ReplaceNode(And, And0.getNode());
3524 return true;
3525 }
3526
3527 // A negative mask allows a smaller encoding. Create a new 'and' node.
3528 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
3529 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
3530 ReplaceNode(And, NewAnd.getNode());
3531 SelectCode(NewAnd.getNode());
3532 return true;
3533}
3534
3535static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
3536 bool FoldedBCast, bool Masked) {
3537 if (Masked) {
3538 if (FoldedLoad) {
3539 switch (TestVT.SimpleTy) {
3540 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3540)
;
3541 case MVT::v16i8:
3542 return IsTestN ? X86::VPTESTNMBZ128rmk : X86::VPTESTMBZ128rmk;
3543 case MVT::v8i16:
3544 return IsTestN ? X86::VPTESTNMWZ128rmk : X86::VPTESTMWZ128rmk;
3545 case MVT::v4i32:
3546 return IsTestN ? X86::VPTESTNMDZ128rmk : X86::VPTESTMDZ128rmk;
3547 case MVT::v2i64:
3548 return IsTestN ? X86::VPTESTNMQZ128rmk : X86::VPTESTMQZ128rmk;
3549 case MVT::v32i8:
3550 return IsTestN ? X86::VPTESTNMBZ256rmk : X86::VPTESTMBZ256rmk;
3551 case MVT::v16i16:
3552 return IsTestN ? X86::VPTESTNMWZ256rmk : X86::VPTESTMWZ256rmk;
3553 case MVT::v8i32:
3554 return IsTestN ? X86::VPTESTNMDZ256rmk : X86::VPTESTMDZ256rmk;
3555 case MVT::v4i64:
3556 return IsTestN ? X86::VPTESTNMQZ256rmk : X86::VPTESTMQZ256rmk;
3557 case MVT::v64i8:
3558 return IsTestN ? X86::VPTESTNMBZrmk : X86::VPTESTMBZrmk;
3559 case MVT::v32i16:
3560 return IsTestN ? X86::VPTESTNMWZrmk : X86::VPTESTMWZrmk;
3561 case MVT::v16i32:
3562 return IsTestN ? X86::VPTESTNMDZrmk : X86::VPTESTMDZrmk;
3563 case MVT::v8i64:
3564 return IsTestN ? X86::VPTESTNMQZrmk : X86::VPTESTMQZrmk;
3565 }
3566 }
3567
3568 if (FoldedBCast) {
3569 switch (TestVT.SimpleTy) {
3570 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3570)
;
3571 case MVT::v4i32:
3572 return IsTestN ? X86::VPTESTNMDZ128rmbk : X86::VPTESTMDZ128rmbk;
3573 case MVT::v2i64:
3574 return IsTestN ? X86::VPTESTNMQZ128rmbk : X86::VPTESTMQZ128rmbk;
3575 case MVT::v8i32:
3576 return IsTestN ? X86::VPTESTNMDZ256rmbk : X86::VPTESTMDZ256rmbk;
3577 case MVT::v4i64:
3578 return IsTestN ? X86::VPTESTNMQZ256rmbk : X86::VPTESTMQZ256rmbk;
3579 case MVT::v16i32:
3580 return IsTestN ? X86::VPTESTNMDZrmbk : X86::VPTESTMDZrmbk;
3581 case MVT::v8i64:
3582 return IsTestN ? X86::VPTESTNMQZrmbk : X86::VPTESTMQZrmbk;
3583 }
3584 }
3585
3586 switch (TestVT.SimpleTy) {
3587 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3587)
;
3588 case MVT::v16i8:
3589 return IsTestN ? X86::VPTESTNMBZ128rrk : X86::VPTESTMBZ128rrk;
3590 case MVT::v8i16:
3591 return IsTestN ? X86::VPTESTNMWZ128rrk : X86::VPTESTMWZ128rrk;
3592 case MVT::v4i32:
3593 return IsTestN ? X86::VPTESTNMDZ128rrk : X86::VPTESTMDZ128rrk;
3594 case MVT::v2i64:
3595 return IsTestN ? X86::VPTESTNMQZ128rrk : X86::VPTESTMQZ128rrk;
3596 case MVT::v32i8:
3597 return IsTestN ? X86::VPTESTNMBZ256rrk : X86::VPTESTMBZ256rrk;
3598 case MVT::v16i16:
3599 return IsTestN ? X86::VPTESTNMWZ256rrk : X86::VPTESTMWZ256rrk;
3600 case MVT::v8i32:
3601 return IsTestN ? X86::VPTESTNMDZ256rrk : X86::VPTESTMDZ256rrk;
3602 case MVT::v4i64:
3603 return IsTestN ? X86::VPTESTNMQZ256rrk : X86::VPTESTMQZ256rrk;
3604 case MVT::v64i8:
3605 return IsTestN ? X86::VPTESTNMBZrrk : X86::VPTESTMBZrrk;
3606 case MVT::v32i16:
3607 return IsTestN ? X86::VPTESTNMWZrrk : X86::VPTESTMWZrrk;
3608 case MVT::v16i32:
3609 return IsTestN ? X86::VPTESTNMDZrrk : X86::VPTESTMDZrrk;
3610 case MVT::v8i64:
3611 return IsTestN ? X86::VPTESTNMQZrrk : X86::VPTESTMQZrrk;
3612 }
3613 }
3614
3615 if (FoldedLoad) {
3616 switch (TestVT.SimpleTy) {
3617 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3617)
;
3618 case MVT::v16i8:
3619 return IsTestN ? X86::VPTESTNMBZ128rm : X86::VPTESTMBZ128rm;
3620 case MVT::v8i16:
3621 return IsTestN ? X86::VPTESTNMWZ128rm : X86::VPTESTMWZ128rm;
3622 case MVT::v4i32:
3623 return IsTestN ? X86::VPTESTNMDZ128rm : X86::VPTESTMDZ128rm;
3624 case MVT::v2i64:
3625 return IsTestN ? X86::VPTESTNMQZ128rm : X86::VPTESTMQZ128rm;
3626 case MVT::v32i8:
3627 return IsTestN ? X86::VPTESTNMBZ256rm : X86::VPTESTMBZ256rm;
3628 case MVT::v16i16:
3629 return IsTestN ? X86::VPTESTNMWZ256rm : X86::VPTESTMWZ256rm;
3630 case MVT::v8i32:
3631 return IsTestN ? X86::VPTESTNMDZ256rm : X86::VPTESTMDZ256rm;
3632 case MVT::v4i64:
3633 return IsTestN ? X86::VPTESTNMQZ256rm : X86::VPTESTMQZ256rm;
3634 case MVT::v64i8:
3635 return IsTestN ? X86::VPTESTNMBZrm : X86::VPTESTMBZrm;
3636 case MVT::v32i16:
3637 return IsTestN ? X86::VPTESTNMWZrm : X86::VPTESTMWZrm;
3638 case MVT::v16i32:
3639 return IsTestN ? X86::VPTESTNMDZrm : X86::VPTESTMDZrm;
3640 case MVT::v8i64:
3641 return IsTestN ? X86::VPTESTNMQZrm : X86::VPTESTMQZrm;
3642 }
3643 }
3644
3645 if (FoldedBCast) {
3646 switch (TestVT.SimpleTy) {
3647 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3647)
;
3648 case MVT::v4i32:
3649 return IsTestN ? X86::VPTESTNMDZ128rmb : X86::VPTESTMDZ128rmb;
3650 case MVT::v2i64:
3651 return IsTestN ? X86::VPTESTNMQZ128rmb : X86::VPTESTMQZ128rmb;
3652 case MVT::v8i32:
3653 return IsTestN ? X86::VPTESTNMDZ256rmb : X86::VPTESTMDZ256rmb;
3654 case MVT::v4i64:
3655 return IsTestN ? X86::VPTESTNMQZ256rmb : X86::VPTESTMQZ256rmb;
3656 case MVT::v16i32:
3657 return IsTestN ? X86::VPTESTNMDZrmb : X86::VPTESTMDZrmb;
3658 case MVT::v8i64:
3659 return IsTestN ? X86::VPTESTNMQZrmb : X86::VPTESTMQZrmb;
3660 }
3661 }
3662
3663 switch (TestVT.SimpleTy) {
3664 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3664)
;
3665 case MVT::v16i8:
3666 return IsTestN ? X86::VPTESTNMBZ128rr : X86::VPTESTMBZ128rr;
3667 case MVT::v8i16:
3668 return IsTestN ? X86::VPTESTNMWZ128rr : X86::VPTESTMWZ128rr;
3669 case MVT::v4i32:
3670 return IsTestN ? X86::VPTESTNMDZ128rr : X86::VPTESTMDZ128rr;
3671 case MVT::v2i64:
3672 return IsTestN ? X86::VPTESTNMQZ128rr : X86::VPTESTMQZ128rr;
3673 case MVT::v32i8:
3674 return IsTestN ? X86::VPTESTNMBZ256rr : X86::VPTESTMBZ256rr;
3675 case MVT::v16i16:
3676 return IsTestN ? X86::VPTESTNMWZ256rr : X86::VPTESTMWZ256rr;
3677 case MVT::v8i32:
3678 return IsTestN ? X86::VPTESTNMDZ256rr : X86::VPTESTMDZ256rr;
3679 case MVT::v4i64:
3680 return IsTestN ? X86::VPTESTNMQZ256rr : X86::VPTESTMQZ256rr;
3681 case MVT::v64i8:
3682 return IsTestN ? X86::VPTESTNMBZrr : X86::VPTESTMBZrr;
3683 case MVT::v32i16:
3684 return IsTestN ? X86::VPTESTNMWZrr : X86::VPTESTMWZrr;
3685 case MVT::v16i32:
3686 return IsTestN ? X86::VPTESTNMDZrr : X86::VPTESTMDZrr;
3687 case MVT::v8i64:
3688 return IsTestN ? X86::VPTESTNMQZrr : X86::VPTESTMQZrr;
3689 }
3690}
3691
3692// Try to create VPTESTM instruction. If InMask is not null, it will be used
3693// to form a masked operation.
3694bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
3695 SDValue InMask) {
3696 assert(Subtarget->hasAVX512() && "Expected AVX512!")((Subtarget->hasAVX512() && "Expected AVX512!") ? static_cast
<void> (0) : __assert_fail ("Subtarget->hasAVX512() && \"Expected AVX512!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3696, __PRETTY_FUNCTION__))
;
1
'?' condition is true
3697 assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&((Setcc.getSimpleValueType().getVectorElementType() == MVT::i1
&& "Unexpected VT!") ? static_cast<void> (0) :
__assert_fail ("Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3698, __PRETTY_FUNCTION__))
2
'?' condition is true
3698 "Unexpected VT!")((Setcc.getSimpleValueType().getVectorElementType() == MVT::i1
&& "Unexpected VT!") ? static_cast<void> (0) :
__assert_fail ("Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3698, __PRETTY_FUNCTION__))
;
3699
3700 // Look for equal and not equal compares.
3701 ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
3702 if (CC != ISD::SETEQ && CC != ISD::SETNE)
3
Assuming 'CC' is equal to SETEQ
3703 return false;
3704
3705 // See if we're comparing against zero. This should have been canonicalized
3706 // to RHS during lowering.
3707 if (!ISD::isBuildVectorAllZeros(Setcc.getOperand(1).getNode()))
4
Assuming the condition is false
5
Taking false branch
3708 return false;
3709
3710 SDValue N0 = Setcc.getOperand(0);
3711
3712 MVT CmpVT = N0.getSimpleValueType();
3713 MVT CmpSVT = CmpVT.getVectorElementType();
3714
3715 // Start with both operands the same. We'll try to refine this.
3716 SDValue Src0 = N0;
3717 SDValue Src1 = N0;
3718
3719 {
3720 // Look through single use bitcasts.
3721 SDValue N0Temp = N0;
3722 if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
6
Assuming the condition is false
3723 N0Temp = N0.getOperand(0);
3724
3725 // Look for single use AND.
3726 if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
7
Assuming the condition is true
8
Assuming the condition is true
9
Taking true branch
3727 Src0 = N0Temp.getOperand(0);
3728 Src1 = N0Temp.getOperand(1);
3729 }
3730 }
3731
3732 // Without VLX we need to widen the load.
3733 bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
10
Assuming the condition is false
3734
3735 // We can only fold loads if the sources are unique.
3736 bool CanFoldLoads = Src0 != Src1;
3737
3738 // Try to fold loads unless we need to widen.
3739 bool FoldedLoad = false;
3740 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Load;
3741 if (!Widen && CanFoldLoads) {
11
Taking true branch
3742 Load = Src1;
3743 FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2, Tmp3,
3744 Tmp4);
3745 if (!FoldedLoad) {
12
Taking true branch
3746 // And is computative.
3747 Load = Src0;
3748 FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2,
3749 Tmp3, Tmp4);
3750 if (FoldedLoad)
13
Taking false branch
3751 std::swap(Src0, Src1);
3752 }
3753 }
3754
3755 auto findBroadcastedOp = [](SDValue Src, MVT CmpSVT, SDNode *&Parent) {
3756 // Look through single use bitcasts.
3757 if (Src.getOpcode() == ISD::BITCAST && Src.hasOneUse())
17
Assuming the condition is false
3758 Src = Src.getOperand(0);
3759
3760 if (Src.getOpcode() == X86ISD::VBROADCAST && Src.hasOneUse()) {
18
Assuming the condition is true
19
Assuming the condition is true
20
Taking true branch
3761 Parent = Src.getNode();
3762 Src = Src.getOperand(0);
3763 if (Src.getSimpleValueType() == CmpSVT)
21
Taking true branch
3764 return Src;
22
Returning without writing to 'Parent'
3765 }
3766
3767 return SDValue();
3768 };
3769
3770 // If we didn't fold a load, try to match broadcast. No widening limitation
3771 // for this. But only 32 and 64 bit types are supported.
3772 bool FoldedBCast = false;
3773 if (!FoldedLoad && CanFoldLoads &&
14
Taking true branch
3774 (CmpSVT == MVT::i32 || CmpSVT == MVT::i64)) {
3775 SDNode *ParentNode = nullptr;
15
'ParentNode' initialized to a null pointer value
3776 if ((Load = findBroadcastedOp(Src1, CmpSVT, ParentNode))) {
16
Calling 'operator()'
23
Returning from 'operator()'
24
Taking true branch
3777 FoldedBCast = tryFoldLoad(Root, ParentNode, Load, Tmp0,
25
Passing null pointer value via 2nd parameter 'P'
26
Calling 'X86DAGToDAGISel::tryFoldLoad'
3778 Tmp1, Tmp2, Tmp3, Tmp4);
3779 }
3780
3781 // Try the other operand.
3782 if (!FoldedBCast) {
3783 if ((Load = findBroadcastedOp(Src0, CmpSVT, ParentNode))) {
3784 FoldedBCast = tryFoldLoad(Root, ParentNode, Load, Tmp0,
3785 Tmp1, Tmp2, Tmp3, Tmp4);
3786 if (FoldedBCast)
3787 std::swap(Src0, Src1);
3788 }
3789 }
3790 }
3791
3792 auto getMaskRC = [](MVT MaskVT) {
3793 switch (MaskVT.SimpleTy) {
3794 default: llvm_unreachable("Unexpected VT!")::llvm::llvm_unreachable_internal("Unexpected VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3794)
;
3795 case MVT::v2i1: return X86::VK2RegClassID;
3796 case MVT::v4i1: return X86::VK4RegClassID;
3797 case MVT::v8i1: return X86::VK8RegClassID;
3798 case MVT::v16i1: return X86::VK16RegClassID;
3799 case MVT::v32i1: return X86::VK32RegClassID;
3800 case MVT::v64i1: return X86::VK64RegClassID;
3801 }
3802 };
3803
3804 bool IsMasked = InMask.getNode() != nullptr;
3805
3806 SDLoc dl(Root);
3807
3808 MVT ResVT = Setcc.getSimpleValueType();
3809 MVT MaskVT = ResVT;
3810 if (Widen) {
3811 // Widen the inputs using insert_subreg or copy_to_regclass.
3812 unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
3813 unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
3814 unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
3815 CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
3816 MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
3817 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
3818 CmpVT), 0);
3819 Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
3820
3821 assert(!FoldedLoad && "Shouldn't have folded the load")((!FoldedLoad && "Shouldn't have folded the load") ? static_cast
<void> (0) : __assert_fail ("!FoldedLoad && \"Shouldn't have folded the load\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3821, __PRETTY_FUNCTION__))
;
3822 if (!FoldedBCast)
3823 Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
3824
3825 if (IsMasked) {
3826 // Widen the mask.
3827 unsigned RegClass = getMaskRC(MaskVT);
3828 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
3829 InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
3830 dl, MaskVT, InMask, RC), 0);
3831 }
3832 }
3833
3834 bool IsTestN = CC == ISD::SETEQ;
3835 unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
3836 IsMasked);
3837
3838 MachineSDNode *CNode;
3839 if (FoldedLoad || FoldedBCast) {
3840 SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
3841
3842 if (IsMasked) {
3843 SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
3844 Load.getOperand(0) };
3845 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
3846 } else {
3847 SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
3848 Load.getOperand(0) };
3849 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
3850 }
3851
3852 // Update the chain.
3853 ReplaceUses(Load.getValue(1), SDValue(CNode, 1));
3854 // Record the mem-refs
3855 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(Load)->getMemOperand()});
3856 } else {
3857 if (IsMasked)
3858 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
3859 else
3860 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
3861 }
3862
3863 // If we widened, we need to shrink the mask VT.
3864 if (Widen) {
3865 unsigned RegClass = getMaskRC(ResVT);
3866 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
3867 CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
3868 dl, ResVT, SDValue(CNode, 0), RC);
3869 }
3870
3871 ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
3872 CurDAG->RemoveDeadNode(Root);
3873 return true;
3874}
3875
3876void X86DAGToDAGISel::Select(SDNode *Node) {
3877 MVT NVT = Node->getSimpleValueType(0);
3878 unsigned Opcode = Node->getOpcode();
3879 SDLoc dl(Node);
3880
3881 if (Node->isMachineOpcode()) {
3882 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "== "; Node->dump(CurDAG);
dbgs() << '\n'; } } while (false)
;
3883 Node->setNodeId(-1);
3884 return; // Already selected.
3885 }
3886
3887 switch (Opcode) {
3888 default: break;
3889 case ISD::INTRINSIC_VOID: {
3890 unsigned IntNo = Node->getConstantOperandVal(1);
3891 switch (IntNo) {
3892 default: break;
3893 case Intrinsic::x86_sse3_monitor:
3894 case Intrinsic::x86_monitorx:
3895 case Intrinsic::x86_clzero: {
3896 bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
3897
3898 unsigned Opc = 0;
3899 switch (IntNo) {
3900 case Intrinsic::x86_sse3_monitor:
3901 if (!Subtarget->hasSSE3())
3902 break;
3903 Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
3904 break;
3905 case Intrinsic::x86_monitorx:
3906 if (!Subtarget->hasMWAITX())
3907 break;
3908 Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
3909 break;
3910 case Intrinsic::x86_clzero:
3911 if (!Subtarget->hasCLZERO())
3912 break;
3913 Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
3914 break;
3915 }
3916
3917 if (Opc) {
3918 unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
3919 SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
3920 Node->getOperand(2), SDValue());
3921 SDValue InFlag = Chain.getValue(1);
3922
3923 if (IntNo == Intrinsic::x86_sse3_monitor ||
3924 IntNo == Intrinsic::x86_monitorx) {
3925 // Copy the other two operands to ECX and EDX.
3926 Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
3927 InFlag);
3928 InFlag = Chain.getValue(1);
3929 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
3930 InFlag);
3931 InFlag = Chain.getValue(1);
3932 }
3933
3934 MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
3935 { Chain, InFlag});
3936 ReplaceNode(Node, CNode);
3937 return;
3938 }
3939 }
3940 }
3941
3942 break;
3943 }
3944 case ISD::BRIND: {
3945 if (Subtarget->isTargetNaCl())
3946 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
3947 // leave the instruction alone.
3948 break;
3949 if (Subtarget->isTarget64BitILP32()) {
3950 // Converts a 32-bit register to a 64-bit, zero-extended version of
3951 // it. This is needed because x86-64 can do many things, but jmp %r32
3952 // ain't one of them.
3953 const SDValue &Target = Node->getOperand(1);
3954 assert(Target.getSimpleValueType() == llvm::MVT::i32)((Target.getSimpleValueType() == llvm::MVT::i32) ? static_cast
<void> (0) : __assert_fail ("Target.getSimpleValueType() == llvm::MVT::i32"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3954, __PRETTY_FUNCTION__))
;
3955 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
3956 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
3957 Node->getOperand(0), ZextTarget);
3958 ReplaceNode(Node, Brind.getNode());
3959 SelectCode(ZextTarget.getNode());
3960 SelectCode(Brind.getNode());
3961 return;
3962 }
3963 break;
3964 }
3965 case X86ISD::GlobalBaseReg:
3966 ReplaceNode(Node, getGlobalBaseReg());
3967 return;
3968
3969 case ISD::BITCAST:
3970 // Just drop all 128/256/512-bit bitcasts.
3971 if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
3972 NVT == MVT::f128) {
3973 ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
3974 CurDAG->RemoveDeadNode(Node);
3975 return;
3976 }
3977 break;
3978
3979 case ISD::VSELECT: {
3980 // Replace VSELECT with non-mask conditions with with BLENDV.
3981 if (Node->getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3982 break;
3983
3984 assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!")((Subtarget->hasSSE41() && "Expected SSE4.1 support!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget->hasSSE41() && \"Expected SSE4.1 support!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 3984, __PRETTY_FUNCTION__))
;
3985 SDValue Blendv = CurDAG->getNode(
3986 X86ISD::BLENDV, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
3987 Node->getOperand(1), Node->getOperand(2));
3988 ReplaceNode(Node, Blendv.getNode());
3989 SelectCode(Blendv.getNode());
3990 // We already called ReplaceUses.
3991 return;
3992 }
3993
3994 case ISD::SRL:
3995 if (matchBitExtract(Node))
3996 return;
3997 LLVM_FALLTHROUGH[[clang::fallthrough]];
3998 case ISD::SRA:
3999 case ISD::SHL:
4000 if (tryShiftAmountMod(Node))
4001 return;
4002 break;
4003
4004 case ISD::AND:
4005 if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) {
4006 // Try to form a masked VPTESTM. Operands can be in either order.
4007 SDValue N0 = Node->getOperand(0);
4008 SDValue N1 = Node->getOperand(1);
4009 if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&
4010 tryVPTESTM(Node, N0, N1))
4011 return;
4012 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
4013 tryVPTESTM(Node, N1, N0))
4014 return;
4015 }
4016
4017 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
4018 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
4019 CurDAG->RemoveDeadNode(Node);
4020 return;
4021 }
4022 if (matchBitExtract(Node))
4023 return;
4024 if (AndImmShrink && shrinkAndImmediate(Node))
4025 return;
4026
4027 LLVM_FALLTHROUGH[[clang::fallthrough]];
4028 case ISD::OR:
4029 case ISD::XOR: {
4030
4031 // For operations of the form (x << C1) op C2, check if we can use a smaller
4032 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
4033 SDValue Shift = Node->getOperand(0);
4034 SDValue N1 = Node->getOperand(1);
4035
4036 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
4037 if (!Cst)
4038 break;
4039
4040 int64_t Val = Cst->getSExtValue();
4041
4042 // If we have an any_extend feeding the AND, look through it to see if there
4043 // is a shift behind it. But only if the AND doesn't use the extended bits.
4044 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
4045 bool FoundAnyExtend = false;
4046 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
4047 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
4048 isUInt<32>(Val)) {
4049 FoundAnyExtend = true;
4050 Shift = Shift.getOperand(0);
4051 }
4052
4053 if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
4054 break;
4055
4056 // i8 is unshrinkable, i16 should be promoted to i32.
4057 if (NVT != MVT::i32 && NVT != MVT::i64)
4058 break;
4059
4060 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4061 if (!ShlCst)
4062 break;
4063
4064 uint64_t ShAmt = ShlCst->getZExtValue();
4065
4066 // Make sure that we don't change the operation by removing bits.
4067 // This only matters for OR and XOR, AND is unaffected.
4068 uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
4069 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
4070 break;
4071
4072 // Check the minimum bitwidth for the new constant.
4073 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
4074 auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
4075 if (Opcode == ISD::AND) {
4076 // AND32ri is the same as AND64ri32 with zext imm.
4077 // Try this before sign extended immediates below.
4078 ShiftedVal = (uint64_t)Val >> ShAmt;
4079 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4080 return true;
4081 // Also swap order when the AND can become MOVZX.
4082 if (ShiftedVal == UINT8_MAX(255) || ShiftedVal == UINT16_MAX(65535))
4083 return true;
4084 }
4085 ShiftedVal = Val >> ShAmt;
4086 if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
4087 (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
4088 return true;
4089 if (Opcode != ISD::AND) {
4090 // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
4091 ShiftedVal = (uint64_t)Val >> ShAmt;
4092 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4093 return true;
4094 }
4095 return false;
4096 };
4097
4098 int64_t ShiftedVal;
4099 if (!CanShrinkImmediate(ShiftedVal))
4100 break;
4101
4102 // Ok, we can reorder to get a smaller immediate.
4103
4104 // But, its possible the original immediate allowed an AND to become MOVZX.
4105 // Doing this late due to avoid the MakedValueIsZero call as late as
4106 // possible.
4107 if (Opcode == ISD::AND) {
4108 // Find the smallest zext this could possibly be.
4109 unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
4110 ZExtWidth = PowerOf2Ceil(std::max(ZExtWidth, 8U));
4111
4112 // Figure out which bits need to be zero to achieve that mask.
4113 APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
4114 ZExtWidth);
4115 NeededMask &= ~Cst->getAPIntValue();
4116
4117 if (CurDAG->MaskedValueIsZero(Node->getOperand(0), NeededMask))
4118 break;
4119 }
4120
4121 SDValue X = Shift.getOperand(0);
4122 if (FoundAnyExtend) {
4123 SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
4124 insertDAGNode(*CurDAG, SDValue(Node, 0), NewX);
4125 X = NewX;
4126 }
4127
4128 SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);
4129 insertDAGNode(*CurDAG, SDValue(Node, 0), NewCst);
4130 SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
4131 insertDAGNode(*CurDAG, SDValue(Node, 0), NewBinOp);
4132 SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
4133 Shift.getOperand(1));
4134 ReplaceNode(Node, NewSHL.getNode());
4135 SelectCode(NewSHL.getNode());
4136 return;
4137 }
4138 case X86ISD::SMUL:
4139 // i16/i32/i64 are handled with isel patterns.
4140 if (NVT != MVT::i8)
4141 break;
4142 LLVM_FALLTHROUGH[[clang::fallthrough]];
4143 case X86ISD::UMUL: {
4144 SDValue N0 = Node->getOperand(0);
4145 SDValue N1 = Node->getOperand(1);
4146
4147 unsigned LoReg, ROpc, MOpc;
4148 switch (NVT.SimpleTy) {
4149 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4149)
;
4150 case MVT::i8:
4151 LoReg = X86::AL;
4152 ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
4153 MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
4154 break;
4155 case MVT::i16:
4156 LoReg = X86::AX;
4157 ROpc = X86::MUL16r;
4158 MOpc = X86::MUL16m;
4159 break;
4160 case MVT::i32:
4161 LoReg = X86::EAX;
4162 ROpc = X86::MUL32r;
4163 MOpc = X86::MUL32m;
4164 break;
4165 case MVT::i64:
4166 LoReg = X86::RAX;
4167 ROpc = X86::MUL64r;
4168 MOpc = X86::MUL64m;
4169 break;
4170 }
4171
4172 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4173 bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4174 // Multiply is commmutative.
4175 if (!FoldedLoad) {
4176 FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4177 if (FoldedLoad)
4178 std::swap(N0, N1);
4179 }
4180
4181 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
4182 N0, SDValue()).getValue(1);
4183
4184 MachineSDNode *CNode;
4185 if (FoldedLoad) {
4186 // i16/i32/i64 use an instruction that produces a low and high result even
4187 // though only the low result is used.
4188 SDVTList VTs;
4189 if (NVT == MVT::i8)
4190 VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4191 else
4192 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
4193
4194 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4195 InFlag };
4196 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4197
4198 // Update the chain.
4199 ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
4200 // Record the mem-refs
4201 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4202 } else {
4203 // i16/i32/i64 use an instruction that produces a low and high result even
4204 // though only the low result is used.
4205 SDVTList VTs;
4206 if (NVT == MVT::i8)
4207 VTs = CurDAG->getVTList(NVT, MVT::i32);
4208 else
4209 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
4210
4211 CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InFlag});
4212 }
4213
4214 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4215 ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
4216 CurDAG->RemoveDeadNode(Node);
4217 return;
4218 }
4219
4220 case ISD::SMUL_LOHI:
4221 case ISD::UMUL_LOHI: {
4222 SDValue N0 = Node->getOperand(0);
4223 SDValue N1 = Node->getOperand(1);
4224
4225 unsigned Opc, MOpc;
4226 bool isSigned = Opcode == ISD::SMUL_LOHI;
4227 if (!isSigned) {
4228 switch (NVT.SimpleTy) {
4229 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4229)
;
4230 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
4231 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
4232 }
4233 } else {
4234 switch (NVT.SimpleTy) {
4235 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4235)
;
4236 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
4237 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
4238 }
4239 }
4240
4241 unsigned SrcReg, LoReg, HiReg;
4242 switch (Opc) {
4243 default: llvm_unreachable("Unknown MUL opcode!")::llvm::llvm_unreachable_internal("Unknown MUL opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4243)
;
4244 case X86::IMUL32r:
4245 case X86::MUL32r:
4246 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
4247 break;
4248 case X86::IMUL64r:
4249 case X86::MUL64r:
4250 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
4251 break;
4252 }
4253
4254 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4255 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4256 // Multiply is commmutative.
4257 if (!foldedLoad) {
4258 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4259 if (foldedLoad)
4260 std::swap(N0, N1);
4261 }
4262
4263 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
4264 N0, SDValue()).getValue(1);
4265 if (foldedLoad) {
4266 SDValue Chain;
4267 MachineSDNode *CNode = nullptr;
4268 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4269 InFlag };
4270 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
4271 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4272 Chain = SDValue(CNode, 0);
4273 InFlag = SDValue(CNode, 1);
4274
4275 // Update the chain.
4276 ReplaceUses(N1.getValue(1), Chain);
4277 // Record the mem-refs
4278 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4279 } else {
4280 SDValue Ops[] = { N1, InFlag };
4281 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
4282 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4283 InFlag = SDValue(CNode, 0);
4284 }
4285
4286 // Copy the low half of the result, if it is needed.
4287 if (!SDValue(Node, 0).use_empty()) {
4288 assert(LoReg && "Register for low half is not defined!")((LoReg && "Register for low half is not defined!") ?
static_cast<void> (0) : __assert_fail ("LoReg && \"Register for low half is not defined!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4288, __PRETTY_FUNCTION__))
;
4289 SDValue ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
4290 NVT, InFlag);
4291 InFlag = ResLo.getValue(2);
4292 ReplaceUses(SDValue(Node, 0), ResLo);
4293 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; ResLo.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
4294 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; ResLo.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
;
4295 }
4296 // Copy the high half of the result, if it is needed.
4297 if (!SDValue(Node, 1).use_empty()) {
4298 assert(HiReg && "Register for high half is not defined!")((HiReg && "Register for high half is not defined!") ?
static_cast<void> (0) : __assert_fail ("HiReg && \"Register for high half is not defined!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4298, __PRETTY_FUNCTION__))
;
4299 SDValue ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
4300 NVT, InFlag);
4301 InFlag = ResHi.getValue(2);
4302 ReplaceUses(SDValue(Node, 1), ResHi);
4303 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; ResHi.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
4304 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; ResHi.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
;
4305 }
4306
4307 CurDAG->RemoveDeadNode(Node);
4308 return;
4309 }
4310
4311 case ISD::SDIVREM:
4312 case ISD::UDIVREM: {
4313 SDValue N0 = Node->getOperand(0);
4314 SDValue N1 = Node->getOperand(1);
4315
4316 unsigned Opc, MOpc;
4317 bool isSigned = Opcode == ISD::SDIVREM;
4318 if (!isSigned) {
4319 switch (NVT.SimpleTy) {
4320 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4320)
;
4321 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
4322 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
4323 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
4324 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
4325 }
4326 } else {
4327 switch (NVT.SimpleTy) {
4328 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4328)
;
4329 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
4330 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
4331 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
4332 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
4333 }
4334 }
4335
4336 unsigned LoReg, HiReg, ClrReg;
4337 unsigned SExtOpcode;
4338 switch (NVT.SimpleTy) {
4339 default: llvm_unreachable("Unsupported VT!")::llvm::llvm_unreachable_internal("Unsupported VT!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4339)
;
4340 case MVT::i8:
4341 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
4342 SExtOpcode = X86::CBW;
4343 break;
4344 case MVT::i16:
4345 LoReg = X86::AX; HiReg = X86::DX;
4346 ClrReg = X86::DX;
4347 SExtOpcode = X86::CWD;
4348 break;
4349 case MVT::i32:
4350 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
4351 SExtOpcode = X86::CDQ;
4352 break;
4353 case MVT::i64:
4354 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
4355 SExtOpcode = X86::CQO;
4356 break;
4357 }
4358
4359 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4360 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4361 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
4362
4363 SDValue InFlag;
4364 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
4365 // Special case for div8, just use a move with zero extension to AX to
4366 // clear the upper 8 bits (AH).
4367 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
4368 MachineSDNode *Move;
4369 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4370 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
4371 Move = CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
4372 MVT::Other, Ops);
4373 Chain = SDValue(Move, 1);
4374 ReplaceUses(N0.getValue(1), Chain);
4375 // Record the mem-refs
4376 CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
4377 } else {
4378 Move = CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0);
4379 Chain = CurDAG->getEntryNode();
4380 }
4381 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, SDValue(Move, 0),
4382 SDValue());
4383 InFlag = Chain.getValue(1);
4384 } else {
4385 InFlag =
4386 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
4387 LoReg, N0, SDValue()).getValue(1);
4388 if (isSigned && !signBitIsZero) {
4389 // Sign extend the low part into the high part.
4390 InFlag =
4391 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
4392 } else {
4393 // Zero out the high part, effectively zero extending the input.
4394 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
4395 switch (NVT.SimpleTy) {
4396 case MVT::i16:
4397 ClrNode =
4398 SDValue(CurDAG->getMachineNode(
4399 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
4400 CurDAG->getTargetConstant(X86::sub_16bit, dl,
4401 MVT::i32)),
4402 0);
4403 break;
4404 case MVT::i32:
4405 break;
4406 case MVT::i64:
4407 ClrNode =
4408 SDValue(CurDAG->getMachineNode(
4409 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
4410 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
4411 CurDAG->getTargetConstant(X86::sub_32bit, dl,
4412 MVT::i32)),
4413 0);
4414 break;
4415 default:
4416 llvm_unreachable("Unexpected division source")::llvm::llvm_unreachable_internal("Unexpected division source"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4416)
;
4417 }
4418
4419 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
4420 ClrNode, InFlag).getValue(1);
4421 }
4422 }
4423
4424 if (foldedLoad) {
4425 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4426 InFlag };
4427 MachineSDNode *CNode =
4428 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
4429 InFlag = SDValue(CNode, 1);
4430 // Update the chain.
4431 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
4432 // Record the mem-refs
4433 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4434 } else {
4435 InFlag =
4436 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
4437 }
4438
4439 // Prevent use of AH in a REX instruction by explicitly copying it to
4440 // an ABCD_L register.
4441 //
4442 // The current assumption of the register allocator is that isel
4443 // won't generate explicit references to the GR8_ABCD_H registers. If
4444 // the allocator and/or the backend get enhanced to be more robust in
4445 // that regard, this can be, and should be, removed.
4446 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
4447 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
4448 unsigned AHExtOpcode =
4449 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
4450
4451 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
4452 MVT::Glue, AHCopy, InFlag);
4453 SDValue Result(RNode, 0);
4454 InFlag = SDValue(RNode, 1);
4455
4456 Result =
4457 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
4458
4459 ReplaceUses(SDValue(Node, 1), Result);
4460 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
4461 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
;
4462 }
4463 // Copy the division (low) result, if it is needed.
4464 if (!SDValue(Node, 0).use_empty()) {
4465 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
4466 LoReg, NVT, InFlag);
4467 InFlag = Result.getValue(2);
4468 ReplaceUses(SDValue(Node, 0), Result);
4469 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
4470 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
;
4471 }
4472 // Copy the remainder (high) result, if it is needed.
4473 if (!SDValue(Node, 1).use_empty()) {
4474 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
4475 HiReg, NVT, InFlag);
4476 InFlag = Result.getValue(2);
4477 ReplaceUses(SDValue(Node, 1), Result);
4478 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
4479 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "=> "; Result.getNode()->
dump(CurDAG); dbgs() << '\n'; } } while (false)
;
4480 }
4481 CurDAG->RemoveDeadNode(Node);
4482 return;
4483 }
4484
4485 case X86ISD::CMP: {
4486 SDValue N0 = Node->getOperand(0);
4487 SDValue N1 = Node->getOperand(1);
4488
4489 // Optimizations for TEST compares.
4490 if (!isNullConstant(N1))
4491 break;
4492
4493 // Save the original VT of the compare.
4494 MVT CmpVT = N0.getSimpleValueType();
4495
4496 // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
4497 // by a test instruction. The test should be removed later by
4498 // analyzeCompare if we are using only the zero flag.
4499 // TODO: Should we check the users and use the BEXTR flags directly?
4500 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4501 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
4502 unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
4503 : X86::TEST32rr;
4504 SDValue BEXTR = SDValue(NewNode, 0);
4505 NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
4506 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
4507 CurDAG->RemoveDeadNode(Node);
4508 return;
4509 }
4510 }
4511
4512 // We can peek through truncates, but we need to be careful below.
4513 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
4514 N0 = N0.getOperand(0);
4515
4516 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
4517 // use a smaller encoding.
4518 // Look past the truncate if CMP is the only use of it.
4519 if (N0.getOpcode() == ISD::AND &&
4520 N0.getNode()->hasOneUse() &&
4521 N0.getValueType() != MVT::i8) {
4522 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4523 if (!C) break;
4524 uint64_t Mask = C->getZExtValue();
4525
4526 // Check if we can replace AND+IMM64 with a shift. This is possible for
4527 // masks/ like 0xFF000000 or 0x00FFFFFF and if we care only about the zero
4528 // flag.
4529 if (CmpVT == MVT::i64 && !isInt<32>(Mask) &&
4530 onlyUsesZeroFlag(SDValue(Node, 0))) {
4531 if (isMask_64(~Mask)) {
4532 unsigned TrailingZeros = countTrailingZeros(Mask);
4533 SDValue Imm = CurDAG->getTargetConstant(TrailingZeros, dl, MVT::i64);
4534 SDValue Shift =
4535 SDValue(CurDAG->getMachineNode(X86::SHR64ri, dl, MVT::i64, MVT::i32,
4536 N0.getOperand(0), Imm), 0);
4537 MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
4538 MVT::i32, Shift, Shift);
4539 ReplaceNode(Node, Test);
4540 return;
4541 }
4542 if (isMask_64(Mask)) {
4543 unsigned LeadingZeros = countLeadingZeros(Mask);
4544 SDValue Imm = CurDAG->getTargetConstant(LeadingZeros, dl, MVT::i64);
4545 SDValue Shift =
4546 SDValue(CurDAG->getMachineNode(X86::SHL64ri, dl, MVT::i64, MVT::i32,
4547 N0.getOperand(0), Imm), 0);
4548 MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
4549 MVT::i32, Shift, Shift);
4550 ReplaceNode(Node, Test);
4551 return;
4552 }
4553 }
4554
4555 MVT VT;
4556 int SubRegOp;
4557 unsigned ROpc, MOpc;
4558
4559 // For each of these checks we need to be careful if the sign flag is
4560 // being used. It is only safe to use the sign flag in two conditions,
4561 // either the sign bit in the shrunken mask is zero or the final test
4562 // size is equal to the original compare size.
4563
4564 if (isUInt<8>(Mask) &&
4565 (!(Mask & 0x80) || CmpVT == MVT::i8 ||
4566 hasNoSignFlagUses(SDValue(Node, 0)))) {
4567 // For example, convert "testl %eax, $8" to "testb %al, $8"
4568 VT = MVT::i8;
4569 SubRegOp = X86::sub_8bit;
4570 ROpc = X86::TEST8ri;
4571 MOpc = X86::TEST8mi;
4572 } else if (OptForMinSize && isUInt<16>(Mask) &&
4573 (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
4574 hasNoSignFlagUses(SDValue(Node, 0)))) {
4575 // For example, "testl %eax, $32776" to "testw %ax, $32776".
4576 // NOTE: We only want to form TESTW instructions if optimizing for
4577 // min size. Otherwise we only save one byte and possibly get a length
4578 // changing prefix penalty in the decoders.
4579 VT = MVT::i16;
4580 SubRegOp = X86::sub_16bit;
4581 ROpc = X86::TEST16ri;
4582 MOpc = X86::TEST16mi;
4583 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
4584 ((!(Mask & 0x80000000) &&
4585 // Without minsize 16-bit Cmps can get here so we need to
4586 // be sure we calculate the correct sign flag if needed.
4587 (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
4588 CmpVT == MVT::i32 ||
4589 hasNoSignFlagUses(SDValue(Node, 0)))) {
4590 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
4591 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
4592 // Otherwize, we find ourselves in a position where we have to do
4593 // promotion. If previous passes did not promote the and, we assume
4594 // they had a good reason not to and do not promote here.
4595 VT = MVT::i32;
4596 SubRegOp = X86::sub_32bit;
4597 ROpc = X86::TEST32ri;
4598 MOpc = X86::TEST32mi;
4599 } else {
4600 // No eligible transformation was found.
4601 break;
4602 }
4603
4604 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
4605 SDValue Reg = N0.getOperand(0);
4606
4607 // Emit a testl or testw.
4608 MachineSDNode *NewNode;
4609 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4610 if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4611 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
4612 Reg.getOperand(0) };
4613 NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
4614 // Update the chain.
4615 ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
4616 // Record the mem-refs
4617 CurDAG->setNodeMemRefs(NewNode,
4618 {cast<LoadSDNode>(Reg)->getMemOperand()});
4619 } else {
4620 // Extract the subregister if necessary.
4621 if (N0.getValueType() != VT)
4622 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
4623
4624 NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
4625 }
4626 // Replace CMP with TEST.
4627 ReplaceNode(Node, NewNode);
4628 return;
4629 }
4630 break;
4631 }
4632 case X86ISD::PCMPISTR: {
4633 if (!Subtarget->hasSSE42())
4634 break;
4635
4636 bool NeedIndex = !SDValue(Node, 0).use_empty();
4637 bool NeedMask = !SDValue(Node, 1).use_empty();
4638 // We can't fold a load if we are going to make two instructions.
4639 bool MayFoldLoad = !NeedIndex || !NeedMask;
4640
4641 MachineSDNode *CNode;
4642 if (NeedMask) {
4643 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
4644 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
4645 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
4646 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
4647 }
4648 if (NeedIndex || !NeedMask) {
4649 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
4650 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
4651 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
4652 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4653 }
4654
4655 // Connect the flag usage to the last instruction created.
4656 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
4657 CurDAG->RemoveDeadNode(Node);
4658 return;
4659 }
4660 case X86ISD::PCMPESTR: {
4661 if (!Subtarget->hasSSE42())
4662 break;
4663
4664 // Copy the two implicit register inputs.
4665 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
4666 Node->getOperand(1),
4667 SDValue()).getValue(1);
4668 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
4669 Node->getOperand(3), InFlag).getValue(1);
4670
4671 bool NeedIndex = !SDValue(Node, 0).use_empty();
4672 bool NeedMask = !SDValue(Node, 1).use_empty();
4673 // We can't fold a load if we are going to make two instructions.
4674 bool MayFoldLoad = !NeedIndex || !NeedMask;
4675
4676 MachineSDNode *CNode;
4677 if (NeedMask) {
4678 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
4679 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
4680 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
4681 InFlag);
4682 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
4683 }
4684 if (NeedIndex || !NeedMask) {
4685 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
4686 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
4687 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
4688 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4689 }
4690 // Connect the flag usage to the last instruction created.
4691 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
4692 CurDAG->RemoveDeadNode(Node);
4693 return;
4694 }
4695
4696 case ISD::SETCC: {
4697 if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))
4698 return;
4699
4700 break;
4701 }
4702
4703 case ISD::STORE:
4704 if (foldLoadStoreIntoMemOperand(Node))
4705 return;
4706 break;
4707 case ISD::FCEIL:
4708 case ISD::FFLOOR:
4709 case ISD::FTRUNC:
4710 case ISD::FNEARBYINT:
4711 case ISD::FRINT: {
4712 // Replace vector rounding with their X86 specific equivalent so we don't
4713 // need 2 sets of patterns.
4714 // FIXME: This can only happen when the nodes started as STRICT_* and have
4715 // been mutated into their non-STRICT equivalents. Eventually this
4716 // mutation will be removed and we should switch the STRICT_ nodes to a
4717 // strict version of RNDSCALE in PreProcessISelDAG.
4718 if (!Node->getValueType(0).isVector())
4719 break;
4720
4721 unsigned Imm;
4722 switch (Node->getOpcode()) {
4723 default: llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4723)
;
4724 case ISD::FCEIL: Imm = 0xA; break;
4725 case ISD::FFLOOR: Imm = 0x9; break;
4726 case ISD::FTRUNC: Imm = 0xB; break;
4727 case ISD::FNEARBYINT: Imm = 0xC; break;
4728 case ISD::FRINT: Imm = 0x4; break;
4729 }
4730 SDLoc dl(Node);
4731 SDValue Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl,
4732 Node->getValueType(0),
4733 Node->getOperand(0),
4734 CurDAG->getConstant(Imm, dl, MVT::i8));
4735 ReplaceNode(Node, Res.getNode());
4736 SelectCode(Res.getNode());
4737 return;
4738 }
4739 }
4740
4741 SelectCode(Node);
4742}
4743
4744bool X86DAGToDAGISel::
4745SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
4746 std::vector<SDValue> &OutOps) {
4747 SDValue Op0, Op1, Op2, Op3, Op4;
4748 switch (ConstraintID) {
4749 default:
4750 llvm_unreachable("Unexpected asm memory constraint")::llvm::llvm_unreachable_internal("Unexpected asm memory constraint"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelDAGToDAG.cpp"
, 4750)
;
4751 case InlineAsm::Constraint_i:
4752 // FIXME: It seems strange that 'i' is needed here since it's supposed to
4753 // be an immediate and not a memory constraint.
4754 LLVM_FALLTHROUGH[[clang::fallthrough]];
4755 case InlineAsm::Constraint_o: // offsetable ??
4756 case InlineAsm::Constraint_v: // not offsetable ??
4757 case InlineAsm::Constraint_m: // memory
4758 case InlineAsm::Constraint_X:
4759 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
4760 return true;
4761 break;
4762 }
4763
4764 OutOps.push_back(Op0);
4765 OutOps.push_back(Op1);
4766 OutOps.push_back(Op2);
4767 OutOps.push_back(Op3);
4768 OutOps.push_back(Op4);
4769 return false;
4770}
4771
4772/// This pass converts a legalized DAG into a X86-specific DAG,
4773/// ready for instruction scheduling.
4774FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
4775 CodeGenOpt::Level OptLevel) {
4776 return new X86DAGToDAGISel(TM, OptLevel);
4777}