Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1345, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name DAGCombiner.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/lib/CodeGen/SelectionDAG -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp

/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp

1//===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
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 pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
10// both before and after the DAG is legalized.
11//
12// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
13// primarily intended to handle simplification opportunities that are implicit
14// in the LLVM IR and exposed by the various codegen lowering phases.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/APFloat.h"
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntervalMap.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/AliasAnalysis.h"
33#include "llvm/Analysis/MemoryLocation.h"
34#include "llvm/Analysis/TargetLibraryInfo.h"
35#include "llvm/Analysis/VectorUtils.h"
36#include "llvm/CodeGen/DAGCombine.h"
37#include "llvm/CodeGen/ISDOpcodes.h"
38#include "llvm/CodeGen/MachineFrameInfo.h"
39#include "llvm/CodeGen/MachineFunction.h"
40#include "llvm/CodeGen/MachineMemOperand.h"
41#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
44#include "llvm/CodeGen/SelectionDAGNodes.h"
45#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
46#include "llvm/CodeGen/TargetLowering.h"
47#include "llvm/CodeGen/TargetRegisterInfo.h"
48#include "llvm/CodeGen/TargetSubtargetInfo.h"
49#include "llvm/CodeGen/ValueTypes.h"
50#include "llvm/IR/Attributes.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DerivedTypes.h"
54#include "llvm/IR/Function.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/CodeGen.h"
59#include "llvm/Support/CommandLine.h"
60#include "llvm/Support/Compiler.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/KnownBits.h"
64#include "llvm/Support/MachineValueType.h"
65#include "llvm/Support/MathExtras.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/Target/TargetMachine.h"
68#include "llvm/Target/TargetOptions.h"
69#include <algorithm>
70#include <cassert>
71#include <cstdint>
72#include <functional>
73#include <iterator>
74#include <string>
75#include <tuple>
76#include <utility>
77
78using namespace llvm;
79
80#define DEBUG_TYPE"dagcombine" "dagcombine"
81
82STATISTIC(NodesCombined , "Number of dag nodes combined")static llvm::Statistic NodesCombined = {"dagcombine", "NodesCombined"
, "Number of dag nodes combined"}
;
83STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created")static llvm::Statistic PreIndexedNodes = {"dagcombine", "PreIndexedNodes"
, "Number of pre-indexed nodes created"}
;
84STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created")static llvm::Statistic PostIndexedNodes = {"dagcombine", "PostIndexedNodes"
, "Number of post-indexed nodes created"}
;
85STATISTIC(OpsNarrowed , "Number of load/op/store narrowed")static llvm::Statistic OpsNarrowed = {"dagcombine", "OpsNarrowed"
, "Number of load/op/store narrowed"}
;
86STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int")static llvm::Statistic LdStFP2Int = {"dagcombine", "LdStFP2Int"
, "Number of fp load/store pairs transformed to int"}
;
87STATISTIC(SlicedLoads, "Number of load sliced")static llvm::Statistic SlicedLoads = {"dagcombine", "SlicedLoads"
, "Number of load sliced"}
;
88STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops")static llvm::Statistic NumFPLogicOpsConv = {"dagcombine", "NumFPLogicOpsConv"
, "Number of logic ops converted to fp ops"}
;
89
90static cl::opt<bool>
91CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
92 cl::desc("Enable DAG combiner's use of IR alias analysis"));
93
94static cl::opt<bool>
95UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
96 cl::desc("Enable DAG combiner's use of TBAA"));
97
98#ifndef NDEBUG
99static cl::opt<std::string>
100CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
101 cl::desc("Only use DAG-combiner alias analysis in this"
102 " function"));
103#endif
104
105/// Hidden option to stress test load slicing, i.e., when this option
106/// is enabled, load slicing bypasses most of its profitability guards.
107static cl::opt<bool>
108StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
109 cl::desc("Bypass the profitability model of load slicing"),
110 cl::init(false));
111
112static cl::opt<bool>
113 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
114 cl::desc("DAG combiner may split indexing from loads"));
115
116static cl::opt<bool>
117 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
118 cl::desc("DAG combiner enable merging multiple stores "
119 "into a wider store"));
120
121static cl::opt<unsigned> TokenFactorInlineLimit(
122 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
123 cl::desc("Limit the number of operands to inline for Token Factors"));
124
125static cl::opt<unsigned> StoreMergeDependenceLimit(
126 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
127 cl::desc("Limit the number of times for the same StoreNode and RootNode "
128 "to bail out in store merging dependence check"));
129
130static cl::opt<bool> EnableReduceLoadOpStoreWidth(
131 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
132 cl::desc("DAG combiner enable reducing the width of load/op/store "
133 "sequence"));
134
135static cl::opt<bool> EnableShrinkLoadReplaceStoreWithStore(
136 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
137 cl::desc("DAG combiner enable load/<replace bytes>/store with "
138 "a narrower store"));
139
140namespace {
141
142 class DAGCombiner {
143 SelectionDAG &DAG;
144 const TargetLowering &TLI;
145 const SelectionDAGTargetInfo *STI;
146 CombineLevel Level;
147 CodeGenOpt::Level OptLevel;
148 bool LegalDAG = false;
149 bool LegalOperations = false;
150 bool LegalTypes = false;
151 bool ForCodeSize;
152 bool DisableGenericCombines;
153
154 /// Worklist of all of the nodes that need to be simplified.
155 ///
156 /// This must behave as a stack -- new nodes to process are pushed onto the
157 /// back and when processing we pop off of the back.
158 ///
159 /// The worklist will not contain duplicates but may contain null entries
160 /// due to nodes being deleted from the underlying DAG.
161 SmallVector<SDNode *, 64> Worklist;
162
163 /// Mapping from an SDNode to its position on the worklist.
164 ///
165 /// This is used to find and remove nodes from the worklist (by nulling
166 /// them) when they are deleted from the underlying DAG. It relies on
167 /// stable indices of nodes within the worklist.
168 DenseMap<SDNode *, unsigned> WorklistMap;
169 /// This records all nodes attempted to add to the worklist since we
170 /// considered a new worklist entry. As we keep do not add duplicate nodes
171 /// in the worklist, this is different from the tail of the worklist.
172 SmallSetVector<SDNode *, 32> PruningList;
173
174 /// Set of nodes which have been combined (at least once).
175 ///
176 /// This is used to allow us to reliably add any operands of a DAG node
177 /// which have not yet been combined to the worklist.
178 SmallPtrSet<SDNode *, 32> CombinedNodes;
179
180 /// Map from candidate StoreNode to the pair of RootNode and count.
181 /// The count is used to track how many times we have seen the StoreNode
182 /// with the same RootNode bail out in dependence check. If we have seen
183 /// the bail out for the same pair many times over a limit, we won't
184 /// consider the StoreNode with the same RootNode as store merging
185 /// candidate again.
186 DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap;
187
188 // AA - Used for DAG load/store alias analysis.
189 AliasAnalysis *AA;
190
191 /// When an instruction is simplified, add all users of the instruction to
192 /// the work lists because they might get more simplified now.
193 void AddUsersToWorklist(SDNode *N) {
194 for (SDNode *Node : N->uses())
195 AddToWorklist(Node);
196 }
197
198 /// Convenient shorthand to add a node and all of its user to the worklist.
199 void AddToWorklistWithUsers(SDNode *N) {
200 AddUsersToWorklist(N);
201 AddToWorklist(N);
202 }
203
204 // Prune potentially dangling nodes. This is called after
205 // any visit to a node, but should also be called during a visit after any
206 // failed combine which may have created a DAG node.
207 void clearAddedDanglingWorklistEntries() {
208 // Check any nodes added to the worklist to see if they are prunable.
209 while (!PruningList.empty()) {
210 auto *N = PruningList.pop_back_val();
211 if (N->use_empty())
212 recursivelyDeleteUnusedNodes(N);
213 }
214 }
215
216 SDNode *getNextWorklistEntry() {
217 // Before we do any work, remove nodes that are not in use.
218 clearAddedDanglingWorklistEntries();
219 SDNode *N = nullptr;
220 // The Worklist holds the SDNodes in order, but it may contain null
221 // entries.
222 while (!N && !Worklist.empty()) {
223 N = Worklist.pop_back_val();
224 }
225
226 if (N) {
227 bool GoodWorklistEntry = WorklistMap.erase(N);
228 (void)GoodWorklistEntry;
229 assert(GoodWorklistEntry &&(static_cast <bool> (GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!"
) ? void (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 230, __extension__
__PRETTY_FUNCTION__))
230 "Found a worklist entry without a corresponding map entry!")(static_cast <bool> (GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!"
) ? void (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 230, __extension__
__PRETTY_FUNCTION__))
;
231 }
232 return N;
233 }
234
235 /// Call the node-specific routine that folds each particular type of node.
236 SDValue visit(SDNode *N);
237
238 public:
239 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
240 : DAG(D), TLI(D.getTargetLoweringInfo()),
241 STI(D.getSubtarget().getSelectionDAGInfo()),
242 Level(BeforeLegalizeTypes), OptLevel(OL), AA(AA) {
243 ForCodeSize = DAG.shouldOptForSize();
244 DisableGenericCombines = STI && STI->disableGenericCombines(OptLevel);
245
246 MaximumLegalStoreInBits = 0;
247 // We use the minimum store size here, since that's all we can guarantee
248 // for the scalable vector types.
249 for (MVT VT : MVT::all_valuetypes())
250 if (EVT(VT).isSimple() && VT != MVT::Other &&
251 TLI.isTypeLegal(EVT(VT)) &&
252 VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits)
253 MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize();
254 }
255
256 void ConsiderForPruning(SDNode *N) {
257 // Mark this for potential pruning.
258 PruningList.insert(N);
259 }
260
261 /// Add to the worklist making sure its instance is at the back (next to be
262 /// processed.)
263 void AddToWorklist(SDNode *N) {
264 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Deleted Node added to Worklist") ? void (0) : __assert_fail
("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 265, __extension__
__PRETTY_FUNCTION__))
265 "Deleted Node added to Worklist")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Deleted Node added to Worklist") ? void (0) : __assert_fail
("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 265, __extension__
__PRETTY_FUNCTION__))
;
266
267 // Skip handle nodes as they can't usefully be combined and confuse the
268 // zero-use deletion strategy.
269 if (N->getOpcode() == ISD::HANDLENODE)
270 return;
271
272 ConsiderForPruning(N);
273
274 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
275 Worklist.push_back(N);
276 }
277
278 /// Remove all instances of N from the worklist.
279 void removeFromWorklist(SDNode *N) {
280 CombinedNodes.erase(N);
281 PruningList.remove(N);
282 StoreRootCountMap.erase(N);
283
284 auto It = WorklistMap.find(N);
285 if (It == WorklistMap.end())
286 return; // Not in the worklist.
287
288 // Null out the entry rather than erasing it to avoid a linear operation.
289 Worklist[It->second] = nullptr;
290 WorklistMap.erase(It);
291 }
292
293 void deleteAndRecombine(SDNode *N);
294 bool recursivelyDeleteUnusedNodes(SDNode *N);
295
296 /// Replaces all uses of the results of one DAG node with new values.
297 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
298 bool AddTo = true);
299
300 /// Replaces all uses of the results of one DAG node with new values.
301 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
302 return CombineTo(N, &Res, 1, AddTo);
303 }
304
305 /// Replaces all uses of the results of one DAG node with new values.
306 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
307 bool AddTo = true) {
308 SDValue To[] = { Res0, Res1 };
309 return CombineTo(N, To, 2, AddTo);
310 }
311
312 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
313
314 private:
315 unsigned MaximumLegalStoreInBits;
316
317 /// Check the specified integer node value to see if it can be simplified or
318 /// if things it uses can be simplified by bit propagation.
319 /// If so, return true.
320 bool SimplifyDemandedBits(SDValue Op) {
321 unsigned BitWidth = Op.getScalarValueSizeInBits();
322 APInt DemandedBits = APInt::getAllOnes(BitWidth);
323 return SimplifyDemandedBits(Op, DemandedBits);
324 }
325
326 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
327 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
328 KnownBits Known;
329 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, false))
330 return false;
331
332 // Revisit the node.
333 AddToWorklist(Op.getNode());
334
335 CommitTargetLoweringOpt(TLO);
336 return true;
337 }
338
339 /// Check the specified vector node value to see if it can be simplified or
340 /// if things it uses can be simplified as it only uses some of the
341 /// elements. If so, return true.
342 bool SimplifyDemandedVectorElts(SDValue Op) {
343 // TODO: For now just pretend it cannot be simplified.
344 if (Op.getValueType().isScalableVector())
345 return false;
346
347 unsigned NumElts = Op.getValueType().getVectorNumElements();
348 APInt DemandedElts = APInt::getAllOnes(NumElts);
349 return SimplifyDemandedVectorElts(Op, DemandedElts);
350 }
351
352 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
353 const APInt &DemandedElts,
354 bool AssumeSingleUse = false);
355 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
356 bool AssumeSingleUse = false);
357
358 bool CombineToPreIndexedLoadStore(SDNode *N);
359 bool CombineToPostIndexedLoadStore(SDNode *N);
360 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
361 bool SliceUpLoad(SDNode *N);
362
363 // Scalars have size 0 to distinguish from singleton vectors.
364 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
365 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
366 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
367
368 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
369 /// load.
370 ///
371 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
372 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
373 /// \param EltNo index of the vector element to load.
374 /// \param OriginalLoad load that EVE came from to be replaced.
375 /// \returns EVE on success SDValue() on failure.
376 SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
377 SDValue EltNo,
378 LoadSDNode *OriginalLoad);
379 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
380 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
381 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
382 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
383 SDValue PromoteIntBinOp(SDValue Op);
384 SDValue PromoteIntShiftOp(SDValue Op);
385 SDValue PromoteExtend(SDValue Op);
386 bool PromoteLoad(SDValue Op);
387
388 /// Call the node-specific routine that knows how to fold each
389 /// particular type of node. If that doesn't do anything, try the
390 /// target-specific DAG combines.
391 SDValue combine(SDNode *N);
392
393 // Visitation implementation - Implement dag node combining for different
394 // node types. The semantics are as follows:
395 // Return Value:
396 // SDValue.getNode() == 0 - No change was made
397 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
398 // otherwise - N should be replaced by the returned Operand.
399 //
400 SDValue visitTokenFactor(SDNode *N);
401 SDValue visitMERGE_VALUES(SDNode *N);
402 SDValue visitADD(SDNode *N);
403 SDValue visitADDLike(SDNode *N);
404 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference);
405 SDValue visitSUB(SDNode *N);
406 SDValue visitADDSAT(SDNode *N);
407 SDValue visitSUBSAT(SDNode *N);
408 SDValue visitADDC(SDNode *N);
409 SDValue visitADDO(SDNode *N);
410 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
411 SDValue visitSUBC(SDNode *N);
412 SDValue visitSUBO(SDNode *N);
413 SDValue visitADDE(SDNode *N);
414 SDValue visitADDCARRY(SDNode *N);
415 SDValue visitSADDO_CARRY(SDNode *N);
416 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
417 SDValue visitSUBE(SDNode *N);
418 SDValue visitSUBCARRY(SDNode *N);
419 SDValue visitSSUBO_CARRY(SDNode *N);
420 SDValue visitMUL(SDNode *N);
421 SDValue visitMULFIX(SDNode *N);
422 SDValue useDivRem(SDNode *N);
423 SDValue visitSDIV(SDNode *N);
424 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
425 SDValue visitUDIV(SDNode *N);
426 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
427 SDValue visitREM(SDNode *N);
428 SDValue visitMULHU(SDNode *N);
429 SDValue visitMULHS(SDNode *N);
430 SDValue visitSMUL_LOHI(SDNode *N);
431 SDValue visitUMUL_LOHI(SDNode *N);
432 SDValue visitMULO(SDNode *N);
433 SDValue visitIMINMAX(SDNode *N);
434 SDValue visitAND(SDNode *N);
435 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
436 SDValue visitOR(SDNode *N);
437 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
438 SDValue visitXOR(SDNode *N);
439 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
440 SDValue visitSHL(SDNode *N);
441 SDValue visitSRA(SDNode *N);
442 SDValue visitSRL(SDNode *N);
443 SDValue visitFunnelShift(SDNode *N);
444 SDValue visitRotate(SDNode *N);
445 SDValue visitABS(SDNode *N);
446 SDValue visitBSWAP(SDNode *N);
447 SDValue visitBITREVERSE(SDNode *N);
448 SDValue visitCTLZ(SDNode *N);
449 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
450 SDValue visitCTTZ(SDNode *N);
451 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
452 SDValue visitCTPOP(SDNode *N);
453 SDValue visitSELECT(SDNode *N);
454 SDValue visitVSELECT(SDNode *N);
455 SDValue visitSELECT_CC(SDNode *N);
456 SDValue visitSETCC(SDNode *N);
457 SDValue visitSETCCCARRY(SDNode *N);
458 SDValue visitSIGN_EXTEND(SDNode *N);
459 SDValue visitZERO_EXTEND(SDNode *N);
460 SDValue visitANY_EXTEND(SDNode *N);
461 SDValue visitAssertExt(SDNode *N);
462 SDValue visitAssertAlign(SDNode *N);
463 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
464 SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
465 SDValue visitTRUNCATE(SDNode *N);
466 SDValue visitBITCAST(SDNode *N);
467 SDValue visitFREEZE(SDNode *N);
468 SDValue visitBUILD_PAIR(SDNode *N);
469 SDValue visitFADD(SDNode *N);
470 SDValue visitSTRICT_FADD(SDNode *N);
471 SDValue visitFSUB(SDNode *N);
472 SDValue visitFMUL(SDNode *N);
473 SDValue visitFMA(SDNode *N);
474 SDValue visitFDIV(SDNode *N);
475 SDValue visitFREM(SDNode *N);
476 SDValue visitFSQRT(SDNode *N);
477 SDValue visitFCOPYSIGN(SDNode *N);
478 SDValue visitFPOW(SDNode *N);
479 SDValue visitSINT_TO_FP(SDNode *N);
480 SDValue visitUINT_TO_FP(SDNode *N);
481 SDValue visitFP_TO_SINT(SDNode *N);
482 SDValue visitFP_TO_UINT(SDNode *N);
483 SDValue visitFP_ROUND(SDNode *N);
484 SDValue visitFP_EXTEND(SDNode *N);
485 SDValue visitFNEG(SDNode *N);
486 SDValue visitFABS(SDNode *N);
487 SDValue visitFCEIL(SDNode *N);
488 SDValue visitFTRUNC(SDNode *N);
489 SDValue visitFFLOOR(SDNode *N);
490 SDValue visitFMinMax(SDNode *N);
491 SDValue visitBRCOND(SDNode *N);
492 SDValue visitBR_CC(SDNode *N);
493 SDValue visitLOAD(SDNode *N);
494
495 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
496 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
497
498 SDValue visitSTORE(SDNode *N);
499 SDValue visitLIFETIME_END(SDNode *N);
500 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
501 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
502 SDValue visitBUILD_VECTOR(SDNode *N);
503 SDValue visitCONCAT_VECTORS(SDNode *N);
504 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
505 SDValue visitVECTOR_SHUFFLE(SDNode *N);
506 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
507 SDValue visitINSERT_SUBVECTOR(SDNode *N);
508 SDValue visitMLOAD(SDNode *N);
509 SDValue visitMSTORE(SDNode *N);
510 SDValue visitMGATHER(SDNode *N);
511 SDValue visitMSCATTER(SDNode *N);
512 SDValue visitFP_TO_FP16(SDNode *N);
513 SDValue visitFP16_TO_FP(SDNode *N);
514 SDValue visitVECREDUCE(SDNode *N);
515 SDValue visitVPOp(SDNode *N);
516
517 SDValue visitFADDForFMACombine(SDNode *N);
518 SDValue visitFSUBForFMACombine(SDNode *N);
519 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
520
521 SDValue XformToShuffleWithZero(SDNode *N);
522 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
523 const SDLoc &DL, SDValue N0,
524 SDValue N1);
525 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
526 SDValue N1);
527 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
528 SDValue N1, SDNodeFlags Flags);
529
530 SDValue visitShiftByConstant(SDNode *N);
531
532 SDValue foldSelectOfConstants(SDNode *N);
533 SDValue foldVSelectOfConstants(SDNode *N);
534 SDValue foldBinOpIntoSelect(SDNode *BO);
535 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
536 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
537 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
538 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
539 SDValue N2, SDValue N3, ISD::CondCode CC,
540 bool NotExtCompare = false);
541 SDValue convertSelectOfFPConstantsToLoadOffset(
542 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
543 ISD::CondCode CC);
544 SDValue foldSignChangeInBitcast(SDNode *N);
545 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
546 SDValue N2, SDValue N3, ISD::CondCode CC);
547 SDValue foldSelectOfBinops(SDNode *N);
548 SDValue foldSextSetcc(SDNode *N);
549 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
550 const SDLoc &DL);
551 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N);
552 SDValue unfoldMaskedMerge(SDNode *N);
553 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
554 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
555 const SDLoc &DL, bool foldBooleans);
556 SDValue rebuildSetCC(SDValue N);
557
558 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
559 SDValue &CC, bool MatchStrict = false) const;
560 bool isOneUseSetCC(SDValue N) const;
561
562 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
563 unsigned HiOp);
564 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
565 SDValue CombineExtLoad(SDNode *N);
566 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
567 SDValue combineRepeatedFPDivisors(SDNode *N);
568 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
569 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
570 SDValue BuildSDIV(SDNode *N);
571 SDValue BuildSDIVPow2(SDNode *N);
572 SDValue BuildUDIV(SDNode *N);
573 SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
574 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
575 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
576 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
577 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
578 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
579 SDNodeFlags Flags, bool Reciprocal);
580 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
581 SDNodeFlags Flags, bool Reciprocal);
582 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
583 bool DemandHighBits = true);
584 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
585 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
586 SDValue InnerPos, SDValue InnerNeg,
587 unsigned PosOpcode, unsigned NegOpcode,
588 const SDLoc &DL);
589 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
590 SDValue InnerPos, SDValue InnerNeg,
591 unsigned PosOpcode, unsigned NegOpcode,
592 const SDLoc &DL);
593 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
594 SDValue MatchLoadCombine(SDNode *N);
595 SDValue mergeTruncStores(StoreSDNode *N);
596 SDValue reduceLoadWidth(SDNode *N);
597 SDValue ReduceLoadOpStoreWidth(SDNode *N);
598 SDValue splitMergedValStore(StoreSDNode *ST);
599 SDValue TransformFPLoadStorePair(SDNode *N);
600 SDValue convertBuildVecZextToZext(SDNode *N);
601 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
602 SDValue reduceBuildVecTruncToBitCast(SDNode *N);
603 SDValue reduceBuildVecToShuffle(SDNode *N);
604 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
605 ArrayRef<int> VectorMask, SDValue VecIn1,
606 SDValue VecIn2, unsigned LeftIdx,
607 bool DidSplitVec);
608 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
609
610 /// Walk up chain skipping non-aliasing memory nodes,
611 /// looking for aliasing nodes and adding them to the Aliases vector.
612 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
613 SmallVectorImpl<SDValue> &Aliases);
614
615 /// Return true if there is any possibility that the two addresses overlap.
616 bool mayAlias(SDNode *Op0, SDNode *Op1) const;
617
618 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
619 /// chain (aliasing node.)
620 SDValue FindBetterChain(SDNode *N, SDValue Chain);
621
622 /// Try to replace a store and any possibly adjacent stores on
623 /// consecutive chains with better chains. Return true only if St is
624 /// replaced.
625 ///
626 /// Notice that other chains may still be replaced even if the function
627 /// returns false.
628 bool findBetterNeighborChains(StoreSDNode *St);
629
630 // Helper for findBetterNeighborChains. Walk up store chain add additional
631 // chained stores that do not overlap and can be parallelized.
632 bool parallelizeChainedStores(StoreSDNode *St);
633
634 /// Holds a pointer to an LSBaseSDNode as well as information on where it
635 /// is located in a sequence of memory operations connected by a chain.
636 struct MemOpLink {
637 // Ptr to the mem node.
638 LSBaseSDNode *MemNode;
639
640 // Offset from the base ptr.
641 int64_t OffsetFromBase;
642
643 MemOpLink(LSBaseSDNode *N, int64_t Offset)
644 : MemNode(N), OffsetFromBase(Offset) {}
645 };
646
647 // Classify the origin of a stored value.
648 enum class StoreSource { Unknown, Constant, Extract, Load };
649 StoreSource getStoreSource(SDValue StoreVal) {
650 switch (StoreVal.getOpcode()) {
651 case ISD::Constant:
652 case ISD::ConstantFP:
653 return StoreSource::Constant;
654 case ISD::EXTRACT_VECTOR_ELT:
655 case ISD::EXTRACT_SUBVECTOR:
656 return StoreSource::Extract;
657 case ISD::LOAD:
658 return StoreSource::Load;
659 default:
660 return StoreSource::Unknown;
661 }
662 }
663
664 /// This is a helper function for visitMUL to check the profitability
665 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
666 /// MulNode is the original multiply, AddNode is (add x, c1),
667 /// and ConstNode is c2.
668 bool isMulAddWithConstProfitable(SDNode *MulNode,
669 SDValue &AddNode,
670 SDValue &ConstNode);
671
672 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
673 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
674 /// the type of the loaded value to be extended.
675 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
676 EVT LoadResultTy, EVT &ExtVT);
677
678 /// Helper function to calculate whether the given Load/Store can have its
679 /// width reduced to ExtVT.
680 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
681 EVT &MemVT, unsigned ShAmt = 0);
682
683 /// Used by BackwardsPropagateMask to find suitable loads.
684 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
685 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
686 ConstantSDNode *Mask, SDNode *&NodeToMask);
687 /// Attempt to propagate a given AND node back to load leaves so that they
688 /// can be combined into narrow loads.
689 bool BackwardsPropagateMask(SDNode *N);
690
691 /// Helper function for mergeConsecutiveStores which merges the component
692 /// store chains.
693 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
694 unsigned NumStores);
695
696 /// This is a helper function for mergeConsecutiveStores. When the source
697 /// elements of the consecutive stores are all constants or all extracted
698 /// vector elements, try to merge them into one larger store introducing
699 /// bitcasts if necessary. \return True if a merged store was created.
700 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
701 EVT MemVT, unsigned NumStores,
702 bool IsConstantSrc, bool UseVector,
703 bool UseTrunc);
704
705 /// This is a helper function for mergeConsecutiveStores. Stores that
706 /// potentially may be merged with St are placed in StoreNodes. RootNode is
707 /// a chain predecessor to all store candidates.
708 void getStoreMergeCandidates(StoreSDNode *St,
709 SmallVectorImpl<MemOpLink> &StoreNodes,
710 SDNode *&Root);
711
712 /// Helper function for mergeConsecutiveStores. Checks if candidate stores
713 /// have indirect dependency through their operands. RootNode is the
714 /// predecessor to all stores calculated by getStoreMergeCandidates and is
715 /// used to prune the dependency check. \return True if safe to merge.
716 bool checkMergeStoreCandidatesForDependencies(
717 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
718 SDNode *RootNode);
719
720 /// This is a helper function for mergeConsecutiveStores. Given a list of
721 /// store candidates, find the first N that are consecutive in memory.
722 /// Returns 0 if there are not at least 2 consecutive stores to try merging.
723 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
724 int64_t ElementSizeBytes) const;
725
726 /// This is a helper function for mergeConsecutiveStores. It is used for
727 /// store chains that are composed entirely of constant values.
728 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
729 unsigned NumConsecutiveStores,
730 EVT MemVT, SDNode *Root, bool AllowVectors);
731
732 /// This is a helper function for mergeConsecutiveStores. It is used for
733 /// store chains that are composed entirely of extracted vector elements.
734 /// When extracting multiple vector elements, try to store them in one
735 /// vector store rather than a sequence of scalar stores.
736 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
737 unsigned NumConsecutiveStores, EVT MemVT,
738 SDNode *Root);
739
740 /// This is a helper function for mergeConsecutiveStores. It is used for
741 /// store chains that are composed entirely of loaded values.
742 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
743 unsigned NumConsecutiveStores, EVT MemVT,
744 SDNode *Root, bool AllowVectors,
745 bool IsNonTemporalStore, bool IsNonTemporalLoad);
746
747 /// Merge consecutive store operations into a wide store.
748 /// This optimization uses wide integers or vectors when possible.
749 /// \return true if stores were merged.
750 bool mergeConsecutiveStores(StoreSDNode *St);
751
752 /// Try to transform a truncation where C is a constant:
753 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
754 ///
755 /// \p N needs to be a truncation and its first operand an AND. Other
756 /// requirements are checked by the function (e.g. that trunc is
757 /// single-use) and if missed an empty SDValue is returned.
758 SDValue distributeTruncateThroughAnd(SDNode *N);
759
760 /// Helper function to determine whether the target supports operation
761 /// given by \p Opcode for type \p VT, that is, whether the operation
762 /// is legal or custom before legalizing operations, and whether is
763 /// legal (but not custom) after legalization.
764 bool hasOperation(unsigned Opcode, EVT VT) {
765 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
766 }
767
768 public:
769 /// Runs the dag combiner on all nodes in the work list
770 void Run(CombineLevel AtLevel);
771
772 SelectionDAG &getDAG() const { return DAG; }
773
774 /// Returns a type large enough to hold any valid shift amount - before type
775 /// legalization these can be huge.
776 EVT getShiftAmountTy(EVT LHSTy) {
777 assert(LHSTy.isInteger() && "Shift amount is not an integer type!")(static_cast <bool> (LHSTy.isInteger() && "Shift amount is not an integer type!"
) ? void (0) : __assert_fail ("LHSTy.isInteger() && \"Shift amount is not an integer type!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 777, __extension__
__PRETTY_FUNCTION__))
;
778 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
779 }
780
781 /// This method returns true if we are running before type legalization or
782 /// if the specified VT is legal.
783 bool isTypeLegal(const EVT &VT) {
784 if (!LegalTypes) return true;
785 return TLI.isTypeLegal(VT);
786 }
787
788 /// Convenience wrapper around TargetLowering::getSetCCResultType
789 EVT getSetCCResultType(EVT VT) const {
790 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
791 }
792
793 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
794 SDValue OrigLoad, SDValue ExtLoad,
795 ISD::NodeType ExtType);
796 };
797
798/// This class is a DAGUpdateListener that removes any deleted
799/// nodes from the worklist.
800class WorklistRemover : public SelectionDAG::DAGUpdateListener {
801 DAGCombiner &DC;
802
803public:
804 explicit WorklistRemover(DAGCombiner &dc)
805 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
806
807 void NodeDeleted(SDNode *N, SDNode *E) override {
808 DC.removeFromWorklist(N);
809 }
810};
811
812class WorklistInserter : public SelectionDAG::DAGUpdateListener {
813 DAGCombiner &DC;
814
815public:
816 explicit WorklistInserter(DAGCombiner &dc)
817 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
818
819 // FIXME: Ideally we could add N to the worklist, but this causes exponential
820 // compile time costs in large DAGs, e.g. Halide.
821 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
822};
823
824} // end anonymous namespace
825
826//===----------------------------------------------------------------------===//
827// TargetLowering::DAGCombinerInfo implementation
828//===----------------------------------------------------------------------===//
829
830void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
831 ((DAGCombiner*)DC)->AddToWorklist(N);
832}
833
834SDValue TargetLowering::DAGCombinerInfo::
835CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
836 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
837}
838
839SDValue TargetLowering::DAGCombinerInfo::
840CombineTo(SDNode *N, SDValue Res, bool AddTo) {
841 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
842}
843
844SDValue TargetLowering::DAGCombinerInfo::
845CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
846 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
847}
848
849bool TargetLowering::DAGCombinerInfo::
850recursivelyDeleteUnusedNodes(SDNode *N) {
851 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
852}
853
854void TargetLowering::DAGCombinerInfo::
855CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
856 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
857}
858
859//===----------------------------------------------------------------------===//
860// Helper Functions
861//===----------------------------------------------------------------------===//
862
863void DAGCombiner::deleteAndRecombine(SDNode *N) {
864 removeFromWorklist(N);
865
866 // If the operands of this node are only used by the node, they will now be
867 // dead. Make sure to re-visit them and recursively delete dead nodes.
868 for (const SDValue &Op : N->ops())
869 // For an operand generating multiple values, one of the values may
870 // become dead allowing further simplification (e.g. split index
871 // arithmetic from an indexed load).
872 if (Op->hasOneUse() || Op->getNumValues() > 1)
873 AddToWorklist(Op.getNode());
874
875 DAG.DeleteNode(N);
876}
877
878// APInts must be the same size for most operations, this helper
879// function zero extends the shorter of the pair so that they match.
880// We provide an Offset so that we can create bitwidths that won't overflow.
881static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
882 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
883 LHS = LHS.zextOrSelf(Bits);
884 RHS = RHS.zextOrSelf(Bits);
885}
886
887// Return true if this node is a setcc, or is a select_cc
888// that selects between the target values used for true and false, making it
889// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
890// the appropriate nodes based on the type of node we are checking. This
891// simplifies life a bit for the callers.
892bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
893 SDValue &CC, bool MatchStrict) const {
894 if (N.getOpcode() == ISD::SETCC) {
895 LHS = N.getOperand(0);
896 RHS = N.getOperand(1);
897 CC = N.getOperand(2);
898 return true;
899 }
900
901 if (MatchStrict &&
902 (N.getOpcode() == ISD::STRICT_FSETCC ||
903 N.getOpcode() == ISD::STRICT_FSETCCS)) {
904 LHS = N.getOperand(1);
905 RHS = N.getOperand(2);
906 CC = N.getOperand(3);
907 return true;
908 }
909
910 if (N.getOpcode() != ISD::SELECT_CC ||
911 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
912 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
913 return false;
914
915 if (TLI.getBooleanContents(N.getValueType()) ==
916 TargetLowering::UndefinedBooleanContent)
917 return false;
918
919 LHS = N.getOperand(0);
920 RHS = N.getOperand(1);
921 CC = N.getOperand(4);
922 return true;
923}
924
925/// Return true if this is a SetCC-equivalent operation with only one use.
926/// If this is true, it allows the users to invert the operation for free when
927/// it is profitable to do so.
928bool DAGCombiner::isOneUseSetCC(SDValue N) const {
929 SDValue N0, N1, N2;
930 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
931 return true;
932 return false;
933}
934
935static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) {
936 if (!ScalarTy.isSimple())
937 return false;
938
939 uint64_t MaskForTy = 0ULL;
940 switch (ScalarTy.getSimpleVT().SimpleTy) {
941 case MVT::i8:
942 MaskForTy = 0xFFULL;
943 break;
944 case MVT::i16:
945 MaskForTy = 0xFFFFULL;
946 break;
947 case MVT::i32:
948 MaskForTy = 0xFFFFFFFFULL;
949 break;
950 default:
951 return false;
952 break;
953 }
954
955 APInt Val;
956 if (ISD::isConstantSplatVector(N, Val))
957 return Val.getLimitedValue() == MaskForTy;
958
959 return false;
960}
961
962// Determines if it is a constant integer or a splat/build vector of constant
963// integers (and undefs).
964// Do not permit build vector implicit truncation.
965static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
966 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
967 return !(Const->isOpaque() && NoOpaques);
968 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
969 return false;
970 unsigned BitWidth = N.getScalarValueSizeInBits();
971 for (const SDValue &Op : N->op_values()) {
972 if (Op.isUndef())
973 continue;
974 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
975 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
976 (Const->isOpaque() && NoOpaques))
977 return false;
978 }
979 return true;
980}
981
982// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
983// undef's.
984static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
985 if (V.getOpcode() != ISD::BUILD_VECTOR)
986 return false;
987 return isConstantOrConstantVector(V, NoOpaques) ||
988 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
989}
990
991// Determine if this an indexed load with an opaque target constant index.
992static bool canSplitIdx(LoadSDNode *LD) {
993 return MaySplitLoadIndex &&
994 (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
995 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
996}
997
998bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
999 const SDLoc &DL,
1000 SDValue N0,
1001 SDValue N1) {
1002 // Currently this only tries to ensure we don't undo the GEP splits done by
1003 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1004 // we check if the following transformation would be problematic:
1005 // (load/store (add, (add, x, offset1), offset2)) ->
1006 // (load/store (add, x, offset1+offset2)).
1007
1008 if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
1009 return false;
1010
1011 if (N0.hasOneUse())
1012 return false;
1013
1014 auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1015 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1016 if (!C1 || !C2)
1017 return false;
1018
1019 const APInt &C1APIntVal = C1->getAPIntValue();
1020 const APInt &C2APIntVal = C2->getAPIntValue();
1021 if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64)
1022 return false;
1023
1024 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1025 if (CombinedValueIntVal.getBitWidth() > 64)
1026 return false;
1027 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1028
1029 for (SDNode *Node : N0->uses()) {
1030 auto LoadStore = dyn_cast<MemSDNode>(Node);
1031 if (LoadStore) {
1032 // Is x[offset2] already not a legal addressing mode? If so then
1033 // reassociating the constants breaks nothing (we test offset2 because
1034 // that's the one we hope to fold into the load or store).
1035 TargetLoweringBase::AddrMode AM;
1036 AM.HasBaseReg = true;
1037 AM.BaseOffs = C2APIntVal.getSExtValue();
1038 EVT VT = LoadStore->getMemoryVT();
1039 unsigned AS = LoadStore->getAddressSpace();
1040 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1041 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1042 continue;
1043
1044 // Would x[offset1+offset2] still be a legal addressing mode?
1045 AM.BaseOffs = CombinedValue;
1046 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1047 return true;
1048 }
1049 }
1050
1051 return false;
1052}
1053
1054// Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
1055// such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
1056SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1057 SDValue N0, SDValue N1) {
1058 EVT VT = N0.getValueType();
1059
1060 if (N0.getOpcode() != Opc)
1061 return SDValue();
1062
1063 SDValue N00 = N0.getOperand(0);
1064 SDValue N01 = N0.getOperand(1);
1065
1066 if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N01))) {
1067 if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N1))) {
1068 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1069 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1}))
1070 return DAG.getNode(Opc, DL, VT, N00, OpNode);
1071 return SDValue();
1072 }
1073 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1074 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1075 // iff (op x, c1) has one use
1076 if (SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1))
1077 return DAG.getNode(Opc, DL, VT, OpNode, N01);
1078 return SDValue();
1079 }
1080 }
1081 return SDValue();
1082}
1083
1084// Try to reassociate commutative binops.
1085SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
1086 SDValue N1, SDNodeFlags Flags) {
1087 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.")(static_cast <bool> (TLI.isCommutativeBinOp(Opc) &&
"Operation not commutative.") ? void (0) : __assert_fail ("TLI.isCommutativeBinOp(Opc) && \"Operation not commutative.\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1087, __extension__
__PRETTY_FUNCTION__))
;
1088
1089 // Floating-point reassociation is not allowed without loose FP math.
1090 if (N0.getValueType().isFloatingPoint() ||
1091 N1.getValueType().isFloatingPoint())
1092 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1093 return SDValue();
1094
1095 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
1096 return Combined;
1097 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
1098 return Combined;
1099 return SDValue();
1100}
1101
1102SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1103 bool AddTo) {
1104 assert(N->getNumValues() == NumTo && "Broken CombineTo call!")(static_cast <bool> (N->getNumValues() == NumTo &&
"Broken CombineTo call!") ? void (0) : __assert_fail ("N->getNumValues() == NumTo && \"Broken CombineTo call!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1104, __extension__
__PRETTY_FUNCTION__))
;
1105 ++NodesCombined;
1106 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo - 1 <<
" other values\n"; } } while (false)
1107 To[0].getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo - 1 <<
" other values\n"; } } while (false)
1108 dbgs() << " and " << NumTo - 1 << " other values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo - 1 <<
" other values\n"; } } while (false)
;
1109 for (unsigned i = 0, e = NumTo; i != e; ++i)
1110 assert((!To[i].getNode() ||(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1112, __extension__
__PRETTY_FUNCTION__))
1111 N->getValueType(i) == To[i].getValueType()) &&(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1112, __extension__
__PRETTY_FUNCTION__))
1112 "Cannot combine value to value of different type!")(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1112, __extension__
__PRETTY_FUNCTION__))
;
1113
1114 WorklistRemover DeadNodes(*this);
1115 DAG.ReplaceAllUsesWith(N, To);
1116 if (AddTo) {
1117 // Push the new nodes and any users onto the worklist
1118 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1119 if (To[i].getNode()) {
1120 AddToWorklist(To[i].getNode());
1121 AddUsersToWorklist(To[i].getNode());
1122 }
1123 }
1124 }
1125
1126 // Finally, if the node is now dead, remove it from the graph. The node
1127 // may not be dead if the replacement process recursively simplified to
1128 // something else needing this node.
1129 if (N->use_empty())
1130 deleteAndRecombine(N);
1131 return SDValue(N, 0);
1132}
1133
1134void DAGCombiner::
1135CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1136 // Replace the old value with the new one.
1137 ++NodesCombined;
1138 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1139 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1140 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
;
1141
1142 // Replace all uses. If any nodes become isomorphic to other nodes and
1143 // are deleted, make sure to remove them from our worklist.
1144 WorklistRemover DeadNodes(*this);
1145 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1146
1147 // Push the new node and any (possibly new) users onto the worklist.
1148 AddToWorklistWithUsers(TLO.New.getNode());
1149
1150 // Finally, if the node is now dead, remove it from the graph. The node
1151 // may not be dead if the replacement process recursively simplified to
1152 // something else needing this node.
1153 if (TLO.Old.getNode()->use_empty())
1154 deleteAndRecombine(TLO.Old.getNode());
1155}
1156
1157/// Check the specified integer node value to see if it can be simplified or if
1158/// things it uses can be simplified by bit propagation. If so, return true.
1159bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1160 const APInt &DemandedElts,
1161 bool AssumeSingleUse) {
1162 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1163 KnownBits Known;
1164 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1165 AssumeSingleUse))
1166 return false;
1167
1168 // Revisit the node.
1169 AddToWorklist(Op.getNode());
1170
1171 CommitTargetLoweringOpt(TLO);
1172 return true;
1173}
1174
1175/// Check the specified vector node value to see if it can be simplified or
1176/// if things it uses can be simplified as it only uses some of the elements.
1177/// If so, return true.
1178bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1179 const APInt &DemandedElts,
1180 bool AssumeSingleUse) {
1181 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1182 APInt KnownUndef, KnownZero;
1183 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1184 TLO, 0, AssumeSingleUse))
1185 return false;
1186
1187 // Revisit the node.
1188 AddToWorklist(Op.getNode());
1189
1190 CommitTargetLoweringOpt(TLO);
1191 return true;
1192}
1193
1194void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1195 SDLoc DL(Load);
1196 EVT VT = Load->getValueType(0);
1197 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1198
1199 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
1200 Trunc.getNode()->dump(&DAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
;
1201 WorklistRemover DeadNodes(*this);
1202 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1203 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1204 deleteAndRecombine(Load);
1205 AddToWorklist(Trunc.getNode());
1206}
1207
1208SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1209 Replace = false;
1210 SDLoc DL(Op);
1211 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1212 LoadSDNode *LD = cast<LoadSDNode>(Op);
1213 EVT MemVT = LD->getMemoryVT();
1214 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1215 : LD->getExtensionType();
1216 Replace = true;
1217 return DAG.getExtLoad(ExtType, DL, PVT,
1218 LD->getChain(), LD->getBasePtr(),
1219 MemVT, LD->getMemOperand());
1220 }
1221
1222 unsigned Opc = Op.getOpcode();
1223 switch (Opc) {
1224 default: break;
1225 case ISD::AssertSext:
1226 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1227 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1228 break;
1229 case ISD::AssertZext:
1230 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1231 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1232 break;
1233 case ISD::Constant: {
1234 unsigned ExtOpc =
1235 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1236 return DAG.getNode(ExtOpc, DL, PVT, Op);
1237 }
1238 }
1239
1240 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1241 return SDValue();
1242 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1243}
1244
1245SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1246 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1247 return SDValue();
1248 EVT OldVT = Op.getValueType();
1249 SDLoc DL(Op);
1250 bool Replace = false;
1251 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1252 if (!NewOp.getNode())
1253 return SDValue();
1254 AddToWorklist(NewOp.getNode());
1255
1256 if (Replace)
1257 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1258 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1259 DAG.getValueType(OldVT));
1260}
1261
1262SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1263 EVT OldVT = Op.getValueType();
1264 SDLoc DL(Op);
1265 bool Replace = false;
1266 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1267 if (!NewOp.getNode())
1268 return SDValue();
1269 AddToWorklist(NewOp.getNode());
1270
1271 if (Replace)
1272 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1273 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1274}
1275
1276/// Promote the specified integer binary operation if the target indicates it is
1277/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1278/// i32 since i16 instructions are longer.
1279SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1280 if (!LegalOperations)
1281 return SDValue();
1282
1283 EVT VT = Op.getValueType();
1284 if (VT.isVector() || !VT.isInteger())
1285 return SDValue();
1286
1287 // If operation type is 'undesirable', e.g. i16 on x86, consider
1288 // promoting it.
1289 unsigned Opc = Op.getOpcode();
1290 if (TLI.isTypeDesirableForOp(Opc, VT))
1291 return SDValue();
1292
1293 EVT PVT = VT;
1294 // Consult target whether it is a good idea to promote this operation and
1295 // what's the right type to promote it to.
1296 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1297 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1297, __extension__
__PRETTY_FUNCTION__))
;
1298
1299 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1300
1301 bool Replace0 = false;
1302 SDValue N0 = Op.getOperand(0);
1303 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1304
1305 bool Replace1 = false;
1306 SDValue N1 = Op.getOperand(1);
1307 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1308 SDLoc DL(Op);
1309
1310 SDValue RV =
1311 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1312
1313 // We are always replacing N0/N1's use in N and only need additional
1314 // replacements if there are additional uses.
1315 // Note: We are checking uses of the *nodes* (SDNode) rather than values
1316 // (SDValue) here because the node may reference multiple values
1317 // (for example, the chain value of a load node).
1318 Replace0 &= !N0->hasOneUse();
1319 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1320
1321 // Combine Op here so it is preserved past replacements.
1322 CombineTo(Op.getNode(), RV);
1323
1324 // If operands have a use ordering, make sure we deal with
1325 // predecessor first.
1326 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1327 std::swap(N0, N1);
1328 std::swap(NN0, NN1);
1329 }
1330
1331 if (Replace0) {
1332 AddToWorklist(NN0.getNode());
1333 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1334 }
1335 if (Replace1) {
1336 AddToWorklist(NN1.getNode());
1337 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1338 }
1339 return Op;
1340 }
1341 return SDValue();
1342}
1343
1344/// Promote the specified integer shift operation if the target indicates it is
1345/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1346/// i32 since i16 instructions are longer.
1347SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1348 if (!LegalOperations)
1349 return SDValue();
1350
1351 EVT VT = Op.getValueType();
1352 if (VT.isVector() || !VT.isInteger())
1353 return SDValue();
1354
1355 // If operation type is 'undesirable', e.g. i16 on x86, consider
1356 // promoting it.
1357 unsigned Opc = Op.getOpcode();
1358 if (TLI.isTypeDesirableForOp(Opc, VT))
1359 return SDValue();
1360
1361 EVT PVT = VT;
1362 // Consult target whether it is a good idea to promote this operation and
1363 // what's the right type to promote it to.
1364 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1365 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1365, __extension__
__PRETTY_FUNCTION__))
;
1366
1367 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1368
1369 bool Replace = false;
1370 SDValue N0 = Op.getOperand(0);
1371 SDValue N1 = Op.getOperand(1);
1372 if (Opc == ISD::SRA)
1373 N0 = SExtPromoteOperand(N0, PVT);
1374 else if (Opc == ISD::SRL)
1375 N0 = ZExtPromoteOperand(N0, PVT);
1376 else
1377 N0 = PromoteOperand(N0, PVT, Replace);
1378
1379 if (!N0.getNode())
1380 return SDValue();
1381
1382 SDLoc DL(Op);
1383 SDValue RV =
1384 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1385
1386 if (Replace)
1387 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1388
1389 // Deal with Op being deleted.
1390 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1391 return RV;
1392 }
1393 return SDValue();
1394}
1395
1396SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1397 if (!LegalOperations)
1398 return SDValue();
1399
1400 EVT VT = Op.getValueType();
1401 if (VT.isVector() || !VT.isInteger())
1402 return SDValue();
1403
1404 // If operation type is 'undesirable', e.g. i16 on x86, consider
1405 // promoting it.
1406 unsigned Opc = Op.getOpcode();
1407 if (TLI.isTypeDesirableForOp(Opc, VT))
1408 return SDValue();
1409
1410 EVT PVT = VT;
1411 // Consult target whether it is a good idea to promote this operation and
1412 // what's the right type to promote it to.
1413 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1414 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1414, __extension__
__PRETTY_FUNCTION__))
;
1415 // fold (aext (aext x)) -> (aext x)
1416 // fold (aext (zext x)) -> (zext x)
1417 // fold (aext (sext x)) -> (sext x)
1418 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1419 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1420 }
1421 return SDValue();
1422}
1423
1424bool DAGCombiner::PromoteLoad(SDValue Op) {
1425 if (!LegalOperations)
1426 return false;
1427
1428 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1429 return false;
1430
1431 EVT VT = Op.getValueType();
1432 if (VT.isVector() || !VT.isInteger())
1433 return false;
1434
1435 // If operation type is 'undesirable', e.g. i16 on x86, consider
1436 // promoting it.
1437 unsigned Opc = Op.getOpcode();
1438 if (TLI.isTypeDesirableForOp(Opc, VT))
1439 return false;
1440
1441 EVT PVT = VT;
1442 // Consult target whether it is a good idea to promote this operation and
1443 // what's the right type to promote it to.
1444 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1445 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1445, __extension__
__PRETTY_FUNCTION__))
;
1446
1447 SDLoc DL(Op);
1448 SDNode *N = Op.getNode();
1449 LoadSDNode *LD = cast<LoadSDNode>(N);
1450 EVT MemVT = LD->getMemoryVT();
1451 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1452 : LD->getExtensionType();
1453 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1454 LD->getChain(), LD->getBasePtr(),
1455 MemVT, LD->getMemOperand());
1456 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1457
1458 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
1459 Result.getNode()->dump(&DAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
;
1460 WorklistRemover DeadNodes(*this);
1461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1462 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1463 deleteAndRecombine(N);
1464 AddToWorklist(Result.getNode());
1465 return true;
1466 }
1467 return false;
1468}
1469
1470/// Recursively delete a node which has no uses and any operands for
1471/// which it is the only use.
1472///
1473/// Note that this both deletes the nodes and removes them from the worklist.
1474/// It also adds any nodes who have had a user deleted to the worklist as they
1475/// may now have only one use and subject to other combines.
1476bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1477 if (!N->use_empty())
1478 return false;
1479
1480 SmallSetVector<SDNode *, 16> Nodes;
1481 Nodes.insert(N);
1482 do {
1483 N = Nodes.pop_back_val();
1484 if (!N)
1485 continue;
1486
1487 if (N->use_empty()) {
1488 for (const SDValue &ChildN : N->op_values())
1489 Nodes.insert(ChildN.getNode());
1490
1491 removeFromWorklist(N);
1492 DAG.DeleteNode(N);
1493 } else {
1494 AddToWorklist(N);
1495 }
1496 } while (!Nodes.empty());
1497 return true;
1498}
1499
1500//===----------------------------------------------------------------------===//
1501// Main DAG Combiner implementation
1502//===----------------------------------------------------------------------===//
1503
1504void DAGCombiner::Run(CombineLevel AtLevel) {
1505 // set the instance variables, so that the various visit routines may use it.
1506 Level = AtLevel;
1507 LegalDAG = Level >= AfterLegalizeDAG;
1508 LegalOperations = Level >= AfterLegalizeVectorOps;
1509 LegalTypes = Level >= AfterLegalizeTypes;
1510
1511 WorklistInserter AddNodes(*this);
1512
1513 // Add all the dag nodes to the worklist.
1514 for (SDNode &Node : DAG.allnodes())
1515 AddToWorklist(&Node);
1516
1517 // Create a dummy node (which is not added to allnodes), that adds a reference
1518 // to the root node, preventing it from being deleted, and tracking any
1519 // changes of the root.
1520 HandleSDNode Dummy(DAG.getRoot());
1521
1522 // While we have a valid worklist entry node, try to combine it.
1523 while (SDNode *N = getNextWorklistEntry()) {
1524 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1525 // N is deleted from the DAG, since they too may now be dead or may have a
1526 // reduced number of uses, allowing other xforms.
1527 if (recursivelyDeleteUnusedNodes(N))
1528 continue;
1529
1530 WorklistRemover DeadNodes(*this);
1531
1532 // If this combine is running after legalizing the DAG, re-legalize any
1533 // nodes pulled off the worklist.
1534 if (LegalDAG) {
1535 SmallSetVector<SDNode *, 16> UpdatedNodes;
1536 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1537
1538 for (SDNode *LN : UpdatedNodes)
1539 AddToWorklistWithUsers(LN);
1540
1541 if (!NIsValid)
1542 continue;
1543 }
1544
1545 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nCombining: "; N->dump
(&DAG); } } while (false)
;
1546
1547 // Add any operands of the new node which have not yet been combined to the
1548 // worklist as well. Because the worklist uniques things already, this
1549 // won't repeatedly process the same operand.
1550 CombinedNodes.insert(N);
1551 for (const SDValue &ChildN : N->op_values())
1552 if (!CombinedNodes.count(ChildN.getNode()))
1553 AddToWorklist(ChildN.getNode());
1554
1555 SDValue RV = combine(N);
1556
1557 if (!RV.getNode())
1558 continue;
1559
1560 ++NodesCombined;
1561
1562 // If we get back the same node we passed in, rather than a new node or
1563 // zero, we know that the node must have defined multiple values and
1564 // CombineTo was used. Since CombineTo takes care of the worklist
1565 // mechanics for us, we have no work to do in this case.
1566 if (RV.getNode() == N)
1567 continue;
1568
1569 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1571, __extension__
__PRETTY_FUNCTION__))
1570 RV.getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1571, __extension__
__PRETTY_FUNCTION__))
1571 "Node was deleted but visit returned new node!")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1571, __extension__
__PRETTY_FUNCTION__))
;
1572
1573 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << " ... into: "; RV.getNode()
->dump(&DAG); } } while (false)
;
1574
1575 if (N->getNumValues() == RV.getNode()->getNumValues())
1576 DAG.ReplaceAllUsesWith(N, RV.getNode());
1577 else {
1578 assert(N->getValueType(0) == RV.getValueType() &&(static_cast <bool> (N->getValueType(0) == RV.getValueType
() && N->getNumValues() == 1 && "Type mismatch"
) ? void (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1579, __extension__
__PRETTY_FUNCTION__))
1579 N->getNumValues() == 1 && "Type mismatch")(static_cast <bool> (N->getValueType(0) == RV.getValueType
() && N->getNumValues() == 1 && "Type mismatch"
) ? void (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1579, __extension__
__PRETTY_FUNCTION__))
;
1580 DAG.ReplaceAllUsesWith(N, &RV);
1581 }
1582
1583 // Push the new node and any users onto the worklist. Omit this if the
1584 // new node is the EntryToken (e.g. if a store managed to get optimized
1585 // out), because re-visiting the EntryToken and its users will not uncover
1586 // any additional opportunities, but there may be a large number of such
1587 // users, potentially causing compile time explosion.
1588 if (RV.getOpcode() != ISD::EntryToken) {
1589 AddToWorklist(RV.getNode());
1590 AddUsersToWorklist(RV.getNode());
1591 }
1592
1593 // Finally, if the node is now dead, remove it from the graph. The node
1594 // may not be dead if the replacement process recursively simplified to
1595 // something else needing this node. This will also take care of adding any
1596 // operands which have lost a user to the worklist.
1597 recursivelyDeleteUnusedNodes(N);
1598 }
1599
1600 // If the root changed (e.g. it was a dead load, update the root).
1601 DAG.setRoot(Dummy.getValue());
1602 DAG.RemoveDeadNodes();
1603}
1604
1605SDValue DAGCombiner::visit(SDNode *N) {
1606 switch (N->getOpcode()) {
1607 default: break;
1608 case ISD::TokenFactor: return visitTokenFactor(N);
1609 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1610 case ISD::ADD: return visitADD(N);
1611 case ISD::SUB: return visitSUB(N);
1612 case ISD::SADDSAT:
1613 case ISD::UADDSAT: return visitADDSAT(N);
1614 case ISD::SSUBSAT:
1615 case ISD::USUBSAT: return visitSUBSAT(N);
1616 case ISD::ADDC: return visitADDC(N);
1617 case ISD::SADDO:
1618 case ISD::UADDO: return visitADDO(N);
1619 case ISD::SUBC: return visitSUBC(N);
1620 case ISD::SSUBO:
1621 case ISD::USUBO: return visitSUBO(N);
1622 case ISD::ADDE: return visitADDE(N);
1623 case ISD::ADDCARRY: return visitADDCARRY(N);
1624 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
1625 case ISD::SUBE: return visitSUBE(N);
1626 case ISD::SUBCARRY: return visitSUBCARRY(N);
1627 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
1628 case ISD::SMULFIX:
1629 case ISD::SMULFIXSAT:
1630 case ISD::UMULFIX:
1631 case ISD::UMULFIXSAT: return visitMULFIX(N);
1632 case ISD::MUL: return visitMUL(N);
1633 case ISD::SDIV: return visitSDIV(N);
1634 case ISD::UDIV: return visitUDIV(N);
1635 case ISD::SREM:
1636 case ISD::UREM: return visitREM(N);
1637 case ISD::MULHU: return visitMULHU(N);
1638 case ISD::MULHS: return visitMULHS(N);
1639 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1640 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1641 case ISD::SMULO:
1642 case ISD::UMULO: return visitMULO(N);
1643 case ISD::SMIN:
1644 case ISD::SMAX:
1645 case ISD::UMIN:
1646 case ISD::UMAX: return visitIMINMAX(N);
1647 case ISD::AND: return visitAND(N);
1648 case ISD::OR: return visitOR(N);
1649 case ISD::XOR: return visitXOR(N);
1650 case ISD::SHL: return visitSHL(N);
1651 case ISD::SRA: return visitSRA(N);
1652 case ISD::SRL: return visitSRL(N);
1653 case ISD::ROTR:
1654 case ISD::ROTL: return visitRotate(N);
1655 case ISD::FSHL:
1656 case ISD::FSHR: return visitFunnelShift(N);
1657 case ISD::ABS: return visitABS(N);
1658 case ISD::BSWAP: return visitBSWAP(N);
1659 case ISD::BITREVERSE: return visitBITREVERSE(N);
1660 case ISD::CTLZ: return visitCTLZ(N);
1661 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1662 case ISD::CTTZ: return visitCTTZ(N);
1663 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1664 case ISD::CTPOP: return visitCTPOP(N);
1665 case ISD::SELECT: return visitSELECT(N);
1666 case ISD::VSELECT: return visitVSELECT(N);
1667 case ISD::SELECT_CC: return visitSELECT_CC(N);
1668 case ISD::SETCC: return visitSETCC(N);
1669 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1670 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1671 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1672 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1673 case ISD::AssertSext:
1674 case ISD::AssertZext: return visitAssertExt(N);
1675 case ISD::AssertAlign: return visitAssertAlign(N);
1676 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1677 case ISD::SIGN_EXTEND_VECTOR_INREG:
1678 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
1679 case ISD::TRUNCATE: return visitTRUNCATE(N);
1680 case ISD::BITCAST: return visitBITCAST(N);
1681 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1682 case ISD::FADD: return visitFADD(N);
1683 case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
1684 case ISD::FSUB: return visitFSUB(N);
1685 case ISD::FMUL: return visitFMUL(N);
1686 case ISD::FMA: return visitFMA(N);
1687 case ISD::FDIV: return visitFDIV(N);
1688 case ISD::FREM: return visitFREM(N);
1689 case ISD::FSQRT: return visitFSQRT(N);
1690 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1691 case ISD::FPOW: return visitFPOW(N);
1692 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1693 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1694 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1695 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1696 case ISD::FP_ROUND: return visitFP_ROUND(N);
1697 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1698 case ISD::FNEG: return visitFNEG(N);
1699 case ISD::FABS: return visitFABS(N);
1700 case ISD::FFLOOR: return visitFFLOOR(N);
1701 case ISD::FMINNUM:
1702 case ISD::FMAXNUM:
1703 case ISD::FMINIMUM:
1704 case ISD::FMAXIMUM: return visitFMinMax(N);
1705 case ISD::FCEIL: return visitFCEIL(N);
1706 case ISD::FTRUNC: return visitFTRUNC(N);
1707 case ISD::BRCOND: return visitBRCOND(N);
1708 case ISD::BR_CC: return visitBR_CC(N);
1709 case ISD::LOAD: return visitLOAD(N);
1710 case ISD::STORE: return visitSTORE(N);
1711 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1712 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1713 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1714 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1715 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1716 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1717 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1718 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1719 case ISD::MGATHER: return visitMGATHER(N);
1720 case ISD::MLOAD: return visitMLOAD(N);
1721 case ISD::MSCATTER: return visitMSCATTER(N);
1722 case ISD::MSTORE: return visitMSTORE(N);
1723 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
1724 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1725 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1726 case ISD::FREEZE: return visitFREEZE(N);
1727 case ISD::VECREDUCE_FADD:
1728 case ISD::VECREDUCE_FMUL:
1729 case ISD::VECREDUCE_ADD:
1730 case ISD::VECREDUCE_MUL:
1731 case ISD::VECREDUCE_AND:
1732 case ISD::VECREDUCE_OR:
1733 case ISD::VECREDUCE_XOR:
1734 case ISD::VECREDUCE_SMAX:
1735 case ISD::VECREDUCE_SMIN:
1736 case ISD::VECREDUCE_UMAX:
1737 case ISD::VECREDUCE_UMIN:
1738 case ISD::VECREDUCE_FMAX:
1739 case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N);
1740#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
1741#include "llvm/IR/VPIntrinsics.def"
1742 return visitVPOp(N);
1743 }
1744 return SDValue();
1745}
1746
1747SDValue DAGCombiner::combine(SDNode *N) {
1748 SDValue RV;
1749 if (!DisableGenericCombines)
1750 RV = visit(N);
1751
1752 // If nothing happened, try a target-specific DAG combine.
1753 if (!RV.getNode()) {
1754 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Node was deleted but visit returned NULL!") ? void
(0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1755, __extension__
__PRETTY_FUNCTION__))
1755 "Node was deleted but visit returned NULL!")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Node was deleted but visit returned NULL!") ? void
(0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1755, __extension__
__PRETTY_FUNCTION__))
;
1756
1757 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1758 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1759
1760 // Expose the DAG combiner to the target combiner impls.
1761 TargetLowering::DAGCombinerInfo
1762 DagCombineInfo(DAG, Level, false, this);
1763
1764 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1765 }
1766 }
1767
1768 // If nothing happened still, try promoting the operation.
1769 if (!RV.getNode()) {
1770 switch (N->getOpcode()) {
1771 default: break;
1772 case ISD::ADD:
1773 case ISD::SUB:
1774 case ISD::MUL:
1775 case ISD::AND:
1776 case ISD::OR:
1777 case ISD::XOR:
1778 RV = PromoteIntBinOp(SDValue(N, 0));
1779 break;
1780 case ISD::SHL:
1781 case ISD::SRA:
1782 case ISD::SRL:
1783 RV = PromoteIntShiftOp(SDValue(N, 0));
1784 break;
1785 case ISD::SIGN_EXTEND:
1786 case ISD::ZERO_EXTEND:
1787 case ISD::ANY_EXTEND:
1788 RV = PromoteExtend(SDValue(N, 0));
1789 break;
1790 case ISD::LOAD:
1791 if (PromoteLoad(SDValue(N, 0)))
1792 RV = SDValue(N, 0);
1793 break;
1794 }
1795 }
1796
1797 // If N is a commutative binary node, try to eliminate it if the commuted
1798 // version is already present in the DAG.
1799 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1800 N->getNumValues() == 1) {
1801 SDValue N0 = N->getOperand(0);
1802 SDValue N1 = N->getOperand(1);
1803
1804 // Constant operands are canonicalized to RHS.
1805 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1806 SDValue Ops[] = {N1, N0};
1807 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1808 N->getFlags());
1809 if (CSENode)
1810 return SDValue(CSENode, 0);
1811 }
1812 }
1813
1814 return RV;
1815}
1816
1817/// Given a node, return its input chain if it has one, otherwise return a null
1818/// sd operand.
1819static SDValue getInputChainForNode(SDNode *N) {
1820 if (unsigned NumOps = N->getNumOperands()) {
1821 if (N->getOperand(0).getValueType() == MVT::Other)
1822 return N->getOperand(0);
1823 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1824 return N->getOperand(NumOps-1);
1825 for (unsigned i = 1; i < NumOps-1; ++i)
1826 if (N->getOperand(i).getValueType() == MVT::Other)
1827 return N->getOperand(i);
1828 }
1829 return SDValue();
1830}
1831
1832SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1833 // If N has two operands, where one has an input chain equal to the other,
1834 // the 'other' chain is redundant.
1835 if (N->getNumOperands() == 2) {
1836 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1837 return N->getOperand(0);
1838 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1839 return N->getOperand(1);
1840 }
1841
1842 // Don't simplify token factors if optnone.
1843 if (OptLevel == CodeGenOpt::None)
1844 return SDValue();
1845
1846 // Don't simplify the token factor if the node itself has too many operands.
1847 if (N->getNumOperands() > TokenFactorInlineLimit)
1848 return SDValue();
1849
1850 // If the sole user is a token factor, we should make sure we have a
1851 // chance to merge them together. This prevents TF chains from inhibiting
1852 // optimizations.
1853 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
1854 AddToWorklist(*(N->use_begin()));
1855
1856 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1857 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1858 SmallPtrSet<SDNode*, 16> SeenOps;
1859 bool Changed = false; // If we should replace this token factor.
1860
1861 // Start out with this token factor.
1862 TFs.push_back(N);
1863
1864 // Iterate through token factors. The TFs grows when new token factors are
1865 // encountered.
1866 for (unsigned i = 0; i < TFs.size(); ++i) {
1867 // Limit number of nodes to inline, to avoid quadratic compile times.
1868 // We have to add the outstanding Token Factors to Ops, otherwise we might
1869 // drop Ops from the resulting Token Factors.
1870 if (Ops.size() > TokenFactorInlineLimit) {
1871 for (unsigned j = i; j < TFs.size(); j++)
1872 Ops.emplace_back(TFs[j], 0);
1873 // Drop unprocessed Token Factors from TFs, so we do not add them to the
1874 // combiner worklist later.
1875 TFs.resize(i);
1876 break;
1877 }
1878
1879 SDNode *TF = TFs[i];
1880 // Check each of the operands.
1881 for (const SDValue &Op : TF->op_values()) {
1882 switch (Op.getOpcode()) {
1883 case ISD::EntryToken:
1884 // Entry tokens don't need to be added to the list. They are
1885 // redundant.
1886 Changed = true;
1887 break;
1888
1889 case ISD::TokenFactor:
1890 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1891 // Queue up for processing.
1892 TFs.push_back(Op.getNode());
1893 Changed = true;
1894 break;
1895 }
1896 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1897
1898 default:
1899 // Only add if it isn't already in the list.
1900 if (SeenOps.insert(Op.getNode()).second)
1901 Ops.push_back(Op);
1902 else
1903 Changed = true;
1904 break;
1905 }
1906 }
1907 }
1908
1909 // Re-visit inlined Token Factors, to clean them up in case they have been
1910 // removed. Skip the first Token Factor, as this is the current node.
1911 for (unsigned i = 1, e = TFs.size(); i < e; i++)
1912 AddToWorklist(TFs[i]);
1913
1914 // Remove Nodes that are chained to another node in the list. Do so
1915 // by walking up chains breath-first stopping when we've seen
1916 // another operand. In general we must climb to the EntryNode, but we can exit
1917 // early if we find all remaining work is associated with just one operand as
1918 // no further pruning is possible.
1919
1920 // List of nodes to search through and original Ops from which they originate.
1921 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1922 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1923 SmallPtrSet<SDNode *, 16> SeenChains;
1924 bool DidPruneOps = false;
1925
1926 unsigned NumLeftToConsider = 0;
1927 for (const SDValue &Op : Ops) {
1928 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1929 OpWorkCount.push_back(1);
1930 }
1931
1932 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1933 // If this is an Op, we can remove the op from the list. Remark any
1934 // search associated with it as from the current OpNumber.
1935 if (SeenOps.contains(Op)) {
1936 Changed = true;
1937 DidPruneOps = true;
1938 unsigned OrigOpNumber = 0;
1939 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1940 OrigOpNumber++;
1941 assert((OrigOpNumber != Ops.size()) &&(static_cast <bool> ((OrigOpNumber != Ops.size()) &&
"expected to find TokenFactor Operand") ? void (0) : __assert_fail
("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1942, __extension__
__PRETTY_FUNCTION__))
1942 "expected to find TokenFactor Operand")(static_cast <bool> ((OrigOpNumber != Ops.size()) &&
"expected to find TokenFactor Operand") ? void (0) : __assert_fail
("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1942, __extension__
__PRETTY_FUNCTION__))
;
1943 // Re-mark worklist from OrigOpNumber to OpNumber
1944 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1945 if (Worklist[i].second == OrigOpNumber) {
1946 Worklist[i].second = OpNumber;
1947 }
1948 }
1949 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1950 OpWorkCount[OrigOpNumber] = 0;
1951 NumLeftToConsider--;
1952 }
1953 // Add if it's a new chain
1954 if (SeenChains.insert(Op).second) {
1955 OpWorkCount[OpNumber]++;
1956 Worklist.push_back(std::make_pair(Op, OpNumber));
1957 }
1958 };
1959
1960 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1961 // We need at least be consider at least 2 Ops to prune.
1962 if (NumLeftToConsider <= 1)
1963 break;
1964 auto CurNode = Worklist[i].first;
1965 auto CurOpNumber = Worklist[i].second;
1966 assert((OpWorkCount[CurOpNumber] > 0) &&(static_cast <bool> ((OpWorkCount[CurOpNumber] > 0) &&
"Node should not appear in worklist") ? void (0) : __assert_fail
("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1967, __extension__
__PRETTY_FUNCTION__))
1967 "Node should not appear in worklist")(static_cast <bool> ((OpWorkCount[CurOpNumber] > 0) &&
"Node should not appear in worklist") ? void (0) : __assert_fail
("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 1967, __extension__
__PRETTY_FUNCTION__))
;
1968 switch (CurNode->getOpcode()) {
1969 case ISD::EntryToken:
1970 // Hitting EntryToken is the only way for the search to terminate without
1971 // hitting
1972 // another operand's search. Prevent us from marking this operand
1973 // considered.
1974 NumLeftToConsider++;
1975 break;
1976 case ISD::TokenFactor:
1977 for (const SDValue &Op : CurNode->op_values())
1978 AddToWorklist(i, Op.getNode(), CurOpNumber);
1979 break;
1980 case ISD::LIFETIME_START:
1981 case ISD::LIFETIME_END:
1982 case ISD::CopyFromReg:
1983 case ISD::CopyToReg:
1984 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1985 break;
1986 default:
1987 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1988 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1989 break;
1990 }
1991 OpWorkCount[CurOpNumber]--;
1992 if (OpWorkCount[CurOpNumber] == 0)
1993 NumLeftToConsider--;
1994 }
1995
1996 // If we've changed things around then replace token factor.
1997 if (Changed) {
1998 SDValue Result;
1999 if (Ops.empty()) {
2000 // The entry token is the only possible outcome.
2001 Result = DAG.getEntryNode();
2002 } else {
2003 if (DidPruneOps) {
2004 SmallVector<SDValue, 8> PrunedOps;
2005 //
2006 for (const SDValue &Op : Ops) {
2007 if (SeenChains.count(Op.getNode()) == 0)
2008 PrunedOps.push_back(Op);
2009 }
2010 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2011 } else {
2012 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2013 }
2014 }
2015 return Result;
2016 }
2017 return SDValue();
2018}
2019
2020/// MERGE_VALUES can always be eliminated.
2021SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2022 WorklistRemover DeadNodes(*this);
2023 // Replacing results may cause a different MERGE_VALUES to suddenly
2024 // be CSE'd with N, and carry its uses with it. Iterate until no
2025 // uses remain, to ensure that the node can be safely deleted.
2026 // First add the users of this node to the work list so that they
2027 // can be tried again once they have new operands.
2028 AddUsersToWorklist(N);
2029 do {
2030 // Do as a single replacement to avoid rewalking use lists.
2031 SmallVector<SDValue, 8> Ops;
2032 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2033 Ops.push_back(N->getOperand(i));
2034 DAG.ReplaceAllUsesWith(N, Ops.data());
2035 } while (!N->use_empty());
2036 deleteAndRecombine(N);
2037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2038}
2039
2040/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2041/// ConstantSDNode pointer else nullptr.
2042static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
2043 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
2044 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2045}
2046
2047/// Return true if 'Use' is a load or a store that uses N as its base pointer
2048/// and that N may be folded in the load / store addressing mode.
2049static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG,
2050 const TargetLowering &TLI) {
2051 EVT VT;
2052 unsigned AS;
2053
2054 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2055 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2056 return false;
2057 VT = LD->getMemoryVT();
2058 AS = LD->getAddressSpace();
2059 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2060 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2061 return false;
2062 VT = ST->getMemoryVT();
2063 AS = ST->getAddressSpace();
2064 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) {
2065 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2066 return false;
2067 VT = LD->getMemoryVT();
2068 AS = LD->getAddressSpace();
2069 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) {
2070 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2071 return false;
2072 VT = ST->getMemoryVT();
2073 AS = ST->getAddressSpace();
2074 } else
2075 return false;
2076
2077 TargetLowering::AddrMode AM;
2078 if (N->getOpcode() == ISD::ADD) {
2079 AM.HasBaseReg = true;
2080 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2081 if (Offset)
2082 // [reg +/- imm]
2083 AM.BaseOffs = Offset->getSExtValue();
2084 else
2085 // [reg +/- reg]
2086 AM.Scale = 1;
2087 } else if (N->getOpcode() == ISD::SUB) {
2088 AM.HasBaseReg = true;
2089 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2090 if (Offset)
2091 // [reg +/- imm]
2092 AM.BaseOffs = -Offset->getSExtValue();
2093 else
2094 // [reg +/- reg]
2095 AM.Scale = 1;
2096 } else
2097 return false;
2098
2099 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2100 VT.getTypeForEVT(*DAG.getContext()), AS);
2101}
2102
2103SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2104 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&(static_cast <bool> (TLI.isBinOp(BO->getOpcode()) &&
BO->getNumValues() == 1 && "Unexpected binary operator"
) ? void (0) : __assert_fail ("TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && \"Unexpected binary operator\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2105, __extension__
__PRETTY_FUNCTION__))
2105 "Unexpected binary operator")(static_cast <bool> (TLI.isBinOp(BO->getOpcode()) &&
BO->getNumValues() == 1 && "Unexpected binary operator"
) ? void (0) : __assert_fail ("TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && \"Unexpected binary operator\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2105, __extension__
__PRETTY_FUNCTION__))
;
2106
2107 // Don't do this unless the old select is going away. We want to eliminate the
2108 // binary operator, not replace a binop with a select.
2109 // TODO: Handle ISD::SELECT_CC.
2110 unsigned SelOpNo = 0;
2111 SDValue Sel = BO->getOperand(0);
2112 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2113 SelOpNo = 1;
2114 Sel = BO->getOperand(1);
2115 }
2116
2117 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2118 return SDValue();
2119
2120 SDValue CT = Sel.getOperand(1);
2121 if (!isConstantOrConstantVector(CT, true) &&
2122 !DAG.isConstantFPBuildVectorOrConstantFP(CT))
2123 return SDValue();
2124
2125 SDValue CF = Sel.getOperand(2);
2126 if (!isConstantOrConstantVector(CF, true) &&
2127 !DAG.isConstantFPBuildVectorOrConstantFP(CF))
2128 return SDValue();
2129
2130 // Bail out if any constants are opaque because we can't constant fold those.
2131 // The exception is "and" and "or" with either 0 or -1 in which case we can
2132 // propagate non constant operands into select. I.e.:
2133 // and (select Cond, 0, -1), X --> select Cond, 0, X
2134 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2135 auto BinOpcode = BO->getOpcode();
2136 bool CanFoldNonConst =
2137 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2138 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) &&
2139 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF));
2140
2141 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2142 if (!CanFoldNonConst &&
2143 !isConstantOrConstantVector(CBO, true) &&
2144 !DAG.isConstantFPBuildVectorOrConstantFP(CBO))
2145 return SDValue();
2146
2147 EVT VT = BO->getValueType(0);
2148
2149 // We have a select-of-constants followed by a binary operator with a
2150 // constant. Eliminate the binop by pulling the constant math into the select.
2151 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2152 SDLoc DL(Sel);
2153 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
2154 : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
2155 if (!CanFoldNonConst && !NewCT.isUndef() &&
2156 !isConstantOrConstantVector(NewCT, true) &&
2157 !DAG.isConstantFPBuildVectorOrConstantFP(NewCT))
2158 return SDValue();
2159
2160 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
2161 : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
2162 if (!CanFoldNonConst && !NewCF.isUndef() &&
2163 !isConstantOrConstantVector(NewCF, true) &&
2164 !DAG.isConstantFPBuildVectorOrConstantFP(NewCF))
2165 return SDValue();
2166
2167 SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
2168 SelectOp->setFlags(BO->getFlags());
2169 return SelectOp;
2170}
2171
2172static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
2173 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&(static_cast <bool> ((N->getOpcode() == ISD::ADD || N
->getOpcode() == ISD::SUB) && "Expecting add or sub"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2174, __extension__
__PRETTY_FUNCTION__))
2174 "Expecting add or sub")(static_cast <bool> ((N->getOpcode() == ISD::ADD || N
->getOpcode() == ISD::SUB) && "Expecting add or sub"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2174, __extension__
__PRETTY_FUNCTION__))
;
2175
2176 // Match a constant operand and a zext operand for the math instruction:
2177 // add Z, C
2178 // sub C, Z
2179 bool IsAdd = N->getOpcode() == ISD::ADD;
2180 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2181 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2182 auto *CN = dyn_cast<ConstantSDNode>(C);
2183 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2184 return SDValue();
2185
2186 // Match the zext operand as a setcc of a boolean.
2187 if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
2188 Z.getOperand(0).getValueType() != MVT::i1)
2189 return SDValue();
2190
2191 // Match the compare as: setcc (X & 1), 0, eq.
2192 SDValue SetCC = Z.getOperand(0);
2193 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
2194 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
2195 SetCC.getOperand(0).getOpcode() != ISD::AND ||
2196 !isOneConstant(SetCC.getOperand(0).getOperand(1)))
2197 return SDValue();
2198
2199 // We are adding/subtracting a constant and an inverted low bit. Turn that
2200 // into a subtract/add of the low bit with incremented/decremented constant:
2201 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2202 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2203 EVT VT = C.getValueType();
2204 SDLoc DL(N);
2205 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
2206 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
2207 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2208 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2209}
2210
2211/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2212/// a shift and add with a different constant.
2213static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
2214 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&(static_cast <bool> ((N->getOpcode() == ISD::ADD || N
->getOpcode() == ISD::SUB) && "Expecting add or sub"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2215, __extension__
__PRETTY_FUNCTION__))
2215 "Expecting add or sub")(static_cast <bool> ((N->getOpcode() == ISD::ADD || N
->getOpcode() == ISD::SUB) && "Expecting add or sub"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2215, __extension__
__PRETTY_FUNCTION__))
;
2216
2217 // We need a constant operand for the add/sub, and the other operand is a
2218 // logical shift right: add (srl), C or sub C, (srl).
2219 bool IsAdd = N->getOpcode() == ISD::ADD;
2220 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2221 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2222 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2223 ShiftOp.getOpcode() != ISD::SRL)
2224 return SDValue();
2225
2226 // The shift must be of a 'not' value.
2227 SDValue Not = ShiftOp.getOperand(0);
2228 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2229 return SDValue();
2230
2231 // The shift must be moving the sign bit to the least-significant-bit.
2232 EVT VT = ShiftOp.getValueType();
2233 SDValue ShAmt = ShiftOp.getOperand(1);
2234 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2235 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2236 return SDValue();
2237
2238 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2239 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2240 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2241 SDLoc DL(N);
2242 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
2243 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
2244 if (SDValue NewC =
2245 DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2246 {ConstantOp, DAG.getConstant(1, DL, VT)}))
2247 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2248 return SDValue();
2249}
2250
2251/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2252/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2253/// are no common bits set in the operands).
2254SDValue DAGCombiner::visitADDLike(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 EVT VT = N0.getValueType();
2258 SDLoc DL(N);
2259
2260 // fold (add x, undef) -> undef
2261 if (N0.isUndef())
2262 return N0;
2263 if (N1.isUndef())
2264 return N1;
2265
2266 // fold (add c1, c2) -> c1+c2
2267 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
2268 return C;
2269
2270 // canonicalize constant to RHS
2271 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2272 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2273 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2274
2275 // fold vector ops
2276 if (VT.isVector()) {
2277 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
2278 return FoldedVOp;
2279
2280 // fold (add x, 0) -> x, vector edition
2281 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
2282 return N0;
2283 }
2284
2285 // fold (add x, 0) -> x
2286 if (isNullConstant(N1))
2287 return N0;
2288
2289 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2290 // fold ((A-c1)+c2) -> (A+(c2-c1))
2291 if (N0.getOpcode() == ISD::SUB &&
2292 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
2293 SDValue Sub =
2294 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)});
2295 assert(Sub && "Constant folding failed")(static_cast <bool> (Sub && "Constant folding failed"
) ? void (0) : __assert_fail ("Sub && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2295, __extension__
__PRETTY_FUNCTION__))
;
2296 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2297 }
2298
2299 // fold ((c1-A)+c2) -> (c1+c2)-A
2300 if (N0.getOpcode() == ISD::SUB &&
2301 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2302 SDValue Add =
2303 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)});
2304 assert(Add && "Constant folding failed")(static_cast <bool> (Add && "Constant folding failed"
) ? void (0) : __assert_fail ("Add && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 2304, __extension__
__PRETTY_FUNCTION__))
;
2305 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2306 }
2307
2308 // add (sext i1 X), 1 -> zext (not i1 X)
2309 // We don't transform this pattern:
2310 // add (zext i1 X), -1 -> sext (not i1 X)
2311 // because most (?) targets generate better code for the zext form.
2312 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2313 isOneOrOneSplat(N1)) {
2314 SDValue X = N0.getOperand(0);
2315 if ((!LegalOperations ||
2316 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2317 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2318 X.getScalarValueSizeInBits() == 1) {
2319 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2320 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2321 }
2322 }
2323
2324 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is
2325 // equivalent to (add x, c0).
2326 if (N0.getOpcode() == ISD::OR &&
2327 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) &&
2328 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2329 if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT,
2330 {N1, N0.getOperand(1)}))
2331 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2332 }
2333 }
2334
2335 if (SDValue NewSel = foldBinOpIntoSelect(N))
2336 return NewSel;
2337
2338 // reassociate add
2339 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) {
2340 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2341 return RADD;
2342
2343 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
2344 // equivalent to (add x, c).
2345 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
2346 if (N0.getOpcode() == ISD::OR && N0.hasOneUse() &&
2347 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) &&
2348 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2349 return DAG.getNode(ISD::ADD, DL, VT,
2350 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
2351 N0.getOperand(1));
2352 }
2353 return SDValue();
2354 };
2355 if (SDValue Add = ReassociateAddOr(N0, N1))
2356 return Add;
2357 if (SDValue Add = ReassociateAddOr(N1, N0))
2358 return Add;
2359 }
2360 // fold ((0-A) + B) -> B-A
2361 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
2362 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2363
2364 // fold (A + (0-B)) -> A-B
2365 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2366 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2367
2368 // fold (A+(B-A)) -> B
2369 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2370 return N1.getOperand(0);
2371
2372 // fold ((B-A)+A) -> B
2373 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2374 return N0.getOperand(0);
2375
2376 // fold ((A-B)+(C-A)) -> (C-B)
2377 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2378 N0.getOperand(0) == N1.getOperand(1))
2379 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2380 N0.getOperand(1));
2381
2382 // fold ((A-B)+(B-C)) -> (A-C)
2383 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2384 N0.getOperand(1) == N1.getOperand(0))
2385 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2386 N1.getOperand(1));
2387
2388 // fold (A+(B-(A+C))) to (B-C)
2389 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2390 N0 == N1.getOperand(1).getOperand(0))
2391 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2392 N1.getOperand(1).getOperand(1));
2393
2394 // fold (A+(B-(C+A))) to (B-C)
2395 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2396 N0 == N1.getOperand(1).getOperand(1))
2397 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2398 N1.getOperand(1).getOperand(0));
2399
2400 // fold (A+((B-A)+or-C)) to (B+or-C)
2401 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2402 N1.getOperand(0).getOpcode() == ISD::SUB &&
2403 N0 == N1.getOperand(0).getOperand(1))
2404 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2405 N1.getOperand(1));
2406
2407 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2408 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2409 SDValue N00 = N0.getOperand(0);
2410 SDValue N01 = N0.getOperand(1);
2411 SDValue N10 = N1.getOperand(0);
2412 SDValue N11 = N1.getOperand(1);
2413
2414 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2415 return DAG.getNode(ISD::SUB, DL, VT,
2416 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2417 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2418 }
2419
2420 // fold (add (umax X, C), -C) --> (usubsat X, C)
2421 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
2422 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
2423 return (!Max && !Op) ||
2424 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
2425 };
2426 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
2427 /*AllowUndefs*/ true))
2428 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
2429 N0.getOperand(1));
2430 }
2431
2432 if (SimplifyDemandedBits(SDValue(N, 0)))
2433 return SDValue(N, 0);
2434
2435 if (isOneOrOneSplat(N1)) {
2436 // fold (add (xor a, -1), 1) -> (sub 0, a)
2437 if (isBitwiseNot(N0))
2438 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2439 N0.getOperand(0));
2440
2441 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2442 if (N0.getOpcode() == ISD::ADD) {
2443 SDValue A, Xor;
2444
2445 if (isBitwiseNot(N0.getOperand(0))) {
2446 A = N0.getOperand(1);
2447 Xor = N0.getOperand(0);
2448 } else if (isBitwiseNot(N0.getOperand(1))) {
2449 A = N0.getOperand(0);
2450 Xor = N0.getOperand(1);
2451 }
2452
2453 if (Xor)
2454 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
2455 }
2456
2457 // Look for:
2458 // add (add x, y), 1
2459 // And if the target does not like this form then turn into:
2460 // sub y, (xor x, -1)
2461 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2462 N0.getOpcode() == ISD::ADD) {
2463 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2464 DAG.getAllOnesConstant(DL, VT));
2465 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
2466 }
2467 }
2468
2469 // (x - y) + -1 -> add (xor y, -1), x
2470 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2471 isAllOnesOrAllOnesSplat(N1)) {
2472 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
2473 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
2474 }
2475
2476 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
2477 return Combined;
2478
2479 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
2480 return Combined;
2481
2482 return SDValue();
2483}
2484
2485SDValue DAGCombiner::visitADD(SDNode *N) {
2486 SDValue N0 = N->getOperand(0);
2487 SDValue N1 = N->getOperand(1);
2488 EVT VT = N0.getValueType();
2489 SDLoc DL(N);
2490
2491 if (SDValue Combined = visitADDLike(N))
2492 return Combined;
2493
2494 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2495 return V;
2496
2497 if (SDValue V = foldAddSubOfSignBit(N, DAG))
2498 return V;
2499
2500 // fold (a+b) -> (a|b) iff a and b share no bits.
2501 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2502 DAG.haveNoCommonBitsSet(N0, N1))
2503 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2504
2505 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
2506 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
2507 const APInt &C0 = N0->getConstantOperandAPInt(0);
2508 const APInt &C1 = N1->getConstantOperandAPInt(0);
2509 return DAG.getVScale(DL, VT, C0 + C1);
2510 }
2511
2512 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
2513 if ((N0.getOpcode() == ISD::ADD) &&
2514 (N0.getOperand(1).getOpcode() == ISD::VSCALE) &&
2515 (N1.getOpcode() == ISD::VSCALE)) {
2516 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
2517 const APInt &VS1 = N1->getConstantOperandAPInt(0);
2518 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
2519 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
2520 }
2521
2522 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
2523 if (N0.getOpcode() == ISD::STEP_VECTOR &&
2524 N1.getOpcode() == ISD::STEP_VECTOR) {
2525 const APInt &C0 = N0->getConstantOperandAPInt(0);
2526 const APInt &C1 = N1->getConstantOperandAPInt(0);
2527 APInt NewStep = C0 + C1;
2528 return DAG.getStepVector(DL, VT, NewStep);
2529 }
2530
2531 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
2532 if ((N0.getOpcode() == ISD::ADD) &&
2533 (N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR) &&
2534 (N1.getOpcode() == ISD::STEP_VECTOR)) {
2535 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
2536 const APInt &SV1 = N1->getConstantOperandAPInt(0);
2537 APInt NewStep = SV0 + SV1;
2538 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
2539 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
2540 }
2541
2542 return SDValue();
2543}
2544
2545SDValue DAGCombiner::visitADDSAT(SDNode *N) {
2546 unsigned Opcode = N->getOpcode();
2547 SDValue N0 = N->getOperand(0);
2548 SDValue N1 = N->getOperand(1);
2549 EVT VT = N0.getValueType();
2550 SDLoc DL(N);
2551
2552 // fold (add_sat x, undef) -> -1
2553 if (N0.isUndef() || N1.isUndef())
2554 return DAG.getAllOnesConstant(DL, VT);
2555
2556 // fold (add_sat c1, c2) -> c3
2557 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
2558 return C;
2559
2560 // canonicalize constant to RHS
2561 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2562 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2563 return DAG.getNode(Opcode, DL, VT, N1, N0);
2564
2565 // fold vector ops
2566 if (VT.isVector()) {
2567 // TODO SimplifyVBinOp
2568
2569 // fold (add_sat x, 0) -> x, vector edition
2570 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
2571 return N0;
2572 }
2573
2574 // fold (add_sat x, 0) -> x
2575 if (isNullConstant(N1))
2576 return N0;
2577
2578 // If it cannot overflow, transform into an add.
2579 if (Opcode == ISD::UADDSAT)
2580 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2581 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
2582
2583 return SDValue();
2584}
2585
2586static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2587 bool Masked = false;
2588
2589 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2590 while (true) {
2591 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2592 V = V.getOperand(0);
2593 continue;
2594 }
2595
2596 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2597 Masked = true;
2598 V = V.getOperand(0);
2599 continue;
2600 }
2601
2602 break;
2603 }
2604
2605 // If this is not a carry, return.
2606 if (V.getResNo() != 1)
2607 return SDValue();
2608
2609 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2610 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2611 return SDValue();
2612
2613 EVT VT = V.getNode()->getValueType(0);
2614 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
2615 return SDValue();
2616
2617 // If the result is masked, then no matter what kind of bool it is we can
2618 // return. If it isn't, then we need to make sure the bool type is either 0 or
2619 // 1 and not other values.
2620 if (Masked ||
2621 TLI.getBooleanContents(V.getValueType()) ==
2622 TargetLoweringBase::ZeroOrOneBooleanContent)
2623 return V;
2624
2625 return SDValue();
2626}
2627
2628/// Given the operands of an add/sub operation, see if the 2nd operand is a
2629/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2630/// the opcode and bypass the mask operation.
2631static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
2632 SelectionDAG &DAG, const SDLoc &DL) {
2633 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
2634 return SDValue();
2635
2636 EVT VT = N0.getValueType();
2637 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
2638 return SDValue();
2639
2640 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2641 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2642 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
2643}
2644
2645/// Helper for doing combines based on N0 and N1 being added to each other.
2646SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
2647 SDNode *LocReference) {
2648 EVT VT = N0.getValueType();
2649 SDLoc DL(LocReference);
2650
2651 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2652 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2653 isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
2654 return DAG.getNode(ISD::SUB, DL, VT, N0,
2655 DAG.getNode(ISD::SHL, DL, VT,
2656 N1.getOperand(0).getOperand(1),
2657 N1.getOperand(1)));
2658
2659 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
2660 return V;
2661
2662 // Look for:
2663 // add (add x, 1), y
2664 // And if the target does not like this form then turn into:
2665 // sub y, (xor x, -1)
2666 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2667 N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) {
2668 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2669 DAG.getAllOnesConstant(DL, VT));
2670 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
2671 }
2672
2673 // Hoist one-use subtraction by non-opaque constant:
2674 // (x - C) + y -> (x + y) - C
2675 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2676 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2677 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
2678 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
2679 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2680 }
2681 // Hoist one-use subtraction from non-opaque constant:
2682 // (C - x) + y -> (y - x) + C
2683 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2684 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
2685 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2686 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
2687 }
2688
2689 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2690 // rather than 'add 0/-1' (the zext should get folded).
2691 // add (sext i1 Y), X --> sub X, (zext i1 Y)
2692 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2693 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
2694 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
2695 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2696 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2697 }
2698
2699 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2700 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2701 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2702 if (TN->getVT() == MVT::i1) {
2703 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2704 DAG.getConstant(1, DL, VT));
2705 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2706 }
2707 }
2708
2709 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2710 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2711 N1.getResNo() == 0)
2712 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2713 N0, N1.getOperand(0), N1.getOperand(2));
2714
2715 // (add X, Carry) -> (addcarry X, 0, Carry)
2716 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2717 if (SDValue Carry = getAsCarry(TLI, N1))
2718 return DAG.getNode(ISD::ADDCARRY, DL,
2719 DAG.getVTList(VT, Carry.getValueType()), N0,
2720 DAG.getConstant(0, DL, VT), Carry);
2721
2722 return SDValue();
2723}
2724
2725SDValue DAGCombiner::visitADDC(SDNode *N) {
2726 SDValue N0 = N->getOperand(0);
2727 SDValue N1 = N->getOperand(1);
2728 EVT VT = N0.getValueType();
2729 SDLoc DL(N);
2730
2731 // If the flag result is dead, turn this into an ADD.
2732 if (!N->hasAnyUseOfValue(1))
2733 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2734 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2735
2736 // canonicalize constant to RHS.
2737 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2738 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2739 if (N0C && !N1C)
2740 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2741
2742 // fold (addc x, 0) -> x + no carry out
2743 if (isNullConstant(N1))
2744 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2745 DL, MVT::Glue));
2746
2747 // If it cannot overflow, transform into an add.
2748 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2749 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2750 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2751
2752 return SDValue();
2753}
2754
2755/**
2756 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2757 * then the flip also occurs if computing the inverse is the same cost.
2758 * This function returns an empty SDValue in case it cannot flip the boolean
2759 * without increasing the cost of the computation. If you want to flip a boolean
2760 * no matter what, use DAG.getLogicalNOT.
2761 */
2762static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
2763 const TargetLowering &TLI,
2764 bool Force) {
2765 if (Force && isa<ConstantSDNode>(V))
2766 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
2767
2768 if (V.getOpcode() != ISD::XOR)
2769 return SDValue();
2770
2771 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
2772 if (!Const)
2773 return SDValue();
2774
2775 EVT VT = V.getValueType();
2776
2777 bool IsFlip = false;
2778 switch(TLI.getBooleanContents(VT)) {
2779 case TargetLowering::ZeroOrOneBooleanContent:
2780 IsFlip = Const->isOne();
2781 break;
2782 case TargetLowering::ZeroOrNegativeOneBooleanContent:
2783 IsFlip = Const->isAllOnes();
2784 break;
2785 case TargetLowering::UndefinedBooleanContent:
2786 IsFlip = (Const->getAPIntValue() & 0x01) == 1;
2787 break;
2788 }
2789
2790 if (IsFlip)
2791 return V.getOperand(0);
2792 if (Force)
2793 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
2794 return SDValue();
2795}
2796
2797SDValue DAGCombiner::visitADDO(SDNode *N) {
2798 SDValue N0 = N->getOperand(0);
2799 SDValue N1 = N->getOperand(1);
2800 EVT VT = N0.getValueType();
2801 bool IsSigned = (ISD::SADDO == N->getOpcode());
2802
2803 EVT CarryVT = N->getValueType(1);
2804 SDLoc DL(N);
2805
2806 // If the flag result is dead, turn this into an ADD.
2807 if (!N->hasAnyUseOfValue(1))
2808 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2809 DAG.getUNDEF(CarryVT));
2810
2811 // canonicalize constant to RHS.
2812 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2813 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2814 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
2815
2816 // fold (addo x, 0) -> x + no carry out
2817 if (isNullOrNullSplat(N1))
2818 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2819
2820 if (!IsSigned) {
2821 // If it cannot overflow, transform into an add.
2822 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2823 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2824 DAG.getConstant(0, DL, CarryVT));
2825
2826 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2827 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
2828 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2829 DAG.getConstant(0, DL, VT), N0.getOperand(0));
2830 return CombineTo(
2831 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
2832 }
2833
2834 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2835 return Combined;
2836
2837 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2838 return Combined;
2839 }
2840
2841 return SDValue();
2842}
2843
2844SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2845 EVT VT = N0.getValueType();
2846 if (VT.isVector())
2847 return SDValue();
2848
2849 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2850 // If Y + 1 cannot overflow.
2851 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2852 SDValue Y = N1.getOperand(0);
2853 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2854 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2855 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2856 N1.getOperand(2));
2857 }
2858
2859 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2860 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2861 if (SDValue Carry = getAsCarry(TLI, N1))
2862 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2863 DAG.getConstant(0, SDLoc(N), VT), Carry);
2864
2865 return SDValue();
2866}
2867
2868SDValue DAGCombiner::visitADDE(SDNode *N) {
2869 SDValue N0 = N->getOperand(0);
2870 SDValue N1 = N->getOperand(1);
2871 SDValue CarryIn = N->getOperand(2);
2872
2873 // canonicalize constant to RHS
2874 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2875 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2876 if (N0C && !N1C)
2877 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2878 N1, N0, CarryIn);
2879
2880 // fold (adde x, y, false) -> (addc x, y)
2881 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2882 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2883
2884 return SDValue();
2885}
2886
2887SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2888 SDValue N0 = N->getOperand(0);
2889 SDValue N1 = N->getOperand(1);
2890 SDValue CarryIn = N->getOperand(2);
2891 SDLoc DL(N);
2892
2893 // canonicalize constant to RHS
2894 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2896 if (N0C && !N1C)
2897 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2898
2899 // fold (addcarry x, y, false) -> (uaddo x, y)
2900 if (isNullConstant(CarryIn)) {
2901 if (!LegalOperations ||
2902 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
2903 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2904 }
2905
2906 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2907 if (isNullConstant(N0) && isNullConstant(N1)) {
2908 EVT VT = N0.getValueType();
2909 EVT CarryVT = CarryIn.getValueType();
2910 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2911 AddToWorklist(CarryExt.getNode());
2912 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2913 DAG.getConstant(1, DL, VT)),
2914 DAG.getConstant(0, DL, CarryVT));
2915 }
2916
2917 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2918 return Combined;
2919
2920 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2921 return Combined;
2922
2923 return SDValue();
2924}
2925
2926SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
2927 SDValue N0 = N->getOperand(0);
2928 SDValue N1 = N->getOperand(1);
2929 SDValue CarryIn = N->getOperand(2);
2930 SDLoc DL(N);
2931
2932 // canonicalize constant to RHS
2933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2934 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2935 if (N0C && !N1C)
2936 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
2937
2938 // fold (saddo_carry x, y, false) -> (saddo x, y)
2939 if (isNullConstant(CarryIn)) {
2940 if (!LegalOperations ||
2941 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
2942 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
2943 }
2944
2945 return SDValue();
2946}
2947
2948/**
2949 * If we are facing some sort of diamond carry propapagtion pattern try to
2950 * break it up to generate something like:
2951 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2952 *
2953 * The end result is usually an increase in operation required, but because the
2954 * carry is now linearized, other tranforms can kick in and optimize the DAG.
2955 *
2956 * Patterns typically look something like
2957 * (uaddo A, B)
2958 * / \
2959 * Carry Sum
2960 * | \
2961 * | (addcarry *, 0, Z)
2962 * | /
2963 * \ Carry
2964 * | /
2965 * (addcarry X, *, *)
2966 *
2967 * But numerous variation exist. Our goal is to identify A, B, X and Z and
2968 * produce a combine with a single path for carry propagation.
2969 */
2970static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
2971 SDValue X, SDValue Carry0, SDValue Carry1,
2972 SDNode *N) {
2973 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
2974 return SDValue();
2975 if (Carry1.getOpcode() != ISD::UADDO)
2976 return SDValue();
2977
2978 SDValue Z;
2979
2980 /**
2981 * First look for a suitable Z. It will present itself in the form of
2982 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2983 */
2984 if (Carry0.getOpcode() == ISD::ADDCARRY &&
2985 isNullConstant(Carry0.getOperand(1))) {
2986 Z = Carry0.getOperand(2);
2987 } else if (Carry0.getOpcode() == ISD::UADDO &&
2988 isOneConstant(Carry0.getOperand(1))) {
2989 EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
2990 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
2991 } else {
2992 // We couldn't find a suitable Z.
2993 return SDValue();
2994 }
2995
2996
2997 auto cancelDiamond = [&](SDValue A,SDValue B) {
2998 SDLoc DL(N);
2999 SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
3000 Combiner.AddToWorklist(NewY.getNode());
3001 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
3002 DAG.getConstant(0, DL, X.getValueType()),
3003 NewY.getValue(1));
3004 };
3005
3006 /**
3007 * (uaddo A, B)
3008 * |
3009 * Sum
3010 * |
3011 * (addcarry *, 0, Z)
3012 */
3013 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3014 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3015 }
3016
3017 /**
3018 * (addcarry A, 0, Z)
3019 * |
3020 * Sum
3021 * |
3022 * (uaddo *, B)
3023 */
3024 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3025 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3026 }
3027
3028 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3029 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3030 }
3031
3032 return SDValue();
3033}
3034
3035// If we are facing some sort of diamond carry/borrow in/out pattern try to
3036// match patterns like:
3037//
3038// (uaddo A, B) CarryIn
3039// | \ |
3040// | \ |
3041// PartialSum PartialCarryOutX /
3042// | | /
3043// | ____|____________/
3044// | / |
3045// (uaddo *, *) \________
3046// | \ \
3047// | \ |
3048// | PartialCarryOutY |
3049// | \ |
3050// | \ /
3051// AddCarrySum | ______/
3052// | /
3053// CarryOut = (or *, *)
3054//
3055// And generate ADDCARRY (or SUBCARRY) with two result values:
3056//
3057// {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn)
3058//
3059// Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with
3060// a single path for carry/borrow out propagation:
3061static SDValue combineCarryDiamond(SelectionDAG &DAG, const TargetLowering &TLI,
3062 SDValue Carry0, SDValue Carry1, SDNode *N) {
3063 if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1)
3064 return SDValue();
3065 unsigned Opcode = Carry0.getOpcode();
3066 if (Opcode != Carry1.getOpcode())
3067 return SDValue();
3068 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3069 return SDValue();
3070
3071 // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the
3072 // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in
3073 // the above ASCII art.)
3074 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3075 Carry1.getOperand(1) != Carry0.getValue(0))
3076 std::swap(Carry0, Carry1);
3077 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3078 Carry1.getOperand(1) != Carry0.getValue(0))
3079 return SDValue();
3080
3081 // The carry in value must be on the righthand side for subtraction.
3082 unsigned CarryInOperandNum =
3083 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3084 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3085 return SDValue();
3086 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3087
3088 unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY;
3089 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3090 return SDValue();
3091
3092 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3093 // TODO: make getAsCarry() aware of how partial carries are merged.
3094 if (CarryIn.getOpcode() != ISD::ZERO_EXTEND)
3095 return SDValue();
3096 CarryIn = CarryIn.getOperand(0);
3097 if (CarryIn.getValueType() != MVT::i1)
3098 return SDValue();
3099
3100 SDLoc DL(N);
3101 SDValue Merged =
3102 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3103 Carry0.getOperand(1), CarryIn);
3104
3105 // Please note that because we have proven that the result of the UADDO/USUBO
3106 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3107 // therefore prove that if the first UADDO/USUBO overflows, the second
3108 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3109 // maximum value.
3110 //
3111 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3112 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3113 //
3114 // This is important because it means that OR and XOR can be used to merge
3115 // carry flags; and that AND can return a constant zero.
3116 //
3117 // TODO: match other operations that can merge flags (ADD, etc)
3118 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3119 if (N->getOpcode() == ISD::AND)
3120 return DAG.getConstant(0, DL, MVT::i1);
3121 return Merged.getValue(1);
3122}
3123
3124SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
3125 SDNode *N) {
3126 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
3127 if (isBitwiseNot(N0))
3128 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3129 SDLoc DL(N);
3130 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
3131 N0.getOperand(0), NotC);
3132 return CombineTo(
3133 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3134 }
3135
3136 // Iff the flag result is dead:
3137 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
3138 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3139 // or the dependency between the instructions.
3140 if ((N0.getOpcode() == ISD::ADD ||
3141 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3142 N0.getValue(1) != CarryIn)) &&
3143 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3144 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
3145 N0.getOperand(0), N0.getOperand(1), CarryIn);
3146
3147 /**
3148 * When one of the addcarry argument is itself a carry, we may be facing
3149 * a diamond carry propagation. In which case we try to transform the DAG
3150 * to ensure linear carry propagation if that is possible.
3151 */
3152 if (auto Y = getAsCarry(TLI, N1)) {
3153 // Because both are carries, Y and Z can be swapped.
3154 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
3155 return R;
3156 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
3157 return R;
3158 }
3159
3160 return SDValue();
3161}
3162
3163// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
3164// clamp/truncation if necessary.
3165static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS,
3166 SDValue RHS, SelectionDAG &DAG,
3167 const SDLoc &DL) {
3168 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&(static_cast <bool> (DstVT.getScalarSizeInBits() <= SrcVT
.getScalarSizeInBits() && "Illegal truncation") ? void
(0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3169, __extension__
__PRETTY_FUNCTION__))
3169 "Illegal truncation")(static_cast <bool> (DstVT.getScalarSizeInBits() <= SrcVT
.getScalarSizeInBits() && "Illegal truncation") ? void
(0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3169, __extension__
__PRETTY_FUNCTION__))
;
3170
3171 if (DstVT == SrcVT)
3172 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
3173
3174 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
3175 // clamping RHS.
3176 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
3177 DstVT.getScalarSizeInBits());
3178 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
3179 return SDValue();
3180
3181 SDValue SatLimit =
3182 DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(),
3183 DstVT.getScalarSizeInBits()),
3184 DL, SrcVT);
3185 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
3186 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
3187 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
3188 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
3189}
3190
3191// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
3192// usubsat(a,b), optionally as a truncated type.
3193SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) {
3194 if (N->getOpcode() != ISD::SUB ||
3195 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
3196 return SDValue();
3197
3198 EVT SubVT = N->getValueType(0);
3199 SDValue Op0 = N->getOperand(0);
3200 SDValue Op1 = N->getOperand(1);
3201
3202 // Try to find umax(a,b) - b or a - umin(a,b) patterns
3203 // they may be converted to usubsat(a,b).
3204 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
3205 SDValue MaxLHS = Op0.getOperand(0);
3206 SDValue MaxRHS = Op0.getOperand(1);
3207 if (MaxLHS == Op1)
3208 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N));
3209 if (MaxRHS == Op1)
3210 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N));
3211 }
3212
3213 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
3214 SDValue MinLHS = Op1.getOperand(0);
3215 SDValue MinRHS = Op1.getOperand(1);
3216 if (MinLHS == Op0)
3217 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N));
3218 if (MinRHS == Op0)
3219 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N));
3220 }
3221
3222 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
3223 if (Op1.getOpcode() == ISD::TRUNCATE &&
3224 Op1.getOperand(0).getOpcode() == ISD::UMIN &&
3225 Op1.getOperand(0).hasOneUse()) {
3226 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
3227 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
3228 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
3229 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
3230 DAG, SDLoc(N));
3231 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
3232 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
3233 DAG, SDLoc(N));
3234 }
3235
3236 return SDValue();
3237}
3238
3239// Since it may not be valid to emit a fold to zero for vector initializers
3240// check if we can before folding.
3241static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
3242 SelectionDAG &DAG, bool LegalOperations) {
3243 if (!VT.isVector())
3244 return DAG.getConstant(0, DL, VT);
3245 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
3246 return DAG.getConstant(0, DL, VT);
3247 return SDValue();
3248}
3249
3250SDValue DAGCombiner::visitSUB(SDNode *N) {
3251 SDValue N0 = N->getOperand(0);
3252 SDValue N1 = N->getOperand(1);
3253 EVT VT = N0.getValueType();
3254 SDLoc DL(N);
3255
3256 // fold (sub x, x) -> 0
3257 // FIXME: Refactor this and xor and other similar operations together.
3258 if (N0 == N1)
3259 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
3260
3261 // fold (sub c1, c2) -> c3
3262 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
3263 return C;
3264
3265 // fold vector ops
3266 if (VT.isVector()) {
3267 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
3268 return FoldedVOp;
3269
3270 // fold (sub x, 0) -> x, vector edition
3271 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
3272 return N0;
3273 }
3274
3275 if (SDValue NewSel = foldBinOpIntoSelect(N))
3276 return NewSel;
3277
3278 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3279
3280 // fold (sub x, c) -> (add x, -c)
3281 if (N1C) {
3282 return DAG.getNode(ISD::ADD, DL, VT, N0,
3283 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3284 }
3285
3286 if (isNullOrNullSplat(N0)) {
3287 unsigned BitWidth = VT.getScalarSizeInBits();
3288 // Right-shifting everything out but the sign bit followed by negation is
3289 // the same as flipping arithmetic/logical shift type without the negation:
3290 // -(X >>u 31) -> (X >>s 31)
3291 // -(X >>s 31) -> (X >>u 31)
3292 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
3293 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
3294 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
3295 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
3296 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
3297 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
3298 }
3299 }
3300
3301 // 0 - X --> 0 if the sub is NUW.
3302 if (N->getFlags().hasNoUnsignedWrap())
3303 return N0;
3304
3305 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
3306 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3307 // N1 must be 0 because negating the minimum signed value is undefined.
3308 if (N->getFlags().hasNoSignedWrap())
3309 return N0;
3310
3311 // 0 - X --> X if X is 0 or the minimum signed value.
3312 return N1;
3313 }
3314
3315 // Convert 0 - abs(x).
3316 if (N1->getOpcode() == ISD::ABS &&
3317 !TLI.isOperationLegalOrCustom(ISD::ABS, VT))
3318 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
3319 return Result;
3320
3321 // Fold neg(splat(neg(x)) -> splat(x)
3322 if (VT.isVector()) {
3323 SDValue N1S = DAG.getSplatValue(N1, true);
3324 if (N1S && N1S.getOpcode() == ISD::SUB &&
3325 isNullConstant(N1S.getOperand(0))) {
3326 if (VT.isScalableVector())
3327 return DAG.getSplatVector(VT, DL, N1S.getOperand(1));
3328 return DAG.getSplatBuildVector(VT, DL, N1S.getOperand(1));
3329 }
3330 }
3331 }
3332
3333 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3334 if (isAllOnesOrAllOnesSplat(N0))
3335 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
3336
3337 // fold (A - (0-B)) -> A+B
3338 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
3339 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
3340
3341 // fold A-(A-B) -> B
3342 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
3343 return N1.getOperand(1);
3344
3345 // fold (A+B)-A -> B
3346 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
3347 return N0.getOperand(1);
3348
3349 // fold (A+B)-B -> A
3350 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
3351 return N0.getOperand(0);
3352
3353 // fold (A+C1)-C2 -> A+(C1-C2)
3354 if (N0.getOpcode() == ISD::ADD &&
3355 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3356 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3357 SDValue NewC =
3358 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1});
3359 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3359, __extension__
__PRETTY_FUNCTION__))
;
3360 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
3361 }
3362
3363 // fold C2-(A+C1) -> (C2-C1)-A
3364 if (N1.getOpcode() == ISD::ADD) {
3365 SDValue N11 = N1.getOperand(1);
3366 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
3367 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
3368 SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11});
3369 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3369, __extension__
__PRETTY_FUNCTION__))
;
3370 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
3371 }
3372 }
3373
3374 // fold (A-C1)-C2 -> A-(C1+C2)
3375 if (N0.getOpcode() == ISD::SUB &&
3376 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3377 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3378 SDValue NewC =
3379 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1});
3380 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3380, __extension__
__PRETTY_FUNCTION__))
;
3381 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
3382 }
3383
3384 // fold (c1-A)-c2 -> (c1-c2)-A
3385 if (N0.getOpcode() == ISD::SUB &&
3386 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3387 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) {
3388 SDValue NewC =
3389 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1});
3390 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3390, __extension__
__PRETTY_FUNCTION__))
;
3391 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
3392 }
3393
3394 // fold ((A+(B+or-C))-B) -> A+or-C
3395 if (N0.getOpcode() == ISD::ADD &&
3396 (N0.getOperand(1).getOpcode() == ISD::SUB ||
3397 N0.getOperand(1).getOpcode() == ISD::ADD) &&
3398 N0.getOperand(1).getOperand(0) == N1)
3399 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
3400 N0.getOperand(1).getOperand(1));
3401
3402 // fold ((A+(C+B))-B) -> A+C
3403 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
3404 N0.getOperand(1).getOperand(1) == N1)
3405 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
3406 N0.getOperand(1).getOperand(0));
3407
3408 // fold ((A-(B-C))-C) -> A-B
3409 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
3410 N0.getOperand(1).getOperand(1) == N1)
3411 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
3412 N0.getOperand(1).getOperand(0));
3413
3414 // fold (A-(B-C)) -> A+(C-B)
3415 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
3416 return DAG.getNode(ISD::ADD, DL, VT, N0,
3417 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
3418 N1.getOperand(0)));
3419
3420 // A - (A & B) -> A & (~B)
3421 if (N1.getOpcode() == ISD::AND) {
3422 SDValue A = N1.getOperand(0);
3423 SDValue B = N1.getOperand(1);
3424 if (A != N0)
3425 std::swap(A, B);
3426 if (A == N0 &&
3427 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) {
3428 SDValue InvB =
3429 DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT));
3430 return DAG.getNode(ISD::AND, DL, VT, A, InvB);
3431 }
3432 }
3433
3434 // fold (X - (-Y * Z)) -> (X + (Y * Z))
3435 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
3436 if (N1.getOperand(0).getOpcode() == ISD::SUB &&
3437 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
3438 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3439 N1.getOperand(0).getOperand(1),
3440 N1.getOperand(1));
3441 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3442 }
3443 if (N1.getOperand(1).getOpcode() == ISD::SUB &&
3444 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
3445 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3446 N1.getOperand(0),
3447 N1.getOperand(1).getOperand(1));
3448 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3449 }
3450 }
3451
3452 // If either operand of a sub is undef, the result is undef
3453 if (N0.isUndef())
3454 return N0;
3455 if (N1.isUndef())
3456 return N1;
3457
3458 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
3459 return V;
3460
3461 if (SDValue V = foldAddSubOfSignBit(N, DAG))
3462 return V;
3463
3464 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
3465 return V;
3466
3467 if (SDValue V = foldSubToUSubSat(VT, N))
3468 return V;
3469
3470 // (x - y) - 1 -> add (xor y, -1), x
3471 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) {
3472 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
3473 DAG.getAllOnesConstant(DL, VT));
3474 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
3475 }
3476
3477 // Look for:
3478 // sub y, (xor x, -1)
3479 // And if the target does not like this form then turn into:
3480 // add (add x, y), 1
3481 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
3482 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
3483 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
3484 }
3485
3486 // Hoist one-use addition by non-opaque constant:
3487 // (x + C) - y -> (x - y) + C
3488 if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
3489 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3490 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3491 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
3492 }
3493 // y - (x + C) -> (y - x) - C
3494 if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD &&
3495 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
3496 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
3497 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
3498 }
3499 // (x - C) - y -> (x - y) - C
3500 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3501 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3502 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3503 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3504 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
3505 }
3506 // (C - x) - y -> C - (x + y)
3507 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3508 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3509 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
3510 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
3511 }
3512
3513 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3514 // rather than 'sub 0/1' (the sext should get folded).
3515 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3516 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
3517 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
3518 TLI.getBooleanContents(VT) ==
3519 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3520 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
3521 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
3522 }
3523
3524 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3525 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
3526 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
3527 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
3528 SDValue S0 = N1.getOperand(0);
3529 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0))
3530 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
3531 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
3532 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
3533 }
3534 }
3535
3536 // If the relocation model supports it, consider symbol offsets.
3537 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
3538 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
3539 // fold (sub Sym, c) -> Sym-c
3540 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
3541 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
3542 GA->getOffset() -
3543 (uint64_t)N1C->getSExtValue());
3544 // fold (sub Sym+c1, Sym+c2) -> c1-c2
3545 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
3546 if (GA->getGlobal() == GB->getGlobal())
3547 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
3548 DL, VT);
3549 }
3550
3551 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3552 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3553 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3554 if (TN->getVT() == MVT::i1) {
3555 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3556 DAG.getConstant(1, DL, VT));
3557 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
3558 }
3559 }
3560
3561 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
3562 if (N1.getOpcode() == ISD::VSCALE) {
3563 const APInt &IntVal = N1.getConstantOperandAPInt(0);
3564 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
3565 }
3566
3567 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
3568 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
3569 APInt NewStep = -N1.getConstantOperandAPInt(0);
3570 return DAG.getNode(ISD::ADD, DL, VT, N0,
3571 DAG.getStepVector(DL, VT, NewStep));
3572 }
3573
3574 // Prefer an add for more folding potential and possibly better codegen:
3575 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3576 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
3577 SDValue ShAmt = N1.getOperand(1);
3578 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
3579 if (ShAmtC &&
3580 ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
3581 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
3582 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
3583 }
3584 }
3585
3586 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) {
3587 // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry)
3588 if (SDValue Carry = getAsCarry(TLI, N0)) {
3589 SDValue X = N1;
3590 SDValue Zero = DAG.getConstant(0, DL, VT);
3591 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
3592 return DAG.getNode(ISD::ADDCARRY, DL,
3593 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
3594 Carry);
3595 }
3596 }
3597
3598 return SDValue();
3599}
3600
3601SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
3602 SDValue N0 = N->getOperand(0);
3603 SDValue N1 = N->getOperand(1);
3604 EVT VT = N0.getValueType();
3605 SDLoc DL(N);
3606
3607 // fold (sub_sat x, undef) -> 0
3608 if (N0.isUndef() || N1.isUndef())
3609 return DAG.getConstant(0, DL, VT);
3610
3611 // fold (sub_sat x, x) -> 0
3612 if (N0 == N1)
3613 return DAG.getConstant(0, DL, VT);
3614
3615 // fold (sub_sat c1, c2) -> c3
3616 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
3617 return C;
3618
3619 // fold vector ops
3620 if (VT.isVector()) {
3621 // TODO SimplifyVBinOp
3622
3623 // fold (sub_sat x, 0) -> x, vector edition
3624 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
3625 return N0;
3626 }
3627
3628 // fold (sub_sat x, 0) -> x
3629 if (isNullConstant(N1))
3630 return N0;
3631
3632 return SDValue();
3633}
3634
3635SDValue DAGCombiner::visitSUBC(SDNode *N) {
3636 SDValue N0 = N->getOperand(0);
3637 SDValue N1 = N->getOperand(1);
3638 EVT VT = N0.getValueType();
3639 SDLoc DL(N);
3640
3641 // If the flag result is dead, turn this into an SUB.
3642 if (!N->hasAnyUseOfValue(1))
3643 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3644 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3645
3646 // fold (subc x, x) -> 0 + no borrow
3647 if (N0 == N1)
3648 return CombineTo(N, DAG.getConstant(0, DL, VT),
3649 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3650
3651 // fold (subc x, 0) -> x + no borrow
3652 if (isNullConstant(N1))
3653 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3654
3655 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3656 if (isAllOnesConstant(N0))
3657 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3658 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3659
3660 return SDValue();
3661}
3662
3663SDValue DAGCombiner::visitSUBO(SDNode *N) {
3664 SDValue N0 = N->getOperand(0);
3665 SDValue N1 = N->getOperand(1);
3666 EVT VT = N0.getValueType();
3667 bool IsSigned = (ISD::SSUBO == N->getOpcode());
3668
3669 EVT CarryVT = N->getValueType(1);
3670 SDLoc DL(N);
3671
3672 // If the flag result is dead, turn this into an SUB.
3673 if (!N->hasAnyUseOfValue(1))
3674 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3675 DAG.getUNDEF(CarryVT));
3676
3677 // fold (subo x, x) -> 0 + no borrow
3678 if (N0 == N1)
3679 return CombineTo(N, DAG.getConstant(0, DL, VT),
3680 DAG.getConstant(0, DL, CarryVT));
3681
3682 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3683
3684 // fold (subox, c) -> (addo x, -c)
3685 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
3686 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
3687 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3688 }
3689
3690 // fold (subo x, 0) -> x + no borrow
3691 if (isNullOrNullSplat(N1))
3692 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3693
3694 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3695 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
3696 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3697 DAG.getConstant(0, DL, CarryVT));
3698
3699 return SDValue();
3700}
3701
3702SDValue DAGCombiner::visitSUBE(SDNode *N) {
3703 SDValue N0 = N->getOperand(0);
3704 SDValue N1 = N->getOperand(1);
3705 SDValue CarryIn = N->getOperand(2);
3706
3707 // fold (sube x, y, false) -> (subc x, y)
3708 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3709 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
3710
3711 return SDValue();
3712}
3713
3714SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
3715 SDValue N0 = N->getOperand(0);
3716 SDValue N1 = N->getOperand(1);
3717 SDValue CarryIn = N->getOperand(2);
3718
3719 // fold (subcarry x, y, false) -> (usubo x, y)
3720 if (isNullConstant(CarryIn)) {
3721 if (!LegalOperations ||
3722 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
3723 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
3724 }
3725
3726 return SDValue();
3727}
3728
3729SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
3730 SDValue N0 = N->getOperand(0);
3731 SDValue N1 = N->getOperand(1);
3732 SDValue CarryIn = N->getOperand(2);
3733
3734 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
3735 if (isNullConstant(CarryIn)) {
3736 if (!LegalOperations ||
3737 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
3738 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
3739 }
3740
3741 return SDValue();
3742}
3743
3744// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
3745// UMULFIXSAT here.
3746SDValue DAGCombiner::visitMULFIX(SDNode *N) {
3747 SDValue N0 = N->getOperand(0);
3748 SDValue N1 = N->getOperand(1);
3749 SDValue Scale = N->getOperand(2);
3750 EVT VT = N0.getValueType();
3751
3752 // fold (mulfix x, undef, scale) -> 0
3753 if (N0.isUndef() || N1.isUndef())
3754 return DAG.getConstant(0, SDLoc(N), VT);
3755
3756 // Canonicalize constant to RHS (vector doesn't have to splat)
3757 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3758 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3759 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
3760
3761 // fold (mulfix x, 0, scale) -> 0
3762 if (isNullConstant(N1))
3763 return DAG.getConstant(0, SDLoc(N), VT);
3764
3765 return SDValue();
3766}
3767
3768SDValue DAGCombiner::visitMUL(SDNode *N) {
3769 SDValue N0 = N->getOperand(0);
3770 SDValue N1 = N->getOperand(1);
3771 EVT VT = N0.getValueType();
3772
3773 // fold (mul x, undef) -> 0
3774 if (N0.isUndef() || N1.isUndef())
3775 return DAG.getConstant(0, SDLoc(N), VT);
3776
3777 // fold (mul c1, c2) -> c1*c2
3778 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1}))
3779 return C;
3780
3781 // canonicalize constant to RHS (vector doesn't have to splat)
3782 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3783 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3784 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
3785
3786 bool N1IsConst = false;
3787 bool N1IsOpaqueConst = false;
3788 APInt ConstValue1;
3789
3790 // fold vector ops
3791 if (VT.isVector()) {
3792 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
3793 return FoldedVOp;
3794
3795 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
3796 assert((!N1IsConst ||(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3798, __extension__
__PRETTY_FUNCTION__))
3797 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3798, __extension__
__PRETTY_FUNCTION__))
3798 "Splat APInt should be element width")(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3798, __extension__
__PRETTY_FUNCTION__))
;
3799 } else {
3800 N1IsConst = isa<ConstantSDNode>(N1);
3801 if (N1IsConst) {
3802 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3803 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3804 }
3805 }
3806
3807 // fold (mul x, 0) -> 0
3808 if (N1IsConst && ConstValue1.isZero())
3809 return N1;
3810
3811 // fold (mul x, 1) -> x
3812 if (N1IsConst && ConstValue1.isOne())
3813 return N0;
3814
3815 if (SDValue NewSel = foldBinOpIntoSelect(N))
3816 return NewSel;
3817
3818 // fold (mul x, -1) -> 0-x
3819 if (N1IsConst && ConstValue1.isAllOnes()) {
3820 SDLoc DL(N);
3821 return DAG.getNode(ISD::SUB, DL, VT,
3822 DAG.getConstant(0, DL, VT), N0);
3823 }
3824
3825 // fold (mul x, (1 << c)) -> x << c
3826 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3827 DAG.isKnownToBeAPowerOfTwo(N1) &&
3828 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
3829 SDLoc DL(N);
3830 SDValue LogBase2 = BuildLogBase2(N1, DL);
3831 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3832 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3833 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
3834 }
3835
3836 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3837 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
3838 unsigned Log2Val = (-ConstValue1).logBase2();
3839 SDLoc DL(N);
3840 // FIXME: If the input is something that is easily negated (e.g. a
3841 // single-use add), we should put the negate there.
3842 return DAG.getNode(ISD::SUB, DL, VT,
3843 DAG.getConstant(0, DL, VT),
3844 DAG.getNode(ISD::SHL, DL, VT, N0,
3845 DAG.getConstant(Log2Val, DL,
3846 getShiftAmountTy(N0.getValueType()))));
3847 }
3848
3849 // Try to transform:
3850 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3851 // mul x, (2^N + 1) --> add (shl x, N), x
3852 // mul x, (2^N - 1) --> sub (shl x, N), x
3853 // Examples: x * 33 --> (x << 5) + x
3854 // x * 15 --> (x << 4) - x
3855 // x * -33 --> -((x << 5) + x)
3856 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3857 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
3858 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
3859 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
3860 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
3861 // x * 0xf800 --> (x << 16) - (x << 11)
3862 // x * -0x8800 --> -((x << 15) + (x << 11))
3863 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
3864 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
3865 // TODO: We could handle more general decomposition of any constant by
3866 // having the target set a limit on number of ops and making a
3867 // callback to determine that sequence (similar to sqrt expansion).
3868 unsigned MathOp = ISD::DELETED_NODE;
3869 APInt MulC = ConstValue1.abs();
3870 // The constant `2` should be treated as (2^0 + 1).
3871 unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros();
3872 MulC.lshrInPlace(TZeros);
3873 if ((MulC - 1).isPowerOf2())
3874 MathOp = ISD::ADD;
3875 else if ((MulC + 1).isPowerOf2())
3876 MathOp = ISD::SUB;
3877
3878 if (MathOp != ISD::DELETED_NODE) {
3879 unsigned ShAmt =
3880 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
3881 ShAmt += TZeros;
3882 assert(ShAmt < VT.getScalarSizeInBits() &&(static_cast <bool> (ShAmt < VT.getScalarSizeInBits(
) && "multiply-by-constant generated out of bounds shift"
) ? void (0) : __assert_fail ("ShAmt < VT.getScalarSizeInBits() && \"multiply-by-constant generated out of bounds shift\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3883, __extension__
__PRETTY_FUNCTION__))
3883 "multiply-by-constant generated out of bounds shift")(static_cast <bool> (ShAmt < VT.getScalarSizeInBits(
) && "multiply-by-constant generated out of bounds shift"
) ? void (0) : __assert_fail ("ShAmt < VT.getScalarSizeInBits() && \"multiply-by-constant generated out of bounds shift\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3883, __extension__
__PRETTY_FUNCTION__))
;
3884 SDLoc DL(N);
3885 SDValue Shl =
3886 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
3887 SDValue R =
3888 TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
3889 DAG.getNode(ISD::SHL, DL, VT, N0,
3890 DAG.getConstant(TZeros, DL, VT)))
3891 : DAG.getNode(MathOp, DL, VT, Shl, N0);
3892 if (ConstValue1.isNegative())
3893 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
3894 return R;
3895 }
3896 }
3897
3898 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3899 if (N0.getOpcode() == ISD::SHL &&
3900 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3901 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3902 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
3903 if (isConstantOrConstantVector(C3))
3904 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
3905 }
3906
3907 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3908 // use.
3909 {
3910 SDValue Sh, Y;
3911
3912 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3913 if (N0.getOpcode() == ISD::SHL &&
3914 isConstantOrConstantVector(N0.getOperand(1)) &&
3915 N0.getNode()->hasOneUse()) {
3916 Sh = N0; Y = N1;
3917 } else if (N1.getOpcode() == ISD::SHL &&
3918 isConstantOrConstantVector(N1.getOperand(1)) &&
3919 N1.getNode()->hasOneUse()) {
3920 Sh = N1; Y = N0;
3921 }
3922
3923 if (Sh.getNode()) {
3924 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
3925 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
3926 }
3927 }
3928
3929 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3930 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
3931 N0.getOpcode() == ISD::ADD &&
3932 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
3933 isMulAddWithConstProfitable(N, N0, N1))
3934 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
3935 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
3936 N0.getOperand(0), N1),
3937 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
3938 N0.getOperand(1), N1));
3939
3940 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
3941 if (N0.getOpcode() == ISD::VSCALE)
3942 if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) {
3943 const APInt &C0 = N0.getConstantOperandAPInt(0);
3944 const APInt &C1 = NC1->getAPIntValue();
3945 return DAG.getVScale(SDLoc(N), VT, C0 * C1);
3946 }
3947
3948 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
3949 APInt MulVal;
3950 if (N0.getOpcode() == ISD::STEP_VECTOR)
3951 if (ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
3952 const APInt &C0 = N0.getConstantOperandAPInt(0);
3953 APInt NewStep = C0 * MulVal;
3954 return DAG.getStepVector(SDLoc(N), VT, NewStep);
3955 }
3956
3957 // Fold ((mul x, 0/undef) -> 0,
3958 // (mul x, 1) -> x) -> x)
3959 // -> and(x, mask)
3960 // We can replace vectors with '0' and '1' factors with a clearing mask.
3961 if (VT.isFixedLengthVector()) {
3962 unsigned NumElts = VT.getVectorNumElements();
3963 SmallBitVector ClearMask;
3964 ClearMask.reserve(NumElts);
3965 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
3966 if (!V || V->isZero()) {
3967 ClearMask.push_back(true);
3968 return true;
3969 }
3970 ClearMask.push_back(false);
3971 return V->isOne();
3972 };
3973 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
3974 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
3975 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector")(static_cast <bool> (N1.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown constant vector") ? void (0) : __assert_fail
("N1.getOpcode() == ISD::BUILD_VECTOR && \"Unknown constant vector\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 3975, __extension__
__PRETTY_FUNCTION__))
;
3976 SDLoc DL(N);
3977 EVT LegalSVT = N1.getOperand(0).getValueType();
3978 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
3979 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
3980 SmallVector<SDValue, 16> Mask(NumElts, AllOnes);
3981 for (unsigned I = 0; I != NumElts; ++I)
3982 if (ClearMask[I])
3983 Mask[I] = Zero;
3984 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
3985 }
3986 }
3987
3988 // reassociate mul
3989 if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
3990 return RMUL;
3991
3992 return SDValue();
3993}
3994
3995/// Return true if divmod libcall is available.
3996static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
3997 const TargetLowering &TLI) {
3998 RTLIB::Libcall LC;
3999 EVT NodeType = Node->getValueType(0);
4000 if (!NodeType.isSimple())
4001 return false;
4002 switch (NodeType.getSimpleVT().SimpleTy) {
4003 default: return false; // No libcall for vector types.
4004 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
4005 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
4006 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
4007 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
4008 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
4009 }
4010
4011 return TLI.getLibcallName(LC) != nullptr;
4012}
4013
4014/// Issue divrem if both quotient and remainder are needed.
4015SDValue DAGCombiner::useDivRem(SDNode *Node) {
4016 if (Node->use_empty())
4017 return SDValue(); // This is a dead node, leave it alone.
4018
4019 unsigned Opcode = Node->getOpcode();
4020 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
4021 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
4022
4023 // DivMod lib calls can still work on non-legal types if using lib-calls.
4024 EVT VT = Node->getValueType(0);
4025 if (VT.isVector() || !VT.isInteger())
4026 return SDValue();
4027
4028 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
4029 return SDValue();
4030
4031 // If DIVREM is going to get expanded into a libcall,
4032 // but there is no libcall available, then don't combine.
4033 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
4034 !isDivRemLibcallAvailable(Node, isSigned, TLI))
4035 return SDValue();
4036
4037 // If div is legal, it's better to do the normal expansion
4038 unsigned OtherOpcode = 0;
4039 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
4040 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
4041 if (TLI.isOperationLegalOrCustom(Opcode, VT))
4042 return SDValue();
4043 } else {
4044 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4045 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
4046 return SDValue();
4047 }
4048
4049 SDValue Op0 = Node->getOperand(0);
4050 SDValue Op1 = Node->getOperand(1);
4051 SDValue combined;
4052 for (SDNode *User : Op0.getNode()->uses()) {
4053 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
4054 User->use_empty())
4055 continue;
4056 // Convert the other matching node(s), too;
4057 // otherwise, the DIVREM may get target-legalized into something
4058 // target-specific that we won't be able to recognize.
4059 unsigned UserOpc = User->getOpcode();
4060 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
4061 User->getOperand(0) == Op0 &&
4062 User->getOperand(1) == Op1) {
4063 if (!combined) {
4064 if (UserOpc == OtherOpcode) {
4065 SDVTList VTs = DAG.getVTList(VT, VT);
4066 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
4067 } else if (UserOpc == DivRemOpc) {
4068 combined = SDValue(User, 0);
4069 } else {
4070 assert(UserOpc == Opcode)(static_cast <bool> (UserOpc == Opcode) ? void (0) : __assert_fail
("UserOpc == Opcode", "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4070, __extension__ __PRETTY_FUNCTION__))
;
4071 continue;
4072 }
4073 }
4074 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
4075 CombineTo(User, combined);
4076 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
4077 CombineTo(User, combined.getValue(1));
4078 }
4079 }
4080 return combined;
4081}
4082
4083static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
4084 SDValue N0 = N->getOperand(0);
4085 SDValue N1 = N->getOperand(1);
4086 EVT VT = N->getValueType(0);
4087 SDLoc DL(N);
4088
4089 unsigned Opc = N->getOpcode();
4090 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
4091 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4092
4093 // X / undef -> undef
4094 // X % undef -> undef
4095 // X / 0 -> undef
4096 // X % 0 -> undef
4097 // NOTE: This includes vectors where any divisor element is zero/undef.
4098 if (DAG.isUndef(Opc, {N0, N1}))
4099 return DAG.getUNDEF(VT);
4100
4101 // undef / X -> 0
4102 // undef % X -> 0
4103 if (N0.isUndef())
4104 return DAG.getConstant(0, DL, VT);
4105
4106 // 0 / X -> 0
4107 // 0 % X -> 0
4108 ConstantSDNode *N0C = isConstOrConstSplat(N0);
4109 if (N0C && N0C->isZero())
4110 return N0;
4111
4112 // X / X -> 1
4113 // X % X -> 0
4114 if (N0 == N1)
4115 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
4116
4117 // X / 1 -> X
4118 // X % 1 -> 0
4119 // If this is a boolean op (single-bit element type), we can't have
4120 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
4121 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
4122 // it's a 1.
4123 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
4124 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
4125
4126 return SDValue();
4127}
4128
4129SDValue DAGCombiner::visitSDIV(SDNode *N) {
4130 SDValue N0 = N->getOperand(0);
4131 SDValue N1 = N->getOperand(1);
4132 EVT VT = N->getValueType(0);
4133 EVT CCVT = getSetCCResultType(VT);
4134 SDLoc DL(N);
4135
4136 // fold (sdiv c1, c2) -> c1/c2
4137 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
4138 return C;
4139
4140 // fold vector ops
4141 if (VT.isVector())
4142 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4143 return FoldedVOp;
4144
4145 // fold (sdiv X, -1) -> 0-X
4146 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4147 if (N1C && N1C->isAllOnes())
4148 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
4149
4150 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
4151 if (N1C && N1C->getAPIntValue().isMinSignedValue())
4152 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4153 DAG.getConstant(1, DL, VT),
4154 DAG.getConstant(0, DL, VT));
4155
4156 if (SDValue V = simplifyDivRem(N, DAG))
4157 return V;
4158
4159 if (SDValue NewSel = foldBinOpIntoSelect(N))
4160 return NewSel;
4161
4162 // If we know the sign bits of both operands are zero, strength reduce to a
4163 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
4164 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4165 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
4166
4167 if (SDValue V = visitSDIVLike(N0, N1, N)) {
4168 // If the corresponding remainder node exists, update its users with
4169 // (Dividend - (Quotient * Divisor).
4170 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
4171 { N0, N1 })) {
4172 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
4173 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4174 AddToWorklist(Mul.getNode());
4175 AddToWorklist(Sub.getNode());
4176 CombineTo(RemNode, Sub);
4177 }
4178 return V;
4179 }
4180
4181 // sdiv, srem -> sdivrem
4182 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4183 // true. Otherwise, we break the simplification logic in visitREM().
4184 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4185 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
4186 if (SDValue DivRem = useDivRem(N))
4187 return DivRem;
4188
4189 return SDValue();
4190}
4191
4192SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
4193 SDLoc DL(N);
4194 EVT VT = N->getValueType(0);
4195 EVT CCVT = getSetCCResultType(VT);
4196 unsigned BitWidth = VT.getScalarSizeInBits();
4197
4198 // Helper for determining whether a value is a power-2 constant scalar or a
4199 // vector of such elements.
4200 auto IsPowerOfTwo = [](ConstantSDNode *C) {
4201 if (C->isZero() || C->isOpaque())
4202 return false;
4203 if (C->getAPIntValue().isPowerOf2())
4204 return true;
4205 if (C->getAPIntValue().isNegatedPowerOf2())
4206 return true;
4207 return false;
4208 };
4209
4210 // fold (sdiv X, pow2) -> simple ops after legalize
4211 // FIXME: We check for the exact bit here because the generic lowering gives
4212 // better results in that case. The target-specific lowering should learn how
4213 // to handle exact sdivs efficiently.
4214 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
4215 // Target-specific implementation of sdiv x, pow2.
4216 if (SDValue Res = BuildSDIVPow2(N))
4217 return Res;
4218
4219 // Create constants that are functions of the shift amount value.
4220 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
4221 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
4222 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
4223 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
4224 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
4225 if (!isConstantOrConstantVector(Inexact))
4226 return SDValue();
4227
4228 // Splat the sign bit into the register
4229 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
4230 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
4231 AddToWorklist(Sign.getNode());
4232
4233 // Add (N0 < 0) ? abs2 - 1 : 0;
4234 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
4235 AddToWorklist(Srl.getNode());
4236 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
4237 AddToWorklist(Add.getNode());
4238 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
4239 AddToWorklist(Sra.getNode());
4240
4241 // Special case: (sdiv X, 1) -> X
4242 // Special Case: (sdiv X, -1) -> 0-X
4243 SDValue One = DAG.getConstant(1, DL, VT);
4244 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4245 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
4246 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
4247 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
4248 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
4249
4250 // If dividing by a positive value, we're done. Otherwise, the result must
4251 // be negated.
4252 SDValue Zero = DAG.getConstant(0, DL, VT);
4253 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
4254
4255 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
4256 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
4257 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
4258 return Res;
4259 }
4260
4261 // If integer divide is expensive and we satisfy the requirements, emit an
4262 // alternate sequence. Targets may check function attributes for size/speed
4263 // trade-offs.
4264 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4265 if (isConstantOrConstantVector(N1) &&
4266 !TLI.isIntDivCheap(N->getValueType(0), Attr))
4267 if (SDValue Op = BuildSDIV(N))
4268 return Op;
4269
4270 return SDValue();
4271}
4272
4273SDValue DAGCombiner::visitUDIV(SDNode *N) {
4274 SDValue N0 = N->getOperand(0);
4275 SDValue N1 = N->getOperand(1);
4276 EVT VT = N->getValueType(0);
4277 EVT CCVT = getSetCCResultType(VT);
4278 SDLoc DL(N);
4279
4280 // fold (udiv c1, c2) -> c1/c2
4281 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
4282 return C;
4283
4284 // fold vector ops
4285 if (VT.isVector())
4286 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4287 return FoldedVOp;
4288
4289 // fold (udiv X, -1) -> select(X == -1, 1, 0)
4290 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4291 if (N1C && N1C->isAllOnes())
4292 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4293 DAG.getConstant(1, DL, VT),
4294 DAG.getConstant(0, DL, VT));
4295
4296 if (SDValue V = simplifyDivRem(N, DAG))
4297 return V;
4298
4299 if (SDValue NewSel = foldBinOpIntoSelect(N))
4300 return NewSel;
4301
4302 if (SDValue V = visitUDIVLike(N0, N1, N)) {
4303 // If the corresponding remainder node exists, update its users with
4304 // (Dividend - (Quotient * Divisor).
4305 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
4306 { N0, N1 })) {
4307 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
4308 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4309 AddToWorklist(Mul.getNode());
4310 AddToWorklist(Sub.getNode());
4311 CombineTo(RemNode, Sub);
4312 }
4313 return V;
4314 }
4315
4316 // sdiv, srem -> sdivrem
4317 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4318 // true. Otherwise, we break the simplification logic in visitREM().
4319 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4320 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
4321 if (SDValue DivRem = useDivRem(N))
4322 return DivRem;
4323
4324 return SDValue();
4325}
4326
4327SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
4328 SDLoc DL(N);
4329 EVT VT = N->getValueType(0);
4330
4331 // fold (udiv x, (1 << c)) -> x >>u c
4332 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4333 DAG.isKnownToBeAPowerOfTwo(N1)) {
4334 SDValue LogBase2 = BuildLogBase2(N1, DL);
4335 AddToWorklist(LogBase2.getNode());
4336
4337 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4338 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4339 AddToWorklist(Trunc.getNode());
4340 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4341 }
4342
4343 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
4344 if (N1.getOpcode() == ISD::SHL) {
4345 SDValue N10 = N1.getOperand(0);
4346 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
4347 DAG.isKnownToBeAPowerOfTwo(N10)) {
4348 SDValue LogBase2 = BuildLogBase2(N10, DL);
4349 AddToWorklist(LogBase2.getNode());
4350
4351 EVT ADDVT = N1.getOperand(1).getValueType();
4352 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
4353 AddToWorklist(Trunc.getNode());
4354 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
4355 AddToWorklist(Add.getNode());
4356 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
4357 }
4358 }
4359
4360 // fold (udiv x, c) -> alternate
4361 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4362 if (isConstantOrConstantVector(N1) &&
4363 !TLI.isIntDivCheap(N->getValueType(0), Attr))
4364 if (SDValue Op = BuildUDIV(N))
4365 return Op;
4366
4367 return SDValue();
4368}
4369
4370// handles ISD::SREM and ISD::UREM
4371SDValue DAGCombiner::visitREM(SDNode *N) {
4372 unsigned Opcode = N->getOpcode();
4373 SDValue N0 = N->getOperand(0);
4374 SDValue N1 = N->getOperand(1);
4375 EVT VT = N->getValueType(0);
4376 EVT CCVT = getSetCCResultType(VT);
4377
4378 bool isSigned = (Opcode == ISD::SREM);
4379 SDLoc DL(N);
4380
4381 // fold (rem c1, c2) -> c1%c2
4382 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4383 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4384 return C;
4385
4386 // fold (urem X, -1) -> select(X == -1, 0, x)
4387 if (!isSigned && N1C && N1C->isAllOnes())
4388 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4389 DAG.getConstant(0, DL, VT), N0);
4390
4391 if (SDValue V = simplifyDivRem(N, DAG))
4392 return V;
4393
4394 if (SDValue NewSel = foldBinOpIntoSelect(N))
4395 return NewSel;
4396
4397 if (isSigned) {
4398 // If we know the sign bits of both operands are zero, strength reduce to a
4399 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4400 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4401 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
4402 } else {
4403 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
4404 // fold (urem x, pow2) -> (and x, pow2-1)
4405 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4406 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4407 AddToWorklist(Add.getNode());
4408 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4409 }
4410 if (N1.getOpcode() == ISD::SHL &&
4411 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
4412 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4413 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4414 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4415 AddToWorklist(Add.getNode());
4416 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4417 }
4418 }
4419
4420 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4421
4422 // If X/C can be simplified by the division-by-constant logic, lower
4423 // X%C to the equivalent of X-X/C*C.
4424 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4425 // speculative DIV must not cause a DIVREM conversion. We guard against this
4426 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
4427 // combine will not return a DIVREM. Regardless, checking cheapness here
4428 // makes sense since the simplification results in fatter code.
4429 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
4430 SDValue OptimizedDiv =
4431 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
4432 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
4433 // If the equivalent Div node also exists, update its users.
4434 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4435 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
4436 { N0, N1 }))
4437 CombineTo(DivNode, OptimizedDiv);
4438 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
4439 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4440 AddToWorklist(OptimizedDiv.getNode());
4441 AddToWorklist(Mul.getNode());
4442 return Sub;
4443 }
4444 }
4445
4446 // sdiv, srem -> sdivrem
4447 if (SDValue DivRem = useDivRem(N))
4448 return DivRem.getValue(1);
4449
4450 return SDValue();
4451}
4452
4453SDValue DAGCombiner::visitMULHS(SDNode *N) {
4454 SDValue N0 = N->getOperand(0);
4455 SDValue N1 = N->getOperand(1);
4456 EVT VT = N->getValueType(0);
4457 SDLoc DL(N);
4458
4459 // fold (mulhs c1, c2)
4460 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
4461 return C;
4462
4463 // canonicalize constant to RHS.
4464 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4465 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4466 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
4467
4468 if (VT.isVector()) {
4469 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4470 return FoldedVOp;
4471
4472 // fold (mulhs x, 0) -> 0
4473 // do not return N1, because undef node may exist.
4474 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
4475 return DAG.getConstant(0, DL, VT);
4476 }
4477
4478 // fold (mulhs x, 0) -> 0
4479 if (isNullConstant(N1))
4480 return N1;
4481
4482 // fold (mulhs x, 1) -> (sra x, size(x)-1)
4483 if (isOneConstant(N1))
4484 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
4485 DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL,
4486 getShiftAmountTy(N0.getValueType())));
4487
4488 // fold (mulhs x, undef) -> 0
4489 if (N0.isUndef() || N1.isUndef())
4490 return DAG.getConstant(0, DL, VT);
4491
4492 // If the type twice as wide is legal, transform the mulhs to a wider multiply
4493 // plus a shift.
4494 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
4495 !VT.isVector()) {
4496 MVT Simple = VT.getSimpleVT();
4497 unsigned SimpleSize = Simple.getSizeInBits();
4498 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4499 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4500 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
4501 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
4502 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4503 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4504 DAG.getConstant(SimpleSize, DL,
4505 getShiftAmountTy(N1.getValueType())));
4506 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4507 }
4508 }
4509
4510 return SDValue();
4511}
4512
4513SDValue DAGCombiner::visitMULHU(SDNode *N) {
4514 SDValue N0 = N->getOperand(0);
4515 SDValue N1 = N->getOperand(1);
4516 EVT VT = N->getValueType(0);
4517 SDLoc DL(N);
4518
4519 // fold (mulhu c1, c2)
4520 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
4521 return C;
4522
4523 // canonicalize constant to RHS.
4524 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4525 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4526 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
4527
4528 if (VT.isVector()) {
4529 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4530 return FoldedVOp;
4531
4532 // fold (mulhu x, 0) -> 0
4533 // do not return N1, because undef node may exist.
4534 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
4535 return DAG.getConstant(0, DL, VT);
4536 }
4537
4538 // fold (mulhu x, 0) -> 0
4539 if (isNullConstant(N1))
4540 return N1;
4541
4542 // fold (mulhu x, 1) -> 0
4543 if (isOneConstant(N1))
4544 return DAG.getConstant(0, DL, N0.getValueType());
4545
4546 // fold (mulhu x, undef) -> 0
4547 if (N0.isUndef() || N1.isUndef())
4548 return DAG.getConstant(0, DL, VT);
4549
4550 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4551 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4552 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
4553 unsigned NumEltBits = VT.getScalarSizeInBits();
4554 SDValue LogBase2 = BuildLogBase2(N1, DL);
4555 SDValue SRLAmt = DAG.getNode(
4556 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
4557 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4558 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
4559 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4560 }
4561
4562 // If the type twice as wide is legal, transform the mulhu to a wider multiply
4563 // plus a shift.
4564 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
4565 !VT.isVector()) {
4566 MVT Simple = VT.getSimpleVT();
4567 unsigned SimpleSize = Simple.getSizeInBits();
4568 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4569 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4570 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
4571 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
4572 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4573 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4574 DAG.getConstant(SimpleSize, DL,
4575 getShiftAmountTy(N1.getValueType())));
4576 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4577 }
4578 }
4579
4580 // Simplify the operands using demanded-bits information.
4581 // We don't have demanded bits support for MULHU so this just enables constant
4582 // folding based on known bits.
4583 if (SimplifyDemandedBits(SDValue(N, 0)))
4584 return SDValue(N, 0);
4585
4586 return SDValue();
4587}
4588
4589/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4590/// give the opcodes for the two computations that are being performed. Return
4591/// true if a simplification was made.
4592SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
4593 unsigned HiOp) {
4594 // If the high half is not needed, just compute the low half.
4595 bool HiExists = N->hasAnyUseOfValue(1);
4596 if (!HiExists && (!LegalOperations ||
4597 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
4598 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4599 return CombineTo(N, Res, Res);
4600 }
4601
4602 // If the low half is not needed, just compute the high half.
4603 bool LoExists = N->hasAnyUseOfValue(0);
4604 if (!LoExists && (!LegalOperations ||
4605 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
4606 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4607 return CombineTo(N, Res, Res);
4608 }
4609
4610 // If both halves are used, return as it is.
4611 if (LoExists && HiExists)
4612 return SDValue();
4613
4614 // If the two computed results can be simplified separately, separate them.
4615 if (LoExists) {
4616 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4617 AddToWorklist(Lo.getNode());
4618 SDValue LoOpt = combine(Lo.getNode());
4619 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
4620 (!LegalOperations ||
4621 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
4622 return CombineTo(N, LoOpt, LoOpt);
4623 }
4624
4625 if (HiExists) {
4626 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4627 AddToWorklist(Hi.getNode());
4628 SDValue HiOpt = combine(Hi.getNode());
4629 if (HiOpt.getNode() && HiOpt != Hi &&
4630 (!LegalOperations ||
4631 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
4632 return CombineTo(N, HiOpt, HiOpt);
4633 }
4634
4635 return SDValue();
4636}
4637
4638SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
4639 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
4640 return Res;
4641
4642 EVT VT = N->getValueType(0);
4643 SDLoc DL(N);
4644
4645 // If the type is twice as wide is legal, transform the mulhu to a wider
4646 // multiply plus a shift.
4647 if (VT.isSimple() && !VT.isVector()) {
4648 MVT Simple = VT.getSimpleVT();
4649 unsigned SimpleSize = Simple.getSizeInBits();
4650 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4651 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4652 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
4653 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
4654 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4655 // Compute the high part as N1.
4656 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4657 DAG.getConstant(SimpleSize, DL,
4658 getShiftAmountTy(Lo.getValueType())));
4659 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4660 // Compute the low part as N0.
4661 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4662 return CombineTo(N, Lo, Hi);
4663 }
4664 }
4665
4666 return SDValue();
4667}
4668
4669SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
4670 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
4671 return Res;
4672
4673 EVT VT = N->getValueType(0);
4674 SDLoc DL(N);
4675
4676 // (umul_lohi N0, 0) -> (0, 0)
4677 if (isNullConstant(N->getOperand(1))) {
4678 SDValue Zero = DAG.getConstant(0, DL, VT);
4679 return CombineTo(N, Zero, Zero);
4680 }
4681
4682 // (umul_lohi N0, 1) -> (N0, 0)
4683 if (isOneConstant(N->getOperand(1))) {
4684 SDValue Zero = DAG.getConstant(0, DL, VT);
4685 return CombineTo(N, N->getOperand(0), Zero);
4686 }
4687
4688 // If the type is twice as wide is legal, transform the mulhu to a wider
4689 // multiply plus a shift.
4690 if (VT.isSimple() && !VT.isVector()) {
4691 MVT Simple = VT.getSimpleVT();
4692 unsigned SimpleSize = Simple.getSizeInBits();
4693 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4694 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4695 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
4696 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
4697 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4698 // Compute the high part as N1.
4699 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4700 DAG.getConstant(SimpleSize, DL,
4701 getShiftAmountTy(Lo.getValueType())));
4702 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4703 // Compute the low part as N0.
4704 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4705 return CombineTo(N, Lo, Hi);
4706 }
4707 }
4708
4709 return SDValue();
4710}
4711
4712SDValue DAGCombiner::visitMULO(SDNode *N) {
4713 SDValue N0 = N->getOperand(0);
4714 SDValue N1 = N->getOperand(1);
4715 EVT VT = N0.getValueType();
4716 bool IsSigned = (ISD::SMULO == N->getOpcode());
4717
4718 EVT CarryVT = N->getValueType(1);
4719 SDLoc DL(N);
4720
4721 ConstantSDNode *N0C = isConstOrConstSplat(N0);
4722 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4723
4724 // fold operation with constant operands.
4725 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
4726 // multiple results.
4727 if (N0C && N1C) {
4728 bool Overflow;
4729 APInt Result =
4730 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
4731 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
4732 return CombineTo(N, DAG.getConstant(Result, DL, VT),
4733 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
4734 }
4735
4736 // canonicalize constant to RHS.
4737 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4738 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4739 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
4740
4741 // fold (mulo x, 0) -> 0 + no carry out
4742 if (isNullOrNullSplat(N1))
4743 return CombineTo(N, DAG.getConstant(0, DL, VT),
4744 DAG.getConstant(0, DL, CarryVT));
4745
4746 // (mulo x, 2) -> (addo x, x)
4747 if (N1C && N1C->getAPIntValue() == 2)
4748 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
4749 N->getVTList(), N0, N0);
4750
4751 if (IsSigned) {
4752 // A 1 bit SMULO overflows if both inputs are 1.
4753 if (VT.getScalarSizeInBits() == 1) {
4754 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
4755 return CombineTo(N, And,
4756 DAG.getSetCC(DL, CarryVT, And,
4757 DAG.getConstant(0, DL, VT), ISD::SETNE));
4758 }
4759
4760 // Multiplying n * m significant bits yields a result of n + m significant
4761 // bits. If the total number of significant bits does not exceed the
4762 // result bit width (minus 1), there is no overflow.
4763 unsigned SignBits = DAG.ComputeNumSignBits(N0);
4764 if (SignBits > 1)
4765 SignBits += DAG.ComputeNumSignBits(N1);
4766 if (SignBits > VT.getScalarSizeInBits() + 1)
4767 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
4768 DAG.getConstant(0, DL, CarryVT));
4769 } else {
4770 KnownBits N1Known = DAG.computeKnownBits(N1);
4771 KnownBits N0Known = DAG.computeKnownBits(N0);
4772 bool Overflow;
4773 (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow);
4774 if (!Overflow)
4775 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
4776 DAG.getConstant(0, DL, CarryVT));
4777 }
4778
4779 return SDValue();
4780}
4781
4782// Function to calculate whether the Min/Max pair of SDNodes (potentially
4783// swapped around) make a signed saturate pattern, clamping to between a signed
4784// saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
4785// Returns the node being clamped and the bitwidth of the clamp in BW. Should
4786// work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
4787// same as SimplifySelectCC. N0<N1 ? N2 : N3.
4788static SDValue isSaturatingMinMax(SDValue N0, SDValue N1, SDValue N2,
4789 SDValue N3, ISD::CondCode CC, unsigned &BW,
4790 bool &Unsigned) {
4791 auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
4792 ISD::CondCode CC) {
4793 // The compare and select operand should be the same or the select operands
4794 // should be truncated versions of the comparison.
4795 if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
4796 return 0;
4797 // The constants need to be the same or a truncated version of each other.
4798 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4799 ConstantSDNode *N3C = isConstOrConstSplat(N3);
4800 if (!N1C || !N3C)
4801 return 0;
4802 const APInt &C1 = N1C->getAPIntValue();
4803 const APInt &C2 = N3C->getAPIntValue();
4804 if (C1.getBitWidth() < C2.getBitWidth() ||
4805 C1 != C2.sextOrSelf(C1.getBitWidth()))
4806 return 0;
4807 return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
4808 };
4809
4810 // Check the initial value is a SMIN/SMAX equivalent.
4811 unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
4812 if (!Opcode0)
4813 return SDValue();
4814
4815 SDValue N00, N01, N02, N03;
4816 ISD::CondCode N0CC;
4817 switch (N0.getOpcode()) {
4818 case ISD::SMIN:
4819 case ISD::SMAX:
4820 N00 = N02 = N0.getOperand(0);
4821 N01 = N03 = N0.getOperand(1);
4822 N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
4823 break;
4824 case ISD::SELECT_CC:
4825 N00 = N0.getOperand(0);
4826 N01 = N0.getOperand(1);
4827 N02 = N0.getOperand(2);
4828 N03 = N0.getOperand(3);
4829 N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
4830 break;
4831 case ISD::SELECT:
4832 case ISD::VSELECT:
4833 if (N0.getOperand(0).getOpcode() != ISD::SETCC)
4834 return SDValue();
4835 N00 = N0.getOperand(0).getOperand(0);
4836 N01 = N0.getOperand(0).getOperand(1);
4837 N02 = N0.getOperand(1);
4838 N03 = N0.getOperand(2);
4839 N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
4840 break;
4841 default:
4842 return SDValue();
4843 }
4844
4845 unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
4846 if (!Opcode1 || Opcode0 == Opcode1)
4847 return SDValue();
4848
4849 ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
4850 ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
4851 if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
4852 return SDValue();
4853
4854 const APInt &MinC = MinCOp->getAPIntValue();
4855 const APInt &MaxC = MaxCOp->getAPIntValue();
4856 APInt MinCPlus1 = MinC + 1;
4857 if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
4858 BW = MinCPlus1.exactLogBase2() + 1;
4859 Unsigned = false;
4860 return N02;
4861 }
4862
4863 if (MaxC == 0 && MinCPlus1.isPowerOf2()) {
4864 BW = MinCPlus1.exactLogBase2();
4865 Unsigned = true;
4866 return N02;
4867 }
4868
4869 return SDValue();
4870}
4871
4872static SDValue PerformMinMaxFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
4873 SDValue N3, ISD::CondCode CC,
4874 SelectionDAG &DAG) {
4875 unsigned BW;
4876 bool Unsigned;
4877 SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned);
4878 if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
4879 return SDValue();
4880 EVT FPVT = Fp.getOperand(0).getValueType();
4881 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
4882 if (FPVT.isVector())
4883 NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
4884 FPVT.getVectorElementCount());
4885 unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
4886 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
4887 return SDValue();
4888 SDLoc DL(Fp);
4889 SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
4890 DAG.getValueType(NewVT.getScalarType()));
4891 return Unsigned ? DAG.getZExtOrTrunc(Sat, DL, N2->getValueType(0))
4892 : DAG.getSExtOrTrunc(Sat, DL, N2->getValueType(0));
4893}
4894
4895static SDValue PerformUMinFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
4896 SDValue N3, ISD::CondCode CC,
4897 SelectionDAG &DAG) {
4898 // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
4899 // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
4900 // be truncated versions of the the setcc (N0/N1).
4901 if ((N0 != N2 &&
4902 (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
4903 N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
4904 return SDValue();
4905 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4906 ConstantSDNode *N3C = isConstOrConstSplat(N3);
4907 if (!N1C || !N3C)
4908 return SDValue();
4909 const APInt &C1 = N1C->getAPIntValue();
4910 const APInt &C3 = N3C->getAPIntValue();
4911 if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
4912 C1 != C3.zextOrSelf(C1.getBitWidth()))
4913 return SDValue();
4914
4915 unsigned BW = (C1 + 1).exactLogBase2();
4916 EVT FPVT = N0.getOperand(0).getValueType();
4917 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
4918 if (FPVT.isVector())
4919 NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
4920 FPVT.getVectorElementCount());
4921 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(ISD::FP_TO_UINT_SAT,
4922 FPVT, NewVT))
4923 return SDValue();
4924
4925 SDValue Sat =
4926 DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
4927 DAG.getValueType(NewVT.getScalarType()));
4928 return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
4929}
4930
4931SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
4932 SDValue N0 = N->getOperand(0);
4933 SDValue N1 = N->getOperand(1);
4934 EVT VT = N0.getValueType();
4935 unsigned Opcode = N->getOpcode();
4936 SDLoc DL(N);
4937
4938 // fold operation with constant operands.
4939 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4940 return C;
4941
4942 // canonicalize constant to RHS
4943 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4944 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4945 return DAG.getNode(Opcode, DL, VT, N1, N0);
4946
4947 // fold vector ops
4948 if (VT.isVector())
4949 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4950 return FoldedVOp;
4951
4952 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4953 // Only do this if the current op isn't legal and the flipped is.
4954 if (!TLI.isOperationLegal(Opcode, VT) &&
4955 (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
4956 (N1.isUndef() || DAG.SignBitIsZero(N1))) {
4957 unsigned AltOpcode;
4958 switch (Opcode) {
4959 case ISD::SMIN: AltOpcode = ISD::UMIN; break;
4960 case ISD::SMAX: AltOpcode = ISD::UMAX; break;
4961 case ISD::UMIN: AltOpcode = ISD::SMIN; break;
4962 case ISD::UMAX: AltOpcode = ISD::SMAX; break;
4963 default: llvm_unreachable("Unknown MINMAX opcode")::llvm::llvm_unreachable_internal("Unknown MINMAX opcode", "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4963)
;
4964 }
4965 if (TLI.isOperationLegal(AltOpcode, VT))
4966 return DAG.getNode(AltOpcode, DL, VT, N0, N1);
4967 }
4968
4969 if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
4970 if (SDValue S = PerformMinMaxFpToSatCombine(
4971 N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
4972 return S;
4973 if (Opcode == ISD::UMIN)
4974 if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
4975 return S;
4976
4977 // Simplify the operands using demanded-bits information.
4978 if (SimplifyDemandedBits(SDValue(N, 0)))
4979 return SDValue(N, 0);
4980
4981 return SDValue();
4982}
4983
4984/// If this is a bitwise logic instruction and both operands have the same
4985/// opcode, try to sink the other opcode after the logic instruction.
4986SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
4987 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
4988 EVT VT = N0.getValueType();
4989 unsigned LogicOpcode = N->getOpcode();
4990 unsigned HandOpcode = N0.getOpcode();
4991 assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||(static_cast <bool> ((LogicOpcode == ISD::AND || LogicOpcode
== ISD::OR || LogicOpcode == ISD::XOR) && "Expected logic opcode"
) ? void (0) : __assert_fail ("(LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && \"Expected logic opcode\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 4992, __extension__
__PRETTY_FUNCTION__))
4992 LogicOpcode == ISD::XOR) && "Expected logic opcode")(static_cast <bool> ((LogicOpcode == ISD::AND || LogicOpcode
== ISD::OR || LogicOpcode == ISD::XOR) && "Expected logic opcode"
) ? void (0) : __assert_fail ("(LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && \"Expected logic opcode\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 4992, __extension__
__PRETTY_FUNCTION__))
;
4993 assert(HandOpcode == N1.getOpcode() && "Bad input!")(static_cast <bool> (HandOpcode == N1.getOpcode() &&
"Bad input!") ? void (0) : __assert_fail ("HandOpcode == N1.getOpcode() && \"Bad input!\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 4993, __extension__
__PRETTY_FUNCTION__))
;
4994
4995 // Bail early if none of these transforms apply.
4996 if (N0.getNumOperands() == 0)
4997 return SDValue();
4998
4999 // FIXME: We should check number of uses of the operands to not increase
5000 // the instruction count for all transforms.
5001
5002 // Handle size-changing casts.
5003 SDValue X = N0.getOperand(0);
5004 SDValue Y = N1.getOperand(0);
5005 EVT XVT = X.getValueType();
5006 SDLoc DL(N);
5007 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
5008 HandOpcode == ISD::SIGN_EXTEND) {
5009 // If both operands have other uses, this transform would create extra
5010 // instructions without eliminating anything.
5011 if (!N0.hasOneUse() && !N1.hasOneUse())
5012 return SDValue();
5013 // We need matching integer source types.
5014 if (XVT != Y.getValueType())
5015 return SDValue();
5016 // Don't create an illegal op during or after legalization. Don't ever
5017 // create an unsupported vector op.
5018 if ((VT.isVector() || LegalOperations) &&
5019 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
5020 return SDValue();
5021 // Avoid infinite looping with PromoteIntBinOp.
5022 // TODO: Should we apply desirable/legal constraints to all opcodes?
5023 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
5024 !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
5025 return SDValue();
5026 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
5027 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
5028 return DAG.getNode(HandOpcode, DL, VT, Logic);
5029 }
5030
5031 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
5032 if (HandOpcode == ISD::TRUNCATE) {
5033 // If both operands have other uses, this transform would create extra
5034 // instructions without eliminating anything.
5035 if (!N0.hasOneUse() && !N1.hasOneUse())
5036 return SDValue();
5037 // We need matching source types.
5038 if (XVT != Y.getValueType())
5039 return SDValue();
5040 // Don't create an illegal op during or after legalization.
5041 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
5042 return SDValue();
5043 // Be extra careful sinking truncate. If it's free, there's no benefit in
5044 // widening a binop. Also, don't create a logic op on an illegal type.
5045 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
5046 return SDValue();
5047 if (!TLI.isTypeLegal(XVT))
5048 return SDValue();
5049 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
5050 return DAG.getNode(HandOpcode, DL, VT, Logic);
5051 }
5052
5053 // For binops SHL/SRL/SRA/AND:
5054 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
5055 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
5056 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
5057 N0.getOperand(1) == N1.getOperand(1)) {
5058 // If either operand has other uses, this transform is not an improvement.
5059 if (!N0.hasOneUse() || !N1.hasOneUse())
5060 return SDValue();
5061 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
5062 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
5063 }
5064
5065 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
5066 if (HandOpcode == ISD::BSWAP) {
5067 // If either operand has other uses, this transform is not an improvement.
5068 if (!N0.hasOneUse() || !N1.hasOneUse())
5069 return SDValue();
5070 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
5071 return DAG.getNode(HandOpcode, DL, VT, Logic);
5072 }
5073
5074 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
5075 // Only perform this optimization up until type legalization, before
5076 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
5077 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
5078 // we don't want to undo this promotion.
5079 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
5080 // on scalars.
5081 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
5082 Level <= AfterLegalizeTypes) {
5083 // Input types must be integer and the same.
5084 if (XVT.isInteger() && XVT == Y.getValueType() &&
5085 !(VT.isVector() && TLI.isTypeLegal(VT) &&
5086 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
5087 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
5088 return DAG.getNode(HandOpcode, DL, VT, Logic);
5089 }
5090 }
5091
5092 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
5093 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
5094 // If both shuffles use the same mask, and both shuffle within a single
5095 // vector, then it is worthwhile to move the swizzle after the operation.
5096 // The type-legalizer generates this pattern when loading illegal
5097 // vector types from memory. In many cases this allows additional shuffle
5098 // optimizations.
5099 // There are other cases where moving the shuffle after the xor/and/or
5100 // is profitable even if shuffles don't perform a swizzle.
5101 // If both shuffles use the same mask, and both shuffles have the same first
5102 // or second operand, then it might still be profitable to move the shuffle
5103 // after the xor/and/or operation.
5104 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
5105 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
5106 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
5107 assert(X.getValueType() == Y.getValueType() &&(static_cast <bool> (X.getValueType() == Y.getValueType
() && "Inputs to shuffles are not the same type") ? void
(0) : __assert_fail ("X.getValueType() == Y.getValueType() && \"Inputs to shuffles are not the same type\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5108, __extension__
__PRETTY_FUNCTION__))
5108 "Inputs to shuffles are not the same type")(static_cast <bool> (X.getValueType() == Y.getValueType
() && "Inputs to shuffles are not the same type") ? void
(0) : __assert_fail ("X.getValueType() == Y.getValueType() && \"Inputs to shuffles are not the same type\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5108, __extension__
__PRETTY_FUNCTION__))
;
5109
5110 // Check that both shuffles use the same mask. The masks are known to be of
5111 // the same length because the result vector type is the same.
5112 // Check also that shuffles have only one use to avoid introducing extra
5113 // instructions.
5114 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
5115 !SVN0->getMask().equals(SVN1->getMask()))
5116 return SDValue();
5117
5118 // Don't try to fold this node if it requires introducing a
5119 // build vector of all zeros that might be illegal at this stage.
5120 SDValue ShOp = N0.getOperand(1);
5121 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
5122 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
5123
5124 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
5125 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
5126 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
5127 N0.getOperand(0), N1.getOperand(0));
5128 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
5129 }
5130
5131 // Don't try to fold this node if it requires introducing a
5132 // build vector of all zeros that might be illegal at this stage.
5133 ShOp = N0.getOperand(0);
5134 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
5135 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
5136
5137 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
5138 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
5139 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
5140 N1.getOperand(1));
5141 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
5142 }
5143 }
5144
5145 return SDValue();
5146}
5147
5148/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
5149SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
5150 const SDLoc &DL) {
5151 SDValue LL, LR, RL, RR, N0CC, N1CC;
5152 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
5153 !isSetCCEquivalent(N1, RL, RR, N1CC))
5154 return SDValue();
5155
5156 assert(N0.getValueType() == N1.getValueType() &&(static_cast <bool> (N0.getValueType() == N1.getValueType
() && "Unexpected operand types for bitwise logic op"
) ? void (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5157, __extension__
__PRETTY_FUNCTION__))
5157 "Unexpected operand types for bitwise logic op")(static_cast <bool> (N0.getValueType() == N1.getValueType
() && "Unexpected operand types for bitwise logic op"
) ? void (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5157, __extension__
__PRETTY_FUNCTION__))
;
5158 assert(LL.getValueType() == LR.getValueType() &&(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5160, __extension__
__PRETTY_FUNCTION__))
5159 RL.getValueType() == RR.getValueType() &&(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5160, __extension__
__PRETTY_FUNCTION__))
5160 "Unexpected operand types for setcc")(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5160, __extension__
__PRETTY_FUNCTION__))
;
5161
5162 // If we're here post-legalization or the logic op type is not i1, the logic
5163 // op type must match a setcc result type. Also, all folds require new
5164 // operations on the left and right operands, so those types must match.
5165 EVT VT = N0.getValueType();
5166 EVT OpVT = LL.getValueType();
5167 if (LegalOperations || VT.getScalarType() != MVT::i1)
5168 if (VT != getSetCCResultType(OpVT))
5169 return SDValue();
5170 if (OpVT != RL.getValueType())
5171 return SDValue();
5172
5173 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
5174 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
5175 bool IsInteger = OpVT.isInteger();
5176 if (LR == RR && CC0 == CC1 && IsInteger) {
5177 bool IsZero = isNullOrNullSplat(LR);
5178 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
5179
5180 // All bits clear?
5181 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
5182 // All sign bits clear?
5183 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
5184 // Any bits set?
5185 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
5186 // Any sign bits set?
5187 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
5188
5189 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
5190 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
5191 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
5192 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
5193 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
5194 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
5195 AddToWorklist(Or.getNode());
5196 return DAG.getSetCC(DL, VT, Or, LR, CC1);
5197 }
5198
5199 // All bits set?
5200 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
5201 // All sign bits set?
5202 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
5203 // Any bits clear?
5204 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
5205 // Any sign bits clear?
5206 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
5207
5208 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
5209 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
5210 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
5211 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
5212 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
5213 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
5214 AddToWorklist(And.getNode());
5215 return DAG.getSetCC(DL, VT, And, LR, CC1);
5216 }
5217 }
5218
5219 // TODO: What is the 'or' equivalent of this fold?
5220 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
5221 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
5222 IsInteger && CC0 == ISD::SETNE &&
5223 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
5224 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
5225 SDValue One = DAG.getConstant(1, DL, OpVT);
5226 SDValue Two = DAG.getConstant(2, DL, OpVT);
5227 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
5228 AddToWorklist(Add.getNode());
5229 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
5230 }
5231
5232 // Try more general transforms if the predicates match and the only user of
5233 // the compares is the 'and' or 'or'.
5234 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
5235 N0.hasOneUse() && N1.hasOneUse()) {
5236 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
5237 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
5238 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
5239 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
5240 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
5241 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
5242 SDValue Zero = DAG.getConstant(0, DL, OpVT);
5243 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
5244 }
5245
5246 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
5247 // TODO - support non-uniform vector amounts.
5248 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
5249 // Match a shared variable operand and 2 non-opaque constant operands.
5250 ConstantSDNode *C0 = isConstOrConstSplat(LR);
5251 ConstantSDNode *C1 = isConstOrConstSplat(RR);
5252 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
5253 const APInt &CMax =
5254 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
5255 const APInt &CMin =
5256 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
5257 // The difference of the constants must be a single bit.
5258 if ((CMax - CMin).isPowerOf2()) {
5259 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
5260 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
5261 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
5262 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
5263 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
5264 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
5265 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
5266 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
5267 SDValue Zero = DAG.getConstant(0, DL, OpVT);
5268 return DAG.getSetCC(DL, VT, And, Zero, CC0);
5269 }
5270 }
5271 }
5272 }
5273
5274 // Canonicalize equivalent operands to LL == RL.
5275 if (LL == RR && LR == RL) {
5276 CC1 = ISD::getSetCCSwappedOperands(CC1);
5277 std::swap(RL, RR);
5278 }
5279
5280 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
5281 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
5282 if (LL == RL && LR == RR) {
5283 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
5284 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
5285 if (NewCC != ISD::SETCC_INVALID &&
5286 (!LegalOperations ||
5287 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
5288 TLI.isOperationLegal(ISD::SETCC, OpVT))))
5289 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
5290 }
5291
5292 return SDValue();
5293}
5294
5295/// This contains all DAGCombine rules which reduce two values combined by
5296/// an And operation to a single value. This makes them reusable in the context
5297/// of visitSELECT(). Rules involving constants are not included as
5298/// visitSELECT() already handles those cases.
5299SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
5300 EVT VT = N1.getValueType();
5301 SDLoc DL(N);
5302
5303 // fold (and x, undef) -> 0
5304 if (N0.isUndef() || N1.isUndef())
5305 return DAG.getConstant(0, DL, VT);
5306
5307 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
5308 return V;
5309
5310 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
5311 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
5312 VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
5313 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5314 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
5315 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
5316 // immediate for an add, but it is legal if its top c2 bits are set,
5317 // transform the ADD so the immediate doesn't need to be materialized
5318 // in a register.
5319 APInt ADDC = ADDI->getAPIntValue();
5320 APInt SRLC = SRLI->getAPIntValue();
5321 if (ADDC.getMinSignedBits() <= 64 &&
5322 SRLC.ult(VT.getSizeInBits()) &&
5323 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
5324 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
5325 SRLC.getZExtValue());
5326 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
5327 ADDC |= Mask;
5328 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
5329 SDLoc DL0(N0);
5330 SDValue NewAdd =
5331 DAG.getNode(ISD::ADD, DL0, VT,
5332 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
5333 CombineTo(N0.getNode(), NewAdd);
5334 // Return N so it doesn't get rechecked!
5335 return SDValue(N, 0);
5336 }
5337 }
5338 }
5339 }
5340 }
5341 }
5342
5343 // Reduce bit extract of low half of an integer to the narrower type.
5344 // (and (srl i64:x, K), KMask) ->
5345 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
5346 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5347 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
5348 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5349 unsigned Size = VT.getSizeInBits();
5350 const APInt &AndMask = CAnd->getAPIntValue();
5351 unsigned ShiftBits = CShift->getZExtValue();
5352
5353 // Bail out, this node will probably disappear anyway.
5354 if (ShiftBits == 0)
5355 return SDValue();
5356
5357 unsigned MaskBits = AndMask.countTrailingOnes();
5358 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
5359
5360 if (AndMask.isMask() &&
5361 // Required bits must not span the two halves of the integer and
5362 // must fit in the half size type.
5363 (ShiftBits + MaskBits <= Size / 2) &&
5364 TLI.isNarrowingProfitable(VT, HalfVT) &&
5365 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
5366 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
5367 TLI.isTruncateFree(VT, HalfVT) &&
5368 TLI.isZExtFree(HalfVT, VT)) {
5369 // The isNarrowingProfitable is to avoid regressions on PPC and
5370 // AArch64 which match a few 64-bit bit insert / bit extract patterns
5371 // on downstream users of this. Those patterns could probably be
5372 // extended to handle extensions mixed in.
5373
5374 SDValue SL(N0);
5375 assert(MaskBits <= Size)(static_cast <bool> (MaskBits <= Size) ? void (0) : __assert_fail
("MaskBits <= Size", "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5375, __extension__ __PRETTY_FUNCTION__))
;
5376
5377 // Extracting the highest bit of the low half.
5378 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
5379 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
5380 N0.getOperand(0));
5381
5382 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
5383 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
5384 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
5385 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
5386 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
5387 }
5388 }
5389 }
5390 }
5391
5392 return SDValue();
5393}
5394
5395bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
5396 EVT LoadResultTy, EVT &ExtVT) {
5397 if (!AndC->getAPIntValue().isMask())
5398 return false;
5399
5400 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
5401
5402 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
5403 EVT LoadedVT = LoadN->getMemoryVT();
5404
5405 if (ExtVT == LoadedVT &&
5406 (!LegalOperations ||
5407 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
5408 // ZEXTLOAD will match without needing to change the size of the value being
5409 // loaded.
5410 return true;
5411 }
5412
5413 // Do not change the width of a volatile or atomic loads.
5414 if (!LoadN->isSimple())
5415 return false;
5416
5417 // Do not generate loads of non-round integer types since these can
5418 // be expensive (and would be wrong if the type is not byte sized).
5419 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
5420 return false;
5421
5422 if (LegalOperations &&
5423 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
5424 return false;
5425
5426 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
5427 return false;
5428
5429 return true;
5430}
5431
5432bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
5433 ISD::LoadExtType ExtType, EVT &MemVT,
5434 unsigned ShAmt) {
5435 if (!LDST)
5436 return false;
5437 // Only allow byte offsets.
5438 if (ShAmt % 8)
5439 return false;
5440
5441 // Do not generate loads of non-round integer types since these can
5442 // be expensive (and would be wrong if the type is not byte sized).
5443 if (!MemVT.isRound())
5444 return false;
5445
5446 // Don't change the width of a volatile or atomic loads.
5447 if (!LDST->isSimple())
5448 return false;
5449
5450 EVT LdStMemVT = LDST->getMemoryVT();
5451
5452 // Bail out when changing the scalable property, since we can't be sure that
5453 // we're actually narrowing here.
5454 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
5455 return false;
5456
5457 // Verify that we are actually reducing a load width here.
5458 if (LdStMemVT.bitsLT(MemVT))
5459 return false;
5460
5461 // Ensure that this isn't going to produce an unsupported memory access.
5462 if (ShAmt) {
5463 assert(ShAmt % 8 == 0 && "ShAmt is byte offset")(static_cast <bool> (ShAmt % 8 == 0 && "ShAmt is byte offset"
) ? void (0) : __assert_fail ("ShAmt % 8 == 0 && \"ShAmt is byte offset\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5463, __extension__
__PRETTY_FUNCTION__))
;
5464 const unsigned ByteShAmt = ShAmt / 8;
5465 const Align LDSTAlign = LDST->getAlign();
5466 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
5467 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5468 LDST->getAddressSpace(), NarrowAlign,
5469 LDST->getMemOperand()->getFlags()))
5470 return false;
5471 }
5472
5473 // It's not possible to generate a constant of extended or untyped type.
5474 EVT PtrType = LDST->getBasePtr().getValueType();
5475 if (PtrType == MVT::Untyped || PtrType.isExtended())
5476 return false;
5477
5478 if (isa<LoadSDNode>(LDST)) {
5479 LoadSDNode *Load = cast<LoadSDNode>(LDST);
5480 // Don't transform one with multiple uses, this would require adding a new
5481 // load.
5482 if (!SDValue(Load, 0).hasOneUse())
5483 return false;
5484
5485 if (LegalOperations &&
5486 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
5487 return false;
5488
5489 // For the transform to be legal, the load must produce only two values
5490 // (the value loaded and the chain). Don't transform a pre-increment
5491 // load, for example, which produces an extra value. Otherwise the
5492 // transformation is not equivalent, and the downstream logic to replace
5493 // uses gets things wrong.
5494 if (Load->getNumValues() > 2)
5495 return false;
5496
5497 // If the load that we're shrinking is an extload and we're not just
5498 // discarding the extension we can't simply shrink the load. Bail.
5499 // TODO: It would be possible to merge the extensions in some cases.
5500 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
5501 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
5502 return false;
5503
5504 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
5505 return false;
5506 } else {
5507 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode")(static_cast <bool> (isa<StoreSDNode>(LDST) &&
"It is not a Load nor a Store SDNode") ? void (0) : __assert_fail
("isa<StoreSDNode>(LDST) && \"It is not a Load nor a Store SDNode\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5507, __extension__
__PRETTY_FUNCTION__))
;
5508 StoreSDNode *Store = cast<StoreSDNode>(LDST);
5509 // Can't write outside the original store
5510 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
5511 return false;
5512
5513 if (LegalOperations &&
5514 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
5515 return false;
5516 }
5517 return true;
5518}
5519
5520bool DAGCombiner::SearchForAndLoads(SDNode *N,
5521 SmallVectorImpl<LoadSDNode*> &Loads,
5522 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
5523 ConstantSDNode *Mask,
5524 SDNode *&NodeToMask) {
5525 // Recursively search for the operands, looking for loads which can be
5526 // narrowed.
5527 for (SDValue Op : N->op_values()) {
5528 if (Op.getValueType().isVector())
5529 return false;
5530
5531 // Some constants may need fixing up later if they are too large.
5532 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
5533 if (Mask->getValueType(0) != C->getValueType(0))
5534 return false;
5535 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
5536 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
5537 NodesWithConsts.insert(N);
5538 continue;
5539 }
5540
5541 if (!Op.hasOneUse())
5542 return false;
5543
5544 switch(Op.getOpcode()) {
5545 case ISD::LOAD: {
5546 auto *Load = cast<LoadSDNode>(Op);
5547 EVT ExtVT;
5548 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
5549 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
5550
5551 // ZEXTLOAD is already small enough.
5552 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
5553 ExtVT.bitsGE(Load->getMemoryVT()))
5554 continue;
5555
5556 // Use LE to convert equal sized loads to zext.
5557 if (ExtVT.bitsLE(Load->getMemoryVT()))
5558 Loads.push_back(Load);
5559
5560 continue;
5561 }
5562 return false;
5563 }
5564 case ISD::ZERO_EXTEND:
5565 case ISD::AssertZext: {
5566 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
5567 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
5568 EVT VT = Op.getOpcode() == ISD::AssertZext
5569 ? cast<VTSDNode>(Op.getOperand(1))->getVT()
5570 : Op.getOperand(0).getValueType();
5571
5572 // We can accept extending nodes if the mask is wider or an equal
5573 // width to the original type.
5574 if (ExtVT.bitsGE(VT))
5575 continue;
5576 break;
5577 }
5578 case ISD::ANY_EXTEND: {
5579 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
5580 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
5581 EVT VT = Op.getOperand(0).getValueType();
5582 if (ExtVT.bitsGE(VT))
5583 break;
5584 // Fallthrough to searching for nodes from the operands of the extend.
5585 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5586 }
5587 case ISD::OR:
5588 case ISD::XOR:
5589 case ISD::AND:
5590 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
5591 NodeToMask))
5592 return false;
5593 continue;
5594 }
5595
5596 // Allow one node which will masked along with any loads found.
5597 if (NodeToMask)
5598 return false;
5599
5600 // Also ensure that the node to be masked only produces one data result.
5601 NodeToMask = Op.getNode();
5602 if (NodeToMask->getNumValues() > 1) {
5603 bool HasValue = false;
5604 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
5605 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
5606 if (VT != MVT::Glue && VT != MVT::Other) {
5607 if (HasValue) {
5608 NodeToMask = nullptr;
5609 return false;
5610 }
5611 HasValue = true;
5612 }
5613 }
5614 assert(HasValue && "Node to be masked has no data result?")(static_cast <bool> (HasValue && "Node to be masked has no data result?"
) ? void (0) : __assert_fail ("HasValue && \"Node to be masked has no data result?\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5614, __extension__
__PRETTY_FUNCTION__))
;
5615 }
5616 }
5617 return true;
5618}
5619
5620bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
5621 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
5622 if (!Mask)
5623 return false;
5624
5625 if (!Mask->getAPIntValue().isMask())
5626 return false;
5627
5628 // No need to do anything if the and directly uses a load.
5629 if (isa<LoadSDNode>(N->getOperand(0)))
5630 return false;
5631
5632 SmallVector<LoadSDNode*, 8> Loads;
5633 SmallPtrSet<SDNode*, 2> NodesWithConsts;
5634 SDNode *FixupNode = nullptr;
5635 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
5636 if (Loads.size() == 0)
5637 return false;
5638
5639 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "Backwards propagate AND: "
; N->dump(); } } while (false)
;
5640 SDValue MaskOp = N->getOperand(1);
5641
5642 // If it exists, fixup the single node we allow in the tree that needs
5643 // masking.
5644 if (FixupNode) {
5645 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "First, need to fix up: "; FixupNode
->dump(); } } while (false)
;
5646 SDValue MaskOpT = DAG.getZExtOrTrunc(MaskOp, SDLoc(FixupNode),
5647 FixupNode->getValueType(0));
5648 SDValue And =
5649 DAG.getNode(ISD::AND, SDLoc(FixupNode), FixupNode->getValueType(0),
5650 SDValue(FixupNode, 0), MaskOpT);
5651 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
5652 if (And.getOpcode() == ISD ::AND)
5653 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOpT);
5654 }
5655
5656 // Narrow any constants that need it.
5657 for (auto *LogicN : NodesWithConsts) {
5658 SDValue Op0 = LogicN->getOperand(0);
5659 SDValue Op1 = LogicN->getOperand(1);
5660
5661 if (isa<ConstantSDNode>(Op0))
5662 std::swap(Op0, Op1);
5663
5664 SDValue MaskOpT =
5665 DAG.getZExtOrTrunc(MaskOp, SDLoc(Op1), Op1.getValueType());
5666 SDValue And =
5667 DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), Op1, MaskOpT);
5668
5669 DAG.UpdateNodeOperands(LogicN, Op0, And);
5670 }
5671
5672 // Create narrow loads.
5673 for (auto *Load : Loads) {
5674 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "Propagate AND back to: "; Load
->dump(); } } while (false)
;
5675 SDValue MaskOpT =
5676 DAG.getZExtOrTrunc(MaskOp, SDLoc(Load), Load->getValueType(0));
5677 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
5678 SDValue(Load, 0), MaskOpT);
5679 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
5680 if (And.getOpcode() == ISD ::AND)
5681 And = SDValue(
5682 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOpT), 0);
5683 SDValue NewLoad = reduceLoadWidth(And.getNode());
5684 assert(NewLoad &&(static_cast <bool> (NewLoad && "Shouldn't be masking the load if it can't be narrowed"
) ? void (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5685, __extension__
__PRETTY_FUNCTION__))
5685 "Shouldn't be masking the load if it can't be narrowed")(static_cast <bool> (NewLoad && "Shouldn't be masking the load if it can't be narrowed"
) ? void (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5685, __extension__
__PRETTY_FUNCTION__))
;
5686 CombineTo(Load, NewLoad, NewLoad.getValue(1));
5687 }
5688 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
5689 return true;
5690 }
5691 return false;
5692}
5693
5694// Unfold
5695// x & (-1 'logical shift' y)
5696// To
5697// (x 'opposite logical shift' y) 'logical shift' y
5698// if it is better for performance.
5699SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
5700 assert(N->getOpcode() == ISD::AND)(static_cast <bool> (N->getOpcode() == ISD::AND) ? void
(0) : __assert_fail ("N->getOpcode() == ISD::AND", "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5700, __extension__ __PRETTY_FUNCTION__))
;
5701
5702 SDValue N0 = N->getOperand(0);
5703 SDValue N1 = N->getOperand(1);
5704
5705 // Do we actually prefer shifts over mask?
5706 if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
5707 return SDValue();
5708
5709 // Try to match (-1 '[outer] logical shift' y)
5710 unsigned OuterShift;
5711 unsigned InnerShift; // The opposite direction to the OuterShift.
5712 SDValue Y; // Shift amount.
5713 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
5714 if (!M.hasOneUse())
5715 return false;
5716 OuterShift = M->getOpcode();
5717 if (OuterShift == ISD::SHL)
5718 InnerShift = ISD::SRL;
5719 else if (OuterShift == ISD::SRL)
5720 InnerShift = ISD::SHL;
5721 else
5722 return false;
5723 if (!isAllOnesConstant(M->getOperand(0)))
5724 return false;
5725 Y = M->getOperand(1);
5726 return true;
5727 };
5728
5729 SDValue X;
5730 if (matchMask(N1))
5731 X = N0;
5732 else if (matchMask(N0))
5733 X = N1;
5734 else
5735 return SDValue();
5736
5737 SDLoc DL(N);
5738 EVT VT = N->getValueType(0);
5739
5740 // tmp = x 'opposite logical shift' y
5741 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
5742 // ret = tmp 'logical shift' y
5743 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
5744
5745 return T1;
5746}
5747
5748/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
5749/// For a target with a bit test, this is expected to become test + set and save
5750/// at least 1 instruction.
5751static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) {
5752 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op")(static_cast <bool> (And->getOpcode() == ISD::AND &&
"Expected an 'and' op") ? void (0) : __assert_fail ("And->getOpcode() == ISD::AND && \"Expected an 'and' op\""
, "llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp", 5752, __extension__
__PRETTY_FUNCTION__))
;
5753
5754 // This is probably not worthwhile without a supported type.
5755 EVT VT = And->getValueType(0);
5756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5757 if (!TLI.isTypeLegal(VT))
5758 return SDValue();
5759
5760 // Look through an optional extension and find a 'not'.
5761 // TODO: Should we favor test+set even without the 'not' op?
5762 SDValue Not = And->getOperand(0), And1 = And->getOperand(1);
5763 if (Not.getOpcode() == ISD::ANY_EXTEND)
5764 Not = Not.getOperand(0);
5765 if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1))
5766 return SDValue();
5767
5768 // Look though an optional truncation. The source operand may not be the same
5769 // type as the original 'and', but that is ok because we are masking off
5770 // everything but the low bit.
5771 SDValue Srl = Not.getOperand(0);
5772 if (Srl.getOpcode() == ISD::TRUNCATE)
5773 Srl = Srl.getOperand(0);
5774
5775 // Match a shift-right by constant.
5776 if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() ||
5777 !isa<ConstantSDNode>(Srl.getOperand(1)))
5778 return SDValue();
5779
5780 // We might have looked through casts that make this transform invalid.
5781 // TODO: If the source type is wider than the result type, do the mask and
5782 // compare in the source type.
5783 const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1);
5784 unsigned VTBitWidth = VT.getSizeInBits();
5785 if (ShiftAmt.uge(VTBitWidth))
5786 return SDValue();
5787
5788 // Turn this into a bit-test pattern using mask op + setcc:
5789 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
5790 SDLoc DL(And);
5791 SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT);
5792 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5793 SDValue Mask = DAG.getConstant(
5794 APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT);
5795 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask);
5796 SDValue Zero = DAG.getConstant(0, DL, VT);
5797 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
5798 return DAG.getZExtOrTrunc(Setcc, DL, VT);
5799}
5800
5801/// For targets that support usubsat, match a bit-hack form of that operation
5802/// that ends in 'and' and convert it.
5803static SDValue foldAndToUsubsat(SDNode *N, SelectionDAG &DAG) {
5804 SDValue N0 = N->getOperand(0);
5805 SDValue N1 = N->getOperand(1);
5806 EVT VT = N1.getValueType();
5807
5808 // Canonicalize SRA as operand 1.
5809 if (N0.getOpcode() == ISD::SRA)
5810 std::swap(N0, N1);
5811
5812 // xor/add with SMIN (signmask) are logically equivalent.
5813 if (N0.getOpcode() != ISD::XOR && N0.getOpcode() != ISD::ADD)
5814 return SDValue();
5815
5816 if (N1.getOpcode() != ISD::SRA || !N0.hasOneUse() || !N1.hasOneUse() ||
5817 N0.getOperand(0) != N1.getOperand(0))
5818 return SDValue();
5819
5820 unsigned BitWidth = VT.getScalarSizeInBits();
5821 ConstantSDNode *XorC = isConstOrConstSplat(N0.getOperand(1), true);
5822 ConstantSDNode *SraC = isConstOrConstSplat(N1.getOperand(1), true);
5823 if (!XorC || !XorC->getAPIntValue().isSignMask() ||
5824 !SraC || SraC->getAPIntValue() != BitWidth - 1)
5825 return SDValue();
5826
5827 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
5828 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
5829 SDLoc DL(N);
5830 SDValue SignMask = DAG.getConstant(XorC->getAPIntValue(), DL, VT);
5831 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), SignMask);
5832}
5833
5834SDValue DAGCombiner::visitAND(SDNode *N) {
5835 SDValue N0 = N->getOperand(0);
5836 SDValue N1 = N->getOperand(1);
5837 EVT VT = N1.getValueType();
5838
5839 // x & x --> x
5840 if (N0 == N1)
5841 return N0;
5842
5843 // fold (and c1, c2) -> c1&c2
5844 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1}))
5845 return C;
5846
5847 // canonicalize constant to RHS
5848 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5849 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5850 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
5851
5852 // fold vector ops
5853 if (VT.isVector()) {
5854 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
5855 return FoldedVOp;
5856
5857 // fold (and x, 0) -> 0, vector edition
5858 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
5859 // do not return N1, because undef node may exist in N1
5860 return DAG.getConstant(APInt::getZero(N1.getScalarValueSizeInBits()),
5861 SDLoc(N), N1.getValueType());
5862
5863 // fold (and x, -1) -> x, vector edition
5864 if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
5865 return N0;
5866
5867 // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load
5868 auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0);
5869 auto *BVec = dyn_cast<BuildVectorSDNode>(N1);
5870 if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD &&
5871 N0.hasOneUse() && N1.hasOneUse()) {
5872 EVT LoadVT = MLoad->getMemoryVT();
5873 EVT ExtVT = VT;
5874 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) {
5875 // For this AND to be a zero extension of the masked load the elements
5876 // of the BuildVec must mask the bottom bits of the extended element
5877 // type
5878 if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) {
5879 uint64_t ElementSize =
5880 LoadVT.getVectorElementType().getScalarSizeInBits();
5881 if (Splat->getAPIntValue().isMask(ElementSize)) {
5882 return DAG.getMaskedLoad(
5883 ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(),
5884 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(),
5885 LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(),
5886 ISD::ZEXTLOAD, MLoad->isExpandingLoad());
5887 }
5888 }
5889 }
5890 }
5891 }
5892
5893 // fold (and x, -1) -> x
5894 if (isAllOnesConstant(N1))
5895 return N0;
5896
5897 // if (and x, c) is known to be zero, return 0
5898 unsigned BitWidth = VT.getScalarSizeInBits();
5899 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5900 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(BitWidth)))
5901 return DAG.getConstant(0, SDLoc(N), VT);
5902
5903 if (SDValue NewSel = foldBinOpIntoSelect(N))
5904 return NewSel;
5905
5906 // reassociate and
5907 if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
5908 return RAND;
5909
5910 // Try to convert a constant mask AND into a shuffle clear mask.
5911 if (VT.isVector())
5912 if (SDValue Shuffle = XformToShuffleWithZero(N))
5913 return Shuffle;
5914
5915 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
5916 return Combined;
5917
5918 // fold (and (or x, C), D) -> D if (C & D) == D
5919 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
5920 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
5921 };
5922 if (N0.getOpcode() == ISD::OR &&
5923 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
5924 return N1;
5925 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5926 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5927 SDValue N0Op0 = N0.getOperand(0);
5928 APInt Mask = ~N1C->getAPIntValue();
5929 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
5930 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
5931 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
5932 N0.getValueType(), N0Op0);
5933
5934 // Replace uses of the AND with uses of the Zero extend node.
5935 CombineTo(N, Zext);
5936
5937 // We actually want to replace all uses of the any_extend with the
5938 // zero_extend, to avoid duplicating things. This will later cause this
5939 // AND to be folded.
5940 CombineTo(N0.getNode(), Zext);
5941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5942 }
5943 }
5944
5945 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5946 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5947 // already be zero by virtue of the width of the base type of the load.
5948 //
5949 // the 'X' node here can either be nothing or an extract_vector_elt to catch
5950 // more cases.
5951 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5952 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
5953 N0.getOperand(0).getOpcode() == ISD::LOAD &&
5954 N0.getOperand(0).getResNo() == 0) ||
5955 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
5956 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
5957 N0 : N0.getOperand(0) );
5958
5959 // Get the constant (if applicable) the zero'th operand is being ANDed with.
5960 // This can be a pure constant or a vector splat, in which case we treat the
5961 // vector as a scalar and use the splat value.
5962 APInt Constant = APInt::getZero(1);
5963 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
5964 Constant = C->getAPIntValue();
5965 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
5966 APInt SplatValue, SplatUndef;
5967 unsigned SplatBitSize;
5968 bool HasAnyUndefs;
5969 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
5970 SplatBitSize, HasAnyUndefs);
5971 if (IsSplat) {
5972 // Undef bits can contribute to a possible optimisation if set, so
5973 // set them.
5974 SplatValue |= SplatUndef;
5975
5976 // The splat value may be something like "0x00FFFFFF", which means 0 for
5977 // the first vector value and FF for the rest, repeating. We need a mask
5978 // that will apply equally to all members of the vector, so AND all the
5979 // lanes of the constant together.
5980 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
5981
5982 // If the splat value has been compressed to a bitlength lower
5983 // than the size of the vector lane, we need to re-expand it to
5984 // the lane size.
5985 if (EltBitWidth > SplatBitSize)
5986 for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
5987 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
5988 SplatValue |= SplatValue.shl(SplatBitSize);
5989
5990 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5991 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5992 if ((SplatBitSize % EltBitWidth) == 0) {
5993 Constant = APInt::getAllOnes(EltBitWidth);
5994 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
5995 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
5996 }
5997 }
5998 }
5999
6000