Bug Summary

File:llvm/include/llvm/ADT/APInt.h
Warning:line 1000, column 15
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/CodeGen/SelectionDAG -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -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-13/lib/clang/13.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 -O2 -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-13~++20210613111130+5be314f79ba7/build-llvm/lib/CodeGen/SelectionDAG -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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 cominber 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 cominber 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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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::getAllOnesValue(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::getAllOnesValue(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);
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 visitFMINNUM(SDNode *N);
491 SDValue visitFMAXNUM(SDNode *N);
492 SDValue visitFMINIMUM(SDNode *N);
493 SDValue visitFMAXIMUM(SDNode *N);
494 SDValue visitBRCOND(SDNode *N);
495 SDValue visitBR_CC(SDNode *N);
496 SDValue visitLOAD(SDNode *N);
497
498 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
499 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
500
501 SDValue visitSTORE(SDNode *N);
502 SDValue visitLIFETIME_END(SDNode *N);
503 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
504 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
505 SDValue visitBUILD_VECTOR(SDNode *N);
506 SDValue visitCONCAT_VECTORS(SDNode *N);
507 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
508 SDValue visitVECTOR_SHUFFLE(SDNode *N);
509 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
510 SDValue visitINSERT_SUBVECTOR(SDNode *N);
511 SDValue visitMLOAD(SDNode *N);
512 SDValue visitMSTORE(SDNode *N);
513 SDValue visitMGATHER(SDNode *N);
514 SDValue visitMSCATTER(SDNode *N);
515 SDValue visitFP_TO_FP16(SDNode *N);
516 SDValue visitFP16_TO_FP(SDNode *N);
517 SDValue visitVECREDUCE(SDNode *N);
518
519 SDValue visitFADDForFMACombine(SDNode *N);
520 SDValue visitFSUBForFMACombine(SDNode *N);
521 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
522
523 SDValue XformToShuffleWithZero(SDNode *N);
524 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
525 const SDLoc &DL, SDValue N0,
526 SDValue N1);
527 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
528 SDValue N1);
529 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
530 SDValue N1, SDNodeFlags Flags);
531
532 SDValue visitShiftByConstant(SDNode *N);
533
534 SDValue foldSelectOfConstants(SDNode *N);
535 SDValue foldVSelectOfConstants(SDNode *N);
536 SDValue foldBinOpIntoSelect(SDNode *BO);
537 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
538 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
539 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
540 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
541 SDValue N2, SDValue N3, ISD::CondCode CC,
542 bool NotExtCompare = false);
543 SDValue convertSelectOfFPConstantsToLoadOffset(
544 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
545 ISD::CondCode CC);
546 SDValue foldSignChangeInBitcast(SDNode *N);
547 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
548 SDValue N2, SDValue N3, ISD::CondCode CC);
549 SDValue foldSextSetcc(SDNode *N);
550 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
551 const SDLoc &DL);
552 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N);
553 SDValue unfoldMaskedMerge(SDNode *N);
554 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
555 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
556 const SDLoc &DL, bool foldBooleans);
557 SDValue rebuildSetCC(SDValue N);
558
559 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
560 SDValue &CC, bool MatchStrict = false) const;
561 bool isOneUseSetCC(SDValue N) const;
562
563 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
564 unsigned HiOp);
565 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
566 SDValue CombineExtLoad(SDNode *N);
567 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
568 SDValue combineRepeatedFPDivisors(SDNode *N);
569 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
570 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
571 SDValue BuildSDIV(SDNode *N);
572 SDValue BuildSDIVPow2(SDNode *N);
573 SDValue BuildUDIV(SDNode *N);
574 SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
575 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
576 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
577 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
578 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
579 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
580 SDNodeFlags Flags, bool Reciprocal);
581 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
582 SDNodeFlags Flags, bool Reciprocal);
583 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
584 bool DemandHighBits = true);
585 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
586 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
587 SDValue InnerPos, SDValue InnerNeg,
588 unsigned PosOpcode, unsigned NegOpcode,
589 const SDLoc &DL);
590 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
591 SDValue InnerPos, SDValue InnerNeg,
592 unsigned PosOpcode, unsigned NegOpcode,
593 const SDLoc &DL);
594 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
595 SDValue MatchLoadCombine(SDNode *N);
596 SDValue mergeTruncStores(StoreSDNode *N);
597 SDValue ReduceLoadWidth(SDNode *N);
598 SDValue ReduceLoadOpStoreWidth(SDNode *N);
599 SDValue splitMergedValStore(StoreSDNode *ST);
600 SDValue TransformFPLoadStorePair(SDNode *N);
601 SDValue convertBuildVecZextToZext(SDNode *N);
602 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
603 SDValue reduceBuildVecTruncToBitCast(SDNode *N);
604 SDValue reduceBuildVecToShuffle(SDNode *N);
605 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
606 ArrayRef<int> VectorMask, SDValue VecIn1,
607 SDValue VecIn2, unsigned LeftIdx,
608 bool DidSplitVec);
609 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
610
611 /// Walk up chain skipping non-aliasing memory nodes,
612 /// looking for aliasing nodes and adding them to the Aliases vector.
613 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
614 SmallVectorImpl<SDValue> &Aliases);
615
616 /// Return true if there is any possibility that the two addresses overlap.
617 bool isAlias(SDNode *Op0, SDNode *Op1) const;
618
619 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
620 /// chain (aliasing node.)
621 SDValue FindBetterChain(SDNode *N, SDValue Chain);
622
623 /// Try to replace a store and any possibly adjacent stores on
624 /// consecutive chains with better chains. Return true only if St is
625 /// replaced.
626 ///
627 /// Notice that other chains may still be replaced even if the function
628 /// returns false.
629 bool findBetterNeighborChains(StoreSDNode *St);
630
631 // Helper for findBetterNeighborChains. Walk up store chain add additional
632 // chained stores that do not overlap and can be parallelized.
633 bool parallelizeChainedStores(StoreSDNode *St);
634
635 /// Holds a pointer to an LSBaseSDNode as well as information on where it
636 /// is located in a sequence of memory operations connected by a chain.
637 struct MemOpLink {
638 // Ptr to the mem node.
639 LSBaseSDNode *MemNode;
640
641 // Offset from the base ptr.
642 int64_t OffsetFromBase;
643
644 MemOpLink(LSBaseSDNode *N, int64_t Offset)
645 : MemNode(N), OffsetFromBase(Offset) {}
646 };
647
648 // Classify the origin of a stored value.
649 enum class StoreSource { Unknown, Constant, Extract, Load };
650 StoreSource getStoreSource(SDValue StoreVal) {
651 switch (StoreVal.getOpcode()) {
652 case ISD::Constant:
653 case ISD::ConstantFP:
654 return StoreSource::Constant;
655 case ISD::EXTRACT_VECTOR_ELT:
656 case ISD::EXTRACT_SUBVECTOR:
657 return StoreSource::Extract;
658 case ISD::LOAD:
659 return StoreSource::Load;
660 default:
661 return StoreSource::Unknown;
662 }
663 }
664
665 /// This is a helper function for visitMUL to check the profitability
666 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
667 /// MulNode is the original multiply, AddNode is (add x, c1),
668 /// and ConstNode is c2.
669 bool isMulAddWithConstProfitable(SDNode *MulNode,
670 SDValue &AddNode,
671 SDValue &ConstNode);
672
673 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
674 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
675 /// the type of the loaded value to be extended.
676 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
677 EVT LoadResultTy, EVT &ExtVT);
678
679 /// Helper function to calculate whether the given Load/Store can have its
680 /// width reduced to ExtVT.
681 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
682 EVT &MemVT, unsigned ShAmt = 0);
683
684 /// Used by BackwardsPropagateMask to find suitable loads.
685 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
686 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
687 ConstantSDNode *Mask, SDNode *&NodeToMask);
688 /// Attempt to propagate a given AND node back to load leaves so that they
689 /// can be combined into narrow loads.
690 bool BackwardsPropagateMask(SDNode *N);
691
692 /// Helper function for mergeConsecutiveStores which merges the component
693 /// store chains.
694 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
695 unsigned NumStores);
696
697 /// This is a helper function for mergeConsecutiveStores. When the source
698 /// elements of the consecutive stores are all constants or all extracted
699 /// vector elements, try to merge them into one larger store introducing
700 /// bitcasts if necessary. \return True if a merged store was created.
701 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
702 EVT MemVT, unsigned NumStores,
703 bool IsConstantSrc, bool UseVector,
704 bool UseTrunc);
705
706 /// This is a helper function for mergeConsecutiveStores. Stores that
707 /// potentially may be merged with St are placed in StoreNodes. RootNode is
708 /// a chain predecessor to all store candidates.
709 void getStoreMergeCandidates(StoreSDNode *St,
710 SmallVectorImpl<MemOpLink> &StoreNodes,
711 SDNode *&Root);
712
713 /// Helper function for mergeConsecutiveStores. Checks if candidate stores
714 /// have indirect dependency through their operands. RootNode is the
715 /// predecessor to all stores calculated by getStoreMergeCandidates and is
716 /// used to prune the dependency check. \return True if safe to merge.
717 bool checkMergeStoreCandidatesForDependencies(
718 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
719 SDNode *RootNode);
720
721 /// This is a helper function for mergeConsecutiveStores. Given a list of
722 /// store candidates, find the first N that are consecutive in memory.
723 /// Returns 0 if there are not at least 2 consecutive stores to try merging.
724 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
725 int64_t ElementSizeBytes) const;
726
727 /// This is a helper function for mergeConsecutiveStores. It is used for
728 /// store chains that are composed entirely of constant values.
729 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
730 unsigned NumConsecutiveStores,
731 EVT MemVT, SDNode *Root, bool AllowVectors);
732
733 /// This is a helper function for mergeConsecutiveStores. It is used for
734 /// store chains that are composed entirely of extracted vector elements.
735 /// When extracting multiple vector elements, try to store them in one
736 /// vector store rather than a sequence of scalar stores.
737 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
738 unsigned NumConsecutiveStores, EVT MemVT,
739 SDNode *Root);
740
741 /// This is a helper function for mergeConsecutiveStores. It is used for
742 /// store chains that are composed entirely of loaded values.
743 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
744 unsigned NumConsecutiveStores, EVT MemVT,
745 SDNode *Root, bool AllowVectors,
746 bool IsNonTemporalStore, bool IsNonTemporalLoad);
747
748 /// Merge consecutive store operations into a wide store.
749 /// This optimization uses wide integers or vectors when possible.
750 /// \return true if stores were merged.
751 bool mergeConsecutiveStores(StoreSDNode *St);
752
753 /// Try to transform a truncation where C is a constant:
754 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
755 ///
756 /// \p N needs to be a truncation and its first operand an AND. Other
757 /// requirements are checked by the function (e.g. that trunc is
758 /// single-use) and if missed an empty SDValue is returned.
759 SDValue distributeTruncateThroughAnd(SDNode *N);
760
761 /// Helper function to determine whether the target supports operation
762 /// given by \p Opcode for type \p VT, that is, whether the operation
763 /// is legal or custom before legalizing operations, and whether is
764 /// legal (but not custom) after legalization.
765 bool hasOperation(unsigned Opcode, EVT VT) {
766 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
767 }
768
769 public:
770 /// Runs the dag combiner on all nodes in the work list
771 void Run(CombineLevel AtLevel);
772
773 SelectionDAG &getDAG() const { return DAG; }
774
775 /// Returns a type large enough to hold any valid shift amount - before type
776 /// legalization these can be huge.
777 EVT getShiftAmountTy(EVT LHSTy) {
778 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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 778, __extension__ __PRETTY_FUNCTION__))
;
779 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
780 }
781
782 /// This method returns true if we are running before type legalization or
783 /// if the specified VT is legal.
784 bool isTypeLegal(const EVT &VT) {
785 if (!LegalTypes) return true;
786 return TLI.isTypeLegal(VT);
787 }
788
789 /// Convenience wrapper around TargetLowering::getSetCCResultType
790 EVT getSetCCResultType(EVT VT) const {
791 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
792 }
793
794 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
795 SDValue OrigLoad, SDValue ExtLoad,
796 ISD::NodeType ExtType);
797 };
798
799/// This class is a DAGUpdateListener that removes any deleted
800/// nodes from the worklist.
801class WorklistRemover : public SelectionDAG::DAGUpdateListener {
802 DAGCombiner &DC;
803
804public:
805 explicit WorklistRemover(DAGCombiner &dc)
806 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
807
808 void NodeDeleted(SDNode *N, SDNode *E) override {
809 DC.removeFromWorklist(N);
810 }
811};
812
813class WorklistInserter : public SelectionDAG::DAGUpdateListener {
814 DAGCombiner &DC;
815
816public:
817 explicit WorklistInserter(DAGCombiner &dc)
818 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
819
820 // FIXME: Ideally we could add N to the worklist, but this causes exponential
821 // compile time costs in large DAGs, e.g. Halide.
822 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
823};
824
825} // end anonymous namespace
826
827//===----------------------------------------------------------------------===//
828// TargetLowering::DAGCombinerInfo implementation
829//===----------------------------------------------------------------------===//
830
831void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
832 ((DAGCombiner*)DC)->AddToWorklist(N);
833}
834
835SDValue TargetLowering::DAGCombinerInfo::
836CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
837 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
838}
839
840SDValue TargetLowering::DAGCombinerInfo::
841CombineTo(SDNode *N, SDValue Res, bool AddTo) {
842 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
843}
844
845SDValue TargetLowering::DAGCombinerInfo::
846CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
847 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
848}
849
850bool TargetLowering::DAGCombinerInfo::
851recursivelyDeleteUnusedNodes(SDNode *N) {
852 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
853}
854
855void TargetLowering::DAGCombinerInfo::
856CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
857 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
858}
859
860//===----------------------------------------------------------------------===//
861// Helper Functions
862//===----------------------------------------------------------------------===//
863
864void DAGCombiner::deleteAndRecombine(SDNode *N) {
865 removeFromWorklist(N);
866
867 // If the operands of this node are only used by the node, they will now be
868 // dead. Make sure to re-visit them and recursively delete dead nodes.
869 for (const SDValue &Op : N->ops())
870 // For an operand generating multiple values, one of the values may
871 // become dead allowing further simplification (e.g. split index
872 // arithmetic from an indexed load).
873 if (Op->hasOneUse() || Op->getNumValues() > 1)
874 AddToWorklist(Op.getNode());
875
876 DAG.DeleteNode(N);
877}
878
879// APInts must be the same size for most operations, this helper
880// function zero extends the shorter of the pair so that they match.
881// We provide an Offset so that we can create bitwidths that won't overflow.
882static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
883 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
884 LHS = LHS.zextOrSelf(Bits);
885 RHS = RHS.zextOrSelf(Bits);
886}
887
888// Return true if this node is a setcc, or is a select_cc
889// that selects between the target values used for true and false, making it
890// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
891// the appropriate nodes based on the type of node we are checking. This
892// simplifies life a bit for the callers.
893bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
894 SDValue &CC, bool MatchStrict) const {
895 if (N.getOpcode() == ISD::SETCC) {
896 LHS = N.getOperand(0);
897 RHS = N.getOperand(1);
898 CC = N.getOperand(2);
899 return true;
900 }
901
902 if (MatchStrict &&
903 (N.getOpcode() == ISD::STRICT_FSETCC ||
904 N.getOpcode() == ISD::STRICT_FSETCCS)) {
905 LHS = N.getOperand(1);
906 RHS = N.getOperand(2);
907 CC = N.getOperand(3);
908 return true;
909 }
910
911 if (N.getOpcode() != ISD::SELECT_CC ||
912 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
913 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
914 return false;
915
916 if (TLI.getBooleanContents(N.getValueType()) ==
917 TargetLowering::UndefinedBooleanContent)
918 return false;
919
920 LHS = N.getOperand(0);
921 RHS = N.getOperand(1);
922 CC = N.getOperand(4);
923 return true;
924}
925
926/// Return true if this is a SetCC-equivalent operation with only one use.
927/// If this is true, it allows the users to invert the operation for free when
928/// it is profitable to do so.
929bool DAGCombiner::isOneUseSetCC(SDValue N) const {
930 SDValue N0, N1, N2;
931 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
932 return true;
933 return false;
934}
935
936static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) {
937 if (!ScalarTy.isSimple())
938 return false;
939
940 uint64_t MaskForTy = 0ULL;
941 switch (ScalarTy.getSimpleVT().SimpleTy) {
942 case MVT::i8:
943 MaskForTy = 0xFFULL;
944 break;
945 case MVT::i16:
946 MaskForTy = 0xFFFFULL;
947 break;
948 case MVT::i32:
949 MaskForTy = 0xFFFFFFFFULL;
950 break;
951 default:
952 return false;
953 break;
954 }
955
956 APInt Val;
957 if (ISD::isConstantSplatVector(N, Val))
958 return Val.getLimitedValue() == MaskForTy;
959
960 return false;
961}
962
963// Determines if it is a constant integer or a splat/build vector of constant
964// integers (and undefs).
965// Do not permit build vector implicit truncation.
966static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
967 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
968 return !(Const->isOpaque() && NoOpaques);
969 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
970 return false;
971 unsigned BitWidth = N.getScalarValueSizeInBits();
972 for (const SDValue &Op : N->op_values()) {
973 if (Op.isUndef())
974 continue;
975 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
976 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
977 (Const->isOpaque() && NoOpaques))
978 return false;
979 }
980 return true;
981}
982
983// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
984// undef's.
985static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
986 if (V.getOpcode() != ISD::BUILD_VECTOR)
987 return false;
988 return isConstantOrConstantVector(V, NoOpaques) ||
989 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
990}
991
992// Determine if this an indexed load with an opaque target constant index.
993static bool canSplitIdx(LoadSDNode *LD) {
994 return MaySplitLoadIndex &&
995 (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
996 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
997}
998
999bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
1000 const SDLoc &DL,
1001 SDValue N0,
1002 SDValue N1) {
1003 // Currently this only tries to ensure we don't undo the GEP splits done by
1004 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1005 // we check if the following transformation would be problematic:
1006 // (load/store (add, (add, x, offset1), offset2)) ->
1007 // (load/store (add, x, offset1+offset2)).
1008
1009 if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
1010 return false;
1011
1012 if (N0.hasOneUse())
1013 return false;
1014
1015 auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1016 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1017 if (!C1 || !C2)
1018 return false;
1019
1020 const APInt &C1APIntVal = C1->getAPIntValue();
1021 const APInt &C2APIntVal = C2->getAPIntValue();
1022 if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64)
1023 return false;
1024
1025 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1026 if (CombinedValueIntVal.getBitWidth() > 64)
1027 return false;
1028 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1029
1030 for (SDNode *Node : N0->uses()) {
1031 auto LoadStore = dyn_cast<MemSDNode>(Node);
1032 if (LoadStore) {
1033 // Is x[offset2] already not a legal addressing mode? If so then
1034 // reassociating the constants breaks nothing (we test offset2 because
1035 // that's the one we hope to fold into the load or store).
1036 TargetLoweringBase::AddrMode AM;
1037 AM.HasBaseReg = true;
1038 AM.BaseOffs = C2APIntVal.getSExtValue();
1039 EVT VT = LoadStore->getMemoryVT();
1040 unsigned AS = LoadStore->getAddressSpace();
1041 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1042 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1043 continue;
1044
1045 // Would x[offset1+offset2] still be a legal addressing mode?
1046 AM.BaseOffs = CombinedValue;
1047 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1048 return true;
1049 }
1050 }
1051
1052 return false;
1053}
1054
1055// Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
1056// such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
1057SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1058 SDValue N0, SDValue N1) {
1059 EVT VT = N0.getValueType();
1060
1061 if (N0.getOpcode() != Opc)
1062 return SDValue();
1063
1064 if (DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
1065 if (DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1066 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1067 if (SDValue OpNode =
1068 DAG.FoldConstantArithmetic(Opc, DL, VT, {N0.getOperand(1), N1}))
1069 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
1070 return SDValue();
1071 }
1072 if (N0.hasOneUse()) {
1073 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1074 // iff (op x, c1) has one use
1075 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
1076 if (!OpNode.getNode())
1077 return SDValue();
1078 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
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.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/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: return visitFMINNUM(N);
1702 case ISD::FMAXNUM: return visitFMAXNUM(N);
1703 case ISD::FMINIMUM: return visitFMINIMUM(N);
1704 case ISD::FMAXIMUM: return visitFMAXIMUM(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 }
1741 return SDValue();
1742}
1743
1744SDValue DAGCombiner::combine(SDNode *N) {
1745 SDValue RV;
1746 if (!DisableGenericCombines)
1747 RV = visit(N);
1748
1749 // If nothing happened, try a target-specific DAG combine.
1750 if (!RV.getNode()) {
1751 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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1752, __extension__ __PRETTY_FUNCTION__))
1752 "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!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1752, __extension__ __PRETTY_FUNCTION__))
;
1753
1754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1756
1757 // Expose the DAG combiner to the target combiner impls.
1758 TargetLowering::DAGCombinerInfo
1759 DagCombineInfo(DAG, Level, false, this);
1760
1761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1762 }
1763 }
1764
1765 // If nothing happened still, try promoting the operation.
1766 if (!RV.getNode()) {
1767 switch (N->getOpcode()) {
1768 default: break;
1769 case ISD::ADD:
1770 case ISD::SUB:
1771 case ISD::MUL:
1772 case ISD::AND:
1773 case ISD::OR:
1774 case ISD::XOR:
1775 RV = PromoteIntBinOp(SDValue(N, 0));
1776 break;
1777 case ISD::SHL:
1778 case ISD::SRA:
1779 case ISD::SRL:
1780 RV = PromoteIntShiftOp(SDValue(N, 0));
1781 break;
1782 case ISD::SIGN_EXTEND:
1783 case ISD::ZERO_EXTEND:
1784 case ISD::ANY_EXTEND:
1785 RV = PromoteExtend(SDValue(N, 0));
1786 break;
1787 case ISD::LOAD:
1788 if (PromoteLoad(SDValue(N, 0)))
1789 RV = SDValue(N, 0);
1790 break;
1791 }
1792 }
1793
1794 // If N is a commutative binary node, try to eliminate it if the commuted
1795 // version is already present in the DAG.
1796 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1797 N->getNumValues() == 1) {
1798 SDValue N0 = N->getOperand(0);
1799 SDValue N1 = N->getOperand(1);
1800
1801 // Constant operands are canonicalized to RHS.
1802 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1803 SDValue Ops[] = {N1, N0};
1804 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1805 N->getFlags());
1806 if (CSENode)
1807 return SDValue(CSENode, 0);
1808 }
1809 }
1810
1811 return RV;
1812}
1813
1814/// Given a node, return its input chain if it has one, otherwise return a null
1815/// sd operand.
1816static SDValue getInputChainForNode(SDNode *N) {
1817 if (unsigned NumOps = N->getNumOperands()) {
1818 if (N->getOperand(0).getValueType() == MVT::Other)
1819 return N->getOperand(0);
1820 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1821 return N->getOperand(NumOps-1);
1822 for (unsigned i = 1; i < NumOps-1; ++i)
1823 if (N->getOperand(i).getValueType() == MVT::Other)
1824 return N->getOperand(i);
1825 }
1826 return SDValue();
1827}
1828
1829SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1830 // If N has two operands, where one has an input chain equal to the other,
1831 // the 'other' chain is redundant.
1832 if (N->getNumOperands() == 2) {
1833 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1834 return N->getOperand(0);
1835 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1836 return N->getOperand(1);
1837 }
1838
1839 // Don't simplify token factors if optnone.
1840 if (OptLevel == CodeGenOpt::None)
1841 return SDValue();
1842
1843 // Don't simplify the token factor if the node itself has too many operands.
1844 if (N->getNumOperands() > TokenFactorInlineLimit)
1845 return SDValue();
1846
1847 // If the sole user is a token factor, we should make sure we have a
1848 // chance to merge them together. This prevents TF chains from inhibiting
1849 // optimizations.
1850 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
1851 AddToWorklist(*(N->use_begin()));
1852
1853 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1854 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1855 SmallPtrSet<SDNode*, 16> SeenOps;
1856 bool Changed = false; // If we should replace this token factor.
1857
1858 // Start out with this token factor.
1859 TFs.push_back(N);
1860
1861 // Iterate through token factors. The TFs grows when new token factors are
1862 // encountered.
1863 for (unsigned i = 0; i < TFs.size(); ++i) {
1864 // Limit number of nodes to inline, to avoid quadratic compile times.
1865 // We have to add the outstanding Token Factors to Ops, otherwise we might
1866 // drop Ops from the resulting Token Factors.
1867 if (Ops.size() > TokenFactorInlineLimit) {
1868 for (unsigned j = i; j < TFs.size(); j++)
1869 Ops.emplace_back(TFs[j], 0);
1870 // Drop unprocessed Token Factors from TFs, so we do not add them to the
1871 // combiner worklist later.
1872 TFs.resize(i);
1873 break;
1874 }
1875
1876 SDNode *TF = TFs[i];
1877 // Check each of the operands.
1878 for (const SDValue &Op : TF->op_values()) {
1879 switch (Op.getOpcode()) {
1880 case ISD::EntryToken:
1881 // Entry tokens don't need to be added to the list. They are
1882 // redundant.
1883 Changed = true;
1884 break;
1885
1886 case ISD::TokenFactor:
1887 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1888 // Queue up for processing.
1889 TFs.push_back(Op.getNode());
1890 Changed = true;
1891 break;
1892 }
1893 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1894
1895 default:
1896 // Only add if it isn't already in the list.
1897 if (SeenOps.insert(Op.getNode()).second)
1898 Ops.push_back(Op);
1899 else
1900 Changed = true;
1901 break;
1902 }
1903 }
1904 }
1905
1906 // Re-visit inlined Token Factors, to clean them up in case they have been
1907 // removed. Skip the first Token Factor, as this is the current node.
1908 for (unsigned i = 1, e = TFs.size(); i < e; i++)
1909 AddToWorklist(TFs[i]);
1910
1911 // Remove Nodes that are chained to another node in the list. Do so
1912 // by walking up chains breath-first stopping when we've seen
1913 // another operand. In general we must climb to the EntryNode, but we can exit
1914 // early if we find all remaining work is associated with just one operand as
1915 // no further pruning is possible.
1916
1917 // List of nodes to search through and original Ops from which they originate.
1918 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1919 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1920 SmallPtrSet<SDNode *, 16> SeenChains;
1921 bool DidPruneOps = false;
1922
1923 unsigned NumLeftToConsider = 0;
1924 for (const SDValue &Op : Ops) {
1925 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1926 OpWorkCount.push_back(1);
1927 }
1928
1929 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1930 // If this is an Op, we can remove the op from the list. Remark any
1931 // search associated with it as from the current OpNumber.
1932 if (SeenOps.contains(Op)) {
1933 Changed = true;
1934 DidPruneOps = true;
1935 unsigned OrigOpNumber = 0;
1936 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1937 OrigOpNumber++;
1938 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1939, __extension__ __PRETTY_FUNCTION__))
1939 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1939, __extension__ __PRETTY_FUNCTION__))
;
1940 // Re-mark worklist from OrigOpNumber to OpNumber
1941 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1942 if (Worklist[i].second == OrigOpNumber) {
1943 Worklist[i].second = OpNumber;
1944 }
1945 }
1946 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1947 OpWorkCount[OrigOpNumber] = 0;
1948 NumLeftToConsider--;
1949 }
1950 // Add if it's a new chain
1951 if (SeenChains.insert(Op).second) {
1952 OpWorkCount[OpNumber]++;
1953 Worklist.push_back(std::make_pair(Op, OpNumber));
1954 }
1955 };
1956
1957 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1958 // We need at least be consider at least 2 Ops to prune.
1959 if (NumLeftToConsider <= 1)
1960 break;
1961 auto CurNode = Worklist[i].first;
1962 auto CurOpNumber = Worklist[i].second;
1963 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1964, __extension__ __PRETTY_FUNCTION__))
1964 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1964, __extension__ __PRETTY_FUNCTION__))
;
1965 switch (CurNode->getOpcode()) {
1966 case ISD::EntryToken:
1967 // Hitting EntryToken is the only way for the search to terminate without
1968 // hitting
1969 // another operand's search. Prevent us from marking this operand
1970 // considered.
1971 NumLeftToConsider++;
1972 break;
1973 case ISD::TokenFactor:
1974 for (const SDValue &Op : CurNode->op_values())
1975 AddToWorklist(i, Op.getNode(), CurOpNumber);
1976 break;
1977 case ISD::LIFETIME_START:
1978 case ISD::LIFETIME_END:
1979 case ISD::CopyFromReg:
1980 case ISD::CopyToReg:
1981 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1982 break;
1983 default:
1984 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1985 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1986 break;
1987 }
1988 OpWorkCount[CurOpNumber]--;
1989 if (OpWorkCount[CurOpNumber] == 0)
1990 NumLeftToConsider--;
1991 }
1992
1993 // If we've changed things around then replace token factor.
1994 if (Changed) {
1995 SDValue Result;
1996 if (Ops.empty()) {
1997 // The entry token is the only possible outcome.
1998 Result = DAG.getEntryNode();
1999 } else {
2000 if (DidPruneOps) {
2001 SmallVector<SDValue, 8> PrunedOps;
2002 //
2003 for (const SDValue &Op : Ops) {
2004 if (SeenChains.count(Op.getNode()) == 0)
2005 PrunedOps.push_back(Op);
2006 }
2007 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2008 } else {
2009 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2010 }
2011 }
2012 return Result;
2013 }
2014 return SDValue();
2015}
2016
2017/// MERGE_VALUES can always be eliminated.
2018SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2019 WorklistRemover DeadNodes(*this);
2020 // Replacing results may cause a different MERGE_VALUES to suddenly
2021 // be CSE'd with N, and carry its uses with it. Iterate until no
2022 // uses remain, to ensure that the node can be safely deleted.
2023 // First add the users of this node to the work list so that they
2024 // can be tried again once they have new operands.
2025 AddUsersToWorklist(N);
2026 do {
2027 // Do as a single replacement to avoid rewalking use lists.
2028 SmallVector<SDValue, 8> Ops;
2029 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2030 Ops.push_back(N->getOperand(i));
2031 DAG.ReplaceAllUsesWith(N, Ops.data());
2032 } while (!N->use_empty());
2033 deleteAndRecombine(N);
2034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2035}
2036
2037/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2038/// ConstantSDNode pointer else nullptr.
2039static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
2040 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
2041 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2042}
2043
2044/// Return true if 'Use' is a load or a store that uses N as its base pointer
2045/// and that N may be folded in the load / store addressing mode.
2046static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG,
2047 const TargetLowering &TLI) {
2048 EVT VT;
2049 unsigned AS;
2050
2051 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2052 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2053 return false;
2054 VT = LD->getMemoryVT();
2055 AS = LD->getAddressSpace();
2056 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2057 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2058 return false;
2059 VT = ST->getMemoryVT();
2060 AS = ST->getAddressSpace();
2061 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) {
2062 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2063 return false;
2064 VT = LD->getMemoryVT();
2065 AS = LD->getAddressSpace();
2066 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) {
2067 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2068 return false;
2069 VT = ST->getMemoryVT();
2070 AS = ST->getAddressSpace();
2071 } else
2072 return false;
2073
2074 TargetLowering::AddrMode AM;
2075 if (N->getOpcode() == ISD::ADD) {
2076 AM.HasBaseReg = true;
2077 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2078 if (Offset)
2079 // [reg +/- imm]
2080 AM.BaseOffs = Offset->getSExtValue();
2081 else
2082 // [reg +/- reg]
2083 AM.Scale = 1;
2084 } else if (N->getOpcode() == ISD::SUB) {
2085 AM.HasBaseReg = true;
2086 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2087 if (Offset)
2088 // [reg +/- imm]
2089 AM.BaseOffs = -Offset->getSExtValue();
2090 else
2091 // [reg +/- reg]
2092 AM.Scale = 1;
2093 } else
2094 return false;
2095
2096 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2097 VT.getTypeForEVT(*DAG.getContext()), AS);
2098}
2099
2100SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2101 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
2102 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
;
2103
2104 // Don't do this unless the old select is going away. We want to eliminate the
2105 // binary operator, not replace a binop with a select.
2106 // TODO: Handle ISD::SELECT_CC.
2107 unsigned SelOpNo = 0;
2108 SDValue Sel = BO->getOperand(0);
2109 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2110 SelOpNo = 1;
2111 Sel = BO->getOperand(1);
2112 }
2113
2114 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2115 return SDValue();
2116
2117 SDValue CT = Sel.getOperand(1);
2118 if (!isConstantOrConstantVector(CT, true) &&
2119 !DAG.isConstantFPBuildVectorOrConstantFP(CT))
2120 return SDValue();
2121
2122 SDValue CF = Sel.getOperand(2);
2123 if (!isConstantOrConstantVector(CF, true) &&
2124 !DAG.isConstantFPBuildVectorOrConstantFP(CF))
2125 return SDValue();
2126
2127 // Bail out if any constants are opaque because we can't constant fold those.
2128 // The exception is "and" and "or" with either 0 or -1 in which case we can
2129 // propagate non constant operands into select. I.e.:
2130 // and (select Cond, 0, -1), X --> select Cond, 0, X
2131 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2132 auto BinOpcode = BO->getOpcode();
2133 bool CanFoldNonConst =
2134 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2135 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) &&
2136 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF));
2137
2138 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2139 if (!CanFoldNonConst &&
2140 !isConstantOrConstantVector(CBO, true) &&
2141 !DAG.isConstantFPBuildVectorOrConstantFP(CBO))
2142 return SDValue();
2143
2144 EVT VT = BO->getValueType(0);
2145
2146 // We have a select-of-constants followed by a binary operator with a
2147 // constant. Eliminate the binop by pulling the constant math into the select.
2148 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2149 SDLoc DL(Sel);
2150 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
2151 : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
2152 if (!CanFoldNonConst && !NewCT.isUndef() &&
2153 !isConstantOrConstantVector(NewCT, true) &&
2154 !DAG.isConstantFPBuildVectorOrConstantFP(NewCT))
2155 return SDValue();
2156
2157 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
2158 : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
2159 if (!CanFoldNonConst && !NewCF.isUndef() &&
2160 !isConstantOrConstantVector(NewCF, true) &&
2161 !DAG.isConstantFPBuildVectorOrConstantFP(NewCF))
2162 return SDValue();
2163
2164 SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
2165 SelectOp->setFlags(BO->getFlags());
2166 return SelectOp;
2167}
2168
2169static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
2170 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2171, __extension__ __PRETTY_FUNCTION__))
2171 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2171, __extension__ __PRETTY_FUNCTION__))
;
2172
2173 // Match a constant operand and a zext operand for the math instruction:
2174 // add Z, C
2175 // sub C, Z
2176 bool IsAdd = N->getOpcode() == ISD::ADD;
2177 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2178 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2179 auto *CN = dyn_cast<ConstantSDNode>(C);
2180 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2181 return SDValue();
2182
2183 // Match the zext operand as a setcc of a boolean.
2184 if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
2185 Z.getOperand(0).getValueType() != MVT::i1)
2186 return SDValue();
2187
2188 // Match the compare as: setcc (X & 1), 0, eq.
2189 SDValue SetCC = Z.getOperand(0);
2190 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
2191 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
2192 SetCC.getOperand(0).getOpcode() != ISD::AND ||
2193 !isOneConstant(SetCC.getOperand(0).getOperand(1)))
2194 return SDValue();
2195
2196 // We are adding/subtracting a constant and an inverted low bit. Turn that
2197 // into a subtract/add of the low bit with incremented/decremented constant:
2198 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2199 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2200 EVT VT = C.getValueType();
2201 SDLoc DL(N);
2202 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
2203 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
2204 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2205 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2206}
2207
2208/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2209/// a shift and add with a different constant.
2210static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
2211 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2212, __extension__ __PRETTY_FUNCTION__))
2212 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2212, __extension__ __PRETTY_FUNCTION__))
;
2213
2214 // We need a constant operand for the add/sub, and the other operand is a
2215 // logical shift right: add (srl), C or sub C, (srl).
2216 bool IsAdd = N->getOpcode() == ISD::ADD;
2217 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2218 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2219 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2220 ShiftOp.getOpcode() != ISD::SRL)
2221 return SDValue();
2222
2223 // The shift must be of a 'not' value.
2224 SDValue Not = ShiftOp.getOperand(0);
2225 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2226 return SDValue();
2227
2228 // The shift must be moving the sign bit to the least-significant-bit.
2229 EVT VT = ShiftOp.getValueType();
2230 SDValue ShAmt = ShiftOp.getOperand(1);
2231 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2232 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2233 return SDValue();
2234
2235 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2236 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2237 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2238 SDLoc DL(N);
2239 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
2240 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
2241 if (SDValue NewC =
2242 DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2243 {ConstantOp, DAG.getConstant(1, DL, VT)}))
2244 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2245 return SDValue();
2246}
2247
2248/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2249/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2250/// are no common bits set in the operands).
2251SDValue DAGCombiner::visitADDLike(SDNode *N) {
2252 SDValue N0 = N->getOperand(0);
2253 SDValue N1 = N->getOperand(1);
2254 EVT VT = N0.getValueType();
2255 SDLoc DL(N);
2256
2257 // fold vector ops
2258 if (VT.isVector()) {
2259 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2260 return FoldedVOp;
2261
2262 // fold (add x, 0) -> x, vector edition
2263 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
2264 return N0;
2265 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()))
2266 return N1;
2267 }
2268
2269 // fold (add x, undef) -> undef
2270 if (N0.isUndef())
2271 return N0;
2272
2273 if (N1.isUndef())
2274 return N1;
2275
2276 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2277 // canonicalize constant to RHS
2278 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2279 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2280 // fold (add c1, c2) -> c1+c2
2281 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1});
2282 }
2283
2284 // fold (add x, 0) -> x
2285 if (isNullConstant(N1))
2286 return N0;
2287
2288 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2289 // fold ((A-c1)+c2) -> (A+(c2-c1))
2290 if (N0.getOpcode() == ISD::SUB &&
2291 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
2292 SDValue Sub =
2293 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)});
2294 assert(Sub && "Constant folding failed")(static_cast <bool> (Sub && "Constant folding failed"
) ? void (0) : __assert_fail ("Sub && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2294, __extension__ __PRETTY_FUNCTION__))
;
2295 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2296 }
2297
2298 // fold ((c1-A)+c2) -> (c1+c2)-A
2299 if (N0.getOpcode() == ISD::SUB &&
2300 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2301 SDValue Add =
2302 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)});
2303 assert(Add && "Constant folding failed")(static_cast <bool> (Add && "Constant folding failed"
) ? void (0) : __assert_fail ("Add && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2305 }
2306
2307 // add (sext i1 X), 1 -> zext (not i1 X)
2308 // We don't transform this pattern:
2309 // add (zext i1 X), -1 -> sext (not i1 X)
2310 // because most (?) targets generate better code for the zext form.
2311 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2312 isOneOrOneSplat(N1)) {
2313 SDValue X = N0.getOperand(0);
2314 if ((!LegalOperations ||
2315 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2316 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2317 X.getScalarValueSizeInBits() == 1) {
2318 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2319 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2320 }
2321 }
2322
2323 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is
2324 // equivalent to (add x, c0).
2325 if (N0.getOpcode() == ISD::OR &&
2326 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) &&
2327 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2328 if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT,
2329 {N1, N0.getOperand(1)}))
2330 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2331 }
2332 }
2333
2334 if (SDValue NewSel = foldBinOpIntoSelect(N))
2335 return NewSel;
2336
2337 // reassociate add
2338 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) {
2339 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2340 return RADD;
2341 }
2342 // fold ((0-A) + B) -> B-A
2343 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
2344 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2345
2346 // fold (A + (0-B)) -> A-B
2347 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2348 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2349
2350 // fold (A+(B-A)) -> B
2351 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2352 return N1.getOperand(0);
2353
2354 // fold ((B-A)+A) -> B
2355 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2356 return N0.getOperand(0);
2357
2358 // fold ((A-B)+(C-A)) -> (C-B)
2359 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2360 N0.getOperand(0) == N1.getOperand(1))
2361 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2362 N0.getOperand(1));
2363
2364 // fold ((A-B)+(B-C)) -> (A-C)
2365 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2366 N0.getOperand(1) == N1.getOperand(0))
2367 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2368 N1.getOperand(1));
2369
2370 // fold (A+(B-(A+C))) to (B-C)
2371 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2372 N0 == N1.getOperand(1).getOperand(0))
2373 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2374 N1.getOperand(1).getOperand(1));
2375
2376 // fold (A+(B-(C+A))) to (B-C)
2377 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2378 N0 == N1.getOperand(1).getOperand(1))
2379 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2380 N1.getOperand(1).getOperand(0));
2381
2382 // fold (A+((B-A)+or-C)) to (B+or-C)
2383 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2384 N1.getOperand(0).getOpcode() == ISD::SUB &&
2385 N0 == N1.getOperand(0).getOperand(1))
2386 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2387 N1.getOperand(1));
2388
2389 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2390 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2391 SDValue N00 = N0.getOperand(0);
2392 SDValue N01 = N0.getOperand(1);
2393 SDValue N10 = N1.getOperand(0);
2394 SDValue N11 = N1.getOperand(1);
2395
2396 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2397 return DAG.getNode(ISD::SUB, DL, VT,
2398 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2399 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2400 }
2401
2402 // fold (add (umax X, C), -C) --> (usubsat X, C)
2403 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
2404 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
2405 return (!Max && !Op) ||
2406 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
2407 };
2408 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
2409 /*AllowUndefs*/ true))
2410 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
2411 N0.getOperand(1));
2412 }
2413
2414 if (SimplifyDemandedBits(SDValue(N, 0)))
2415 return SDValue(N, 0);
2416
2417 if (isOneOrOneSplat(N1)) {
2418 // fold (add (xor a, -1), 1) -> (sub 0, a)
2419 if (isBitwiseNot(N0))
2420 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2421 N0.getOperand(0));
2422
2423 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2424 if (N0.getOpcode() == ISD::ADD ||
2425 N0.getOpcode() == ISD::UADDO ||
2426 N0.getOpcode() == ISD::SADDO) {
2427 SDValue A, Xor;
2428
2429 if (isBitwiseNot(N0.getOperand(0))) {
2430 A = N0.getOperand(1);
2431 Xor = N0.getOperand(0);
2432 } else if (isBitwiseNot(N0.getOperand(1))) {
2433 A = N0.getOperand(0);
2434 Xor = N0.getOperand(1);
2435 }
2436
2437 if (Xor)
2438 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
2439 }
2440
2441 // Look for:
2442 // add (add x, y), 1
2443 // And if the target does not like this form then turn into:
2444 // sub y, (xor x, -1)
2445 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2446 N0.getOpcode() == ISD::ADD) {
2447 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2448 DAG.getAllOnesConstant(DL, VT));
2449 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
2450 }
2451 }
2452
2453 // (x - y) + -1 -> add (xor y, -1), x
2454 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2455 isAllOnesOrAllOnesSplat(N1)) {
2456 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
2457 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
2458 }
2459
2460 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
2461 return Combined;
2462
2463 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
2464 return Combined;
2465
2466 return SDValue();
2467}
2468
2469SDValue DAGCombiner::visitADD(SDNode *N) {
2470 SDValue N0 = N->getOperand(0);
2471 SDValue N1 = N->getOperand(1);
2472 EVT VT = N0.getValueType();
2473 SDLoc DL(N);
2474
2475 if (SDValue Combined = visitADDLike(N))
2476 return Combined;
2477
2478 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2479 return V;
2480
2481 if (SDValue V = foldAddSubOfSignBit(N, DAG))
2482 return V;
2483
2484 // fold (a+b) -> (a|b) iff a and b share no bits.
2485 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2486 DAG.haveNoCommonBitsSet(N0, N1))
2487 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2488
2489 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
2490 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
2491 const APInt &C0 = N0->getConstantOperandAPInt(0);
2492 const APInt &C1 = N1->getConstantOperandAPInt(0);
2493 return DAG.getVScale(DL, VT, C0 + C1);
2494 }
2495
2496 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
2497 if ((N0.getOpcode() == ISD::ADD) &&
2498 (N0.getOperand(1).getOpcode() == ISD::VSCALE) &&
2499 (N1.getOpcode() == ISD::VSCALE)) {
2500 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
2501 const APInt &VS1 = N1->getConstantOperandAPInt(0);
2502 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
2503 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
2504 }
2505
2506 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
2507 if (N0.getOpcode() == ISD::STEP_VECTOR &&
2508 N1.getOpcode() == ISD::STEP_VECTOR) {
2509 const APInt &C0 = N0->getConstantOperandAPInt(0);
2510 const APInt &C1 = N1->getConstantOperandAPInt(0);
2511 EVT SVT = N0.getOperand(0).getValueType();
2512 SDValue NewStep = DAG.getConstant(C0 + C1, DL, SVT);
2513 return DAG.getStepVector(DL, VT, NewStep);
2514 }
2515
2516 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
2517 if ((N0.getOpcode() == ISD::ADD) &&
2518 (N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR) &&
2519 (N1.getOpcode() == ISD::STEP_VECTOR)) {
2520 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
2521 const APInt &SV1 = N1->getConstantOperandAPInt(0);
2522 EVT SVT = N1.getOperand(0).getValueType();
2523 assert(N1.getOperand(0).getValueType() ==(static_cast <bool> (N1.getOperand(0).getValueType() ==
N0.getOperand(1)->getOperand(0).getValueType() &&
"Different operand types of STEP_VECTOR.") ? void (0) : __assert_fail
("N1.getOperand(0).getValueType() == N0.getOperand(1)->getOperand(0).getValueType() && \"Different operand types of STEP_VECTOR.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2525, __extension__ __PRETTY_FUNCTION__))
2524 N0.getOperand(1)->getOperand(0).getValueType() &&(static_cast <bool> (N1.getOperand(0).getValueType() ==
N0.getOperand(1)->getOperand(0).getValueType() &&
"Different operand types of STEP_VECTOR.") ? void (0) : __assert_fail
("N1.getOperand(0).getValueType() == N0.getOperand(1)->getOperand(0).getValueType() && \"Different operand types of STEP_VECTOR.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2525, __extension__ __PRETTY_FUNCTION__))
2525 "Different operand types of STEP_VECTOR.")(static_cast <bool> (N1.getOperand(0).getValueType() ==
N0.getOperand(1)->getOperand(0).getValueType() &&
"Different operand types of STEP_VECTOR.") ? void (0) : __assert_fail
("N1.getOperand(0).getValueType() == N0.getOperand(1)->getOperand(0).getValueType() && \"Different operand types of STEP_VECTOR.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2525, __extension__ __PRETTY_FUNCTION__))
;
2526 SDValue NewStep = DAG.getConstant(SV0 + SV1, DL, SVT);
2527 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
2528 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
2529 }
2530
2531 return SDValue();
2532}
2533
2534SDValue DAGCombiner::visitADDSAT(SDNode *N) {
2535 unsigned Opcode = N->getOpcode();
2536 SDValue N0 = N->getOperand(0);
2537 SDValue N1 = N->getOperand(1);
2538 EVT VT = N0.getValueType();
2539 SDLoc DL(N);
2540
2541 // fold vector ops
2542 if (VT.isVector()) {
2543 // TODO SimplifyVBinOp
2544
2545 // fold (add_sat x, 0) -> x, vector edition
2546 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
2547 return N0;
2548 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()))
2549 return N1;
2550 }
2551
2552 // fold (add_sat x, undef) -> -1
2553 if (N0.isUndef() || N1.isUndef())
2554 return DAG.getAllOnesConstant(DL, VT);
2555
2556 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2557 // canonicalize constant to RHS
2558 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2559 return DAG.getNode(Opcode, DL, VT, N1, N0);
2560 // fold (add_sat c1, c2) -> c3
2561 return DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1});
2562 }
2563
2564 // fold (add_sat x, 0) -> x
2565 if (isNullConstant(N1))
2566 return N0;
2567
2568 // If it cannot overflow, transform into an add.
2569 if (Opcode == ISD::UADDSAT)
2570 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2571 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
2572
2573 return SDValue();
2574}
2575
2576static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2577 bool Masked = false;
2578
2579 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2580 while (true) {
2581 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2582 V = V.getOperand(0);
2583 continue;
2584 }
2585
2586 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2587 Masked = true;
2588 V = V.getOperand(0);
2589 continue;
2590 }
2591
2592 break;
2593 }
2594
2595 // If this is not a carry, return.
2596 if (V.getResNo() != 1)
2597 return SDValue();
2598
2599 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2600 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2601 return SDValue();
2602
2603 EVT VT = V.getNode()->getValueType(0);
2604 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
2605 return SDValue();
2606
2607 // If the result is masked, then no matter what kind of bool it is we can
2608 // return. If it isn't, then we need to make sure the bool type is either 0 or
2609 // 1 and not other values.
2610 if (Masked ||
2611 TLI.getBooleanContents(V.getValueType()) ==
2612 TargetLoweringBase::ZeroOrOneBooleanContent)
2613 return V;
2614
2615 return SDValue();
2616}
2617
2618/// Given the operands of an add/sub operation, see if the 2nd operand is a
2619/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2620/// the opcode and bypass the mask operation.
2621static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
2622 SelectionDAG &DAG, const SDLoc &DL) {
2623 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
2624 return SDValue();
2625
2626 EVT VT = N0.getValueType();
2627 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
2628 return SDValue();
2629
2630 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2631 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2632 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
2633}
2634
2635/// Helper for doing combines based on N0 and N1 being added to each other.
2636SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
2637 SDNode *LocReference) {
2638 EVT VT = N0.getValueType();
2639 SDLoc DL(LocReference);
2640
2641 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2642 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2643 isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
2644 return DAG.getNode(ISD::SUB, DL, VT, N0,
2645 DAG.getNode(ISD::SHL, DL, VT,
2646 N1.getOperand(0).getOperand(1),
2647 N1.getOperand(1)));
2648
2649 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
2650 return V;
2651
2652 // Look for:
2653 // add (add x, 1), y
2654 // And if the target does not like this form then turn into:
2655 // sub y, (xor x, -1)
2656 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2657 N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) {
2658 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2659 DAG.getAllOnesConstant(DL, VT));
2660 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
2661 }
2662
2663 // Hoist one-use subtraction by non-opaque constant:
2664 // (x - C) + y -> (x + y) - C
2665 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2666 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2667 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
2668 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
2669 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2670 }
2671 // Hoist one-use subtraction from non-opaque constant:
2672 // (C - x) + y -> (y - x) + C
2673 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2674 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
2675 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2676 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
2677 }
2678
2679 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2680 // rather than 'add 0/-1' (the zext should get folded).
2681 // add (sext i1 Y), X --> sub X, (zext i1 Y)
2682 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2683 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
2684 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
2685 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2686 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2687 }
2688
2689 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2690 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2691 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2692 if (TN->getVT() == MVT::i1) {
2693 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2694 DAG.getConstant(1, DL, VT));
2695 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2696 }
2697 }
2698
2699 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2700 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2701 N1.getResNo() == 0)
2702 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2703 N0, N1.getOperand(0), N1.getOperand(2));
2704
2705 // (add X, Carry) -> (addcarry X, 0, Carry)
2706 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2707 if (SDValue Carry = getAsCarry(TLI, N1))
2708 return DAG.getNode(ISD::ADDCARRY, DL,
2709 DAG.getVTList(VT, Carry.getValueType()), N0,
2710 DAG.getConstant(0, DL, VT), Carry);
2711
2712 return SDValue();
2713}
2714
2715SDValue DAGCombiner::visitADDC(SDNode *N) {
2716 SDValue N0 = N->getOperand(0);
2717 SDValue N1 = N->getOperand(1);
2718 EVT VT = N0.getValueType();
2719 SDLoc DL(N);
2720
2721 // If the flag result is dead, turn this into an ADD.
2722 if (!N->hasAnyUseOfValue(1))
2723 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2724 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2725
2726 // canonicalize constant to RHS.
2727 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2728 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2729 if (N0C && !N1C)
2730 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2731
2732 // fold (addc x, 0) -> x + no carry out
2733 if (isNullConstant(N1))
2734 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2735 DL, MVT::Glue));
2736
2737 // If it cannot overflow, transform into an add.
2738 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2739 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2740 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2741
2742 return SDValue();
2743}
2744
2745/**
2746 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2747 * then the flip also occurs if computing the inverse is the same cost.
2748 * This function returns an empty SDValue in case it cannot flip the boolean
2749 * without increasing the cost of the computation. If you want to flip a boolean
2750 * no matter what, use DAG.getLogicalNOT.
2751 */
2752static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
2753 const TargetLowering &TLI,
2754 bool Force) {
2755 if (Force && isa<ConstantSDNode>(V))
2756 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
2757
2758 if (V.getOpcode() != ISD::XOR)
2759 return SDValue();
2760
2761 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
2762 if (!Const)
2763 return SDValue();
2764
2765 EVT VT = V.getValueType();
2766
2767 bool IsFlip = false;
2768 switch(TLI.getBooleanContents(VT)) {
2769 case TargetLowering::ZeroOrOneBooleanContent:
2770 IsFlip = Const->isOne();
2771 break;
2772 case TargetLowering::ZeroOrNegativeOneBooleanContent:
2773 IsFlip = Const->isAllOnesValue();
2774 break;
2775 case TargetLowering::UndefinedBooleanContent:
2776 IsFlip = (Const->getAPIntValue() & 0x01) == 1;
2777 break;
2778 }
2779
2780 if (IsFlip)
2781 return V.getOperand(0);
2782 if (Force)
2783 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
2784 return SDValue();
2785}
2786
2787SDValue DAGCombiner::visitADDO(SDNode *N) {
2788 SDValue N0 = N->getOperand(0);
2789 SDValue N1 = N->getOperand(1);
2790 EVT VT = N0.getValueType();
2791 bool IsSigned = (ISD::SADDO == N->getOpcode());
2792
2793 EVT CarryVT = N->getValueType(1);
2794 SDLoc DL(N);
2795
2796 // If the flag result is dead, turn this into an ADD.
2797 if (!N->hasAnyUseOfValue(1))
2798 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2799 DAG.getUNDEF(CarryVT));
2800
2801 // canonicalize constant to RHS.
2802 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2803 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2804 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
2805
2806 // fold (addo x, 0) -> x + no carry out
2807 if (isNullOrNullSplat(N1))
2808 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2809
2810 if (!IsSigned) {
2811 // If it cannot overflow, transform into an add.
2812 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2813 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2814 DAG.getConstant(0, DL, CarryVT));
2815
2816 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2817 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
2818 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2819 DAG.getConstant(0, DL, VT), N0.getOperand(0));
2820 return CombineTo(
2821 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
2822 }
2823
2824 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2825 return Combined;
2826
2827 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2828 return Combined;
2829 }
2830
2831 return SDValue();
2832}
2833
2834SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2835 EVT VT = N0.getValueType();
2836 if (VT.isVector())
2837 return SDValue();
2838
2839 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2840 // If Y + 1 cannot overflow.
2841 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2842 SDValue Y = N1.getOperand(0);
2843 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2844 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2845 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2846 N1.getOperand(2));
2847 }
2848
2849 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2850 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2851 if (SDValue Carry = getAsCarry(TLI, N1))
2852 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2853 DAG.getConstant(0, SDLoc(N), VT), Carry);
2854
2855 return SDValue();
2856}
2857
2858SDValue DAGCombiner::visitADDE(SDNode *N) {
2859 SDValue N0 = N->getOperand(0);
2860 SDValue N1 = N->getOperand(1);
2861 SDValue CarryIn = N->getOperand(2);
2862
2863 // canonicalize constant to RHS
2864 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2865 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2866 if (N0C && !N1C)
2867 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2868 N1, N0, CarryIn);
2869
2870 // fold (adde x, y, false) -> (addc x, y)
2871 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2872 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2873
2874 return SDValue();
2875}
2876
2877SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2878 SDValue N0 = N->getOperand(0);
2879 SDValue N1 = N->getOperand(1);
2880 SDValue CarryIn = N->getOperand(2);
2881 SDLoc DL(N);
2882
2883 // canonicalize constant to RHS
2884 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2885 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2886 if (N0C && !N1C)
2887 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2888
2889 // fold (addcarry x, y, false) -> (uaddo x, y)
2890 if (isNullConstant(CarryIn)) {
2891 if (!LegalOperations ||
2892 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
2893 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2894 }
2895
2896 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2897 if (isNullConstant(N0) && isNullConstant(N1)) {
2898 EVT VT = N0.getValueType();
2899 EVT CarryVT = CarryIn.getValueType();
2900 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2901 AddToWorklist(CarryExt.getNode());
2902 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2903 DAG.getConstant(1, DL, VT)),
2904 DAG.getConstant(0, DL, CarryVT));
2905 }
2906
2907 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2908 return Combined;
2909
2910 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2911 return Combined;
2912
2913 return SDValue();
2914}
2915
2916SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
2917 SDValue N0 = N->getOperand(0);
2918 SDValue N1 = N->getOperand(1);
2919 SDValue CarryIn = N->getOperand(2);
2920 SDLoc DL(N);
2921
2922 // canonicalize constant to RHS
2923 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2924 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2925 if (N0C && !N1C)
2926 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
2927
2928 // fold (saddo_carry x, y, false) -> (saddo x, y)
2929 if (isNullConstant(CarryIn)) {
2930 if (!LegalOperations ||
2931 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
2932 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
2933 }
2934
2935 return SDValue();
2936}
2937
2938/**
2939 * If we are facing some sort of diamond carry propapagtion pattern try to
2940 * break it up to generate something like:
2941 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2942 *
2943 * The end result is usually an increase in operation required, but because the
2944 * carry is now linearized, other tranforms can kick in and optimize the DAG.
2945 *
2946 * Patterns typically look something like
2947 * (uaddo A, B)
2948 * / \
2949 * Carry Sum
2950 * | \
2951 * | (addcarry *, 0, Z)
2952 * | /
2953 * \ Carry
2954 * | /
2955 * (addcarry X, *, *)
2956 *
2957 * But numerous variation exist. Our goal is to identify A, B, X and Z and
2958 * produce a combine with a single path for carry propagation.
2959 */
2960static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
2961 SDValue X, SDValue Carry0, SDValue Carry1,
2962 SDNode *N) {
2963 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
2964 return SDValue();
2965 if (Carry1.getOpcode() != ISD::UADDO)
2966 return SDValue();
2967
2968 SDValue Z;
2969
2970 /**
2971 * First look for a suitable Z. It will present itself in the form of
2972 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2973 */
2974 if (Carry0.getOpcode() == ISD::ADDCARRY &&
2975 isNullConstant(Carry0.getOperand(1))) {
2976 Z = Carry0.getOperand(2);
2977 } else if (Carry0.getOpcode() == ISD::UADDO &&
2978 isOneConstant(Carry0.getOperand(1))) {
2979 EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
2980 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
2981 } else {
2982 // We couldn't find a suitable Z.
2983 return SDValue();
2984 }
2985
2986
2987 auto cancelDiamond = [&](SDValue A,SDValue B) {
2988 SDLoc DL(N);
2989 SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
2990 Combiner.AddToWorklist(NewY.getNode());
2991 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
2992 DAG.getConstant(0, DL, X.getValueType()),
2993 NewY.getValue(1));
2994 };
2995
2996 /**
2997 * (uaddo A, B)
2998 * |
2999 * Sum
3000 * |
3001 * (addcarry *, 0, Z)
3002 */
3003 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3004 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3005 }
3006
3007 /**
3008 * (addcarry A, 0, Z)
3009 * |
3010 * Sum
3011 * |
3012 * (uaddo *, B)
3013 */
3014 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3015 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3016 }
3017
3018 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3019 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3020 }
3021
3022 return SDValue();
3023}
3024
3025// If we are facing some sort of diamond carry/borrow in/out pattern try to
3026// match patterns like:
3027//
3028// (uaddo A, B) CarryIn
3029// | \ |
3030// | \ |
3031// PartialSum PartialCarryOutX /
3032// | | /
3033// | ____|____________/
3034// | / |
3035// (uaddo *, *) \________
3036// | \ \
3037// | \ |
3038// | PartialCarryOutY |
3039// | \ |
3040// | \ /
3041// AddCarrySum | ______/
3042// | /
3043// CarryOut = (or *, *)
3044//
3045// And generate ADDCARRY (or SUBCARRY) with two result values:
3046//
3047// {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn)
3048//
3049// Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with
3050// a single path for carry/borrow out propagation:
3051static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
3052 const TargetLowering &TLI, SDValue Carry0,
3053 SDValue Carry1, SDNode *N) {
3054 if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1)
3055 return SDValue();
3056 unsigned Opcode = Carry0.getOpcode();
3057 if (Opcode != Carry1.getOpcode())
3058 return SDValue();
3059 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3060 return SDValue();
3061
3062 // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the
3063 // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in
3064 // the above ASCII art.)
3065 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3066 Carry1.getOperand(1) != Carry0.getValue(0))
3067 std::swap(Carry0, Carry1);
3068 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3069 Carry1.getOperand(1) != Carry0.getValue(0))
3070 return SDValue();
3071
3072 // The carry in value must be on the righthand side for subtraction.
3073 unsigned CarryInOperandNum =
3074 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3075 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3076 return SDValue();
3077 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3078
3079 unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY;
3080 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3081 return SDValue();
3082
3083 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3084 // TODO: make getAsCarry() aware of how partial carries are merged.
3085 if (CarryIn.getOpcode() != ISD::ZERO_EXTEND)
3086 return SDValue();
3087 CarryIn = CarryIn.getOperand(0);
3088 if (CarryIn.getValueType() != MVT::i1)
3089 return SDValue();
3090
3091 SDLoc DL(N);
3092 SDValue Merged =
3093 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3094 Carry0.getOperand(1), CarryIn);
3095
3096 // Please note that because we have proven that the result of the UADDO/USUBO
3097 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3098 // therefore prove that if the first UADDO/USUBO overflows, the second
3099 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3100 // maximum value.
3101 //
3102 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3103 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3104 //
3105 // This is important because it means that OR and XOR can be used to merge
3106 // carry flags; and that AND can return a constant zero.
3107 //
3108 // TODO: match other operations that can merge flags (ADD, etc)
3109 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3110 if (N->getOpcode() == ISD::AND)
3111 return DAG.getConstant(0, DL, MVT::i1);
3112 return Merged.getValue(1);
3113}
3114
3115SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
3116 SDNode *N) {
3117 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
3118 if (isBitwiseNot(N0))
3119 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3120 SDLoc DL(N);
3121 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
3122 N0.getOperand(0), NotC);
3123 return CombineTo(
3124 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3125 }
3126
3127 // Iff the flag result is dead:
3128 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
3129 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3130 // or the dependency between the instructions.
3131 if ((N0.getOpcode() == ISD::ADD ||
3132 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3133 N0.getValue(1) != CarryIn)) &&
3134 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3135 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
3136 N0.getOperand(0), N0.getOperand(1), CarryIn);
3137
3138 /**
3139 * When one of the addcarry argument is itself a carry, we may be facing
3140 * a diamond carry propagation. In which case we try to transform the DAG
3141 * to ensure linear carry propagation if that is possible.
3142 */
3143 if (auto Y = getAsCarry(TLI, N1)) {
3144 // Because both are carries, Y and Z can be swapped.
3145 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
3146 return R;
3147 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
3148 return R;
3149 }
3150
3151 return SDValue();
3152}
3153
3154// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
3155// clamp/truncation if necessary.
3156static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS,
3157 SDValue RHS, SelectionDAG &DAG,
3158 const SDLoc &DL) {
3159 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&(static_cast <bool> (DstVT.getScalarSizeInBits() <= SrcVT
.getScalarSizeInBits() && "Illegal truncation") ? void
(0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3160, __extension__ __PRETTY_FUNCTION__))
3160 "Illegal truncation")(static_cast <bool> (DstVT.getScalarSizeInBits() <= SrcVT
.getScalarSizeInBits() && "Illegal truncation") ? void
(0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3160, __extension__ __PRETTY_FUNCTION__))
;
3161
3162 if (DstVT == SrcVT)
3163 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
3164
3165 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
3166 // clamping RHS.
3167 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
3168 DstVT.getScalarSizeInBits());
3169 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
3170 return SDValue();
3171
3172 SDValue SatLimit =
3173 DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(),
3174 DstVT.getScalarSizeInBits()),
3175 DL, SrcVT);
3176 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
3177 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
3178 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
3179 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
3180}
3181
3182// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
3183// usubsat(a,b), optionally as a truncated type.
3184SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) {
3185 if (N->getOpcode() != ISD::SUB ||
3186 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
3187 return SDValue();
3188
3189 EVT SubVT = N->getValueType(0);
3190 SDValue Op0 = N->getOperand(0);
3191 SDValue Op1 = N->getOperand(1);
3192
3193 // Try to find umax(a,b) - b or a - umin(a,b) patterns
3194 // they may be converted to usubsat(a,b).
3195 if (Op0.getOpcode() == ISD::UMAX) {
3196 SDValue MaxLHS = Op0.getOperand(0);
3197 SDValue MaxRHS = Op0.getOperand(1);
3198 if (MaxLHS == Op1)
3199 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N));
3200 if (MaxRHS == Op1)
3201 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N));
3202 }
3203
3204 if (Op1.getOpcode() == ISD::UMIN) {
3205 SDValue MinLHS = Op1.getOperand(0);
3206 SDValue MinRHS = Op1.getOperand(1);
3207 if (MinLHS == Op0)
3208 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N));
3209 if (MinRHS == Op0)
3210 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N));
3211 }
3212
3213 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
3214 if (Op1.getOpcode() == ISD::TRUNCATE &&
3215 Op1.getOperand(0).getOpcode() == ISD::UMIN) {
3216 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
3217 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
3218 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
3219 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
3220 DAG, SDLoc(N));
3221 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
3222 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
3223 DAG, SDLoc(N));
3224 }
3225
3226 return SDValue();
3227}
3228
3229// Since it may not be valid to emit a fold to zero for vector initializers
3230// check if we can before folding.
3231static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
3232 SelectionDAG &DAG, bool LegalOperations) {
3233 if (!VT.isVector())
3234 return DAG.getConstant(0, DL, VT);
3235 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
3236 return DAG.getConstant(0, DL, VT);
3237 return SDValue();
3238}
3239
3240SDValue DAGCombiner::visitSUB(SDNode *N) {
3241 SDValue N0 = N->getOperand(0);
3242 SDValue N1 = N->getOperand(1);
3243 EVT VT = N0.getValueType();
3244 SDLoc DL(N);
3245
3246 // fold vector ops
3247 if (VT.isVector()) {
3248 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3249 return FoldedVOp;
3250
3251 // fold (sub x, 0) -> x, vector edition
3252 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
3253 return N0;
3254 }
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 if (SDValue NewSel = foldBinOpIntoSelect(N))
3266 return NewSel;
3267
3268 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3269
3270 // fold (sub x, c) -> (add x, -c)
3271 if (N1C) {
3272 return DAG.getNode(ISD::ADD, DL, VT, N0,
3273 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3274 }
3275
3276 if (isNullOrNullSplat(N0)) {
3277 unsigned BitWidth = VT.getScalarSizeInBits();
3278 // Right-shifting everything out but the sign bit followed by negation is
3279 // the same as flipping arithmetic/logical shift type without the negation:
3280 // -(X >>u 31) -> (X >>s 31)
3281 // -(X >>s 31) -> (X >>u 31)
3282 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
3283 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
3284 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
3285 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
3286 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
3287 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
3288 }
3289 }
3290
3291 // 0 - X --> 0 if the sub is NUW.
3292 if (N->getFlags().hasNoUnsignedWrap())
3293 return N0;
3294
3295 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
3296 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3297 // N1 must be 0 because negating the minimum signed value is undefined.
3298 if (N->getFlags().hasNoSignedWrap())
3299 return N0;
3300
3301 // 0 - X --> X if X is 0 or the minimum signed value.
3302 return N1;
3303 }
3304
3305 // Convert 0 - abs(x).
3306 SDValue Result;
3307 if (N1->getOpcode() == ISD::ABS &&
3308 !TLI.isOperationLegalOrCustom(ISD::ABS, VT) &&
3309 TLI.expandABS(N1.getNode(), Result, DAG, true))
3310 return Result;
3311 }
3312
3313 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3314 if (isAllOnesOrAllOnesSplat(N0))
3315 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
3316
3317 // fold (A - (0-B)) -> A+B
3318 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
3319 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
3320
3321 // fold A-(A-B) -> B
3322 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
3323 return N1.getOperand(1);
3324
3325 // fold (A+B)-A -> B
3326 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
3327 return N0.getOperand(1);
3328
3329 // fold (A+B)-B -> A
3330 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
3331 return N0.getOperand(0);
3332
3333 // fold (A+C1)-C2 -> A+(C1-C2)
3334 if (N0.getOpcode() == ISD::ADD &&
3335 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3336 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3337 SDValue NewC =
3338 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1});
3339 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3339, __extension__ __PRETTY_FUNCTION__))
;
3340 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
3341 }
3342
3343 // fold C2-(A+C1) -> (C2-C1)-A
3344 if (N1.getOpcode() == ISD::ADD) {
3345 SDValue N11 = N1.getOperand(1);
3346 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
3347 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
3348 SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11});
3349 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3349, __extension__ __PRETTY_FUNCTION__))
;
3350 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
3351 }
3352 }
3353
3354 // fold (A-C1)-C2 -> A-(C1+C2)
3355 if (N0.getOpcode() == ISD::SUB &&
3356 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3357 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3358 SDValue NewC =
3359 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1});
3360 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3360, __extension__ __PRETTY_FUNCTION__))
;
3361 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
3362 }
3363
3364 // fold (c1-A)-c2 -> (c1-c2)-A
3365 if (N0.getOpcode() == ISD::SUB &&
3366 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3367 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) {
3368 SDValue NewC =
3369 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1});
3370 assert(NewC && "Constant folding failed")(static_cast <bool> (NewC && "Constant folding failed"
) ? void (0) : __assert_fail ("NewC && \"Constant folding failed\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3370, __extension__ __PRETTY_FUNCTION__))
;
3371 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
3372 }
3373
3374 // fold ((A+(B+or-C))-B) -> A+or-C
3375 if (N0.getOpcode() == ISD::ADD &&
3376 (N0.getOperand(1).getOpcode() == ISD::SUB ||
3377 N0.getOperand(1).getOpcode() == ISD::ADD) &&
3378 N0.getOperand(1).getOperand(0) == N1)
3379 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
3380 N0.getOperand(1).getOperand(1));
3381
3382 // fold ((A+(C+B))-B) -> A+C
3383 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
3384 N0.getOperand(1).getOperand(1) == N1)
3385 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
3386 N0.getOperand(1).getOperand(0));
3387
3388 // fold ((A-(B-C))-C) -> A-B
3389 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
3390 N0.getOperand(1).getOperand(1) == N1)
3391 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
3392 N0.getOperand(1).getOperand(0));
3393
3394 // fold (A-(B-C)) -> A+(C-B)
3395 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
3396 return DAG.getNode(ISD::ADD, DL, VT, N0,
3397 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
3398 N1.getOperand(0)));
3399
3400 // A - (A & B) -> A & (~B)
3401 if (N1.getOpcode() == ISD::AND) {
3402 SDValue A = N1.getOperand(0);
3403 SDValue B = N1.getOperand(1);
3404 if (A != N0)
3405 std::swap(A, B);
3406 if (A == N0 &&
3407 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) {
3408 SDValue InvB =
3409 DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT));
3410 return DAG.getNode(ISD::AND, DL, VT, A, InvB);
3411 }
3412 }
3413
3414 // fold (X - (-Y * Z)) -> (X + (Y * Z))
3415 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
3416 if (N1.getOperand(0).getOpcode() == ISD::SUB &&
3417 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
3418 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3419 N1.getOperand(0).getOperand(1),
3420 N1.getOperand(1));
3421 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3422 }
3423 if (N1.getOperand(1).getOpcode() == ISD::SUB &&
3424 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
3425 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3426 N1.getOperand(0),
3427 N1.getOperand(1).getOperand(1));
3428 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3429 }
3430 }
3431
3432 // If either operand of a sub is undef, the result is undef
3433 if (N0.isUndef())
3434 return N0;
3435 if (N1.isUndef())
3436 return N1;
3437
3438 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
3439 return V;
3440
3441 if (SDValue V = foldAddSubOfSignBit(N, DAG))
3442 return V;
3443
3444 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
3445 return V;
3446
3447 if (SDValue V = foldSubToUSubSat(VT, N))
3448 return V;
3449
3450 // (x - y) - 1 -> add (xor y, -1), x
3451 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) {
3452 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
3453 DAG.getAllOnesConstant(DL, VT));
3454 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
3455 }
3456
3457 // Look for:
3458 // sub y, (xor x, -1)
3459 // And if the target does not like this form then turn into:
3460 // add (add x, y), 1
3461 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
3462 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
3463 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
3464 }
3465
3466 // Hoist one-use addition by non-opaque constant:
3467 // (x + C) - y -> (x - y) + C
3468 if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
3469 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3470 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3471 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
3472 }
3473 // y - (x + C) -> (y - x) - C
3474 if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD &&
3475 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
3476 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
3477 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
3478 }
3479 // (x - C) - y -> (x - y) - C
3480 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3481 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3482 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3483 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3484 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
3485 }
3486 // (C - x) - y -> C - (x + y)
3487 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3488 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3489 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
3490 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
3491 }
3492
3493 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3494 // rather than 'sub 0/1' (the sext should get folded).
3495 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3496 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
3497 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
3498 TLI.getBooleanContents(VT) ==
3499 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3500 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
3501 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
3502 }
3503
3504 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3505 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
3506 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
3507 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
3508 SDValue S0 = N1.getOperand(0);
3509 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0))
3510 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
3511 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
3512 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
3513 }
3514 }
3515
3516 // If the relocation model supports it, consider symbol offsets.
3517 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
3518 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
3519 // fold (sub Sym, c) -> Sym-c
3520 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
3521 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
3522 GA->getOffset() -
3523 (uint64_t)N1C->getSExtValue());
3524 // fold (sub Sym+c1, Sym+c2) -> c1-c2
3525 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
3526 if (GA->getGlobal() == GB->getGlobal())
3527 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
3528 DL, VT);
3529 }
3530
3531 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3532 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3533 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3534 if (TN->getVT() == MVT::i1) {
3535 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3536 DAG.getConstant(1, DL, VT));
3537 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
3538 }
3539 }
3540
3541 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
3542 if (N1.getOpcode() == ISD::VSCALE) {
3543 const APInt &IntVal = N1.getConstantOperandAPInt(0);
3544 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
3545 }
3546
3547 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
3548 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
3549 SDValue NewStep = DAG.getConstant(-N1.getConstantOperandAPInt(0), DL,
3550 N1.getOperand(0).getValueType());
3551 return DAG.getNode(ISD::ADD, DL, VT, N0,
3552 DAG.getStepVector(DL, VT, NewStep));
3553 }
3554
3555 // Prefer an add for more folding potential and possibly better codegen:
3556 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3557 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
3558 SDValue ShAmt = N1.getOperand(1);
3559 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
3560 if (ShAmtC &&
3561 ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
3562 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
3563 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
3564 }
3565 }
3566
3567 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) {
3568 // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry)
3569 if (SDValue Carry = getAsCarry(TLI, N0)) {
3570 SDValue X = N1;
3571 SDValue Zero = DAG.getConstant(0, DL, VT);
3572 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
3573 return DAG.getNode(ISD::ADDCARRY, DL,
3574 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
3575 Carry);
3576 }
3577 }
3578
3579 return SDValue();
3580}
3581
3582SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
3583 SDValue N0 = N->getOperand(0);
3584 SDValue N1 = N->getOperand(1);
3585 EVT VT = N0.getValueType();
3586 SDLoc DL(N);
3587
3588 // fold vector ops
3589 if (VT.isVector()) {
3590 // TODO SimplifyVBinOp
3591
3592 // fold (sub_sat x, 0) -> x, vector edition
3593 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
3594 return N0;
3595 }
3596
3597 // fold (sub_sat x, undef) -> 0
3598 if (N0.isUndef() || N1.isUndef())
3599 return DAG.getConstant(0, DL, VT);
3600
3601 // fold (sub_sat x, x) -> 0
3602 if (N0 == N1)
3603 return DAG.getConstant(0, DL, VT);
3604
3605 // fold (sub_sat c1, c2) -> c3
3606 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
3607 return C;
3608
3609 // fold (sub_sat x, 0) -> x
3610 if (isNullConstant(N1))
3611 return N0;
3612
3613 return SDValue();
3614}
3615
3616SDValue DAGCombiner::visitSUBC(SDNode *N) {
3617 SDValue N0 = N->getOperand(0);
3618 SDValue N1 = N->getOperand(1);
3619 EVT VT = N0.getValueType();
3620 SDLoc DL(N);
3621
3622 // If the flag result is dead, turn this into an SUB.
3623 if (!N->hasAnyUseOfValue(1))
3624 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3625 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3626
3627 // fold (subc x, x) -> 0 + no borrow
3628 if (N0 == N1)
3629 return CombineTo(N, DAG.getConstant(0, DL, VT),
3630 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3631
3632 // fold (subc x, 0) -> x + no borrow
3633 if (isNullConstant(N1))
3634 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3635
3636 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3637 if (isAllOnesConstant(N0))
3638 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3639 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3640
3641 return SDValue();
3642}
3643
3644SDValue DAGCombiner::visitSUBO(SDNode *N) {
3645 SDValue N0 = N->getOperand(0);
3646 SDValue N1 = N->getOperand(1);
3647 EVT VT = N0.getValueType();
3648 bool IsSigned = (ISD::SSUBO == N->getOpcode());
3649
3650 EVT CarryVT = N->getValueType(1);
3651 SDLoc DL(N);
3652
3653 // If the flag result is dead, turn this into an SUB.
3654 if (!N->hasAnyUseOfValue(1))
3655 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3656 DAG.getUNDEF(CarryVT));
3657
3658 // fold (subo x, x) -> 0 + no borrow
3659 if (N0 == N1)
3660 return CombineTo(N, DAG.getConstant(0, DL, VT),
3661 DAG.getConstant(0, DL, CarryVT));
3662
3663 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3664
3665 // fold (subox, c) -> (addo x, -c)
3666 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
3667 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
3668 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3669 }
3670
3671 // fold (subo x, 0) -> x + no borrow
3672 if (isNullOrNullSplat(N1))
3673 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3674
3675 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3676 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
3677 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3678 DAG.getConstant(0, DL, CarryVT));
3679
3680 return SDValue();
3681}
3682
3683SDValue DAGCombiner::visitSUBE(SDNode *N) {
3684 SDValue N0 = N->getOperand(0);
3685 SDValue N1 = N->getOperand(1);
3686 SDValue CarryIn = N->getOperand(2);
3687
3688 // fold (sube x, y, false) -> (subc x, y)
3689 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3690 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
3691
3692 return SDValue();
3693}
3694
3695SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
3696 SDValue N0 = N->getOperand(0);
3697 SDValue N1 = N->getOperand(1);
3698 SDValue CarryIn = N->getOperand(2);
3699
3700 // fold (subcarry x, y, false) -> (usubo x, y)
3701 if (isNullConstant(CarryIn)) {
3702 if (!LegalOperations ||
3703 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
3704 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
3705 }
3706
3707 return SDValue();
3708}
3709
3710SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
3711 SDValue N0 = N->getOperand(0);
3712 SDValue N1 = N->getOperand(1);
3713 SDValue CarryIn = N->getOperand(2);
3714
3715 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
3716 if (isNullConstant(CarryIn)) {
3717 if (!LegalOperations ||
3718 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
3719 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
3720 }
3721
3722 return SDValue();
3723}
3724
3725// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
3726// UMULFIXSAT here.
3727SDValue DAGCombiner::visitMULFIX(SDNode *N) {
3728 SDValue N0 = N->getOperand(0);
3729 SDValue N1 = N->getOperand(1);
3730 SDValue Scale = N->getOperand(2);
3731 EVT VT = N0.getValueType();
3732
3733 // fold (mulfix x, undef, scale) -> 0
3734 if (N0.isUndef() || N1.isUndef())
3735 return DAG.getConstant(0, SDLoc(N), VT);
3736
3737 // Canonicalize constant to RHS (vector doesn't have to splat)
3738 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3739 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3740 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
3741
3742 // fold (mulfix x, 0, scale) -> 0
3743 if (isNullConstant(N1))
3744 return DAG.getConstant(0, SDLoc(N), VT);
3745
3746 return SDValue();
3747}
3748
3749SDValue DAGCombiner::visitMUL(SDNode *N) {
3750 SDValue N0 = N->getOperand(0);
3751 SDValue N1 = N->getOperand(1);
3752 EVT VT = N0.getValueType();
3753
3754 // fold (mul x, undef) -> 0
3755 if (N0.isUndef() || N1.isUndef())
3756 return DAG.getConstant(0, SDLoc(N), VT);
3757
3758 bool N1IsConst = false;
3759 bool N1IsOpaqueConst = false;
3760 APInt ConstValue1;
3761
3762 // fold vector ops
3763 if (VT.isVector()) {
3764 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3765 return FoldedVOp;
3766
3767 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
3768 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3770, __extension__ __PRETTY_FUNCTION__))
3769 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3770, __extension__ __PRETTY_FUNCTION__))
3770 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3770, __extension__ __PRETTY_FUNCTION__))
;
3771 } else {
3772 N1IsConst = isa<ConstantSDNode>(N1);
3773 if (N1IsConst) {
3774 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3775 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3776 }
3777 }
3778
3779 // fold (mul c1, c2) -> c1*c2
3780 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1}))
3781 return C;
3782
3783 // canonicalize constant to RHS (vector doesn't have to splat)
3784 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3785 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3786 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
3787
3788 // fold (mul x, 0) -> 0
3789 if (N1IsConst && ConstValue1.isNullValue())
3790 return N1;
3791
3792 // fold (mul x, 1) -> x
3793 if (N1IsConst && ConstValue1.isOneValue())
3794 return N0;
3795
3796 if (SDValue NewSel = foldBinOpIntoSelect(N))
3797 return NewSel;
3798
3799 // fold (mul x, -1) -> 0-x
3800 if (N1IsConst && ConstValue1.isAllOnesValue()) {
3801 SDLoc DL(N);
3802 return DAG.getNode(ISD::SUB, DL, VT,
3803 DAG.getConstant(0, DL, VT), N0);
3804 }
3805
3806 // fold (mul x, (1 << c)) -> x << c
3807 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3808 DAG.isKnownToBeAPowerOfTwo(N1) &&
3809 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
3810 SDLoc DL(N);
3811 SDValue LogBase2 = BuildLogBase2(N1, DL);
3812 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3813 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3814 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
3815 }
3816
3817 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3818 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
3819 unsigned Log2Val = (-ConstValue1).logBase2();
3820 SDLoc DL(N);
3821 // FIXME: If the input is something that is easily negated (e.g. a
3822 // single-use add), we should put the negate there.
3823 return DAG.getNode(ISD::SUB, DL, VT,
3824 DAG.getConstant(0, DL, VT),
3825 DAG.getNode(ISD::SHL, DL, VT, N0,
3826 DAG.getConstant(Log2Val, DL,
3827 getShiftAmountTy(N0.getValueType()))));
3828 }
3829
3830 // Try to transform:
3831 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3832 // mul x, (2^N + 1) --> add (shl x, N), x
3833 // mul x, (2^N - 1) --> sub (shl x, N), x
3834 // Examples: x * 33 --> (x << 5) + x
3835 // x * 15 --> (x << 4) - x
3836 // x * -33 --> -((x << 5) + x)
3837 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3838 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
3839 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
3840 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
3841 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
3842 // x * 0xf800 --> (x << 16) - (x << 11)
3843 // x * -0x8800 --> -((x << 15) + (x << 11))
3844 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
3845 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
3846 // TODO: We could handle more general decomposition of any constant by
3847 // having the target set a limit on number of ops and making a
3848 // callback to determine that sequence (similar to sqrt expansion).
3849 unsigned MathOp = ISD::DELETED_NODE;
3850 APInt MulC = ConstValue1.abs();
3851 // The constant `2` should be treated as (2^0 + 1).
3852 unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros();
3853 MulC.lshrInPlace(TZeros);
3854 if ((MulC - 1).isPowerOf2())
3855 MathOp = ISD::ADD;
3856 else if ((MulC + 1).isPowerOf2())
3857 MathOp = ISD::SUB;
3858
3859 if (MathOp != ISD::DELETED_NODE) {
3860 unsigned ShAmt =
3861 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
3862 ShAmt += TZeros;
3863 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3864, __extension__ __PRETTY_FUNCTION__))
3864 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3864, __extension__ __PRETTY_FUNCTION__))
;
3865 SDLoc DL(N);
3866 SDValue Shl =
3867 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
3868 SDValue R =
3869 TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
3870 DAG.getNode(ISD::SHL, DL, VT, N0,
3871 DAG.getConstant(TZeros, DL, VT)))
3872 : DAG.getNode(MathOp, DL, VT, Shl, N0);
3873 if (ConstValue1.isNegative())
3874 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
3875 return R;
3876 }
3877 }
3878
3879 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3880 if (N0.getOpcode() == ISD::SHL &&
3881 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3882 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3883 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
3884 if (isConstantOrConstantVector(C3))
3885 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
3886 }
3887
3888 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3889 // use.
3890 {
3891 SDValue Sh(nullptr, 0), Y(nullptr, 0);
3892
3893 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3894 if (N0.getOpcode() == ISD::SHL &&
3895 isConstantOrConstantVector(N0.getOperand(1)) &&
3896 N0.getNode()->hasOneUse()) {
3897 Sh = N0; Y = N1;
3898 } else if (N1.getOpcode() == ISD::SHL &&
3899 isConstantOrConstantVector(N1.getOperand(1)) &&
3900 N1.getNode()->hasOneUse()) {
3901 Sh = N1; Y = N0;
3902 }
3903
3904 if (Sh.getNode()) {
3905 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
3906 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
3907 }
3908 }
3909
3910 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3911 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
3912 N0.getOpcode() == ISD::ADD &&
3913 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
3914 isMulAddWithConstProfitable(N, N0, N1))
3915 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
3916 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
3917 N0.getOperand(0), N1),
3918 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
3919 N0.getOperand(1), N1));
3920
3921 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
3922 if (N0.getOpcode() == ISD::VSCALE)
3923 if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) {
3924 const APInt &C0 = N0.getConstantOperandAPInt(0);
3925 const APInt &C1 = NC1->getAPIntValue();
3926 return DAG.getVScale(SDLoc(N), VT, C0 * C1);
3927 }
3928
3929 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
3930 APInt MulVal;
3931 if (N0.getOpcode() == ISD::STEP_VECTOR)
3932 if (ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
3933 const APInt &C0 = N0.getConstantOperandAPInt(0);
3934 EVT SVT = N0.getOperand(0).getValueType();
3935 SDValue NewStep = DAG.getConstant(
3936 C0 * MulVal.sextOrTrunc(SVT.getSizeInBits()), SDLoc(N), SVT);
3937 return DAG.getStepVector(SDLoc(N), VT, NewStep);
3938 }
3939
3940 // Fold ((mul x, 0/undef) -> 0,
3941 // (mul x, 1) -> x) -> x)
3942 // -> and(x, mask)
3943 // We can replace vectors with '0' and '1' factors with a clearing mask.
3944 if (VT.isFixedLengthVector()) {
3945 unsigned NumElts = VT.getVectorNumElements();
3946 SmallBitVector ClearMask;
3947 ClearMask.reserve(NumElts);
3948 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
3949 if (!V || V->isNullValue()) {
3950 ClearMask.push_back(true);
3951 return true;
3952 }
3953 ClearMask.push_back(false);
3954 return V->isOne();
3955 };
3956 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
3957 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
3958 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3958, __extension__ __PRETTY_FUNCTION__))
;
3959 SDLoc DL(N);
3960 EVT LegalSVT = N1.getOperand(0).getValueType();
3961 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
3962 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
3963 SmallVector<SDValue, 16> Mask(NumElts, AllOnes);
3964 for (unsigned I = 0; I != NumElts; ++I)
3965 if (ClearMask[I])
3966 Mask[I] = Zero;
3967 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
3968 }
3969 }
3970
3971 // reassociate mul
3972 if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
3973 return RMUL;
3974
3975 return SDValue();
3976}
3977
3978/// Return true if divmod libcall is available.
3979static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
3980 const TargetLowering &TLI) {
3981 RTLIB::Libcall LC;
3982 EVT NodeType = Node->getValueType(0);
3983 if (!NodeType.isSimple())
3984 return false;
3985 switch (NodeType.getSimpleVT().SimpleTy) {
3986 default: return false; // No libcall for vector types.
3987 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
3988 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
3989 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
3990 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
3991 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
3992 }
3993
3994 return TLI.getLibcallName(LC) != nullptr;
3995}
3996
3997/// Issue divrem if both quotient and remainder are needed.
3998SDValue DAGCombiner::useDivRem(SDNode *Node) {
3999 if (Node->use_empty())
4000 return SDValue(); // This is a dead node, leave it alone.
4001
4002 unsigned Opcode = Node->getOpcode();
4003 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
4004 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
4005
4006 // DivMod lib calls can still work on non-legal types if using lib-calls.
4007 EVT VT = Node->getValueType(0);
4008 if (VT.isVector() || !VT.isInteger())
4009 return SDValue();
4010
4011 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
4012 return SDValue();
4013
4014 // If DIVREM is going to get expanded into a libcall,
4015 // but there is no libcall available, then don't combine.
4016 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
4017 !isDivRemLibcallAvailable(Node, isSigned, TLI))
4018 return SDValue();
4019
4020 // If div is legal, it's better to do the normal expansion
4021 unsigned OtherOpcode = 0;
4022 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
4023 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
4024 if (TLI.isOperationLegalOrCustom(Opcode, VT))
4025 return SDValue();
4026 } else {
4027 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4028 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
4029 return SDValue();
4030 }
4031
4032 SDValue Op0 = Node->getOperand(0);
4033 SDValue Op1 = Node->getOperand(1);
4034 SDValue combined;
4035 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
4036 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
4037 SDNode *User = *UI;
4038 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
4039 User->use_empty())
4040 continue;
4041 // Convert the other matching node(s), too;
4042 // otherwise, the DIVREM may get target-legalized into something
4043 // target-specific that we won't be able to recognize.
4044 unsigned UserOpc = User->getOpcode();
4045 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
4046 User->getOperand(0) == Op0 &&
4047 User->getOperand(1) == Op1) {
4048 if (!combined) {
4049 if (UserOpc == OtherOpcode) {
4050 SDVTList VTs = DAG.getVTList(VT, VT);
4051 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
4052 } else if (UserOpc == DivRemOpc) {
4053 combined = SDValue(User, 0);
4054 } else {
4055 assert(UserOpc == Opcode)(static_cast <bool> (UserOpc == Opcode) ? void (0) : __assert_fail
("UserOpc == Opcode", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4055, __extension__ __PRETTY_FUNCTION__))
;
4056 continue;
4057 }
4058 }
4059 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
4060 CombineTo(User, combined);
4061 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
4062 CombineTo(User, combined.getValue(1));
4063 }
4064 }
4065 return combined;
4066}
4067
4068static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
4069 SDValue N0 = N->getOperand(0);
4070 SDValue N1 = N->getOperand(1);
4071 EVT VT = N->getValueType(0);
4072 SDLoc DL(N);
4073
4074 unsigned Opc = N->getOpcode();
4075 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
4076 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4077
4078 // X / undef -> undef
4079 // X % undef -> undef
4080 // X / 0 -> undef
4081 // X % 0 -> undef
4082 // NOTE: This includes vectors where any divisor element is zero/undef.
4083 if (DAG.isUndef(Opc, {N0, N1}))
4084 return DAG.getUNDEF(VT);
4085
4086 // undef / X -> 0
4087 // undef % X -> 0
4088 if (N0.isUndef())
4089 return DAG.getConstant(0, DL, VT);
4090
4091 // 0 / X -> 0
4092 // 0 % X -> 0
4093 ConstantSDNode *N0C = isConstOrConstSplat(N0);
4094 if (N0C && N0C->isNullValue())
4095 return N0;
4096
4097 // X / X -> 1
4098 // X % X -> 0
4099 if (N0 == N1)
4100 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
4101
4102 // X / 1 -> X
4103 // X % 1 -> 0
4104 // If this is a boolean op (single-bit element type), we can't have
4105 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
4106 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
4107 // it's a 1.
4108 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
4109 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
4110
4111 return SDValue();
4112}
4113
4114SDValue DAGCombiner::visitSDIV(SDNode *N) {
4115 SDValue N0 = N->getOperand(0);
4116 SDValue N1 = N->getOperand(1);
4117 EVT VT = N->getValueType(0);
4118 EVT CCVT = getSetCCResultType(VT);
4119
4120 // fold vector ops
4121 if (VT.isVector())
4122 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4123 return FoldedVOp;
4124
4125 SDLoc DL(N);
4126
4127 // fold (sdiv c1, c2) -> c1/c2
4128 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4129 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
4130 return C;
4131
4132 // fold (sdiv X, -1) -> 0-X
4133 if (N1C && N1C->isAllOnesValue())
4134 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
4135
4136 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
4137 if (N1C && N1C->getAPIntValue().isMinSignedValue())
4138 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4139 DAG.getConstant(1, DL, VT),
4140 DAG.getConstant(0, DL, VT));
4141
4142 if (SDValue V = simplifyDivRem(N, DAG))
4143 return V;
4144
4145 if (SDValue NewSel = foldBinOpIntoSelect(N))
4146 return NewSel;
4147
4148 // If we know the sign bits of both operands are zero, strength reduce to a
4149 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
4150 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4151 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
4152
4153 if (SDValue V = visitSDIVLike(N0, N1, N)) {
4154 // If the corresponding remainder node exists, update its users with
4155 // (Dividend - (Quotient * Divisor).
4156 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
4157 { N0, N1 })) {
4158 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
4159 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4160 AddToWorklist(Mul.getNode());
4161 AddToWorklist(Sub.getNode());
4162 CombineTo(RemNode, Sub);
4163 }
4164 return V;
4165 }
4166
4167 // sdiv, srem -> sdivrem
4168 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4169 // true. Otherwise, we break the simplification logic in visitREM().
4170 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4171 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
4172 if (SDValue DivRem = useDivRem(N))
4173 return DivRem;
4174
4175 return SDValue();
4176}
4177
4178SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
4179 SDLoc DL(N);
4180 EVT VT = N->getValueType(0);
4181 EVT CCVT = getSetCCResultType(VT);
4182 unsigned BitWidth = VT.getScalarSizeInBits();
4183
4184 // Helper for determining whether a value is a power-2 constant scalar or a
4185 // vector of such elements.
4186 auto IsPowerOfTwo = [](ConstantSDNode *C) {
4187 if (C->isNullValue() || C->isOpaque())
4188 return false;
4189 if (C->getAPIntValue().isPowerOf2())
4190 return true;
4191 if ((-C->getAPIntValue()).isPowerOf2())
4192 return true;
4193 return false;
4194 };
4195
4196 // fold (sdiv X, pow2) -> simple ops after legalize
4197 // FIXME: We check for the exact bit here because the generic lowering gives
4198 // better results in that case. The target-specific lowering should learn how
4199 // to handle exact sdivs efficiently.
4200 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
4201 // Target-specific implementation of sdiv x, pow2.
4202 if (SDValue Res = BuildSDIVPow2(N))
4203 return Res;
4204
4205 // Create constants that are functions of the shift amount value.
4206 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
4207 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
4208 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
4209 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
4210 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
4211 if (!isConstantOrConstantVector(Inexact))
4212 return SDValue();
4213
4214 // Splat the sign bit into the register
4215 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
4216 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
4217 AddToWorklist(Sign.getNode());
4218
4219 // Add (N0 < 0) ? abs2 - 1 : 0;
4220 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
4221 AddToWorklist(Srl.getNode());
4222 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
4223 AddToWorklist(Add.getNode());
4224 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
4225 AddToWorklist(Sra.getNode());
4226
4227 // Special case: (sdiv X, 1) -> X
4228 // Special Case: (sdiv X, -1) -> 0-X
4229 SDValue One = DAG.getConstant(1, DL, VT);
4230 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4231 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
4232 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
4233 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
4234 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
4235
4236 // If dividing by a positive value, we're done. Otherwise, the result must
4237 // be negated.
4238 SDValue Zero = DAG.getConstant(0, DL, VT);
4239 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
4240
4241 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
4242 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
4243 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
4244 return Res;
4245 }
4246
4247 // If integer divide is expensive and we satisfy the requirements, emit an
4248 // alternate sequence. Targets may check function attributes for size/speed
4249 // trade-offs.
4250 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4251 if (isConstantOrConstantVector(N1) &&
4252 !TLI.isIntDivCheap(N->getValueType(0), Attr))
4253 if (SDValue Op = BuildSDIV(N))
4254 return Op;
4255
4256 return SDValue();
4257}
4258
4259SDValue DAGCombiner::visitUDIV(SDNode *N) {
4260 SDValue N0 = N->getOperand(0);
4261 SDValue N1 = N->getOperand(1);
4262 EVT VT = N->getValueType(0);
4263 EVT CCVT = getSetCCResultType(VT);
4264
4265 // fold vector ops
4266 if (VT.isVector())
4267 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4268 return FoldedVOp;
4269
4270 SDLoc DL(N);
4271
4272 // fold (udiv c1, c2) -> c1/c2
4273 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4274 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
4275 return C;
4276
4277 // fold (udiv X, -1) -> select(X == -1, 1, 0)
4278 if (N1C && N1C->getAPIntValue().isAllOnesValue())
4279 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4280 DAG.getConstant(1, DL, VT),
4281 DAG.getConstant(0, DL, VT));
4282
4283 if (SDValue V = simplifyDivRem(N, DAG))
4284 return V;
4285
4286 if (SDValue NewSel = foldBinOpIntoSelect(N))
4287 return NewSel;
4288
4289 if (SDValue V = visitUDIVLike(N0, N1, N)) {
4290 // If the corresponding remainder node exists, update its users with
4291 // (Dividend - (Quotient * Divisor).
4292 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
4293 { N0, N1 })) {
4294 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
4295 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4296 AddToWorklist(Mul.getNode());
4297 AddToWorklist(Sub.getNode());
4298 CombineTo(RemNode, Sub);
4299 }
4300 return V;
4301 }
4302
4303 // sdiv, srem -> sdivrem
4304 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4305 // true. Otherwise, we break the simplification logic in visitREM().
4306 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4307 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
4308 if (SDValue DivRem = useDivRem(N))
4309 return DivRem;
4310
4311 return SDValue();
4312}
4313
4314SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
4315 SDLoc DL(N);
4316 EVT VT = N->getValueType(0);
4317
4318 // fold (udiv x, (1 << c)) -> x >>u c
4319 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4320 DAG.isKnownToBeAPowerOfTwo(N1)) {
4321 SDValue LogBase2 = BuildLogBase2(N1, DL);
4322 AddToWorklist(LogBase2.getNode());
4323
4324 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4325 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4326 AddToWorklist(Trunc.getNode());
4327 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4328 }
4329
4330 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
4331 if (N1.getOpcode() == ISD::SHL) {
4332 SDValue N10 = N1.getOperand(0);
4333 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
4334 DAG.isKnownToBeAPowerOfTwo(N10)) {
4335 SDValue LogBase2 = BuildLogBase2(N10, DL);
4336 AddToWorklist(LogBase2.getNode());
4337
4338 EVT ADDVT = N1.getOperand(1).getValueType();
4339 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
4340 AddToWorklist(Trunc.getNode());
4341 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
4342 AddToWorklist(Add.getNode());
4343 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
4344 }
4345 }
4346
4347 // fold (udiv x, c) -> alternate
4348 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4349 if (isConstantOrConstantVector(N1) &&
4350 !TLI.isIntDivCheap(N->getValueType(0), Attr))
4351 if (SDValue Op = BuildUDIV(N))
4352 return Op;
4353
4354 return SDValue();
4355}
4356
4357// handles ISD::SREM and ISD::UREM
4358SDValue DAGCombiner::visitREM(SDNode *N) {
4359 unsigned Opcode = N->getOpcode();
4360 SDValue N0 = N->getOperand(0);
4361 SDValue N1 = N->getOperand(1);
4362 EVT VT = N->getValueType(0);
4363 EVT CCVT = getSetCCResultType(VT);
4364
4365 bool isSigned = (Opcode == ISD::SREM);
4366 SDLoc DL(N);
4367
4368 // fold (rem c1, c2) -> c1%c2
4369 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4370 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4371 return C;
4372
4373 // fold (urem X, -1) -> select(X == -1, 0, x)
4374 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue())
4375 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4376 DAG.getConstant(0, DL, VT), N0);
4377
4378 if (SDValue V = simplifyDivRem(N, DAG))
4379 return V;
4380
4381 if (SDValue NewSel = foldBinOpIntoSelect(N))
4382 return NewSel;
4383
4384 if (isSigned) {
4385 // If we know the sign bits of both operands are zero, strength reduce to a
4386 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4387 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4388 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
4389 } else {
4390 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
4391 // fold (urem x, pow2) -> (and x, pow2-1)
4392 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4393 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4394 AddToWorklist(Add.getNode());
4395 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4396 }
4397 if (N1.getOpcode() == ISD::SHL &&
4398 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
4399 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4400 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4401 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4402 AddToWorklist(Add.getNode());
4403 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4404 }
4405 }
4406
4407 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4408
4409 // If X/C can be simplified by the division-by-constant logic, lower
4410 // X%C to the equivalent of X-X/C*C.
4411 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4412 // speculative DIV must not cause a DIVREM conversion. We guard against this
4413 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
4414 // combine will not return a DIVREM. Regardless, checking cheapness here
4415 // makes sense since the simplification results in fatter code.
4416 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
4417 SDValue OptimizedDiv =
4418 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
4419 if (OptimizedDiv.getNode()) {
4420 // If the equivalent Div node also exists, update its users.
4421 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4422 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
4423 { N0, N1 }))
4424 CombineTo(DivNode, OptimizedDiv);
4425 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
4426 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4427 AddToWorklist(OptimizedDiv.getNode());
4428 AddToWorklist(Mul.getNode());
4429 return Sub;
4430 }
4431 }
4432
4433 // sdiv, srem -> sdivrem
4434 if (SDValue DivRem = useDivRem(N))
4435 return DivRem.getValue(1);
4436
4437 return SDValue();
4438}
4439
4440SDValue DAGCombiner::visitMULHS(SDNode *N) {
4441 SDValue N0 = N->getOperand(0);
4442 SDValue N1 = N->getOperand(1);
4443 EVT VT = N->getValueType(0);
4444 SDLoc DL(N);
4445
4446 if (VT.isVector()) {
4447 // fold (mulhs x, 0) -> 0
4448 // do not return N0/N1, because undef node may exist.
4449 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) ||
4450 ISD::isConstantSplatVectorAllZeros(N1.getNode()))
4451 return DAG.getConstant(0, DL, VT);
4452 }
4453
4454 // fold (mulhs x, 0) -> 0
4455 if (isNullConstant(N1))
4456 return N1;
4457 // fold (mulhs x, 1) -> (sra x, size(x)-1)
4458 if (isOneConstant(N1))
4459 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
4460 DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL,
4461 getShiftAmountTy(N0.getValueType())));
4462
4463 // fold (mulhs x, undef) -> 0
4464 if (N0.isUndef() || N1.isUndef())
4465 return DAG.getConstant(0, DL, VT);
4466
4467 // If the type twice as wide is legal, transform the mulhs to a wider multiply
4468 // plus a shift.
4469 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
4470 !VT.isVector()) {
4471 MVT Simple = VT.getSimpleVT();
4472 unsigned SimpleSize = Simple.getSizeInBits();
4473 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4474 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4475 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
4476 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
4477 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4478 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4479 DAG.getConstant(SimpleSize, DL,
4480 getShiftAmountTy(N1.getValueType())));
4481 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4482 }
4483 }
4484
4485 return SDValue();
4486}
4487
4488SDValue DAGCombiner::visitMULHU(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 EVT VT = N->getValueType(0);
4492 SDLoc DL(N);
4493
4494 if (VT.isVector()) {
4495 // fold (mulhu x, 0) -> 0
4496 // do not return N0/N1, because undef node may exist.
4497 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) ||
4498 ISD::isConstantSplatVectorAllZeros(N1.getNode()))
4499 return DAG.getConstant(0, DL, VT);
4500 }
4501
4502 // fold (mulhu x, 0) -> 0
4503 if (isNullConstant(N1))
4504 return N1;
4505 // fold (mulhu x, 1) -> 0
4506 if (isOneConstant(N1))
4507 return DAG.getConstant(0, DL, N0.getValueType());
4508 // fold (mulhu x, undef) -> 0
4509 if (N0.isUndef() || N1.isUndef())
4510 return DAG.getConstant(0, DL, VT);
4511
4512 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4513 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4514 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
4515 unsigned NumEltBits = VT.getScalarSizeInBits();
4516 SDValue LogBase2 = BuildLogBase2(N1, DL);
4517 SDValue SRLAmt = DAG.getNode(
4518 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
4519 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4520 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
4521 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4522 }
4523
4524 // If the type twice as wide is legal, transform the mulhu to a wider multiply
4525 // plus a shift.
4526 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
4527 !VT.isVector()) {
4528 MVT Simple = VT.getSimpleVT();
4529 unsigned SimpleSize = Simple.getSizeInBits();
4530 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4531 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4532 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
4533 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
4534 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4535 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4536 DAG.getConstant(SimpleSize, DL,
4537 getShiftAmountTy(N1.getValueType())));
4538 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4539 }
4540 }
4541
4542 return SDValue();
4543}
4544
4545/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4546/// give the opcodes for the two computations that are being performed. Return
4547/// true if a simplification was made.
4548SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
4549 unsigned HiOp) {
4550 // If the high half is not needed, just compute the low half.
4551 bool HiExists = N->hasAnyUseOfValue(1);
4552 if (!HiExists && (!LegalOperations ||
4553 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
4554 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4555 return CombineTo(N, Res, Res);
4556 }
4557
4558 // If the low half is not needed, just compute the high half.
4559 bool LoExists = N->hasAnyUseOfValue(0);
4560 if (!LoExists && (!LegalOperations ||
4561 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
4562 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4563 return CombineTo(N, Res, Res);
4564 }
4565
4566 // If both halves are used, return as it is.
4567 if (LoExists && HiExists)
4568 return SDValue();
4569
4570 // If the two computed results can be simplified separately, separate them.
4571 if (LoExists) {
4572 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4573 AddToWorklist(Lo.getNode());
4574 SDValue LoOpt = combine(Lo.getNode());
4575 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
4576 (!LegalOperations ||
4577 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
4578 return CombineTo(N, LoOpt, LoOpt);
4579 }
4580
4581 if (HiExists) {
4582 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4583 AddToWorklist(Hi.getNode());
4584 SDValue HiOpt = combine(Hi.getNode());
4585 if (HiOpt.getNode() && HiOpt != Hi &&
4586 (!LegalOperations ||
4587 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
4588 return CombineTo(N, HiOpt, HiOpt);
4589 }
4590
4591 return SDValue();
4592}
4593
4594SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
4595 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
4596 return Res;
4597
4598 EVT VT = N->getValueType(0);
4599 SDLoc DL(N);
4600
4601 // If the type is twice as wide is legal, transform the mulhu to a wider
4602 // multiply plus a shift.
4603 if (VT.isSimple() && !VT.isVector()) {
4604 MVT Simple = VT.getSimpleVT();
4605 unsigned SimpleSize = Simple.getSizeInBits();
4606 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4607 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4608 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
4609 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
4610 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4611 // Compute the high part as N1.
4612 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4613 DAG.getConstant(SimpleSize, DL,
4614 getShiftAmountTy(Lo.getValueType())));
4615 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4616 // Compute the low part as N0.
4617 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4618 return CombineTo(N, Lo, Hi);
4619 }
4620 }
4621
4622 return SDValue();
4623}
4624
4625SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
4626 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
4627 return Res;
4628
4629 EVT VT = N->getValueType(0);
4630 SDLoc DL(N);
4631
4632 // (umul_lohi N0, 0) -> (0, 0)
4633 if (isNullConstant(N->getOperand(1))) {
4634 SDValue Zero = DAG.getConstant(0, DL, VT);
4635 return CombineTo(N, Zero, Zero);
4636 }
4637
4638 // (umul_lohi N0, 1) -> (N0, 0)
4639 if (isOneConstant(N->getOperand(1))) {
4640 SDValue Zero = DAG.getConstant(0, DL, VT);
4641 return CombineTo(N, N->getOperand(0), Zero);
4642 }
4643
4644 // If the type is twice as wide is legal, transform the mulhu to a wider
4645 // multiply plus a shift.
4646 if (VT.isSimple() && !VT.isVector()) {
4647 MVT Simple = VT.getSimpleVT();
4648 unsigned SimpleSize = Simple.getSizeInBits();
4649 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4650 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4651 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
4652 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
4653 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4654 // Compute the high part as N1.
4655 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4656 DAG.getConstant(SimpleSize, DL,
4657 getShiftAmountTy(Lo.getValueType())));
4658 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4659 // Compute the low part as N0.
4660 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4661 return CombineTo(N, Lo, Hi);
4662 }
4663 }
4664
4665 return SDValue();
4666}
4667
4668SDValue DAGCombiner::visitMULO(SDNode *N) {
4669 SDValue N0 = N->getOperand(0);
4670 SDValue N1 = N->getOperand(1);
4671 EVT VT = N0.getValueType();
4672 bool IsSigned = (ISD::SMULO == N->getOpcode());
4673
4674 EVT CarryVT = N->getValueType(1);
4675 SDLoc DL(N);
4676
4677 ConstantSDNode *N0C = isConstOrConstSplat(N0);
4678 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4679
4680 // fold operation with constant operands.
4681 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
4682 // multiple results.
4683 if (N0C && N1C) {
4684 bool Overflow;
4685 APInt Result =
4686 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
4687 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
4688 return CombineTo(N, DAG.getConstant(Result, DL, VT),
4689 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
4690 }
4691
4692 // canonicalize constant to RHS.
4693 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4694 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4695 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
4696
4697 // fold (mulo x, 0) -> 0 + no carry out
4698 if (isNullOrNullSplat(N1))
4699 return CombineTo(N, DAG.getConstant(0, DL, VT),
4700 DAG.getConstant(0, DL, CarryVT));
4701
4702 // (mulo x, 2) -> (addo x, x)
4703 if (N1C && N1C->getAPIntValue() == 2)
4704 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
4705 N->getVTList(), N0, N0);
4706
4707 if (IsSigned) {
4708 // A 1 bit SMULO overflows if both inputs are 1.
4709 if (VT.getScalarSizeInBits() == 1) {
4710 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
4711 return CombineTo(N, And,
4712 DAG.getSetCC(DL, CarryVT, And,
4713 DAG.getConstant(0, DL, VT), ISD::SETNE));
4714 }
4715
4716 // Multiplying n * m significant bits yields a result of n + m significant
4717 // bits. If the total number of significant bits does not exceed the
4718 // result bit width (minus 1), there is no overflow.
4719 unsigned SignBits = DAG.ComputeNumSignBits(N0);
4720 if (SignBits > 1)
4721 SignBits += DAG.ComputeNumSignBits(N1);
4722 if (SignBits > VT.getScalarSizeInBits() + 1)
4723 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
4724 DAG.getConstant(0, DL, CarryVT));
4725 } else {
4726 KnownBits N1Known = DAG.computeKnownBits(N1);
4727 KnownBits N0Known = DAG.computeKnownBits(N0);
4728 bool Overflow;
4729 (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow);
4730 if (!Overflow)
4731 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
4732 DAG.getConstant(0, DL, CarryVT));
4733 }
4734
4735 return SDValue();
4736}
4737
4738SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
4739 SDValue N0 = N->getOperand(0);
4740 SDValue N1 = N->getOperand(1);
4741 EVT VT = N0.getValueType();
4742 unsigned Opcode = N->getOpcode();
4743
4744 // fold vector ops
4745 if (VT.isVector())
4746 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4747 return FoldedVOp;
4748
4749 // fold operation with constant operands.
4750 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT, {N0, N1}))
4751 return C;
4752
4753 // canonicalize constant to RHS
4754 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4755 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4756 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
4757
4758 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4759 // Only do this if the current op isn't legal and the flipped is.
4760 if (!TLI.isOperationLegal(Opcode, VT) &&
4761 (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
4762 (N1.isUndef() || DAG.SignBitIsZero(N1))) {
4763 unsigned AltOpcode;
4764 switch (Opcode) {
4765 case ISD::SMIN: AltOpcode = ISD::UMIN; break;
4766 case ISD::SMAX: AltOpcode = ISD::UMAX; break;
4767 case ISD::UMIN: AltOpcode = ISD::SMIN; break;
4768 case ISD::UMAX: AltOpcode = ISD::SMAX; break;
4769 default: llvm_unreachable("Unknown MINMAX opcode")::llvm::llvm_unreachable_internal("Unknown MINMAX opcode", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4769)
;
4770 }
4771 if (TLI.isOperationLegal(AltOpcode, VT))
4772 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
4773 }
4774
4775 // Simplify the operands using demanded-bits information.
4776 if (SimplifyDemandedBits(SDValue(N, 0)))
4777 return SDValue(N, 0);
4778
4779 return SDValue();
4780}
4781
4782/// If this is a bitwise logic instruction and both operands have the same
4783/// opcode, try to sink the other opcode after the logic instruction.
4784SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
4785 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
4786 EVT VT = N0.getValueType();
4787 unsigned LogicOpcode = N->getOpcode();
4788 unsigned HandOpcode = N0.getOpcode();
4789 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4790, __extension__ __PRETTY_FUNCTION__))
4790 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4790, __extension__ __PRETTY_FUNCTION__))
;
4791 assert(HandOpcode == N1.getOpcode() && "Bad input!")(static_cast <bool> (HandOpcode == N1.getOpcode() &&
"Bad input!") ? void (0) : __assert_fail ("HandOpcode == N1.getOpcode() && \"Bad input!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4791, __extension__ __PRETTY_FUNCTION__))
;
4792
4793 // Bail early if none of these transforms apply.
4794 if (N0.getNumOperands() == 0)
4795 return SDValue();
4796
4797 // FIXME: We should check number of uses of the operands to not increase
4798 // the instruction count for all transforms.
4799
4800 // Handle size-changing casts.
4801 SDValue X = N0.getOperand(0);
4802 SDValue Y = N1.getOperand(0);
4803 EVT XVT = X.getValueType();
4804 SDLoc DL(N);
4805 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
4806 HandOpcode == ISD::SIGN_EXTEND) {
4807 // If both operands have other uses, this transform would create extra
4808 // instructions without eliminating anything.
4809 if (!N0.hasOneUse() && !N1.hasOneUse())
4810 return SDValue();
4811 // We need matching integer source types.
4812 if (XVT != Y.getValueType())
4813 return SDValue();
4814 // Don't create an illegal op during or after legalization. Don't ever
4815 // create an unsupported vector op.
4816 if ((VT.isVector() || LegalOperations) &&
4817 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
4818 return SDValue();
4819 // Avoid infinite looping with PromoteIntBinOp.
4820 // TODO: Should we apply desirable/legal constraints to all opcodes?
4821 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
4822 !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
4823 return SDValue();
4824 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
4825 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4826 return DAG.getNode(HandOpcode, DL, VT, Logic);
4827 }
4828
4829 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
4830 if (HandOpcode == ISD::TRUNCATE) {
4831 // If both operands have other uses, this transform would create extra
4832 // instructions without eliminating anything.
4833 if (!N0.hasOneUse() && !N1.hasOneUse())
4834 return SDValue();
4835 // We need matching source types.
4836 if (XVT != Y.getValueType())
4837 return SDValue();
4838 // Don't create an illegal op during or after legalization.
4839 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
4840 return SDValue();
4841 // Be extra careful sinking truncate. If it's free, there's no benefit in
4842 // widening a binop. Also, don't create a logic op on an illegal type.
4843 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
4844 return SDValue();
4845 if (!TLI.isTypeLegal(XVT))
4846 return SDValue();
4847 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4848 return DAG.getNode(HandOpcode, DL, VT, Logic);
4849 }
4850
4851 // For binops SHL/SRL/SRA/AND:
4852 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
4853 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
4854 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
4855 N0.getOperand(1) == N1.getOperand(1)) {
4856 // If either operand has other uses, this transform is not an improvement.
4857 if (!N0.hasOneUse() || !N1.hasOneUse())
4858 return SDValue();
4859 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4860 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
4861 }
4862
4863 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
4864 if (HandOpcode == ISD::BSWAP) {
4865 // If either operand has other uses, this transform is not an improvement.
4866 if (!N0.hasOneUse() || !N1.hasOneUse())
4867 return SDValue();
4868 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4869 return DAG.getNode(HandOpcode, DL, VT, Logic);
4870 }
4871
4872 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4873 // Only perform this optimization up until type legalization, before
4874 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4875 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4876 // we don't want to undo this promotion.
4877 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4878 // on scalars.
4879 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
4880 Level <= AfterLegalizeTypes) {
4881 // Input types must be integer and the same.
4882 if (XVT.isInteger() && XVT == Y.getValueType() &&
4883 !(VT.isVector() && TLI.isTypeLegal(VT) &&
4884 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
4885 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4886 return DAG.getNode(HandOpcode, DL, VT, Logic);
4887 }
4888 }
4889
4890 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4891 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4892 // If both shuffles use the same mask, and both shuffle within a single
4893 // vector, then it is worthwhile to move the swizzle after the operation.
4894 // The type-legalizer generates this pattern when loading illegal
4895 // vector types from memory. In many cases this allows additional shuffle
4896 // optimizations.
4897 // There are other cases where moving the shuffle after the xor/and/or
4898 // is profitable even if shuffles don't perform a swizzle.
4899 // If both shuffles use the same mask, and both shuffles have the same first
4900 // or second operand, then it might still be profitable to move the shuffle
4901 // after the xor/and/or operation.
4902 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
4903 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
4904 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
4905 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4906, __extension__ __PRETTY_FUNCTION__))
4906 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4906, __extension__ __PRETTY_FUNCTION__))
;
4907
4908 // Check that both shuffles use the same mask. The masks are known to be of
4909 // the same length because the result vector type is the same.
4910 // Check also that shuffles have only one use to avoid introducing extra
4911 // instructions.
4912 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
4913 !SVN0->getMask().equals(SVN1->getMask()))
4914 return SDValue();
4915
4916 // Don't try to fold this node if it requires introducing a
4917 // build vector of all zeros that might be illegal at this stage.
4918 SDValue ShOp = N0.getOperand(1);
4919 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4920 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4921
4922 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4923 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
4924 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
4925 N0.getOperand(0), N1.getOperand(0));
4926 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
4927 }
4928
4929 // Don't try to fold this node if it requires introducing a
4930 // build vector of all zeros that might be illegal at this stage.
4931 ShOp = N0.getOperand(0);
4932 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4933 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4934
4935 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4936 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
4937 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
4938 N1.getOperand(1));
4939 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
4940 }
4941 }
4942
4943 return SDValue();
4944}
4945
4946/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4947SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
4948 const SDLoc &DL) {
4949 SDValue LL, LR, RL, RR, N0CC, N1CC;
4950 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
4951 !isSetCCEquivalent(N1, RL, RR, N1CC))
4952 return SDValue();
4953
4954 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4955, __extension__ __PRETTY_FUNCTION__))
4955 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4955, __extension__ __PRETTY_FUNCTION__))
;
4956 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4958, __extension__ __PRETTY_FUNCTION__))
4957 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4958, __extension__ __PRETTY_FUNCTION__))
4958 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4958, __extension__ __PRETTY_FUNCTION__))
;
4959
4960 // If we're here post-legalization or the logic op type is not i1, the logic
4961 // op type must match a setcc result type. Also, all folds require new
4962 // operations on the left and right operands, so those types must match.
4963 EVT VT = N0.getValueType();
4964 EVT OpVT = LL.getValueType();
4965 if (LegalOperations || VT.getScalarType() != MVT::i1)
4966 if (VT != getSetCCResultType(OpVT))
4967 return SDValue();
4968 if (OpVT != RL.getValueType())
4969 return SDValue();
4970
4971 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
4972 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
4973 bool IsInteger = OpVT.isInteger();
4974 if (LR == RR && CC0 == CC1 && IsInteger) {
4975 bool IsZero = isNullOrNullSplat(LR);
4976 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
4977
4978 // All bits clear?
4979 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
4980 // All sign bits clear?
4981 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
4982 // Any bits set?
4983 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
4984 // Any sign bits set?
4985 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
4986
4987 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
4988 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4989 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
4990 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
4991 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
4992 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
4993 AddToWorklist(Or.getNode());
4994 return DAG.getSetCC(DL, VT, Or, LR, CC1);
4995 }
4996
4997 // All bits set?
4998 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
4999 // All sign bits set?
5000 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
5001 // Any bits clear?
5002 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
5003 // Any sign bits clear?
5004 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
5005
5006 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
5007 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
5008 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
5009 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
5010 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
5011 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
5012 AddToWorklist(And.getNode());
5013 return DAG.getSetCC(DL, VT, And, LR, CC1);
5014 }
5015 }
5016
5017 // TODO: What is the 'or' equivalent of this fold?
5018 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
5019 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
5020 IsInteger && CC0 == ISD::SETNE &&
5021 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
5022 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
5023 SDValue One = DAG.getConstant(1, DL, OpVT);
5024 SDValue Two = DAG.getConstant(2, DL, OpVT);
5025 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
5026 AddToWorklist(Add.getNode());
5027 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
5028 }
5029
5030 // Try more general transforms if the predicates match and the only user of
5031 // the compares is the 'and' or 'or'.
5032 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
5033 N0.hasOneUse() && N1.hasOneUse()) {
5034 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
5035 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
5036 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
5037 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
5038 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
5039 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
5040 SDValue Zero = DAG.getConstant(0, DL, OpVT);
5041 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
5042 }
5043
5044 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
5045 // TODO - support non-uniform vector amounts.
5046 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
5047 // Match a shared variable operand and 2 non-opaque constant operands.
5048 ConstantSDNode *C0 = isConstOrConstSplat(LR);
5049 ConstantSDNode *C1 = isConstOrConstSplat(RR);
5050 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
5051 const APInt &CMax =
5052 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
5053 const APInt &CMin =
5054 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
5055 // The difference of the constants must be a single bit.
5056 if ((CMax - CMin).isPowerOf2()) {
5057 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
5058 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
5059 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
5060 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
5061 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
5062 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
5063 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
5064 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
5065 SDValue Zero = DAG.getConstant(0, DL, OpVT);
5066 return DAG.getSetCC(DL, VT, And, Zero, CC0);
5067 }
5068 }
5069 }
5070 }
5071
5072 // Canonicalize equivalent operands to LL == RL.
5073 if (LL == RR && LR == RL) {
5074 CC1 = ISD::getSetCCSwappedOperands(CC1);
5075 std::swap(RL, RR);
5076 }
5077
5078 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
5079 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
5080 if (LL == RL && LR == RR) {
5081 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
5082 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
5083 if (NewCC != ISD::SETCC_INVALID &&
5084 (!LegalOperations ||
5085 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
5086 TLI.isOperationLegal(ISD::SETCC, OpVT))))
5087 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
5088 }
5089
5090 return SDValue();
5091}
5092
5093/// This contains all DAGCombine rules which reduce two values combined by
5094/// an And operation to a single value. This makes them reusable in the context
5095/// of visitSELECT(). Rules involving constants are not included as
5096/// visitSELECT() already handles those cases.
5097SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
5098 EVT VT = N1.getValueType();
5099 SDLoc DL(N);
5100
5101 // fold (and x, undef) -> 0
5102 if (N0.isUndef() || N1.isUndef())
5103 return DAG.getConstant(0, DL, VT);
5104
5105 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
5106 return V;
5107
5108 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
5109 VT.getSizeInBits() <= 64) {
5110 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5111 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
5112 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
5113 // immediate for an add, but it is legal if its top c2 bits are set,
5114 // transform the ADD so the immediate doesn't need to be materialized
5115 // in a register.
5116 APInt ADDC = ADDI->getAPIntValue();
5117 APInt SRLC = SRLI->getAPIntValue();
5118 if (ADDC.getMinSignedBits() <= 64 &&
5119 SRLC.ult(VT.getSizeInBits()) &&
5120 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
5121 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
5122 SRLC.getZExtValue());
5123 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
5124 ADDC |= Mask;
5125 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
5126 SDLoc DL0(N0);
5127 SDValue NewAdd =
5128 DAG.getNode(ISD::ADD, DL0, VT,
5129 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
5130 CombineTo(N0.getNode(), NewAdd);
5131 // Return N so it doesn't get rechecked!
5132 return SDValue(N, 0);
5133 }
5134 }
5135 }
5136 }
5137 }
5138 }
5139
5140 // Reduce bit extract of low half of an integer to the narrower type.
5141 // (and (srl i64:x, K), KMask) ->
5142 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
5143 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5144 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
5145 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5146 unsigned Size = VT.getSizeInBits();
5147 const APInt &AndMask = CAnd->getAPIntValue();
5148 unsigned ShiftBits = CShift->getZExtValue();
5149
5150 // Bail out, this node will probably disappear anyway.
5151 if (ShiftBits == 0)
5152 return SDValue();
5153
5154 unsigned MaskBits = AndMask.countTrailingOnes();
5155 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
5156
5157 if (AndMask.isMask() &&
5158 // Required bits must not span the two halves of the integer and
5159 // must fit in the half size type.
5160 (ShiftBits + MaskBits <= Size / 2) &&
5161 TLI.isNarrowingProfitable(VT, HalfVT) &&
5162 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
5163 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
5164 TLI.isTruncateFree(VT, HalfVT) &&
5165 TLI.isZExtFree(HalfVT, VT)) {
5166 // The isNarrowingProfitable is to avoid regressions on PPC and
5167 // AArch64 which match a few 64-bit bit insert / bit extract patterns
5168 // on downstream users of this. Those patterns could probably be
5169 // extended to handle extensions mixed in.
5170
5171 SDValue SL(N0);
5172 assert(MaskBits <= Size)(static_cast <bool> (MaskBits <= Size) ? void (0) : __assert_fail
("MaskBits <= Size", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5172, __extension__ __PRETTY_FUNCTION__))
;
5173
5174 // Extracting the highest bit of the low half.
5175 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
5176 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
5177 N0.getOperand(0));
5178
5179 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
5180 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
5181 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
5182 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
5183 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
5184 }
5185 }
5186 }
5187 }
5188
5189 return SDValue();
5190}
5191
5192bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
5193 EVT LoadResultTy, EVT &ExtVT) {
5194 if (!AndC->getAPIntValue().isMask())
5195 return false;
5196
5197 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
5198
5199 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
5200 EVT LoadedVT = LoadN->getMemoryVT();
5201
5202 if (ExtVT == LoadedVT &&
5203 (!LegalOperations ||
5204 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
5205 // ZEXTLOAD will match without needing to change the size of the value being
5206 // loaded.
5207 return true;
5208 }
5209
5210 // Do not change the width of a volatile or atomic loads.
5211 if (!LoadN->isSimple())
5212 return false;
5213
5214 // Do not generate loads of non-round integer types since these can
5215 // be expensive (and would be wrong if the type is not byte sized).
5216 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
5217 return false;
5218
5219 if (LegalOperations &&
5220 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
5221 return false;
5222
5223 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
5224 return false;
5225
5226 return true;
5227}
5228
5229bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
5230 ISD::LoadExtType ExtType, EVT &MemVT,
5231 unsigned ShAmt) {
5232 if (!LDST)
5233 return false;
5234 // Only allow byte offsets.
5235 if (ShAmt % 8)
5236 return false;
5237
5238 // Do not generate loads of non-round integer types since these can
5239 // be expensive (and would be wrong if the type is not byte sized).
5240 if (!MemVT.isRound())
5241 return false;
5242
5243 // Don't change the width of a volatile or atomic loads.
5244 if (!LDST->isSimple())
5245 return false;
5246
5247 EVT LdStMemVT = LDST->getMemoryVT();
5248
5249 // Bail out when changing the scalable property, since we can't be sure that
5250 // we're actually narrowing here.
5251 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
5252 return false;
5253
5254 // Verify that we are actually reducing a load width here.
5255 if (LdStMemVT.bitsLT(MemVT))
5256 return false;
5257
5258 // Ensure that this isn't going to produce an unsupported memory access.
5259 if (ShAmt) {
5260 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5260, __extension__ __PRETTY_FUNCTION__))
;
5261 const unsigned ByteShAmt = ShAmt / 8;
5262 const Align LDSTAlign = LDST->getAlign();
5263 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
5264 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5265 LDST->getAddressSpace(), NarrowAlign,
5266 LDST->getMemOperand()->getFlags()))
5267 return false;
5268 }
5269
5270 // It's not possible to generate a constant of extended or untyped type.
5271 EVT PtrType = LDST->getBasePtr().getValueType();
5272 if (PtrType == MVT::Untyped || PtrType.isExtended())
5273 return false;
5274
5275 if (isa<LoadSDNode>(LDST)) {
5276 LoadSDNode *Load = cast<LoadSDNode>(LDST);
5277 // Don't transform one with multiple uses, this would require adding a new
5278 // load.
5279 if (!SDValue(Load, 0).hasOneUse())
5280 return false;
5281
5282 if (LegalOperations &&
5283 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
5284 return false;
5285
5286 // For the transform to be legal, the load must produce only two values
5287 // (the value loaded and the chain). Don't transform a pre-increment
5288 // load, for example, which produces an extra value. Otherwise the
5289 // transformation is not equivalent, and the downstream logic to replace
5290 // uses gets things wrong.
5291 if (Load->getNumValues() > 2)
5292 return false;
5293
5294 // If the load that we're shrinking is an extload and we're not just
5295 // discarding the extension we can't simply shrink the load. Bail.
5296 // TODO: It would be possible to merge the extensions in some cases.
5297 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
5298 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
5299 return false;
5300
5301 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
5302 return false;
5303 } else {
5304 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5304, __extension__ __PRETTY_FUNCTION__))
;
5305 StoreSDNode *Store = cast<StoreSDNode>(LDST);
5306 // Can't write outside the original store
5307 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
5308 return false;
5309
5310 if (LegalOperations &&
5311 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
5312 return false;
5313 }
5314 return true;
5315}
5316
5317bool DAGCombiner::SearchForAndLoads(SDNode *N,
5318 SmallVectorImpl<LoadSDNode*> &Loads,
5319 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
5320 ConstantSDNode *Mask,
5321 SDNode *&NodeToMask) {
5322 // Recursively search for the operands, looking for loads which can be
5323 // narrowed.
5324 for (SDValue Op : N->op_values()) {
5325 if (Op.getValueType().isVector())
5326 return false;
5327
5328 // Some constants may need fixing up later if they are too large.
5329 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
5330 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
5331 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
5332 NodesWithConsts.insert(N);
5333 continue;
5334 }
5335
5336 if (!Op.hasOneUse())
5337 return false;
5338
5339 switch(Op.getOpcode()) {
5340 case ISD::LOAD: {
5341 auto *Load = cast<LoadSDNode>(Op);
5342 EVT ExtVT;
5343 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
5344 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
5345
5346 // ZEXTLOAD is already small enough.
5347 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
5348 ExtVT.bitsGE(Load->getMemoryVT()))
5349 continue;
5350
5351 // Use LE to convert equal sized loads to zext.
5352 if (ExtVT.bitsLE(Load->getMemoryVT()))
5353 Loads.push_back(Load);
5354
5355 continue;
5356 }
5357 return false;
5358 }
5359 case ISD::ZERO_EXTEND:
5360 case ISD::AssertZext: {
5361 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
5362 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
5363 EVT VT = Op.getOpcode() == ISD::AssertZext ?
5364 cast<VTSDNode>(Op.getOperand(1))->getVT() :
5365 Op.getOperand(0).getValueType();
5366
5367 // We can accept extending nodes if the mask is wider or an equal
5368 // width to the original type.
5369 if (ExtVT.bitsGE(VT))
5370 continue;
5371 break;
5372 }
5373 case ISD::OR:
5374 case ISD::XOR:
5375 case ISD::AND:
5376 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
5377 NodeToMask))
5378 return false;
5379 continue;
5380 }
5381
5382 // Allow one node which will masked along with any loads found.
5383 if (NodeToMask)
5384 return false;
5385
5386 // Also ensure that the node to be masked only produces one data result.
5387 NodeToMask = Op.getNode();
5388 if (NodeToMask->getNumValues() > 1) {
5389 bool HasValue = false;
5390 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
5391 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
5392 if (VT != MVT::Glue && VT != MVT::Other) {
5393 if (HasValue) {
5394 NodeToMask = nullptr;
5395 return false;
5396 }
5397 HasValue = true;
5398 }
5399 }
5400 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?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5400, __extension__ __PRETTY_FUNCTION__))
;
5401 }
5402 }
5403 return true;
5404}
5405
5406bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
5407 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
5408 if (!Mask)
5409 return false;
5410
5411 if (!Mask->getAPIntValue().isMask())
5412 return false;
5413
5414 // No need to do anything if the and directly uses a load.
5415 if (isa<LoadSDNode>(N->getOperand(0)))
5416 return false;
5417
5418 SmallVector<LoadSDNode*, 8> Loads;
5419 SmallPtrSet<SDNode*, 2> NodesWithConsts;
5420 SDNode *FixupNode = nullptr;
5421 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
5422 if (Loads.size() == 0)
5423 return false;
5424
5425 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "Backwards propagate AND: "
; N->dump(); } } while (false)
;
5426 SDValue MaskOp = N->getOperand(1);
5427
5428 // If it exists, fixup the single node we allow in the tree that needs
5429 // masking.
5430 if (FixupNode) {
5431 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)
;
5432 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
5433 FixupNode->getValueType(0),
5434 SDValue(FixupNode, 0), MaskOp);
5435 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
5436 if (And.getOpcode() == ISD ::AND)
5437 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
5438 }
5439
5440 // Narrow any constants that need it.
5441 for (auto *LogicN : NodesWithConsts) {
5442 SDValue Op0 = LogicN->getOperand(0);
5443 SDValue Op1 = LogicN->getOperand(1);
5444
5445 if (isa<ConstantSDNode>(Op0))
5446 std::swap(Op0, Op1);
5447
5448 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
5449 Op1, MaskOp);
5450
5451 DAG.UpdateNodeOperands(LogicN, Op0, And);
5452 }
5453
5454 // Create narrow loads.
5455 for (auto *Load : Loads) {
5456 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)
;
5457 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
5458 SDValue(Load, 0), MaskOp);
5459 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
5460 if (And.getOpcode() == ISD ::AND)
5461 And = SDValue(
5462 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
5463 SDValue NewLoad = ReduceLoadWidth(And.getNode());
5464 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5465, __extension__ __PRETTY_FUNCTION__))
5465 "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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5465, __extension__ __PRETTY_FUNCTION__))
;
5466 CombineTo(Load, NewLoad, NewLoad.getValue(1));
5467 }
5468 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
5469 return true;
5470 }
5471 return false;
5472}
5473
5474// Unfold
5475// x & (-1 'logical shift' y)
5476// To
5477// (x 'opposite logical shift' y) 'logical shift' y
5478// if it is better for performance.
5479SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
5480 assert(N->getOpcode() == ISD::AND)(static_cast <bool> (N->getOpcode() == ISD::AND) ? void
(0) : __assert_fail ("N->getOpcode() == ISD::AND", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5480, __extension__ __PRETTY_FUNCTION__))
;
5481
5482 SDValue N0 = N->getOperand(0);
5483 SDValue N1 = N->getOperand(1);
5484
5485 // Do we actually prefer shifts over mask?
5486 if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
5487 return SDValue();
5488
5489 // Try to match (-1 '[outer] logical shift' y)
5490 unsigned OuterShift;
5491 unsigned InnerShift; // The opposite direction to the OuterShift.
5492 SDValue Y; // Shift amount.
5493 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
5494 if (!M.hasOneUse())
5495 return false;
5496 OuterShift = M->getOpcode();
5497 if (OuterShift == ISD::SHL)
5498 InnerShift = ISD::SRL;
5499 else if (OuterShift == ISD::SRL)
5500 InnerShift = ISD::SHL;
5501 else
5502 return false;
5503 if (!isAllOnesConstant(M->getOperand(0)))
5504 return false;
5505 Y = M->getOperand(1);
5506 return true;
5507 };
5508
5509 SDValue X;
5510 if (matchMask(N1))
5511 X = N0;
5512 else if (matchMask(N0))
5513 X = N1;
5514 else
5515 return SDValue();
5516
5517 SDLoc DL(N);
5518 EVT VT = N->getValueType(0);
5519
5520 // tmp = x 'opposite logical shift' y
5521 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
5522 // ret = tmp 'logical shift' y
5523 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
5524
5525 return T1;
5526}
5527
5528/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
5529/// For a target with a bit test, this is expected to become test + set and save
5530/// at least 1 instruction.
5531static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) {
5532 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\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5532, __extension__ __PRETTY_FUNCTION__))
;
5533
5534 // This is probably not worthwhile without a supported type.
5535 EVT VT = And->getValueType(0);
5536 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5537 if (!TLI.isTypeLegal(VT))
5538 return SDValue();
5539
5540 // Look through an optional extension and find a 'not'.
5541 // TODO: Should we favor test+set even without the 'not' op?
5542 SDValue Not = And->getOperand(0), And1 = And->getOperand(1);
5543 if (Not.getOpcode() == ISD::ANY_EXTEND)
5544 Not = Not.getOperand(0);
5545 if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1))
5546 return SDValue();
5547
5548 // Look though an optional truncation. The source operand may not be the same
5549 // type as the original 'and', but that is ok because we are masking off
5550 // everything but the low bit.
5551 SDValue Srl = Not.getOperand(0);
5552 if (Srl.getOpcode() == ISD::TRUNCATE)
5553 Srl = Srl.getOperand(0);
5554
5555 // Match a shift-right by constant.
5556 if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() ||
5557 !isa<ConstantSDNode>(Srl.getOperand(1)))
5558 return SDValue();
5559
5560 // We might have looked through casts that make this transform invalid.
5561 // TODO: If the source type is wider than the result type, do the mask and
5562 // compare in the source type.
5563 const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1);
5564 unsigned VTBitWidth = VT.getSizeInBits();
5565 if (ShiftAmt.uge(VTBitWidth))
5566 return SDValue();
5567
5568 // Turn this into a bit-test pattern using mask op + setcc:
5569 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
5570 SDLoc DL(And);
5571 SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT);
5572 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5573 SDValue Mask = DAG.getConstant(
5574 APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT);
5575 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask);
5576 SDValue Zero = DAG.getConstant(0, DL, VT);
5577 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
5578 return DAG.getZExtOrTrunc(Setcc, DL, VT);
5579}
5580
5581SDValue DAGCombiner::visitAND(SDNode *N) {
5582 SDValue N0 = N->getOperand(0);
5583 SDValue N1 = N->getOperand(1);
5584 EVT VT = N1.getValueType();
5585
5586 // x & x --> x
5587 if (N0 == N1)
5588 return N0;
5589
5590 // fold vector ops
5591 if (VT.isVector()) {
5592 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5593 return FoldedVOp;
5594
5595 // fold (and x, 0) -> 0, vector edition
5596 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()))
5597 // do not return N0, because undef node may exist in N0
5598 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
5599 SDLoc(N), N0.getValueType());
5600 if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
5601 // do not return N1, because undef node may exist in N1
5602 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
5603 SDLoc(N), N1.getValueType());
5604
5605 // fold (and x, -1) -> x, vector edition
5606 if (ISD::isConstantSplatVectorAllOnes(N0.getNode()))
5607 return N1;
5608 if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
5609 return N0;
5610
5611 // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load
5612 auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0);
5613 auto *BVec = dyn_cast<BuildVectorSDNode>(N1);
5614 if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD &&
5615 N0.hasOneUse() && N1.hasOneUse()) {
5616 EVT LoadVT = MLoad->getMemoryVT();
5617 EVT ExtVT = VT;
5618 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) {
5619 // For this AND to be a zero extension of the masked load the elements
5620 // of the BuildVec must mask the bottom bits of the extended element
5621 // type
5622 if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) {
5623 uint64_t ElementSize =
5624 LoadVT.getVectorElementType().getScalarSizeInBits();
5625 if (Splat->getAPIntValue().isMask(ElementSize)) {
5626 return DAG.getMaskedLoad(
5627 ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(),
5628 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(),
5629 LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(),
5630 ISD::ZEXTLOAD, MLoad->isExpandingLoad());
5631 }
5632 }
5633 }
5634 }
5635 }
5636
5637 // fold (and c1, c2) -> c1&c2
5638 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5639 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1}))
5640 return C;
5641
5642 // canonicalize constant to RHS
5643 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5644 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5645 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
5646
5647 // fold (and x, -1) -> x
5648 if (isAllOnesConstant(N1))
5649 return N0;
5650
5651 // if (and x, c) is known to be zero, return 0
5652 unsigned BitWidth = VT.getScalarSizeInBits();
5653 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5654 APInt::getAllOnesValue(BitWidth)))
5655 return DAG.getConstant(0, SDLoc(N), VT);
5656
5657 if (SDValue NewSel = foldBinOpIntoSelect(N))
5658 return NewSel;
5659
5660 // reassociate and
5661 if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
5662 return RAND;
5663
5664 // Try to convert a constant mask AND into a shuffle clear mask.
5665 if (VT.isVector())
5666 if (SDValue Shuffle = XformToShuffleWithZero(N))
5667 return Shuffle;
5668
5669 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N))
5670 return Combined;
5671
5672 // fold (and (or x, C), D) -> D if (C & D) == D
5673 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
5674 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
5675 };
5676 if (N0.getOpcode() == ISD::OR &&
5677 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
5678 return N1;
5679 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5680 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5681 SDValue N0Op0 = N0.getOperand(0);
5682 APInt Mask = ~N1C->getAPIntValue();
5683 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
5684 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
5685 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
5686 N0.getValueType(), N0Op0);
5687
5688 // Replace uses of the AND with uses of the Zero extend node.
5689 CombineTo(N, Zext);
5690
5691 // We actually want to replace all uses of the any_extend with the
5692 // zero_extend, to avoid duplicating things. This will later cause this
5693 // AND to be folded.
5694 CombineTo(N0.getNode(), Zext);
5695 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5696 }
5697 }
5698
5699 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5700 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5701 // already be zero by virtue of the width of the base type of the load.
5702 //
5703 // the 'X' node here can either be nothing or an extract_vector_elt to catch
5704 // more cases.
5705 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5706 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
5707 N0.getOperand(0).getOpcode() == ISD::LOAD &&
5708 N0.getOperand(0).getResNo() == 0) ||
5709 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
5710 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
5711 N0 : N0.getOperand(0) );
5712
5713 // Get the constant (if applicable) the zero'th operand is being ANDed with.
5714 // This can be a pure constant or a vector splat, in which case we treat the
5715 // vector as a scalar and use the splat value.
5716 APInt Constant = APInt::getNullValue(1);
5717 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
5718 Constant = C->getAPIntValue();
5719 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
5720 APInt SplatValue, SplatUndef;
5721 unsigned SplatBitSize;
5722 bool HasAnyUndefs;
5723 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
5724 SplatBitSize, HasAnyUndefs);
5725 if (IsSplat) {
5726 // Undef bits can contribute to a possible optimisation if set, so
5727 // set them.
5728 SplatValue |= SplatUndef;
5729
5730 // The splat value may be something like "0x00FFFFFF", which means 0 for
5731 // the first vector value and FF for the rest, repeating. We need a mask
5732 // that will apply equally to all members of the vector, so AND all the
5733 // lanes of the constant together.
5734 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
5735
5736 // If the splat value has been compressed to a bitlength lower
5737 // than the size of the vector lane, we need to re-expand it to
5738 // the lane size.
5739 if (EltBitWidth > SplatBitSize)
5740 for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
5741 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
5742 SplatValue |= SplatValue.shl(SplatBitSize);
5743
5744 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5745 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5746 if ((SplatBitSize % EltBitWidth) == 0) {
5747 Constant = APInt::getAllOnesValue(EltBitWidth);
5748 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
5749 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
5750 }
5751 }
5752 }
5753
5754 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
5755 // actually legal and isn't going to get expanded, else this is a false
5756 // optimisation.
5757 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
5758 Load->getValueType(0),
5759 Load->getMemoryVT());
5760
5761 // Resize the constant to the same size as the original memory access before
5762 // extension. If it is still the AllOnesValue then this AND is completely
5763 // unneeded.
5764 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
5765
5766 bool B;
5767 switch (Load->getExtensionType()) {
5768 default: B = false; break;
5769 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
5770 case ISD::ZEXTLOAD:
5771 case ISD::NON_EXTLOAD: B = true; break;
5772 }
5773
5774 if (B && Constant.isAllOnesValue()) {
5775 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
5776 // preserve semantics once we get rid of the AND.
5777 SDValue NewLoad(Load, 0);
5778
5779 // Fold the AND away. NewLoad may get replaced immediately.
5780 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
5781
5782 if (Load->getExtensionType() == ISD::EXTLOAD) {
5783 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
5784 Load->getValueType(0), SDLoc(Load),
5785 Load->getChain(), Load->getBasePtr(),
5786 Load->getOffset(), Load->getMemoryVT(),
5787 Load->getMemOperand());
5788 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
5789 if (Load->getNumValues() == 3) {
5790 // PRE/POST_INC loads have 3 values.
5791 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
5792 NewLoad.getValue(2) };
5793 CombineTo(Load, To, 3, true);
5794 } else {
5795 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
5796 }
5797 }
5798
5799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5800 }
5801 }
5802
5803 // fold (and (masked_gather x)) -> (zext_masked_gather x)
5804 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
5805 EVT MemVT = GN0->getMemoryVT();
5806 EVT ScalarVT = MemVT.getScalarType();
5807
5808 if (SDValue(GN0, 0).hasOneUse() &&
5809 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
5810 TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) {
5811 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
5812 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
5813
5814 SDValue ZExtLoad = DAG.getMaskedGather(
5815 DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops,
5816 GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD);
5817
5818 CombineTo(N, ZExtLoad);
5819 AddToWorklist(ZExtLoad.getNode());
5820 // Avoid recheck of N.
5821 return SDValue(N, 0);
5822 }
5823 }
5824
5825 // fold (and (load x), 255) -> (zextload x, i8)
5826 // fold (and (extload x, i16), 255) -> (zextload x, i8)
5827 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
5828 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
5829 (N0.getOpcode() == ISD::ANY_EXTEND &&
5830 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
5831 if (SDValue Res = ReduceLoadWidth(N)) {
5832 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
5833 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
5834 AddToWorklist(N);
5835 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res);
5836 return SDValue(N, 0);
5837 }
5838 }
5839
5840 if (LegalTypes) {
5841 // Attempt to propagate the AND back up to the leaves which, if they're
5842 // loads, can be combined to narrow loads and the AND node can be removed.
5843 // Perform after legalization so that extend nodes will already be
5844 // combined into the loads.
5845 if (BackwardsPropagateMask(N))
5846 return SDValue(N, 0);
5847 }
5848
5849 if (SDValue Combined = visitANDLike(N0, N1, N))
5850 return Combined;
5851
5852 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
5853 if (N0.getOpcode() == N1.getOpcode())
5854 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5855 return V;
5856
5857 // Masking the negated extension of a boolean is just the zero-extended
5858 // boolean:
5859 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
5860 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
5861 //
5862 // Note: the SimplifyDemandedBits fold below can make an information-losing
5863 // transform, and then we have no way to find this better fold.
5864 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
5865 if (isNullOrNullSplat(N0.getOperand(0))) {
5866 SDValue SubRHS = N0.getOperand(1);
5867 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
5868 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5869 return SubRHS;
5870 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
5871 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5872 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
5873 }
5874 }
5875
5876 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
5877 // fold (and (sra)) -> (and (srl)) when possible.
5878 if (SimplifyDemandedBits(SDValue(N, 0)))
5879 return SDValue(N, 0);
5880
5881 // fold (zext_inreg (extload x)) -> (zextload x)
5882 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
5883 if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
5884 (ISD::isEXTLoad(N0.getNode()) ||
5885 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
5886 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5887 EVT MemVT = LN0->getMemoryVT();
5888 // If we zero all the possible extended bits, then we can turn this into
5889 // a zextload if we are running before legalize or the operation is legal.
5890 unsigned ExtBitSize = N1.getScalarValueSizeInBits();
5891 unsigned MemBitSize = MemVT.getScalarSizeInBits();
5892 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
5893 if (DAG.MaskedValueIsZero(N1, ExtBits) &&
5894 ((!LegalOperations && LN0->isSimple()) ||
5895 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
5896 SDValue ExtLoad =
5897 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
5898 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
5899 AddToWorklist(N);
5900 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5901 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5902 }
5903 }
5904
5905 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
5906 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
5907 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5908 N0.getOperand(1), false))
5909 return BSwap;
5910 }
5911
5912 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
5913 return Shifts;
5914
5915 if (TLI.hasBitTest(N0, N1))
5916 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
5917 return V;
5918
5919 // Recognize the following pattern:
5920 //
5921 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
5922 //
5923 // where bitmask is a mask that clears the upper bits of AndVT. The
5924 // number of bits in bitmask must be a power of two.
5925 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
5926 if (LHS->getOpcode() != ISD::SIGN_EXTEND)
5927 return false;
5928
5929 auto *C = dyn_cast<ConstantSDNode>(RHS);
5930 if (!C)
5931 return false;
5932
5933 if (!C->getAPIntValue().isMask(
5934 LHS.getOperand(0).getValueType().getFixedSizeInBits()))
5935 return false;
5936
5937 return true;
5938 };
5939
5940 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
5941 if (IsAndZeroExtMask(N0, N1))
5942 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0));
5943
5944 return SDValue();
5945}
5946
5947/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
5948SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
5949 bool DemandHighBits) {
5950 if (!LegalOperations)
5951 return SDValue();
5952
5953 EVT VT = N->getValueType(0);
5954 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
5955 return SDValue();
5956 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
5957 return SDValue();
5958
5959 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
5960 bool LookPassAnd0 = false;
5961 bool LookPassAnd1 = false;
5962 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
5963 std::swap(N0, N1);
5964 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
5965 std::swap(N0, N1);
5966 if (N0.getOpcode() == ISD::AND) {
5967 if (!N0.getNode()->hasOneUse())
5968 return SDValue();
5969 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5970 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
5971 // This is needed for X86.
5972 if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
5973 N01C->getZExtValue() != 0xFFFF))
5974 return SDValue();
5975 N0 = N0.getOperand(0);
5976 LookPassAnd0 = true;
5977 }
5978
5979 if (N1.getOpcode() == ISD::AND) {
5980 if (!N1.getNode()->hasOneUse())
5981 return SDValue();
5982 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5983 if (!N11C || N11C->getZExtValue() != 0xFF)
5984 return SDValue();
5985 N1 = N1.getOperand(0);
5986 LookPassAnd1 = true;
5987 }
5988
5989 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
5990 std::swap(N0, N1);
5991 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
5992 return SDValue();
5993 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
5994 return SDValue();
5995
5996 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5997 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5998 if (!N01C || !N11C)
5999 return SDValue();
6000 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
6001 return SDValue();
6002
6003 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
6004 SDValue N00 = N0->getOperand(0);
6005 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
6006 if (!N00.getNode()->hasOneUse())
6007 return SDValue();
6008 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
6009 if (!N001C || N001C->getZExtValue() != 0xFF)
6010 return SDValue();
6011 N00 = N00.getOperand(0);
6012 LookPassAnd0 = true;
6013 }
6014
6015 SDValue N10 = N1->getOperand(0);
6016 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
6017 if (!N10.getNode()->hasOneUse())
6018 return SDValue();
6019 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
6020 // Also allow 0xFFFF since the bits will be shifted out. This is needed
6021 // for X86.
6022 if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
6023 N101C->getZExtValue() != 0xFFFF))
6024 return SDValue();
6025 N10 = N10.getOperand(0);
6026 LookPassAnd1 = true;
6027 }
6028
6029 if (N00 != N10)
6030 return SDValue();
6031