LLVM 23.0.0git
DAGCombiner.cpp
Go to the documentation of this file.
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/APSInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/Statistic.h"
52#include "llvm/IR/Attributes.h"
53#include "llvm/IR/Constant.h"
54#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Metadata.h"
63#include "llvm/Support/Debug.h"
71#include <algorithm>
72#include <cassert>
73#include <cstdint>
74#include <functional>
75#include <iterator>
76#include <optional>
77#include <string>
78#include <tuple>
79#include <utility>
80#include <variant>
81
82#include "MatchContext.h"
83#include "SDNodeDbgValue.h"
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88#define DEBUG_TYPE "dagcombine"
89
90STATISTIC(NodesCombined , "Number of dag nodes combined");
91STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
92STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
93STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
94STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
95STATISTIC(SlicedLoads, "Number of load sliced");
96STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
97
98DEBUG_COUNTER(DAGCombineCounter, "dagcombine",
99 "Controls whether a DAG combine is performed for a node");
100
101static cl::opt<bool>
102CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
103 cl::desc("Enable DAG combiner's use of IR alias analysis"));
104
105static cl::opt<bool>
106UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
107 cl::desc("Enable DAG combiner's use of TBAA"));
108
109#ifndef NDEBUG
111CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
112 cl::desc("Only use DAG-combiner alias analysis in this"
113 " function"));
114#endif
115
116/// Hidden option to stress test load slicing, i.e., when this option
117/// is enabled, load slicing bypasses most of its profitability guards.
118static cl::opt<bool>
119StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
120 cl::desc("Bypass the profitability model of load slicing"),
121 cl::init(false));
122
123static cl::opt<bool>
124 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
125 cl::desc("DAG combiner may split indexing from loads"));
126
127static cl::opt<bool>
128 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
129 cl::desc("DAG combiner enable merging multiple stores "
130 "into a wider store"));
131
133 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
134 cl::desc("Limit the number of operands to inline for Token Factors"));
135
137 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
138 cl::desc("Limit the number of times for the same StoreNode and RootNode "
139 "to bail out in store merging dependence check"));
140
142 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
143 cl::desc("DAG combiner enable reducing the width of load/op/store "
144 "sequence"));
146 "combiner-reduce-load-op-store-width-force-narrowing-profitable",
147 cl::Hidden, cl::init(false),
148 cl::desc("DAG combiner force override the narrowing profitable check when "
149 "reducing the width of load/op/store sequences"));
150
152 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
153 cl::desc("DAG combiner enable load/<replace bytes>/store with "
154 "a narrower store"));
155
157 "combiner-topological-sorting", cl::Hidden, cl::init(false),
158 cl::desc("DAG combiner nodes consistently processed in topological order"));
159
160static cl::opt<bool> DisableCombines("combiner-disabled", cl::Hidden,
161 cl::init(false),
162 cl::desc("Disable the DAG combiner"));
163
164namespace {
165
166 class DAGCombiner {
167 SelectionDAG &DAG;
168 const TargetLowering &TLI;
169 const SelectionDAGTargetInfo *STI;
171 CodeGenOptLevel OptLevel;
172 bool LegalDAG = false;
173 bool LegalOperations = false;
174 bool LegalTypes = false;
175 bool ForCodeSize;
176 bool DisableGenericCombines;
177
178 /// Worklist of all of the nodes that need to be simplified.
179 ///
180 /// This must behave as a stack -- new nodes to process are pushed onto the
181 /// back and when processing we pop off of the back.
182 ///
183 /// The worklist will not contain duplicates but may contain null entries
184 /// due to nodes being deleted from the underlying DAG. For fast lookup and
185 /// deduplication, the index of the node in this vector is stored in the
186 /// node in SDNode::CombinerWorklistIndex.
188
189 /// This records all nodes attempted to be added to the worklist since we
190 /// considered a new worklist entry. As we keep do not add duplicate nodes
191 /// in the worklist, this is different from the tail of the worklist.
193
194 /// Map from candidate StoreNode to the pair of RootNode and count.
195 /// The count is used to track how many times we have seen the StoreNode
196 /// with the same RootNode bail out in dependence check. If we have seen
197 /// the bail out for the same pair many times over a limit, we won't
198 /// consider the StoreNode with the same RootNode as store merging
199 /// candidate again.
201
202 // BatchAA - Used for DAG load/store alias analysis.
203 BatchAAResults *BatchAA;
204
205 /// This caches all chains that have already been processed in
206 /// DAGCombiner::getStoreMergeCandidates() and found to have no mergeable
207 /// stores candidates.
208 SmallPtrSet<SDNode *, 4> ChainsWithoutMergeableStores;
209
210 /// When an instruction is simplified, add all users of the instruction to
211 /// the work lists because they might get more simplified now.
212 void AddUsersToWorklist(SDNode *N) {
213 for (SDNode *Node : N->users())
214 AddToWorklist(Node);
215 }
216
217 /// Convenient shorthand to add a node and all of its user to the worklist.
218 void AddToWorklistWithUsers(SDNode *N) {
219 AddUsersToWorklist(N);
220 AddToWorklist(N);
221 }
222
223 // Prune potentially dangling nodes. This is called after
224 // any visit to a node, but should also be called during a visit after any
225 // failed combine which may have created a DAG node.
226 void clearAddedDanglingWorklistEntries() {
227 // Check any nodes added to the worklist to see if they are prunable.
228 while (!PruningList.empty()) {
229 auto *N = PruningList.pop_back_val();
230 if (N->use_empty())
231 recursivelyDeleteUnusedNodes(N);
232 }
233 }
234
235 SDNode *getNextWorklistEntry() {
236 // Before we do any work, remove nodes that are not in use.
237 clearAddedDanglingWorklistEntries();
238 SDNode *N = nullptr;
239 // The Worklist holds the SDNodes in order, but it may contain null
240 // entries.
241 while (!N && !Worklist.empty()) {
242 N = Worklist.pop_back_val();
243 }
244
245 if (N) {
246 assert(N->getCombinerWorklistIndex() >= 0 &&
247 "Found a worklist entry without a corresponding map entry!");
248 // Set to -2 to indicate that we combined the node.
249 N->setCombinerWorklistIndex(-2);
250 }
251 return N;
252 }
253
254 /// Call the node-specific routine that folds each particular type of node.
255 SDValue visit(SDNode *N);
256
257 public:
258 DAGCombiner(SelectionDAG &D, BatchAAResults *BatchAA, CodeGenOptLevel OL)
259 : DAG(D), TLI(D.getTargetLoweringInfo()),
260 STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL),
261 BatchAA(BatchAA) {
262 ForCodeSize = DAG.shouldOptForSize();
263 DisableGenericCombines =
264 DisableCombines || (STI && STI->disableGenericCombines(OptLevel));
265 }
266
267 void ConsiderForPruning(SDNode *N) {
268 // Mark this for potential pruning.
269 PruningList.insert(N);
270 }
271
272 /// Add to the worklist making sure its instance is at the back (next to be
273 /// processed.)
274 void AddToWorklist(SDNode *N, bool IsCandidateForPruning = true,
275 bool SkipIfCombinedBefore = false) {
276 assert(N->getOpcode() != ISD::DELETED_NODE &&
277 "Deleted Node added to Worklist");
278
279 // Skip handle nodes as they can't usefully be combined and confuse the
280 // zero-use deletion strategy.
281 if (N->getOpcode() == ISD::HANDLENODE)
282 return;
283
284 if (SkipIfCombinedBefore && N->getCombinerWorklistIndex() == -2)
285 return;
286
287 if (IsCandidateForPruning)
288 ConsiderForPruning(N);
289
290 if (N->getCombinerWorklistIndex() < 0) {
291 N->setCombinerWorklistIndex(Worklist.size());
292 Worklist.push_back(N);
293 }
294 }
295
296 /// Remove all instances of N from the worklist.
297 void removeFromWorklist(SDNode *N) {
298 PruningList.remove(N);
299 StoreRootCountMap.erase(N);
300
301 int WorklistIndex = N->getCombinerWorklistIndex();
302 // If not in the worklist, the index might be -1 or -2 (was combined
303 // before). As the node gets deleted anyway, there's no need to update
304 // the index.
305 if (WorklistIndex < 0)
306 return; // Not in the worklist.
307
308 // Null out the entry rather than erasing it to avoid a linear operation.
309 Worklist[WorklistIndex] = nullptr;
310 N->setCombinerWorklistIndex(-1);
311 }
312
313 void deleteAndRecombine(SDNode *N);
314 bool recursivelyDeleteUnusedNodes(SDNode *N);
315
316 /// Replaces all uses of the results of one DAG node with new values.
317 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
318 bool AddTo = true);
319
320 /// Replaces all uses of the results of one DAG node with new values.
321 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
322 return CombineTo(N, &Res, 1, AddTo);
323 }
324
325 /// Replaces all uses of the results of one DAG node with new values.
326 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
327 bool AddTo = true) {
328 SDValue To[] = { Res0, Res1 };
329 return CombineTo(N, To, 2, AddTo);
330 }
331
332 SDValue CombineTo(SDNode *N, SmallVectorImpl<SDValue> *To,
333 bool AddTo = true) {
334 return CombineTo(N, To->data(), To->size(), AddTo);
335 }
336
337 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
338
339 private:
340 /// Check the specified integer node value to see if it can be simplified or
341 /// if things it uses can be simplified by bit propagation.
342 /// If so, return true.
343 bool SimplifyDemandedBits(SDValue Op) {
344 unsigned BitWidth = Op.getScalarValueSizeInBits();
345 APInt DemandedBits = APInt::getAllOnes(BitWidth);
346 return SimplifyDemandedBits(Op, DemandedBits);
347 }
348
349 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
350 EVT VT = Op.getValueType();
351 APInt DemandedElts = VT.isFixedLengthVector()
353 : APInt(1, 1);
354 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, false);
355 }
356
357 /// Check the specified vector node value to see if it can be simplified or
358 /// if things it uses can be simplified as it only uses some of the
359 /// elements. If so, return true.
360 bool SimplifyDemandedVectorElts(SDValue Op) {
361 // TODO: For now just pretend it cannot be simplified.
362 if (Op.getValueType().isScalableVector())
363 return false;
364
365 unsigned NumElts = Op.getValueType().getVectorNumElements();
366 APInt DemandedElts = APInt::getAllOnes(NumElts);
367 return SimplifyDemandedVectorElts(Op, DemandedElts);
368 }
369
370 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
371 const APInt &DemandedElts,
372 bool AssumeSingleUse = false);
373 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
374 bool AssumeSingleUse = false);
375
376 bool CombineToPreIndexedLoadStore(SDNode *N);
377 bool CombineToPostIndexedLoadStore(SDNode *N);
378 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
379 bool SliceUpLoad(SDNode *N);
380
381 // Looks up the chain to find a unique (unaliased) store feeding the passed
382 // load. If no such store is found, returns a nullptr.
383 // Note: This will look past a CALLSEQ_START if the load is chained to it so
384 // so that it can find stack stores for byval params.
385 StoreSDNode *getUniqueStoreFeeding(LoadSDNode *LD, int64_t &Offset);
386 // Scalars have size 0 to distinguish from singleton vectors.
387 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
388 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
389 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
390
391 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
392 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
393 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
394 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
395 SDValue PromoteIntBinOp(SDValue Op);
396 SDValue PromoteIntShiftOp(SDValue Op);
397 SDValue PromoteExtend(SDValue Op);
398 bool PromoteLoad(SDValue Op);
399
400 SDValue foldShiftToAvg(SDNode *N, const SDLoc &DL);
401 // Fold `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`
402 SDValue foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT);
403
404 SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
405 SDValue RHS, SDValue True, SDValue False,
406 ISD::CondCode CC);
407
408 /// Call the node-specific routine that knows how to fold each
409 /// particular type of node. If that doesn't do anything, try the
410 /// target-specific DAG combines.
411 SDValue combine(SDNode *N);
412
413 // Visitation implementation - Implement dag node combining for different
414 // node types. The semantics are as follows:
415 // Return Value:
416 // SDValue.getNode() == 0 - No change was made
417 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
418 // otherwise - N should be replaced by the returned Operand.
419 //
420 SDValue visitTokenFactor(SDNode *N);
421 SDValue visitMERGE_VALUES(SDNode *N);
422 SDValue visitADD(SDNode *N);
423 SDValue visitADDLike(SDNode *N);
424 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1,
425 SDNode *LocReference);
426 SDValue visitPTRADD(SDNode *N);
427 SDValue visitSUB(SDNode *N);
428 SDValue visitADDSAT(SDNode *N);
429 SDValue visitSUBSAT(SDNode *N);
430 SDValue visitADDC(SDNode *N);
431 SDValue visitADDO(SDNode *N);
432 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
433 SDValue visitSUBC(SDNode *N);
434 SDValue visitSUBO(SDNode *N);
435 SDValue visitADDE(SDNode *N);
436 SDValue visitUADDO_CARRY(SDNode *N);
437 SDValue visitSADDO_CARRY(SDNode *N);
438 SDValue visitUADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
439 SDNode *N);
440 SDValue visitSADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
441 SDNode *N);
442 SDValue visitSUBE(SDNode *N);
443 SDValue visitUSUBO_CARRY(SDNode *N);
444 SDValue visitSSUBO_CARRY(SDNode *N);
445 SDValue visitMUL(SDNode *N);
446 SDValue visitMULFIX(SDNode *N);
447 SDValue useDivRem(SDNode *N);
448 SDValue visitSDIV(SDNode *N);
449 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
450 SDValue visitUDIV(SDNode *N);
451 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
452 SDValue visitREM(SDNode *N);
453 SDValue visitMULHU(SDNode *N);
454 SDValue visitMULHS(SDNode *N);
455 SDValue visitAVG(SDNode *N);
456 SDValue visitABD(SDNode *N);
457 SDValue visitSMUL_LOHI(SDNode *N);
458 SDValue visitUMUL_LOHI(SDNode *N);
459 SDValue visitMULO(SDNode *N);
460 SDValue visitIMINMAX(SDNode *N);
461 SDValue visitAND(SDNode *N);
462 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
463 SDValue visitOR(SDNode *N);
464 SDValue visitORLike(SDValue N0, SDValue N1, const SDLoc &DL);
465 SDValue visitXOR(SDNode *N);
466 SDValue SimplifyVCastOp(SDNode *N, const SDLoc &DL);
467 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
468 SDValue visitSHL(SDNode *N);
469 SDValue visitSRA(SDNode *N);
470 SDValue visitSRL(SDNode *N);
471 SDValue visitFunnelShift(SDNode *N);
472 SDValue visitSHLSAT(SDNode *N);
473 SDValue visitRotate(SDNode *N);
474 SDValue visitABS(SDNode *N);
475 SDValue visitABS_MIN_POISON(SDNode *N);
476 SDValue visitCLMUL(SDNode *N);
477 SDValue visitBSWAP(SDNode *N);
478 SDValue visitBITREVERSE(SDNode *N);
479 SDValue visitCTLZ(SDNode *N);
480 SDValue visitCTLZ_ZERO_POISON(SDNode *N);
481 SDValue visitCTTZ(SDNode *N);
482 SDValue visitCTTZ_ZERO_POISON(SDNode *N);
483 SDValue visitCTPOP(SDNode *N);
484 SDValue visitSELECT(SDNode *N);
485 SDValue visitVSELECT(SDNode *N);
486 SDValue visitVP_SELECT(SDNode *N);
487 SDValue visitSELECT_CC(SDNode *N);
488 SDValue visitSETCC(SDNode *N);
489 SDValue visitSETCCCARRY(SDNode *N);
490 SDValue visitSIGN_EXTEND(SDNode *N);
491 SDValue visitZERO_EXTEND(SDNode *N);
492 SDValue visitANY_EXTEND(SDNode *N);
493 SDValue visitAssertExt(SDNode *N);
494 SDValue visitAssertAlign(SDNode *N);
495 SDValue visitIS_FPCLASS(SDNode *N);
496 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
497 SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
498 SDValue visitTRUNCATE(SDNode *N);
499 SDValue visitTRUNCATE_USAT_U(SDNode *N);
500 SDValue visitBITCAST(SDNode *N);
501 SDValue visitFREEZE(SDNode *N);
502 SDValue visitBUILD_PAIR(SDNode *N);
503 SDValue visitFADD(SDNode *N);
504 SDValue visitSTRICT_FADD(SDNode *N);
505 SDValue visitFSUB(SDNode *N);
506 SDValue visitFMUL(SDNode *N);
507 SDValue visitFMA(SDNode *N);
508 SDValue visitFMAD(SDNode *N);
509 SDValue visitFMULADD(SDNode *N);
510 SDValue visitFDIV(SDNode *N);
511 SDValue visitFREM(SDNode *N);
512 SDValue visitFSQRT(SDNode *N);
513 SDValue visitFCOPYSIGN(SDNode *N);
514 SDValue visitFPOW(SDNode *N);
515 SDValue visitFCANONICALIZE(SDNode *N);
516 SDValue visitSINT_TO_FP(SDNode *N);
517 SDValue visitUINT_TO_FP(SDNode *N);
518 SDValue visitFP_TO_SINT(SDNode *N);
519 SDValue visitFP_TO_UINT(SDNode *N);
520 SDValue visitXROUND(SDNode *N);
521 SDValue visitFP_ROUND(SDNode *N);
522 SDValue visitFP_EXTEND(SDNode *N);
523 SDValue visitFNEG(SDNode *N);
524 SDValue visitFABS(SDNode *N);
525 SDValue visitFCEIL(SDNode *N);
526 SDValue visitFTRUNC(SDNode *N);
527 SDValue visitFFREXP(SDNode *N);
528 SDValue visitFFLOOR(SDNode *N);
529 SDValue visitFMinMax(SDNode *N);
530 SDValue visitBRCOND(SDNode *N);
531 SDValue visitBR_CC(SDNode *N);
532 SDValue visitLOAD(SDNode *N);
533
534 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
535 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
536 SDValue replaceStoreOfInsertLoad(StoreSDNode *ST);
537
538 bool refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(SDNode *N);
539 SDValue combineStoreConcatTruncVector(StoreSDNode *N);
540 SDValue visitSTORE(SDNode *N);
541 SDValue visitATOMIC_STORE(SDNode *N);
542 SDValue visitLIFETIME_END(SDNode *N);
543 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
544 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
545 SDValue visitBUILD_VECTOR(SDNode *N);
546 SDValue visitCONCAT_VECTORS(SDNode *N);
547 SDValue visitVECTOR_INTERLEAVE(SDNode *N);
548 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
549 SDValue visitVECTOR_SHUFFLE(SDNode *N);
550 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
551 SDValue visitINSERT_SUBVECTOR(SDNode *N);
552 SDValue visitVECTOR_COMPRESS(SDNode *N);
553 SDValue visitMLOAD(SDNode *N);
554 SDValue visitMSTORE(SDNode *N);
555 SDValue visitMGATHER(SDNode *N);
556 SDValue visitMSCATTER(SDNode *N);
557 SDValue visitMHISTOGRAM(SDNode *N);
558 SDValue visitPARTIAL_REDUCE_MLA(SDNode *N);
559 SDValue visitVPGATHER(SDNode *N);
560 SDValue visitVPSCATTER(SDNode *N);
561 SDValue visitVP_STRIDED_LOAD(SDNode *N);
562 SDValue visitVP_STRIDED_STORE(SDNode *N);
563 SDValue visitFP_TO_FP16(SDNode *N);
564 SDValue visitFP16_TO_FP(SDNode *N);
565 SDValue visitFP_TO_BF16(SDNode *N);
566 SDValue visitBF16_TO_FP(SDNode *N);
567 SDValue visitVECREDUCE(SDNode *N);
568 SDValue visitVPOp(SDNode *N);
569 SDValue visitGET_FPENV_MEM(SDNode *N);
570 SDValue visitSET_FPENV_MEM(SDNode *N);
571
572 SDValue visitFADDForFMACombine(SDNode *N);
573 SDValue visitFSUBForFMACombine(SDNode *N);
574 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
575
576 SDValue XformToShuffleWithZero(SDNode *N);
577 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
578 const SDLoc &DL,
579 SDNode *N,
580 SDValue N0,
581 SDValue N1);
582 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
583 SDValue N1, SDNodeFlags Flags);
584 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
585 SDValue N1, SDNodeFlags Flags);
586 SDValue reassociateReduction(unsigned RedOpc, unsigned Opc, const SDLoc &DL,
587 EVT VT, SDValue N0, SDValue N1,
588 SDNodeFlags Flags = SDNodeFlags());
589
590 SDValue visitShiftByConstant(SDNode *N);
591
592 SDValue foldSelectOfConstants(SDNode *N);
593 SDValue foldVSelectOfConstants(SDNode *N);
594 SDValue foldBinOpIntoSelect(SDNode *BO);
595 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
596 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
597 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
598 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
599 SDValue N2, SDValue N3, ISD::CondCode CC,
600 bool NotExtCompare = false);
601 SDValue convertSelectOfFPConstantsToLoadOffset(
602 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
603 ISD::CondCode CC);
604 SDValue foldSignChangeInBitcast(SDNode *N);
605 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
606 SDValue N2, SDValue N3, ISD::CondCode CC);
607 SDValue foldSelectOfBinops(SDNode *N);
608 SDValue foldSextSetcc(SDNode *N);
609 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
610 const SDLoc &DL);
611 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL);
612 SDValue foldABSToABD(SDNode *N, const SDLoc &DL);
613 SDValue foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
614 SDValue False, ISD::CondCode CC, const SDLoc &DL);
615 SDValue foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
616 SDValue False, ISD::CondCode CC, const SDLoc &DL);
617 SDValue unfoldMaskedMerge(SDNode *N);
618 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
619 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
620 const SDLoc &DL, bool foldBooleans);
621 SDValue rebuildSetCC(SDValue N);
622
623 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
624 SDValue &CC, bool MatchStrict = false) const;
625 bool isOneUseSetCC(SDValue N) const;
626
627 SDValue foldAddToAvg(SDNode *N, const SDLoc &DL);
628 SDValue foldSubToAvg(SDNode *N, const SDLoc &DL);
629
630 SDValue foldCTLZToCTLS(SDValue Src, const SDLoc &DL);
631
632 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
633 unsigned HiOp);
634 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
635 SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
636 const TargetLowering &TLI);
637 SDValue foldPartialReduceMLAMulOp(SDNode *N);
638 SDValue foldPartialReduceAdd(SDNode *N);
639
640 SDValue CombineExtLoad(SDNode *N);
641 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
642 SDValue combineRepeatedFPDivisors(SDNode *N);
643 SDValue combineFMulOrFDivWithIntPow2(SDNode *N);
644 SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf);
645 SDValue mergeInsertEltWithShuffle(SDNode *N, unsigned InsIndex);
646 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
647 SDValue combineInsertEltToLoad(SDNode *N, unsigned InsIndex);
648 SDValue foldExtractSubvectorFromConcatVectors(EVT VT, SDValue V,
649 uint64_t ExtIdx,
650 const SDLoc &DL);
651 SDValue BuildSDIV(SDNode *N);
652 SDValue BuildSDIVPow2(SDNode *N);
653 SDValue BuildUDIV(SDNode *N);
654 SDValue BuildSREMPow2(SDNode *N);
655 SDValue buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N);
656 SDValue BuildLogBase2(SDValue V, const SDLoc &DL,
657 bool KnownNeverZero = false,
658 bool InexpensiveOnly = false,
659 std::optional<EVT> OutVT = std::nullopt);
660 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
661 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
662 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
663 SDValue buildSqrtEstimateImpl(SDValue Op, bool Recip, SDNodeFlags Flags);
664 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
665 bool Reciprocal);
666 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
667 bool Reciprocal);
668 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
669 bool DemandHighBits = true);
670 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
671 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
672 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
673 bool HasPos, unsigned PosOpcode,
674 unsigned NegOpcode, const SDLoc &DL);
675 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
676 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
677 bool HasPos, unsigned PosOpcode,
678 unsigned NegOpcode, const SDLoc &DL);
679 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
680 bool FromAdd);
681 SDValue MatchLoadCombine(SDNode *N);
682 SDValue mergeTruncStores(StoreSDNode *N);
683 SDValue reduceLoadWidth(SDNode *N);
684 SDValue ReduceLoadOpStoreWidth(SDNode *N);
685 SDValue splitMergedValStore(StoreSDNode *ST);
686 SDValue TransformFPLoadStorePair(SDNode *N);
687 SDValue convertBuildVecExtToExt(SDNode *N);
688 SDValue convertBuildVecZextToBuildVecWithZeros(SDNode *N);
689 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
690 SDValue reduceBuildVecTruncToBitCast(SDNode *N);
691 SDValue reduceBuildVecToShuffle(SDNode *N);
692 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
693 ArrayRef<int> VectorMask, SDValue VecIn1,
694 SDValue VecIn2, unsigned LeftIdx,
695 bool DidSplitVec);
696 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
697
698 /// Walk up chain skipping non-aliasing memory nodes,
699 /// looking for aliasing nodes and adding them to the Aliases vector.
700 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
701 SmallVectorImpl<SDValue> &Aliases);
702
703 /// Return true if there is any possibility that the two addresses overlap.
704 bool mayAlias(SDNode *Op0, SDNode *Op1) const;
705
706 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
707 /// chain (aliasing node.)
708 SDValue FindBetterChain(SDNode *N, SDValue Chain);
709
710 /// Try to replace a store and any possibly adjacent stores on
711 /// consecutive chains with better chains. Return true only if St is
712 /// replaced.
713 ///
714 /// Notice that other chains may still be replaced even if the function
715 /// returns false.
716 bool findBetterNeighborChains(StoreSDNode *St);
717
718 // Helper for findBetterNeighborChains. Walk up store chain add additional
719 // chained stores that do not overlap and can be parallelized.
720 bool parallelizeChainedStores(StoreSDNode *St);
721
722 /// Holds a pointer to an LSBaseSDNode as well as information on where it
723 /// is located in a sequence of memory operations connected by a chain.
724 struct MemOpLink {
725 // Ptr to the mem node.
726 LSBaseSDNode *MemNode;
727
728 // Offset from the base ptr.
729 int64_t OffsetFromBase;
730
731 MemOpLink(LSBaseSDNode *N, int64_t Offset)
732 : MemNode(N), OffsetFromBase(Offset) {}
733 };
734
735 // Classify the origin of a stored value.
736 enum class StoreSource { Unknown, Constant, Extract, Load };
737 StoreSource getStoreSource(SDValue StoreVal) {
738 switch (StoreVal.getOpcode()) {
739 case ISD::Constant:
740 case ISD::ConstantFP:
741 return StoreSource::Constant;
745 return StoreSource::Constant;
746 return StoreSource::Unknown;
749 return StoreSource::Extract;
750 case ISD::LOAD:
751 return StoreSource::Load;
752 default:
753 return StoreSource::Unknown;
754 }
755 }
756
757 /// This is a helper function for visitMUL to check the profitability
758 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
759 /// MulNode is the original multiply, AddNode is (add x, c1),
760 /// and ConstNode is c2.
761 bool isMulAddWithConstProfitable(SDNode *MulNode, SDValue AddNode,
762 SDValue ConstNode);
763
764 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
765 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
766 /// the type of the loaded value to be extended.
767 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
768 EVT LoadResultTy, EVT &ExtVT);
769
770 /// Helper function to calculate whether the given Load/Store can have its
771 /// width reduced to ExtVT.
772 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
773 EVT &MemVT, unsigned ShAmt = 0);
774
775 /// Used by BackwardsPropagateMask to find suitable loads.
776 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
777 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
778 ConstantSDNode *Mask, SDNode *&NodeToMask);
779 /// Attempt to propagate a given AND node back to load leaves so that they
780 /// can be combined into narrow loads.
781 bool BackwardsPropagateMask(SDNode *N);
782
783 /// Helper function for mergeConsecutiveStores which merges the component
784 /// store chains.
785 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
786 unsigned NumStores);
787
788 /// Helper function for mergeConsecutiveStores which checks if all the store
789 /// nodes have the same underlying object. We can still reuse the first
790 /// store's pointer info if all the stores are from the same object.
791 bool hasSameUnderlyingObj(ArrayRef<MemOpLink> StoreNodes);
792
793 /// This is a helper function for mergeConsecutiveStores. When the source
794 /// elements of the consecutive stores are all constants or all extracted
795 /// vector elements, try to merge them into one larger store introducing
796 /// bitcasts if necessary. \return True if a merged store was created.
797 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
798 EVT MemVT, unsigned NumStores,
799 bool IsConstantSrc, bool UseVector,
800 bool UseTrunc);
801
802 /// This is a helper function for mergeConsecutiveStores. Stores that
803 /// potentially may be merged with St are placed in StoreNodes. On success,
804 /// returns a chain predecessor to all store candidates.
805 SDNode *getStoreMergeCandidates(StoreSDNode *St,
806 SmallVectorImpl<MemOpLink> &StoreNodes);
807
808 /// Helper function for mergeConsecutiveStores. Checks if candidate stores
809 /// have indirect dependency through their operands. RootNode is the
810 /// predecessor to all stores calculated by getStoreMergeCandidates and is
811 /// used to prune the dependency check. \return True if safe to merge.
812 bool checkMergeStoreCandidatesForDependencies(
813 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
814 SDNode *RootNode);
815
816 /// Helper function for tryStoreMergeOfLoads. Checks if the load/store
817 /// chain has a call in it. \return True if a call is found.
818 bool hasCallInLdStChain(StoreSDNode *St, LoadSDNode *Ld);
819
820 /// This is a helper function for mergeConsecutiveStores. Given a list of
821 /// store candidates, find the first N that are consecutive in memory.
822 /// Returns 0 if there are not at least 2 consecutive stores to try merging.
823 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
824 int64_t ElementSizeBytes) const;
825
826 /// This is a helper function for mergeConsecutiveStores. It is used for
827 /// store chains that are composed entirely of constant values.
828 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
829 unsigned NumConsecutiveStores,
830 EVT MemVT, SDNode *Root, bool AllowVectors);
831
832 /// This is a helper function for mergeConsecutiveStores. It is used for
833 /// store chains that are composed entirely of extracted vector elements.
834 /// When extracting multiple vector elements, try to store them in one
835 /// vector store rather than a sequence of scalar stores.
836 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
837 unsigned NumConsecutiveStores, EVT MemVT,
838 SDNode *Root);
839
840 /// This is a helper function for mergeConsecutiveStores. It is used for
841 /// store chains that are composed entirely of loaded values.
842 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
843 unsigned NumConsecutiveStores, EVT MemVT,
844 SDNode *Root, bool AllowVectors,
845 bool IsNonTemporalStore, bool IsNonTemporalLoad);
846
847 /// Merge consecutive store operations into a wide store.
848 /// This optimization uses wide integers or vectors when possible.
849 /// \return true if stores were merged.
850 bool mergeConsecutiveStores(StoreSDNode *St);
851
852 /// Try to transform a truncation where C is a constant:
853 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
854 ///
855 /// \p N needs to be a truncation and its first operand an AND. Other
856 /// requirements are checked by the function (e.g. that trunc is
857 /// single-use) and if missed an empty SDValue is returned.
858 SDValue distributeTruncateThroughAnd(SDNode *N);
859
860 /// Helper function to determine whether the target supports operation
861 /// given by \p Opcode for type \p VT, that is, whether the operation
862 /// is legal or custom before legalizing operations, and whether is
863 /// legal (but not custom) after legalization.
864 bool hasOperation(unsigned Opcode, EVT VT) {
865 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
866 }
867
868 bool hasUMin(EVT VT) const {
869 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
870 return (LK.first == TargetLoweringBase::TypeLegal ||
872 TLI.isOperationLegalOrCustom(ISD::UMIN, LK.second);
873 }
874
875 public:
876 /// Runs the dag combiner on all nodes in the work list
877 void Run(CombineLevel AtLevel);
878
879 SelectionDAG &getDAG() const { return DAG; }
880
881 /// Convenience wrapper around TargetLowering::getShiftAmountTy.
882 EVT getShiftAmountTy(EVT LHSTy) {
883 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout());
884 }
885
886 /// This method returns true if we are running before type legalization or
887 /// if the specified VT is legal.
888 bool isTypeLegal(const EVT &VT) {
889 if (!LegalTypes) return true;
890 return TLI.isTypeLegal(VT);
891 }
892
893 /// Convenience wrapper around TargetLowering::getSetCCResultType
894 EVT getSetCCResultType(EVT VT) const {
895 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
896 }
897
898 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
899 SDValue OrigLoad, SDValue ExtLoad,
900 ISD::NodeType ExtType);
901 };
902
903/// This class is a DAGUpdateListener that removes any deleted
904/// nodes from the worklist.
905class WorklistRemover : public SelectionDAG::DAGUpdateListener {
906 DAGCombiner &DC;
907
908public:
909 explicit WorklistRemover(DAGCombiner &dc)
910 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
911
912 void NodeDeleted(SDNode *N, SDNode *E) override {
913 DC.removeFromWorklist(N);
914 }
915};
916
917class WorklistInserter : public SelectionDAG::DAGUpdateListener {
918 DAGCombiner &DC;
919
920public:
921 explicit WorklistInserter(DAGCombiner &dc)
922 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
923
924 // FIXME: Ideally we could add N to the worklist, but this causes exponential
925 // compile time costs in large DAGs, e.g. Halide.
926 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
927};
928
929} // end anonymous namespace
930
931//===----------------------------------------------------------------------===//
932// TargetLowering::DAGCombinerInfo implementation
933//===----------------------------------------------------------------------===//
934
936 ((DAGCombiner*)DC)->AddToWorklist(N);
937}
938
940CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
941 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
942}
943
945CombineTo(SDNode *N, SDValue Res, bool AddTo) {
946 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
947}
948
950CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
951 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
952}
953
956 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
957}
958
961 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
962}
963
964//===----------------------------------------------------------------------===//
965// Helper Functions
966//===----------------------------------------------------------------------===//
967
968void DAGCombiner::deleteAndRecombine(SDNode *N) {
969 removeFromWorklist(N);
970
971 // If the operands of this node are only used by the node, they will now be
972 // dead. Make sure to re-visit them and recursively delete dead nodes.
973 for (const SDValue &Op : N->ops())
974 // For an operand generating multiple values, one of the values may
975 // become dead allowing further simplification (e.g. split index
976 // arithmetic from an indexed load).
977 if (Op->hasOneUse() || Op->getNumValues() > 1)
978 AddToWorklist(Op.getNode());
979
980 DAG.DeleteNode(N);
981}
982
983// APInts must be the same size for most operations, this helper
984// function zero extends the shorter of the pair so that they match.
985// We provide an Offset so that we can create bitwidths that won't overflow.
986static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
987 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
988 LHS = LHS.zext(Bits);
989 RHS = RHS.zext(Bits);
990}
991
992// Return true if this node is a setcc, or is a select_cc
993// that selects between the target values used for true and false, making it
994// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
995// the appropriate nodes based on the type of node we are checking. This
996// simplifies life a bit for the callers.
997bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
998 SDValue &CC, bool MatchStrict) const {
999 if (N.getOpcode() == ISD::SETCC) {
1000 LHS = N.getOperand(0);
1001 RHS = N.getOperand(1);
1002 CC = N.getOperand(2);
1003 return true;
1004 }
1005
1006 if (MatchStrict &&
1007 (N.getOpcode() == ISD::STRICT_FSETCC ||
1008 N.getOpcode() == ISD::STRICT_FSETCCS)) {
1009 LHS = N.getOperand(1);
1010 RHS = N.getOperand(2);
1011 CC = N.getOperand(3);
1012 return true;
1013 }
1014
1015 if (N.getOpcode() != ISD::SELECT_CC || !TLI.isConstTrueVal(N.getOperand(2)) ||
1016 !TLI.isConstFalseVal(N.getOperand(3)))
1017 return false;
1018
1019 if (TLI.getBooleanContents(N.getValueType()) ==
1021 return false;
1022
1023 LHS = N.getOperand(0);
1024 RHS = N.getOperand(1);
1025 CC = N.getOperand(4);
1026 return true;
1027}
1028
1029/// Return true if this is a SetCC-equivalent operation with only one use.
1030/// If this is true, it allows the users to invert the operation for free when
1031/// it is profitable to do so.
1032bool DAGCombiner::isOneUseSetCC(SDValue N) const {
1033 SDValue N0, N1, N2;
1034 if (isSetCCEquivalent(N, N0, N1, N2) && N->hasOneUse())
1035 return true;
1036 return false;
1037}
1038
1040 if (!ScalarTy.isSimple())
1041 return false;
1042
1043 uint64_t MaskForTy = 0ULL;
1044 switch (ScalarTy.getSimpleVT().SimpleTy) {
1045 case MVT::i8:
1046 MaskForTy = 0xFFULL;
1047 break;
1048 case MVT::i16:
1049 MaskForTy = 0xFFFFULL;
1050 break;
1051 case MVT::i32:
1052 MaskForTy = 0xFFFFFFFFULL;
1053 break;
1054 default:
1055 return false;
1056 break;
1057 }
1058
1059 APInt Val;
1060 if (ISD::isConstantSplatVector(N, Val))
1061 return Val.getLimitedValue() == MaskForTy;
1062
1063 return false;
1064}
1065
1066// Determines if it is a constant integer or a splat/build vector of constant
1067// integers (and undefs).
1068// Do not permit build vector implicit truncation unless AllowTruncation is set.
1069static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false,
1070 bool AllowTruncation = false) {
1072 return !(Const->isOpaque() && NoOpaques);
1073 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
1074 return false;
1075 unsigned BitWidth = N.getScalarValueSizeInBits();
1076 for (const SDValue &Op : N->op_values()) {
1077 if (Op.isUndef())
1078 continue;
1080 if (!Const || (Const->isOpaque() && NoOpaques))
1081 return false;
1082 // When AllowTruncation is true, allow constants that have been promoted
1083 // during type legalization as long as the value fits in the target type.
1084 if ((AllowTruncation &&
1085 Const->getAPIntValue().getActiveBits() > BitWidth) ||
1086 (!AllowTruncation && Const->getAPIntValue().getBitWidth() != BitWidth))
1087 return false;
1088 }
1089 return true;
1090}
1091
1092// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1093// undef's.
1094static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
1095 if (V.getOpcode() != ISD::BUILD_VECTOR)
1096 return false;
1097 return isConstantOrConstantVector(V, NoOpaques) ||
1099}
1100
1101// Determine if this an indexed load with an opaque target constant index.
1102static bool canSplitIdx(LoadSDNode *LD) {
1103 return MaySplitLoadIndex &&
1104 (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
1105 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
1106}
1107
1108bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
1109 const SDLoc &DL,
1110 SDNode *N,
1111 SDValue N0,
1112 SDValue N1) {
1113 // Currently this only tries to ensure we don't undo the GEP splits done by
1114 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1115 // we check if the following transformation would be problematic:
1116 // (load/store (add, (add, x, offset1), offset2)) ->
1117 // (load/store (add, x, offset1+offset2)).
1118
1119 // (load/store (add, (add, x, y), offset2)) ->
1120 // (load/store (add, (add, x, offset2), y)).
1121
1122 if (!N0.isAnyAdd())
1123 return false;
1124
1125 // Check for vscale addressing modes.
1126 // (load/store (add/sub (add x, y), vscale))
1127 // (load/store (add/sub (add x, y), (lsl vscale, C)))
1128 // (load/store (add/sub (add x, y), (mul vscale, C)))
1129 if ((N1.getOpcode() == ISD::VSCALE ||
1130 ((N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::MUL) &&
1131 N1.getOperand(0).getOpcode() == ISD::VSCALE &&
1133 N1.getValueType().getFixedSizeInBits() <= 64) {
1134 int64_t ScalableOffset = N1.getOpcode() == ISD::VSCALE
1135 ? N1.getConstantOperandVal(0)
1136 : (N1.getOperand(0).getConstantOperandVal(0) *
1137 (N1.getOpcode() == ISD::SHL
1138 ? (1LL << N1.getConstantOperandVal(1))
1139 : N1.getConstantOperandVal(1)));
1140 if (Opc == ISD::SUB)
1141 ScalableOffset = -ScalableOffset;
1142 if (all_of(N->users(), [&](SDNode *Node) {
1143 if (auto *LoadStore = dyn_cast<MemSDNode>(Node);
1144 LoadStore && LoadStore->hasUniqueMemOperand() &&
1145 LoadStore->getBasePtr().getNode() == N) {
1146 TargetLoweringBase::AddrMode AM;
1147 AM.HasBaseReg = true;
1148 AM.ScalableOffset = ScalableOffset;
1149 EVT VT = LoadStore->getMemoryVT();
1150 unsigned AS = LoadStore->getAddressSpace();
1151 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1152 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy,
1153 AS);
1154 }
1155 return false;
1156 }))
1157 return true;
1158 }
1159
1160 if (Opc != ISD::ADD && Opc != ISD::PTRADD)
1161 return false;
1162
1163 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1164 if (!C2)
1165 return false;
1166
1167 const APInt &C2APIntVal = C2->getAPIntValue();
1168 if (C2APIntVal.getSignificantBits() > 64)
1169 return false;
1170
1171 if (auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1172 if (N0.hasOneUse())
1173 return false;
1174
1175 const APInt &C1APIntVal = C1->getAPIntValue();
1176 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1177 if (CombinedValueIntVal.getSignificantBits() > 64)
1178 return false;
1179 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1180
1181 for (SDNode *Node : N->users()) {
1182 if (auto *LoadStore = dyn_cast<MemSDNode>(Node)) {
1183 if (!LoadStore->hasUniqueMemOperand())
1184 continue;
1185 // Is x[offset2] already not a legal addressing mode? If so then
1186 // reassociating the constants breaks nothing (we test offset2 because
1187 // that's the one we hope to fold into the load or store).
1188 TargetLoweringBase::AddrMode AM;
1189 AM.HasBaseReg = true;
1190 AM.BaseOffs = C2APIntVal.getSExtValue();
1191 EVT VT = LoadStore->getMemoryVT();
1192 unsigned AS = LoadStore->getAddressSpace();
1193 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1194 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1195 continue;
1196
1197 // Would x[offset1+offset2] still be a legal addressing mode?
1198 AM.BaseOffs = CombinedValue;
1199 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1200 return true;
1201 }
1202 }
1203 } else {
1204 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N0.getOperand(1)))
1205 if (GA->getOpcode() == ISD::GlobalAddress && TLI.isOffsetFoldingLegal(GA))
1206 return false;
1207
1208 for (SDNode *Node : N->users()) {
1209 auto *LoadStore = dyn_cast<MemSDNode>(Node);
1210 if (!LoadStore || !LoadStore->hasUniqueMemOperand())
1211 return false;
1212
1213 // Is x[offset2] a legal addressing mode? If so then
1214 // reassociating the constants breaks address pattern
1215 TargetLoweringBase::AddrMode AM;
1216 AM.HasBaseReg = true;
1217 AM.BaseOffs = C2APIntVal.getSExtValue();
1218 EVT VT = LoadStore->getMemoryVT();
1219 unsigned AS = LoadStore->getAddressSpace();
1220 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1221 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1222 return false;
1223 }
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// Helper for DAGCombiner::reassociateOps. Try to reassociate (Opc N0, N1) if
1231/// \p N0 is the same kind of operation as \p Opc.
1232SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1233 SDValue N0, SDValue N1,
1234 SDNodeFlags Flags) {
1235 EVT VT = N0.getValueType();
1236
1237 if (N0.getOpcode() != Opc)
1238 return SDValue();
1239
1240 SDValue N00 = N0.getOperand(0);
1241 SDValue N01 = N0.getOperand(1);
1242
1244 SDNodeFlags NewFlags;
1245 if (N0.getOpcode() == ISD::ADD && N0->getFlags().hasNoUnsignedWrap() &&
1246 Flags.hasNoUnsignedWrap())
1247 NewFlags |= SDNodeFlags::NoUnsignedWrap;
1248
1250 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1251 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1})) {
1252 NewFlags.setDisjoint(Flags.hasDisjoint() &&
1253 N0->getFlags().hasDisjoint());
1254 return DAG.getNode(Opc, DL, VT, N00, OpNode, NewFlags);
1255 }
1256 return SDValue();
1257 }
1258 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1259 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1260 // iff (op x, c1) has one use
1261 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, NewFlags);
1262 return DAG.getNode(Opc, DL, VT, OpNode, N01, NewFlags);
1263 }
1264 }
1265
1266 // Check for repeated operand logic simplifications.
1267 if (Opc == ISD::AND || Opc == ISD::OR) {
1268 // (N00 & N01) & N00 --> N00 & N01
1269 // (N00 & N01) & N01 --> N00 & N01
1270 // (N00 | N01) | N00 --> N00 | N01
1271 // (N00 | N01) | N01 --> N00 | N01
1272 if (N1 == N00 || N1 == N01)
1273 return N0;
1274 }
1275 if (Opc == ISD::XOR) {
1276 // (N00 ^ N01) ^ N00 --> N01
1277 if (N1 == N00)
1278 return N01;
1279 // (N00 ^ N01) ^ N01 --> N00
1280 if (N1 == N01)
1281 return N00;
1282 }
1283
1284 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1285 if (N1 != N01) {
1286 // Reassociate if (op N00, N1) already exist
1287 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N00, N1})) {
1288 // if Op (Op N00, N1), N01 already exist
1289 // we need to stop reassciate to avoid dead loop
1290 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N01}))
1291 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N01);
1292 }
1293 }
1294
1295 if (N1 != N00) {
1296 // Reassociate if (op N01, N1) already exist
1297 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N01, N1})) {
1298 // if Op (Op N01, N1), N00 already exist
1299 // we need to stop reassciate to avoid dead loop
1300 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N00}))
1301 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N00);
1302 }
1303 }
1304
1305 // Reassociate the operands from (OR/AND (OR/AND(N00, N001)), N1) to (OR/AND
1306 // (OR/AND(N00, N1)), N01) when N00 and N1 are comparisons with the same
1307 // predicate or to (OR/AND (OR/AND(N1, N01)), N00) when N01 and N1 are
1308 // comparisons with the same predicate. This enables optimizations as the
1309 // following one:
1310 // CMP(A,C)||CMP(B,C) => CMP(MIN/MAX(A,B), C)
1311 // CMP(A,C)&&CMP(B,C) => CMP(MIN/MAX(A,B), C)
1312 if (Opc == ISD::AND || Opc == ISD::OR) {
1313 if (N1->getOpcode() == ISD::SETCC && N00->getOpcode() == ISD::SETCC &&
1314 N01->getOpcode() == ISD::SETCC) {
1315 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
1316 ISD::CondCode CC00 = cast<CondCodeSDNode>(N00.getOperand(2))->get();
1317 ISD::CondCode CC01 = cast<CondCodeSDNode>(N01.getOperand(2))->get();
1318 if (CC1 == CC00 && CC1 != CC01) {
1319 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, Flags);
1320 return DAG.getNode(Opc, DL, VT, OpNode, N01, Flags);
1321 }
1322 if (CC1 == CC01 && CC1 != CC00) {
1323 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N01, N1, Flags);
1324 return DAG.getNode(Opc, DL, VT, OpNode, N00, Flags);
1325 }
1326 }
1327 }
1328 }
1329
1330 return SDValue();
1331}
1332
1333/// Try to reassociate commutative (Opc N0, N1) if either \p N0 or \p N1 is the
1334/// same kind of operation as \p Opc.
1335SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
1336 SDValue N1, SDNodeFlags Flags) {
1337 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
1338
1339 // Floating-point reassociation is not allowed without loose FP math.
1340 if (N0.getValueType().isFloatingPoint() ||
1342 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1343 return SDValue();
1344
1345 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1, Flags))
1346 return Combined;
1347 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0, Flags))
1348 return Combined;
1349 return SDValue();
1350}
1351
1352// Try to fold Opc(vecreduce(x), vecreduce(y)) -> vecreduce(Opc(x, y))
1353// Note that we only expect Flags to be passed from FP operations. For integer
1354// operations they need to be dropped.
1355SDValue DAGCombiner::reassociateReduction(unsigned RedOpc, unsigned Opc,
1356 const SDLoc &DL, EVT VT, SDValue N0,
1357 SDValue N1, SDNodeFlags Flags) {
1358 if (N0.getOpcode() == RedOpc && N1.getOpcode() == RedOpc &&
1359 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1360 N0->hasOneUse() && N1->hasOneUse() &&
1362 TLI.shouldReassociateReduction(RedOpc, N0.getOperand(0).getValueType())) {
1363 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
1364 return DAG.getNode(RedOpc, DL, VT,
1365 DAG.getNode(Opc, DL, N0.getOperand(0).getValueType(),
1366 N0.getOperand(0), N1.getOperand(0)));
1367 }
1368
1369 // Reassociate op(op(vecreduce(a), b), op(vecreduce(c), d)) into
1370 // op(vecreduce(op(a, c)), op(b, d)), to combine the reductions into a
1371 // single node.
1372 SDValue A, B, C, D, RedA, RedB;
1373 if (sd_match(N0, m_OneUse(m_c_BinOp(
1374 Opc,
1375 m_AllOf(m_OneUse(m_UnaryOp(RedOpc, m_Value(A))),
1376 m_Value(RedA)),
1377 m_Value(B)))) &&
1379 Opc,
1380 m_AllOf(m_OneUse(m_UnaryOp(RedOpc, m_Value(C))),
1381 m_Value(RedB)),
1382 m_Value(D)))) &&
1383 !sd_match(B, m_UnaryOp(RedOpc, m_Value())) &&
1384 !sd_match(D, m_UnaryOp(RedOpc, m_Value())) &&
1385 A.getValueType() == C.getValueType() &&
1386 hasOperation(Opc, A.getValueType()) &&
1387 TLI.shouldReassociateReduction(RedOpc, VT)) {
1388 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1389 (!N0->getFlags().hasAllowReassociation() ||
1391 !RedA->getFlags().hasAllowReassociation() ||
1392 !RedB->getFlags().hasAllowReassociation()))
1393 return SDValue();
1394 SelectionDAG::FlagInserter FlagsInserter(
1395 DAG, Flags & N0->getFlags() & N1->getFlags() & RedA->getFlags() &
1396 RedB->getFlags());
1397 SDValue Op = DAG.getNode(Opc, DL, A.getValueType(), A, C);
1398 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1399 SDValue Op2 = DAG.getNode(Opc, DL, VT, B, D);
1400 return DAG.getNode(Opc, DL, VT, Red, Op2);
1401 }
1402 return SDValue();
1403}
1404
1405SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1406 bool AddTo) {
1407 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1408 ++NodesCombined;
1409 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1410 To[0].dump(&DAG);
1411 dbgs() << " and " << NumTo - 1 << " other values\n");
1412 for (unsigned i = 0, e = NumTo; i != e; ++i)
1413 assert((!To[i].getNode() ||
1414 N->getValueType(i) == To[i].getValueType()) &&
1415 "Cannot combine value to value of different type!");
1416
1417 WorklistRemover DeadNodes(*this);
1418 DAG.ReplaceAllUsesWith(N, To);
1419 if (AddTo) {
1420 // Push the new nodes and any users onto the worklist
1421 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1422 if (To[i].getNode())
1423 AddToWorklistWithUsers(To[i].getNode());
1424 }
1425 }
1426
1427 // Finally, if the node is now dead, remove it from the graph. The node
1428 // may not be dead if the replacement process recursively simplified to
1429 // something else needing this node.
1430 if (N->use_empty())
1431 deleteAndRecombine(N);
1432 return SDValue(N, 0);
1433}
1434
1435void DAGCombiner::
1436CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1437 // Replace the old value with the new one.
1438 ++NodesCombined;
1439 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.dump(&DAG);
1440 dbgs() << "\nWith: "; TLO.New.dump(&DAG); dbgs() << '\n');
1441
1442 // Replace all uses.
1443 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1444
1445 // Push the new node and any (possibly new) users onto the worklist.
1446 AddToWorklistWithUsers(TLO.New.getNode());
1447
1448 // Finally, if the node is now dead, remove it from the graph.
1449 recursivelyDeleteUnusedNodes(TLO.Old.getNode());
1450}
1451
1452/// Check the specified integer node value to see if it can be simplified or if
1453/// things it uses can be simplified by bit propagation. If so, return true.
1454bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1455 const APInt &DemandedElts,
1456 bool AssumeSingleUse) {
1457 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1458 KnownBits Known;
1459 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1460 AssumeSingleUse))
1461 return false;
1462
1463 // Revisit the node.
1464 AddToWorklist(Op.getNode());
1465
1466 CommitTargetLoweringOpt(TLO);
1467 return true;
1468}
1469
1470/// Check the specified vector node value to see if it can be simplified or
1471/// if things it uses can be simplified as it only uses some of the elements.
1472/// If so, return true.
1473bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1474 const APInt &DemandedElts,
1475 bool AssumeSingleUse) {
1476 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1477 APInt KnownUndef, KnownZero;
1478 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1479 TLO, 0, AssumeSingleUse))
1480 return false;
1481
1482 // Revisit the node.
1483 AddToWorklist(Op.getNode());
1484
1485 CommitTargetLoweringOpt(TLO);
1486 return true;
1487}
1488
1489void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1490 SDLoc DL(Load);
1491 EVT VT = Load->getValueType(0);
1492 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1493
1494 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1495 Trunc.dump(&DAG); dbgs() << '\n');
1496
1497 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1498 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1499
1500 AddToWorklist(Trunc.getNode());
1501 recursivelyDeleteUnusedNodes(Load);
1502}
1503
1504SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1505 Replace = false;
1506 SDLoc DL(Op);
1507 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1508 LoadSDNode *LD = cast<LoadSDNode>(Op);
1509 EVT MemVT = LD->getMemoryVT();
1511 : LD->getExtensionType();
1512 Replace = true;
1513 return DAG.getExtLoad(ExtType, DL, PVT,
1514 LD->getChain(), LD->getBasePtr(),
1515 MemVT, LD->getMemOperand());
1516 }
1517
1518 unsigned Opc = Op.getOpcode();
1519 switch (Opc) {
1520 default: break;
1521 case ISD::AssertSext:
1522 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1523 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1524 break;
1525 case ISD::AssertZext:
1526 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1527 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1528 break;
1529 case ISD::Constant: {
1530 unsigned ExtOpc =
1531 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1532 return DAG.getNode(ExtOpc, DL, PVT, Op);
1533 }
1534 }
1535
1536 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1537 return SDValue();
1538 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1539}
1540
1541SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1543 return SDValue();
1544 EVT OldVT = Op.getValueType();
1545 SDLoc DL(Op);
1546 bool Replace = false;
1547 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1548 if (!NewOp.getNode())
1549 return SDValue();
1550 AddToWorklist(NewOp.getNode());
1551
1552 if (Replace)
1553 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1554 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1555 DAG.getValueType(OldVT));
1556}
1557
1558SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1559 EVT OldVT = Op.getValueType();
1560 SDLoc DL(Op);
1561 bool Replace = false;
1562 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1563 if (!NewOp.getNode())
1564 return SDValue();
1565 AddToWorklist(NewOp.getNode());
1566
1567 if (Replace)
1568 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1569 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1570}
1571
1572/// Promote the specified integer binary operation if the target indicates it is
1573/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1574/// i32 since i16 instructions are longer.
1575SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1576 if (!LegalOperations)
1577 return SDValue();
1578
1579 EVT VT = Op.getValueType();
1580 if (VT.isVector() || !VT.isInteger())
1581 return SDValue();
1582
1583 // If operation type is 'undesirable', e.g. i16 on x86, consider
1584 // promoting it.
1585 unsigned Opc = Op.getOpcode();
1586 if (TLI.isTypeDesirableForOp(Opc, VT))
1587 return SDValue();
1588
1589 EVT PVT = VT;
1590 // Consult target whether it is a good idea to promote this operation and
1591 // what's the right type to promote it to.
1592 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1593 assert(PVT != VT && "Don't know what type to promote to!");
1594
1595 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1596
1597 bool Replace0 = false;
1598 SDValue N0 = Op.getOperand(0);
1599 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1600
1601 bool Replace1 = false;
1602 SDValue N1 = Op.getOperand(1);
1603 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1604 SDLoc DL(Op);
1605
1606 SDValue RV =
1607 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1608
1609 // We are always replacing N0/N1's use in N and only need additional
1610 // replacements if there are additional uses.
1611 // Note: We are checking uses of the *nodes* (SDNode) rather than values
1612 // (SDValue) here because the node may reference multiple values
1613 // (for example, the chain value of a load node).
1614 Replace0 &= !N0->hasOneUse();
1615 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1616
1617 // Combine Op here so it is preserved past replacements.
1618 CombineTo(Op.getNode(), RV);
1619
1620 // If operands have a use ordering, make sure we deal with
1621 // predecessor first.
1622 if (Replace0 && Replace1 && N0->isPredecessorOf(N1.getNode())) {
1623 std::swap(N0, N1);
1624 std::swap(NN0, NN1);
1625 }
1626
1627 if (Replace0) {
1628 AddToWorklist(NN0.getNode());
1629 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1630 }
1631 if (Replace1) {
1632 AddToWorklist(NN1.getNode());
1633 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1634 }
1635 return Op;
1636 }
1637 return SDValue();
1638}
1639
1640/// Promote the specified integer shift operation if the target indicates it is
1641/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1642/// i32 since i16 instructions are longer.
1643SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1644 if (!LegalOperations)
1645 return SDValue();
1646
1647 EVT VT = Op.getValueType();
1648 if (VT.isVector() || !VT.isInteger())
1649 return SDValue();
1650
1651 // If operation type is 'undesirable', e.g. i16 on x86, consider
1652 // promoting it.
1653 unsigned Opc = Op.getOpcode();
1654 if (TLI.isTypeDesirableForOp(Opc, VT))
1655 return SDValue();
1656
1657 EVT PVT = VT;
1658 // Consult target whether it is a good idea to promote this operation and
1659 // what's the right type to promote it to.
1660 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1661 assert(PVT != VT && "Don't know what type to promote to!");
1662
1663 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1664
1665 SDNodeFlags TruncFlags;
1666 bool Replace = false;
1667 SDValue N0 = Op.getOperand(0);
1668 if (Opc == ISD::SRA) {
1669 N0 = SExtPromoteOperand(N0, PVT);
1670 } else if (Opc == ISD::SRL) {
1671 N0 = ZExtPromoteOperand(N0, PVT);
1672 } else {
1673 if (Op->getFlags().hasNoUnsignedWrap()) {
1674 N0 = ZExtPromoteOperand(N0, PVT);
1675 TruncFlags = SDNodeFlags::NoUnsignedWrap;
1676 } else if (Op->getFlags().hasNoSignedWrap()) {
1677 N0 = SExtPromoteOperand(N0, PVT);
1678 TruncFlags = SDNodeFlags::NoSignedWrap;
1679 } else {
1680 N0 = PromoteOperand(N0, PVT, Replace);
1681 }
1682 }
1683
1684 if (!N0.getNode())
1685 return SDValue();
1686
1687 SDLoc DL(Op);
1688 SDValue N1 = Op.getOperand(1);
1689 SDValue RV = DAG.getNode(ISD::TRUNCATE, DL, VT,
1690 DAG.getNode(Opc, DL, PVT, N0, N1), TruncFlags);
1691
1692 if (Replace)
1693 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1694
1695 // Deal with Op being deleted.
1696 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1697 return RV;
1698 }
1699 return SDValue();
1700}
1701
1702SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1703 if (!LegalOperations)
1704 return SDValue();
1705
1706 EVT VT = Op.getValueType();
1707 if (VT.isVector() || !VT.isInteger())
1708 return SDValue();
1709
1710 // If operation type is 'undesirable', e.g. i16 on x86, consider
1711 // promoting it.
1712 unsigned Opc = Op.getOpcode();
1713 if (TLI.isTypeDesirableForOp(Opc, VT))
1714 return SDValue();
1715
1716 EVT PVT = VT;
1717 // Consult target whether it is a good idea to promote this operation and
1718 // what's the right type to promote it to.
1719 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1720 assert(PVT != VT && "Don't know what type to promote to!");
1721 // fold (aext (aext x)) -> (aext x)
1722 // fold (aext (zext x)) -> (zext x)
1723 // fold (aext (sext x)) -> (sext x)
1724 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1725 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1726 }
1727 return SDValue();
1728}
1729
1730bool DAGCombiner::PromoteLoad(SDValue Op) {
1731 if (!LegalOperations)
1732 return false;
1733
1734 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1735 return false;
1736
1737 EVT VT = Op.getValueType();
1738 if (VT.isVector() || !VT.isInteger())
1739 return false;
1740
1741 // If operation type is 'undesirable', e.g. i16 on x86, consider
1742 // promoting it.
1743 unsigned Opc = Op.getOpcode();
1744 if (TLI.isTypeDesirableForOp(Opc, VT))
1745 return false;
1746
1747 EVT PVT = VT;
1748 // Consult target whether it is a good idea to promote this operation and
1749 // what's the right type to promote it to.
1750 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1751 assert(PVT != VT && "Don't know what type to promote to!");
1752
1753 SDLoc DL(Op);
1754 SDNode *N = Op.getNode();
1755 LoadSDNode *LD = cast<LoadSDNode>(N);
1756 EVT MemVT = LD->getMemoryVT();
1758 : LD->getExtensionType();
1759 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1760 LD->getChain(), LD->getBasePtr(),
1761 MemVT, LD->getMemOperand());
1762 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1763
1764 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1765 Result.dump(&DAG); dbgs() << '\n');
1766
1767 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1768 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1769
1770 AddToWorklist(Result.getNode());
1771 recursivelyDeleteUnusedNodes(N);
1772 return true;
1773 }
1774
1775 return false;
1776}
1777
1778/// Recursively delete a node which has no uses and any operands for
1779/// which it is the only use.
1780///
1781/// Note that this both deletes the nodes and removes them from the worklist.
1782/// It also adds any nodes who have had a user deleted to the worklist as they
1783/// may now have only one use and subject to other combines.
1784bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1785 if (!N->use_empty())
1786 return false;
1787
1788 SmallSetVector<SDNode *, 16> Nodes;
1789 Nodes.insert(N);
1790 do {
1791 N = Nodes.pop_back_val();
1792 if (!N)
1793 continue;
1794
1795 if (N->use_empty()) {
1796 for (const SDValue &ChildN : N->op_values())
1797 Nodes.insert(ChildN.getNode());
1798
1799 removeFromWorklist(N);
1800 DAG.DeleteNode(N);
1801 } else {
1802 AddToWorklist(N);
1803 }
1804 } while (!Nodes.empty());
1805 return true;
1806}
1807
1808//===----------------------------------------------------------------------===//
1809// Main DAG Combiner implementation
1810//===----------------------------------------------------------------------===//
1811
1812void DAGCombiner::Run(CombineLevel AtLevel) {
1813 // set the instance variables, so that the various visit routines may use it.
1814 Level = AtLevel;
1815 LegalDAG = Level >= AfterLegalizeDAG;
1816 LegalOperations = Level >= AfterLegalizeVectorOps;
1817 LegalTypes = Level >= AfterLegalizeTypes;
1818
1819 bool UseTopologicalSorting = EnableTopologicalSorting.getNumOccurrences() > 0
1821 : TLI.useTopologicalSorting();
1822
1823 WorklistInserter AddNodes(*this);
1824
1825 if (UseTopologicalSorting)
1827
1828 // Add all the dag nodes to the worklist.
1829 //
1830 // Note: All nodes are not added to PruningList here, this is because the only
1831 // nodes which can be deleted are those which have no uses and all other nodes
1832 // which would otherwise be added to the worklist by the first call to
1833 // getNextWorklistEntry are already present in it.
1834 if (UseTopologicalSorting) {
1835 for (SDNode &Node : reverse(DAG.allnodes()))
1836 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1837 } else {
1838 for (SDNode &Node : DAG.allnodes())
1839 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1840 }
1841
1842 // Create a dummy node (which is not added to allnodes), that adds a reference
1843 // to the root node, preventing it from being deleted, and tracking any
1844 // changes of the root.
1845 HandleSDNode Dummy(DAG.getRoot());
1846
1847 // While we have a valid worklist entry node, try to combine it.
1848 while (SDNode *N = getNextWorklistEntry()) {
1849 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1850 // N is deleted from the DAG, since they too may now be dead or may have a
1851 // reduced number of uses, allowing other xforms.
1852 if (recursivelyDeleteUnusedNodes(N))
1853 continue;
1854
1855 WorklistRemover DeadNodes(*this);
1856
1857 // If this combine is running after legalizing the DAG, re-legalize any
1858 // nodes pulled off the worklist.
1859 if (LegalDAG) {
1860 SmallSetVector<SDNode *, 16> UpdatedNodes;
1861 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1862
1863 for (SDNode *LN : UpdatedNodes)
1864 AddToWorklistWithUsers(LN);
1865
1866 if (!NIsValid)
1867 continue;
1868 }
1869
1870 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1871
1872 // Add any operands of the new node which have not yet been combined to the
1873 // worklist as well. getNextWorklistEntry flags nodes that have been
1874 // combined before. Because the worklist uniques things already, this won't
1875 // repeatedly process the same operand.
1876 for (const SDValue &ChildN : N->op_values())
1877 AddToWorklist(ChildN.getNode(), /*IsCandidateForPruning=*/true,
1878 /*SkipIfCombinedBefore=*/true);
1879
1880 SDValue RV = combine(N);
1881
1882 if (!RV.getNode())
1883 continue;
1884
1885 ++NodesCombined;
1886
1887 // Invalidate cached info.
1888 ChainsWithoutMergeableStores.clear();
1889
1890 // If we get back the same node we passed in, rather than a new node or
1891 // zero, we know that the node must have defined multiple values and
1892 // CombineTo was used. Since CombineTo takes care of the worklist
1893 // mechanics for us, we have no work to do in this case.
1894 if (RV.getNode() == N)
1895 continue;
1896
1897 assert(N->getOpcode() != ISD::DELETED_NODE &&
1898 RV.getOpcode() != ISD::DELETED_NODE &&
1899 "Node was deleted but visit returned new node!");
1900
1901 LLVM_DEBUG(dbgs() << " ... into: "; RV.dump(&DAG));
1902
1903 if (N->getNumValues() == RV->getNumValues())
1904 DAG.ReplaceAllUsesWith(N, RV.getNode());
1905 else {
1906 assert(N->getValueType(0) == RV.getValueType() &&
1907 N->getNumValues() == 1 && "Type mismatch");
1908 DAG.ReplaceAllUsesWith(N, &RV);
1909 }
1910
1911 // Push the new node and any users onto the worklist. Omit this if the
1912 // new node is the EntryToken (e.g. if a store managed to get optimized
1913 // out), because re-visiting the EntryToken and its users will not uncover
1914 // any additional opportunities, but there may be a large number of such
1915 // users, potentially causing compile time explosion.
1916 if (RV.getOpcode() != ISD::EntryToken)
1917 AddToWorklistWithUsers(RV.getNode());
1918
1919 // Finally, if the node is now dead, remove it from the graph. The node
1920 // may not be dead if the replacement process recursively simplified to
1921 // something else needing this node. This will also take care of adding any
1922 // operands which have lost a user to the worklist.
1923 recursivelyDeleteUnusedNodes(N);
1924 }
1925
1926 // If the root changed (e.g. it was a dead load, update the root).
1927 DAG.setRoot(Dummy.getValue());
1928 DAG.RemoveDeadNodes();
1929}
1930
1931SDValue DAGCombiner::visit(SDNode *N) {
1932 // clang-format off
1933 switch (N->getOpcode()) {
1934 default: break;
1935 case ISD::TokenFactor: return visitTokenFactor(N);
1936 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1937 case ISD::ADD: return visitADD(N);
1938 case ISD::PTRADD: return visitPTRADD(N);
1939 case ISD::SUB: return visitSUB(N);
1940 case ISD::SADDSAT:
1941 case ISD::UADDSAT: return visitADDSAT(N);
1942 case ISD::SSUBSAT:
1943 case ISD::USUBSAT: return visitSUBSAT(N);
1944 case ISD::ADDC: return visitADDC(N);
1945 case ISD::SADDO:
1946 case ISD::UADDO: return visitADDO(N);
1947 case ISD::SUBC: return visitSUBC(N);
1948 case ISD::SSUBO:
1949 case ISD::USUBO: return visitSUBO(N);
1950 case ISD::ADDE: return visitADDE(N);
1951 case ISD::UADDO_CARRY: return visitUADDO_CARRY(N);
1952 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
1953 case ISD::SUBE: return visitSUBE(N);
1954 case ISD::USUBO_CARRY: return visitUSUBO_CARRY(N);
1955 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
1956 case ISD::SMULFIX:
1957 case ISD::SMULFIXSAT:
1958 case ISD::UMULFIX:
1959 case ISD::UMULFIXSAT: return visitMULFIX(N);
1960 case ISD::MUL: return visitMUL(N);
1961 case ISD::SDIV: return visitSDIV(N);
1962 case ISD::UDIV: return visitUDIV(N);
1963 case ISD::SREM:
1964 case ISD::UREM: return visitREM(N);
1965 case ISD::MULHU: return visitMULHU(N);
1966 case ISD::MULHS: return visitMULHS(N);
1967 case ISD::AVGFLOORS:
1968 case ISD::AVGFLOORU:
1969 case ISD::AVGCEILS:
1970 case ISD::AVGCEILU: return visitAVG(N);
1971 case ISD::ABDS:
1972 case ISD::ABDU: return visitABD(N);
1973 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1974 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1975 case ISD::SMULO:
1976 case ISD::UMULO: return visitMULO(N);
1977 case ISD::SMIN:
1978 case ISD::SMAX:
1979 case ISD::UMIN:
1980 case ISD::UMAX: return visitIMINMAX(N);
1981 case ISD::AND: return visitAND(N);
1982 case ISD::OR: return visitOR(N);
1983 case ISD::XOR: return visitXOR(N);
1984 case ISD::SHL: return visitSHL(N);
1985 case ISD::SRA: return visitSRA(N);
1986 case ISD::SRL: return visitSRL(N);
1987 case ISD::ROTR:
1988 case ISD::ROTL: return visitRotate(N);
1989 case ISD::FSHL:
1990 case ISD::FSHR: return visitFunnelShift(N);
1991 case ISD::SSHLSAT:
1992 case ISD::USHLSAT: return visitSHLSAT(N);
1993 case ISD::ABS: return visitABS(N);
1994 case ISD::ABS_MIN_POISON: return visitABS_MIN_POISON(N);
1995 case ISD::CLMUL:
1996 case ISD::CLMULR:
1997 case ISD::CLMULH: return visitCLMUL(N);
1998 case ISD::BSWAP: return visitBSWAP(N);
1999 case ISD::BITREVERSE: return visitBITREVERSE(N);
2000 case ISD::CTLZ: return visitCTLZ(N);
2001 case ISD::CTLZ_ZERO_POISON: return visitCTLZ_ZERO_POISON(N);
2002 case ISD::CTTZ: return visitCTTZ(N);
2003 case ISD::CTTZ_ZERO_POISON: return visitCTTZ_ZERO_POISON(N);
2004 case ISD::CTPOP: return visitCTPOP(N);
2005 case ISD::SELECT: return visitSELECT(N);
2006 case ISD::VSELECT: return visitVSELECT(N);
2007 case ISD::SELECT_CC: return visitSELECT_CC(N);
2008 case ISD::SETCC: return visitSETCC(N);
2009 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
2010 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
2011 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
2012 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
2013 case ISD::AssertSext:
2014 case ISD::AssertZext: return visitAssertExt(N);
2015 case ISD::AssertAlign: return visitAssertAlign(N);
2016 case ISD::IS_FPCLASS: return visitIS_FPCLASS(N);
2017 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
2020 case ISD::ANY_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
2021 case ISD::TRUNCATE: return visitTRUNCATE(N);
2022 case ISD::TRUNCATE_USAT_U: return visitTRUNCATE_USAT_U(N);
2023 case ISD::BITCAST: return visitBITCAST(N);
2024 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
2025 case ISD::FADD: return visitFADD(N);
2026 case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
2027 case ISD::FSUB: return visitFSUB(N);
2028 case ISD::FMUL: return visitFMUL(N);
2029 case ISD::FMA: return visitFMA(N);
2030 case ISD::FMAD: return visitFMAD(N);
2031 case ISD::FMULADD: return visitFMULADD(N);
2032 case ISD::FDIV: return visitFDIV(N);
2033 case ISD::FREM: return visitFREM(N);
2034 case ISD::FSQRT: return visitFSQRT(N);
2035 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
2036 case ISD::FPOW: return visitFPOW(N);
2037 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
2038 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
2039 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
2040 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
2041 case ISD::LROUND:
2042 case ISD::LLROUND:
2043 case ISD::LRINT:
2044 case ISD::LLRINT: return visitXROUND(N);
2045 case ISD::FP_ROUND: return visitFP_ROUND(N);
2046 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
2047 case ISD::FNEG: return visitFNEG(N);
2048 case ISD::FABS: return visitFABS(N);
2049 case ISD::FFLOOR: return visitFFLOOR(N);
2050 case ISD::FMINNUM:
2051 case ISD::FMAXNUM:
2052 case ISD::FMINIMUM:
2053 case ISD::FMAXIMUM:
2054 case ISD::FMINIMUMNUM:
2055 case ISD::FMAXIMUMNUM: return visitFMinMax(N);
2056 case ISD::FCEIL: return visitFCEIL(N);
2057 case ISD::FTRUNC: return visitFTRUNC(N);
2058 case ISD::FFREXP: return visitFFREXP(N);
2059 case ISD::BRCOND: return visitBRCOND(N);
2060 case ISD::BR_CC: return visitBR_CC(N);
2061 case ISD::LOAD: return visitLOAD(N);
2062 case ISD::STORE: return visitSTORE(N);
2063 case ISD::ATOMIC_STORE: return visitATOMIC_STORE(N);
2064 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
2065 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
2066 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
2067 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
2068 case ISD::VECTOR_INTERLEAVE: return visitVECTOR_INTERLEAVE(N);
2069 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
2070 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
2071 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
2072 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
2073 case ISD::MGATHER: return visitMGATHER(N);
2074 case ISD::MLOAD: return visitMLOAD(N);
2075 case ISD::MSCATTER: return visitMSCATTER(N);
2076 case ISD::MSTORE: return visitMSTORE(N);
2077 case ISD::EXPERIMENTAL_VECTOR_HISTOGRAM: return visitMHISTOGRAM(N);
2082 return visitPARTIAL_REDUCE_MLA(N);
2083 case ISD::VECTOR_COMPRESS: return visitVECTOR_COMPRESS(N);
2084 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
2085 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
2086 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
2087 case ISD::FP_TO_BF16: return visitFP_TO_BF16(N);
2088 case ISD::BF16_TO_FP: return visitBF16_TO_FP(N);
2089 case ISD::FREEZE: return visitFREEZE(N);
2090 case ISD::GET_FPENV_MEM: return visitGET_FPENV_MEM(N);
2091 case ISD::SET_FPENV_MEM: return visitSET_FPENV_MEM(N);
2092 case ISD::FCANONICALIZE: return visitFCANONICALIZE(N);
2095 case ISD::VECREDUCE_ADD:
2096 case ISD::VECREDUCE_MUL:
2097 case ISD::VECREDUCE_AND:
2098 case ISD::VECREDUCE_OR:
2099 case ISD::VECREDUCE_XOR:
2107 case ISD::VECREDUCE_FMINIMUM: return visitVECREDUCE(N);
2108#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
2109#include "llvm/IR/VPIntrinsics.def"
2110 return visitVPOp(N);
2111 }
2112 // clang-format on
2113 return SDValue();
2114}
2115
2116SDValue DAGCombiner::combine(SDNode *N) {
2117 if (!DebugCounter::shouldExecute(DAGCombineCounter))
2118 return SDValue();
2119
2120 SDValue RV;
2121 if (!DisableGenericCombines)
2122 RV = visit(N);
2123
2124 // If nothing happened, try a target-specific DAG combine.
2125 if (!RV.getNode()) {
2126 assert(N->getOpcode() != ISD::DELETED_NODE &&
2127 "Node was deleted but visit returned NULL!");
2128
2129 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
2130 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
2131
2132 // Expose the DAG combiner to the target combiner impls.
2133 TargetLowering::DAGCombinerInfo
2134 DagCombineInfo(DAG, Level, false, this);
2135
2136 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
2137 }
2138 }
2139
2140 // If nothing happened still, try promoting the operation.
2141 if (!RV.getNode()) {
2142 switch (N->getOpcode()) {
2143 default: break;
2144 case ISD::ADD:
2145 case ISD::SUB:
2146 case ISD::MUL:
2147 case ISD::AND:
2148 case ISD::OR:
2149 case ISD::XOR:
2150 RV = PromoteIntBinOp(SDValue(N, 0));
2151 break;
2152 case ISD::SHL:
2153 case ISD::SRA:
2154 case ISD::SRL:
2155 RV = PromoteIntShiftOp(SDValue(N, 0));
2156 break;
2157 case ISD::SIGN_EXTEND:
2158 case ISD::ZERO_EXTEND:
2159 case ISD::ANY_EXTEND:
2160 RV = PromoteExtend(SDValue(N, 0));
2161 break;
2162 case ISD::LOAD:
2163 if (PromoteLoad(SDValue(N, 0)))
2164 RV = SDValue(N, 0);
2165 break;
2166 }
2167 }
2168
2169 // If N is a commutative binary node, try to eliminate it if the commuted
2170 // version is already present in the DAG.
2171 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode())) {
2172 SDValue N0 = N->getOperand(0);
2173 SDValue N1 = N->getOperand(1);
2174
2175 // Constant operands are canonicalized to RHS.
2176 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
2177 SDValue Ops[] = {N1, N0};
2178 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
2179 N->getFlags());
2180 if (CSENode)
2181 return SDValue(CSENode, 0);
2182 }
2183 }
2184
2185 return RV;
2186}
2187
2188/// Given a node, return its input chain if it has one, otherwise return a null
2189/// sd operand.
2191 if (unsigned NumOps = N->getNumOperands()) {
2192 if (N->getOperand(0).getValueType() == MVT::Other)
2193 return N->getOperand(0);
2194 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
2195 return N->getOperand(NumOps-1);
2196 for (unsigned i = 1; i < NumOps-1; ++i)
2197 if (N->getOperand(i).getValueType() == MVT::Other)
2198 return N->getOperand(i);
2199 }
2200 return SDValue();
2201}
2202
2203SDValue DAGCombiner::visitFCANONICALIZE(SDNode *N) {
2204 SDValue Operand = N->getOperand(0);
2205 EVT VT = Operand.getValueType();
2206 SDLoc dl(N);
2207
2208 // Canonicalize undef to quiet NaN.
2209 if (Operand.isUndef()) {
2210 APFloat CanonicalQNaN = APFloat::getQNaN(VT.getFltSemantics());
2211 return DAG.getConstantFP(CanonicalQNaN, dl, VT);
2212 }
2213 return SDValue();
2214}
2215
2216SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
2217 // If N has two operands, where one has an input chain equal to the other,
2218 // the 'other' chain is redundant.
2219 if (N->getNumOperands() == 2) {
2220 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
2221 return N->getOperand(0);
2222 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
2223 return N->getOperand(1);
2224 }
2225
2226 // Don't simplify token factors if optnone.
2227 if (OptLevel == CodeGenOptLevel::None)
2228 return SDValue();
2229
2230 // Don't simplify the token factor if the node itself has too many operands.
2231 if (N->getNumOperands() > TokenFactorInlineLimit)
2232 return SDValue();
2233
2234 // If the sole user is a token factor, we should make sure we have a
2235 // chance to merge them together. This prevents TF chains from inhibiting
2236 // optimizations.
2237 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TokenFactor)
2238 AddToWorklist(*(N->user_begin()));
2239
2240 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
2241 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
2242 SmallPtrSet<SDNode*, 16> SeenOps;
2243 bool Changed = false; // If we should replace this token factor.
2244
2245 // Start out with this token factor.
2246 TFs.push_back(N);
2247
2248 // Iterate through token factors. The TFs grows when new token factors are
2249 // encountered.
2250 for (unsigned i = 0; i < TFs.size(); ++i) {
2251 // Limit number of nodes to inline, to avoid quadratic compile times.
2252 // We have to add the outstanding Token Factors to Ops, otherwise we might
2253 // drop Ops from the resulting Token Factors.
2254 if (Ops.size() > TokenFactorInlineLimit) {
2255 for (unsigned j = i; j < TFs.size(); j++)
2256 Ops.emplace_back(TFs[j], 0);
2257 // Drop unprocessed Token Factors from TFs, so we do not add them to the
2258 // combiner worklist later.
2259 TFs.resize(i);
2260 break;
2261 }
2262
2263 SDNode *TF = TFs[i];
2264 // Check each of the operands.
2265 for (const SDValue &Op : TF->op_values()) {
2266 switch (Op.getOpcode()) {
2267 case ISD::EntryToken:
2268 // Entry tokens don't need to be added to the list. They are
2269 // redundant.
2270 Changed = true;
2271 break;
2272
2273 case ISD::TokenFactor:
2274 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
2275 // Queue up for processing.
2276 TFs.push_back(Op.getNode());
2277 Changed = true;
2278 break;
2279 }
2280 [[fallthrough]];
2281
2282 default:
2283 // Only add if it isn't already in the list.
2284 if (SeenOps.insert(Op.getNode()).second)
2285 Ops.push_back(Op);
2286 else
2287 Changed = true;
2288 break;
2289 }
2290 }
2291 }
2292
2293 // Re-visit inlined Token Factors, to clean them up in case they have been
2294 // removed. Skip the first Token Factor, as this is the current node.
2295 for (unsigned i = 1, e = TFs.size(); i < e; i++)
2296 AddToWorklist(TFs[i]);
2297
2298 // Remove Nodes that are chained to another node in the list. Do so
2299 // by walking up chains breath-first stopping when we've seen
2300 // another operand. In general we must climb to the EntryNode, but we can exit
2301 // early if we find all remaining work is associated with just one operand as
2302 // no further pruning is possible.
2303
2304 // List of nodes to search through and original Ops from which they originate.
2306 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
2307 SmallPtrSet<SDNode *, 16> SeenChains;
2308 bool DidPruneOps = false;
2309
2310 unsigned NumLeftToConsider = 0;
2311 for (const SDValue &Op : Ops) {
2312 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
2313 OpWorkCount.push_back(1);
2314 }
2315
2316 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
2317 // If this is an Op, we can remove the op from the list. Remark any
2318 // search associated with it as from the current OpNumber.
2319 if (SeenOps.contains(Op)) {
2320 Changed = true;
2321 DidPruneOps = true;
2322 unsigned OrigOpNumber = 0;
2323 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
2324 OrigOpNumber++;
2325 assert((OrigOpNumber != Ops.size()) &&
2326 "expected to find TokenFactor Operand");
2327 // Re-mark worklist from OrigOpNumber to OpNumber
2328 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
2329 if (Worklist[i].second == OrigOpNumber) {
2330 Worklist[i].second = OpNumber;
2331 }
2332 }
2333 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
2334 OpWorkCount[OrigOpNumber] = 0;
2335 NumLeftToConsider--;
2336 }
2337 // Add if it's a new chain
2338 if (SeenChains.insert(Op).second) {
2339 OpWorkCount[OpNumber]++;
2340 Worklist.push_back(std::make_pair(Op, OpNumber));
2341 }
2342 };
2343
2344 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
2345 // We need at least be consider at least 2 Ops to prune.
2346 if (NumLeftToConsider <= 1)
2347 break;
2348 auto CurNode = Worklist[i].first;
2349 auto CurOpNumber = Worklist[i].second;
2350 assert((OpWorkCount[CurOpNumber] > 0) &&
2351 "Node should not appear in worklist");
2352 switch (CurNode->getOpcode()) {
2353 case ISD::EntryToken:
2354 // Hitting EntryToken is the only way for the search to terminate without
2355 // hitting
2356 // another operand's search. Prevent us from marking this operand
2357 // considered.
2358 NumLeftToConsider++;
2359 break;
2360 case ISD::TokenFactor:
2361 for (const SDValue &Op : CurNode->op_values())
2362 AddToWorklist(i, Op.getNode(), CurOpNumber);
2363 break;
2365 case ISD::LIFETIME_END:
2366 case ISD::CopyFromReg:
2367 case ISD::CopyToReg:
2368 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
2369 break;
2370 default:
2371 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
2372 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
2373 break;
2374 }
2375 OpWorkCount[CurOpNumber]--;
2376 if (OpWorkCount[CurOpNumber] == 0)
2377 NumLeftToConsider--;
2378 }
2379
2380 // If we've changed things around then replace token factor.
2381 if (Changed) {
2383 if (Ops.empty()) {
2384 // The entry token is the only possible outcome.
2385 Result = DAG.getEntryNode();
2386 } else {
2387 if (DidPruneOps) {
2388 SmallVector<SDValue, 8> PrunedOps;
2389 //
2390 for (const SDValue &Op : Ops) {
2391 if (SeenChains.count(Op.getNode()) == 0)
2392 PrunedOps.push_back(Op);
2393 }
2394 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2395 } else {
2396 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2397 }
2398 }
2399 return Result;
2400 }
2401 return SDValue();
2402}
2403
2404/// MERGE_VALUES can always be eliminated.
2405SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2406 WorklistRemover DeadNodes(*this);
2407 // Replacing results may cause a different MERGE_VALUES to suddenly
2408 // be CSE'd with N, and carry its uses with it. Iterate until no
2409 // uses remain, to ensure that the node can be safely deleted.
2410 // First add the users of this node to the work list so that they
2411 // can be tried again once they have new operands.
2412 AddUsersToWorklist(N);
2413 do {
2414 // Do as a single replacement to avoid rewalking use lists.
2416 DAG.ReplaceAllUsesWith(N, Ops.data());
2417 } while (!N->use_empty());
2418 deleteAndRecombine(N);
2419 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2420}
2421
2422/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2423/// ConstantSDNode pointer else nullptr.
2426 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2427}
2428
2429// isTruncateOf - If N is a truncate of some other value, return true, record
2430// the value being truncated in Op and which of Op's bits are zero/one in Known.
2431// This function computes KnownBits to avoid a duplicated call to
2432// computeKnownBits in the caller.
2434 KnownBits &Known) {
2435 if (N->getOpcode() == ISD::TRUNCATE) {
2436 Op = N->getOperand(0);
2437 Known = DAG.computeKnownBits(Op);
2438 if (N->getFlags().hasNoUnsignedWrap())
2439 Known.Zero.setBitsFrom(N.getScalarValueSizeInBits());
2440 return true;
2441 }
2442
2443 if (N.getValueType().getScalarType() != MVT::i1 ||
2444 !sd_match(
2446 return false;
2447
2448 Known = DAG.computeKnownBits(Op);
2449 return (Known.Zero | 1).isAllOnes();
2450}
2451
2452/// Return true if 'Use' is a load or a store that uses N as its base pointer
2453/// and that N may be folded in the load / store addressing mode.
2455 const TargetLowering &TLI) {
2456 EVT VT;
2457 unsigned AS;
2458
2459 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2460 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2461 return false;
2462 VT = LD->getMemoryVT();
2463 AS = LD->getAddressSpace();
2464 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2465 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2466 return false;
2467 VT = ST->getMemoryVT();
2468 AS = ST->getAddressSpace();
2470 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2471 return false;
2472 VT = LD->getMemoryVT();
2473 AS = LD->getAddressSpace();
2475 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2476 return false;
2477 VT = ST->getMemoryVT();
2478 AS = ST->getAddressSpace();
2479 } else {
2480 return false;
2481 }
2482
2484 if (N->isAnyAdd()) {
2485 AM.HasBaseReg = true;
2487 if (Offset)
2488 // [reg +/- imm]
2489 AM.BaseOffs = Offset->getSExtValue();
2490 else
2491 // [reg +/- reg]
2492 AM.Scale = 1;
2493 } else if (N->getOpcode() == ISD::SUB) {
2494 AM.HasBaseReg = true;
2496 if (Offset)
2497 // [reg +/- imm]
2498 AM.BaseOffs = -Offset->getSExtValue();
2499 else
2500 // [reg +/- reg]
2501 AM.Scale = 1;
2502 } else {
2503 return false;
2504 }
2505
2506 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2507 VT.getTypeForEVT(*DAG.getContext()), AS);
2508}
2509
2510/// This inverts a canonicalization in IR that replaces a variable select arm
2511/// with an identity constant. Codegen improves if we re-use the variable
2512/// operand rather than load a constant. This can also be converted into a
2513/// masked vector operation if the target supports it.
2515 bool ShouldCommuteOperands) {
2516 SDValue N0 = N->getOperand(0);
2517 SDValue N1 = N->getOperand(1);
2518
2519 // Match a select as operand 1. The identity constant that we are looking for
2520 // is only valid as operand 1 of a non-commutative binop.
2521 if (ShouldCommuteOperands)
2522 std::swap(N0, N1);
2523
2524 SDValue Cond, TVal, FVal;
2526 m_Value(FVal)))))
2527 return SDValue();
2528
2529 // We can't hoist all instructions because of immediate UB (not speculatable).
2530 // For example div/rem by zero.
2532 return SDValue();
2533
2534 unsigned SelOpcode = N1.getOpcode();
2535 unsigned Opcode = N->getOpcode();
2536 EVT VT = N->getValueType(0);
2537 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2538
2539 // This transform increases uses of N0, so freeze it to be safe.
2540 // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
2541 unsigned OpNo = ShouldCommuteOperands ? 0 : 1;
2542 if (DAG.isIdentityElement(Opcode, N->getFlags(), TVal, OpNo) &&
2543 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2544 FVal)) {
2545 SDValue F0 = DAG.getFreeze(N0);
2546 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
2547 return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
2548 }
2549 // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
2550 if (DAG.isIdentityElement(Opcode, N->getFlags(), FVal, OpNo) &&
2551 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2552 TVal)) {
2553 SDValue F0 = DAG.getFreeze(N0);
2554 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
2555 return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
2556 }
2557
2558 return SDValue();
2559}
2560
2561SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2562 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2563 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
2564 "Unexpected binary operator");
2565
2566 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
2567 return Sel;
2568
2569 if (TLI.isCommutativeBinOp(BO->getOpcode()))
2570 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
2571 return Sel;
2572
2573 // Don't do this unless the old select is going away. We want to eliminate the
2574 // binary operator, not replace a binop with a select.
2575 // TODO: Handle ISD::SELECT_CC.
2576 unsigned SelOpNo = 0;
2577 SDValue Sel = BO->getOperand(0);
2578 auto BinOpcode = BO->getOpcode();
2579 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2580 SelOpNo = 1;
2581 Sel = BO->getOperand(1);
2582
2583 // Peek through trunc to shift amount type.
2584 if ((BinOpcode == ISD::SHL || BinOpcode == ISD::SRA ||
2585 BinOpcode == ISD::SRL) && Sel.hasOneUse()) {
2586 // This is valid when the truncated bits of x are already zero.
2587 SDValue Op;
2588 KnownBits Known;
2589 if (isTruncateOf(DAG, Sel, Op, Known) &&
2591 Sel = Op;
2592 }
2593 }
2594
2595 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2596 return SDValue();
2597
2598 SDValue CT = Sel.getOperand(1);
2599 if (!isConstantOrConstantVector(CT, true) &&
2601 return SDValue();
2602
2603 SDValue CF = Sel.getOperand(2);
2604 if (!isConstantOrConstantVector(CF, true) &&
2606 return SDValue();
2607
2608 // Bail out if any constants are opaque because we can't constant fold those.
2609 // The exception is "and" and "or" with either 0 or -1 in which case we can
2610 // propagate non constant operands into select. I.e.:
2611 // and (select Cond, 0, -1), X --> select Cond, 0, X
2612 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2613 bool CanFoldNonConst =
2614 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2617
2618 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2619 if (!CanFoldNonConst &&
2620 !isConstantOrConstantVector(CBO, true) &&
2622 return SDValue();
2623
2624 SDLoc DL(Sel);
2625 SDValue NewCT, NewCF;
2626 EVT VT = BO->getValueType(0);
2627
2628 if (CanFoldNonConst) {
2629 // If CBO is an opaque constant, we can't rely on getNode to constant fold.
2630 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CT)) ||
2631 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CT)))
2632 NewCT = CT;
2633 else
2634 NewCT = CBO;
2635
2636 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CF)) ||
2637 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CF)))
2638 NewCF = CF;
2639 else
2640 NewCF = CBO;
2641 } else {
2642 // We have a select-of-constants followed by a binary operator with a
2643 // constant. Eliminate the binop by pulling the constant math into the
2644 // select. Example: add (select Cond, CT, CF), CBO --> select Cond, CT +
2645 // CBO, CF + CBO
2646 NewCT = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CT})
2647 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CT, CBO});
2648 if (!NewCT)
2649 return SDValue();
2650
2651 NewCF = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CF})
2652 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CF, CBO});
2653 if (!NewCF)
2654 return SDValue();
2655 }
2656
2657 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF, BO->getFlags());
2658}
2659
2661 SelectionDAG &DAG) {
2662 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2663 "Expecting add or sub");
2664
2665 // Match a constant operand and a zext operand for the math instruction:
2666 // add Z, C
2667 // sub C, Z
2668 bool IsAdd = N->getOpcode() == ISD::ADD;
2669 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2670 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2671 auto *CN = dyn_cast<ConstantSDNode>(C);
2672 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2673 return SDValue();
2674
2675 // Match the zext operand as a setcc of a boolean.
2676 if (Z.getOperand(0).getValueType() != MVT::i1)
2677 return SDValue();
2678
2679 // Match the compare as: setcc (X & 1), 0, eq.
2680 if (!sd_match(Z.getOperand(0), m_SetCC(m_And(m_Value(), m_One()), m_Zero(),
2682 return SDValue();
2683
2684 // We are adding/subtracting a constant and an inverted low bit. Turn that
2685 // into a subtract/add of the low bit with incremented/decremented constant:
2686 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2687 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2688 EVT VT = C.getValueType();
2689 SDValue LowBit = DAG.getZExtOrTrunc(Z.getOperand(0).getOperand(0), DL, VT);
2690 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT)
2691 : DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2692 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2693}
2694
2695// Attempt to form avgceil(A, B) from (A | B) - ((A ^ B) >> 1)
2696SDValue DAGCombiner::foldSubToAvg(SDNode *N, const SDLoc &DL) {
2697 SDValue N0 = N->getOperand(0);
2698 EVT VT = N0.getValueType();
2699 SDValue A, B;
2700
2701 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
2703 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2704 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
2705 }
2706 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
2708 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2709 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
2710 }
2711 return SDValue();
2712}
2713
2714/// Try to fold a pointer arithmetic node.
2715/// This needs to be done separately from normal addition, because pointer
2716/// addition is not commutative.
2717SDValue DAGCombiner::visitPTRADD(SDNode *N) {
2718 SDValue N0 = N->getOperand(0);
2719 SDValue N1 = N->getOperand(1);
2720 EVT PtrVT = N0.getValueType();
2721 EVT IntVT = N1.getValueType();
2722 SDLoc DL(N);
2723
2724 // This is already ensured by an assert in SelectionDAG::getNode(). Several
2725 // combines here depend on this assumption.
2726 assert(PtrVT == IntVT &&
2727 "PTRADD with different operand types is not supported");
2728
2729 // fold (ptradd x, 0) -> x
2730 if (isNullConstant(N1))
2731 return N0;
2732
2733 // fold (ptradd 0, x) -> x
2734 if (PtrVT == IntVT && isNullConstant(N0))
2735 return N1;
2736
2737 if (N0.getOpcode() == ISD::PTRADD &&
2738 !reassociationCanBreakAddressingModePattern(ISD::PTRADD, DL, N, N0, N1)) {
2739 SDValue X = N0.getOperand(0);
2740 SDValue Y = N0.getOperand(1);
2741 SDValue Z = N1;
2742 bool N0OneUse = N0.hasOneUse();
2743 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2744 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2745
2746 // (ptradd (ptradd x, y), z) -> (ptradd x, (add y, z)) if:
2747 // * y is a constant and (ptradd x, y) has one use; or
2748 // * y and z are both constants.
2749 if ((YIsConstant && N0OneUse) || (YIsConstant && ZIsConstant)) {
2750 // If both additions in the original were NUW, the new ones are as well.
2751 SDNodeFlags Flags =
2752 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2753 SDValue Add = DAG.getNode(ISD::ADD, DL, IntVT, {Y, Z}, Flags);
2754 AddToWorklist(Add.getNode());
2755 // We can't set InBounds even if both original ptradds were InBounds and
2756 // NUW: SDAG usually represents pointers as integers, therefore, the
2757 // matched pattern behaves as if it had implicit casts:
2758 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds x, y))), z)
2759 // The outer inbounds ptradd might therefore rely on a provenance that x
2760 // does not have.
2761 return DAG.getMemBasePlusOffset(X, Add, DL, Flags);
2762 }
2763 }
2764
2765 // The following combines can turn in-bounds pointer arithmetic out of bounds.
2766 // That is problematic for settings like AArch64's CPA, which checks that
2767 // intermediate results of pointer arithmetic remain in bounds. The target
2768 // therefore needs to opt-in to enable them.
2770 DAG.getMachineFunction().getFunction(), PtrVT))
2771 return SDValue();
2772
2773 if (N0.getOpcode() == ISD::PTRADD && isa<ConstantSDNode>(N1)) {
2774 // Fold (ptradd (ptradd GA, v), c) -> (ptradd (ptradd GA, c) v) with
2775 // global address GA and constant c, such that c can be folded into GA.
2776 // TODO: Support constant vector splats.
2777 SDValue GAValue = N0.getOperand(0);
2778 if (const GlobalAddressSDNode *GA =
2780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2781 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2782 // If both additions in the original were NUW, reassociation preserves
2783 // that.
2784 SDNodeFlags Flags =
2785 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2786 // We can't set InBounds even if both original ptradds were InBounds and
2787 // NUW: SDAG usually represents pointers as integers, therefore, the
2788 // matched pattern behaves as if it had implicit casts:
2789 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds GA, v))), c)
2790 // The outer inbounds ptradd might therefore rely on a provenance that
2791 // GA does not have.
2792 SDValue Inner = DAG.getMemBasePlusOffset(GAValue, N1, DL, Flags);
2793 AddToWorklist(Inner.getNode());
2794 return DAG.getMemBasePlusOffset(Inner, N0.getOperand(1), DL, Flags);
2795 }
2796 }
2797 }
2798
2799 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse()) {
2800 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if z is a constant,
2801 // y is not, and (add y, z) is used only once.
2802 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if y is a constant,
2803 // z is not, and (add y, z) is used only once.
2804 // The goal is to move constant offsets to the outermost ptradd, to create
2805 // more opportunities to fold offsets into memory instructions.
2806 // Together with the another combine above, this also implements
2807 // (ptradd (ptradd x, y), z) -> (ptradd (ptradd x, z), y)).
2808 SDValue X = N0;
2809 SDValue Y = N1.getOperand(0);
2810 SDValue Z = N1.getOperand(1);
2811 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2812 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2813
2814 // If both additions in the original were NUW, reassociation preserves that.
2815 SDNodeFlags CommonFlags = N->getFlags() & N1->getFlags();
2816 SDNodeFlags ReassocFlags = CommonFlags & SDNodeFlags::NoUnsignedWrap;
2817 if (CommonFlags.hasNoUnsignedWrap()) {
2818 // If both operations are NUW and the PTRADD is inbounds, the offests are
2819 // both non-negative, so the reassociated PTRADDs are also inbounds.
2820 ReassocFlags |= N->getFlags() & SDNodeFlags::InBounds;
2821 }
2822
2823 if (ZIsConstant != YIsConstant) {
2824 if (YIsConstant)
2825 std::swap(Y, Z);
2826 SDValue Inner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
2827 AddToWorklist(Inner.getNode());
2828 return DAG.getMemBasePlusOffset(Inner, Z, DL, ReassocFlags);
2829 }
2830 }
2831
2832 // Transform (ptradd a, b) -> (or disjoint a, b) if it is equivalent and if
2833 // that transformation can't block an offset folding at any use of the ptradd.
2834 // This should be done late, after legalization, so that it doesn't block
2835 // other ptradd combines that could enable more offset folding.
2836 if (LegalOperations && DAG.haveNoCommonBitsSet(N0, N1)) {
2837 bool TransformCannotBreakAddrMode = none_of(N->users(), [&](SDNode *User) {
2838 return canFoldInAddressingMode(N, User, DAG, TLI);
2839 });
2840
2841 if (TransformCannotBreakAddrMode)
2842 return DAG.getNode(ISD::OR, DL, PtrVT, N0, N1, SDNodeFlags::Disjoint);
2843 }
2844
2845 return SDValue();
2846}
2847
2848/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2849/// a shift and add with a different constant.
2851 SelectionDAG &DAG) {
2852 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2853 "Expecting add or sub");
2854
2855 // We need a constant operand for the add/sub, and the other operand is a
2856 // logical shift right: add (srl), C or sub C, (srl).
2857 bool IsAdd = N->getOpcode() == ISD::ADD;
2858 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2859 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2860 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2861 ShiftOp.getOpcode() != ISD::SRL)
2862 return SDValue();
2863
2864 // The shift must be of a 'not' value.
2865 SDValue Not = ShiftOp.getOperand(0);
2866 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2867 return SDValue();
2868
2869 // The shift must be moving the sign bit to the least-significant-bit.
2870 EVT VT = ShiftOp.getValueType();
2871 SDValue ShAmt = ShiftOp.getOperand(1);
2872 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2873 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2874 return SDValue();
2875
2876 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2877 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2878 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2879 if (SDValue NewC = DAG.FoldConstantArithmetic(
2880 IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2881 {ConstantOp, DAG.getConstant(1, DL, VT)})) {
2882 SDValue NewShift = DAG.getNode(IsAdd ? ISD::SRA : ISD::SRL, DL, VT,
2883 Not.getOperand(0), ShAmt);
2884 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2885 }
2886
2887 return SDValue();
2888}
2889
2890static bool
2892 return (isBitwiseNot(Op0) && Op0.getOperand(0) == Op1) ||
2893 (isBitwiseNot(Op1) && Op1.getOperand(0) == Op0);
2894}
2895
2896/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2897/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2898/// are no common bits set in the operands).
2899SDValue DAGCombiner::visitADDLike(SDNode *N) {
2900 SDValue N0 = N->getOperand(0);
2901 SDValue N1 = N->getOperand(1);
2902 EVT VT = N0.getValueType();
2903 SDLoc DL(N);
2904
2905 // fold (add x, undef) -> undef
2906 if (N0.isUndef())
2907 return N0;
2908 if (N1.isUndef())
2909 return N1;
2910
2911 // fold (add c1, c2) -> c1+c2
2912 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
2913 return C;
2914
2915 // canonicalize constant to RHS
2918 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2919
2920 if (areBitwiseNotOfEachother(N0, N1))
2921 return DAG.getConstant(APInt::getAllOnes(VT.getScalarSizeInBits()), DL, VT);
2922
2923 // fold vector ops
2924 if (VT.isVector()) {
2925 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
2926 return FoldedVOp;
2927
2928 // fold (add x, 0) -> x, vector edition
2930 return N0;
2931 }
2932
2933 // fold (add x, 0) -> x
2934 if (isNullConstant(N1))
2935 return N0;
2936
2937 if (N0.getOpcode() == ISD::SUB) {
2938 SDValue N00 = N0.getOperand(0);
2939 SDValue N01 = N0.getOperand(1);
2940
2941 // fold ((A-c1)+c2) -> (A+(c2-c1))
2942 if (SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N01}))
2943 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2944
2945 // fold ((c1-A)+c2) -> (c1+c2)-A
2946 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N00}))
2947 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2948 }
2949
2950 // add (sext i1 X), 1 -> zext (not i1 X)
2951 // We don't transform this pattern:
2952 // add (zext i1 X), -1 -> sext (not i1 X)
2953 // because most (?) targets generate better code for the zext form.
2954 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2955 isOneOrOneSplat(N1)) {
2956 SDValue X = N0.getOperand(0);
2957 if ((!LegalOperations ||
2958 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2960 X.getScalarValueSizeInBits() == 1) {
2961 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2962 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2963 }
2964 }
2965
2966 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1))
2967 // iff (or x, c0) is equivalent to (add x, c0).
2968 // Fold (add (xor x, c0), c1) -> (add x, (c0 + c1))
2969 // iff (xor x, c0) is equivalent to (add x, c0).
2970 if (DAG.isADDLike(N0)) {
2971 SDValue N01 = N0.getOperand(1);
2972 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N01}))
2973 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add);
2974 }
2975
2976 if (SDValue NewSel = foldBinOpIntoSelect(N))
2977 return NewSel;
2978
2979 // reassociate add
2980 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N, N0, N1)) {
2981 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2982 return RADD;
2983
2984 // (X + Y) + X --> Y + (X + X)
2985 SDValue X, Y, InnerAdd;
2986 if (sd_match(
2987 N, m_Add(m_OneUse(m_Value(InnerAdd, m_Add(m_Value(X), m_Value(Y)))),
2988 m_Deferred(X)))) {
2989 if (X != Y) {
2990 // Redistribute shared NUW flag.
2991 // TODO: If NSW+NUW occurs on both adds, that can be redistributed too.
2992 SDNodeFlags NewFlags =
2993 N->getFlags() & InnerAdd->getFlags() & SDNodeFlags::NoUnsignedWrap;
2994 SDValue X2 = DAG.getNode(ISD::ADD, DL, VT, X, X, NewFlags);
2995 return DAG.getNode(ISD::ADD, DL, VT, Y, X2, NewFlags);
2996 }
2997 }
2998
2999 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
3000 // equivalent to (add x, c).
3001 // Reassociate (add (xor x, c), y) -> (add add(x, y), c)) if (xor x, c) is
3002 // equivalent to (add x, c).
3003 // Do this optimization only when adding c does not introduce instructions
3004 // for adding carries.
3005 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
3006 if (DAG.isADDLike(N0) && N0.hasOneUse() &&
3007 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
3008 // If N0's type does not split or is a sign mask, it does not introduce
3009 // add carry.
3010 auto TyActn = TLI.getTypeAction(*DAG.getContext(), N0.getValueType());
3011 bool NoAddCarry = TyActn == TargetLoweringBase::TypeLegal ||
3014 if (NoAddCarry)
3015 return DAG.getNode(
3016 ISD::ADD, DL, VT,
3017 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
3018 N0.getOperand(1));
3019 }
3020 return SDValue();
3021 };
3022 if (SDValue Add = ReassociateAddOr(N0, N1))
3023 return Add;
3024 if (SDValue Add = ReassociateAddOr(N1, N0))
3025 return Add;
3026
3027 // Fold add(vecreduce(x), vecreduce(y)) -> vecreduce(add(x, y))
3028 if (SDValue SD =
3029 reassociateReduction(ISD::VECREDUCE_ADD, ISD::ADD, DL, VT, N0, N1))
3030 return SD;
3031 }
3032
3033 SDValue A, B, C, D;
3034
3035 // fold ((0-A) + B) -> B-A
3036 if (sd_match(N0, m_Neg(m_Value(A))))
3037 return DAG.getNode(ISD::SUB, DL, VT, N1, A);
3038
3039 // fold (A + (0-B)) -> A-B
3040 if (sd_match(N1, m_Neg(m_Value(B))))
3041 return DAG.getNode(ISD::SUB, DL, VT, N0, B);
3042
3043 // fold (A+(B-A)) -> B
3044 if (sd_match(N1, m_Sub(m_Value(B), m_Specific(N0))))
3045 return B;
3046
3047 // fold ((B-A)+A) -> B
3048 if (sd_match(N0, m_Sub(m_Value(B), m_Specific(N1))))
3049 return B;
3050
3051 // fold ((A-B)+(C-A)) -> (C-B)
3052 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3054 return DAG.getNode(ISD::SUB, DL, VT, C, B);
3055
3056 // fold ((A-B)+(B-C)) -> (A-C)
3057 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3059 return DAG.getNode(ISD::SUB, DL, VT, A, C);
3060
3061 // fold (A+(B-(A+C))) to (B-C)
3062 // fold (A+(B-(C+A))) to (B-C)
3063 if (sd_match(N1, m_Sub(m_Value(B), m_Add(m_Specific(N0), m_Value(C)))))
3064 return DAG.getNode(ISD::SUB, DL, VT, B, C);
3065
3066 // fold (A+((B-A)+or-C)) to (B+or-C)
3067 if (sd_match(N1,
3069 m_Sub(m_Sub(m_Value(B), m_Specific(N0)), m_Value(C)))))
3070 return DAG.getNode(N1.getOpcode(), DL, VT, B, C);
3071
3072 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
3073 if (sd_match(N0, m_OneUse(m_Sub(m_Value(A), m_Value(B)))) &&
3074 sd_match(N1, m_OneUse(m_Sub(m_Value(C), m_Value(D)))) &&
3076 return DAG.getNode(ISD::SUB, DL, VT,
3077 DAG.getNode(ISD::ADD, SDLoc(N0), VT, A, C),
3078 DAG.getNode(ISD::ADD, SDLoc(N1), VT, B, D));
3079
3080 // fold (add (umax X, C), -C) --> (usubsat X, C)
3081 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
3082 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
3083 return (!Max && !Op) ||
3084 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
3085 };
3086 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
3087 /*AllowUndefs*/ true))
3088 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
3089 N0.getOperand(1));
3090 }
3091
3093 return SDValue(N, 0);
3094
3095 if (isOneOrOneSplat(N1)) {
3096 // fold (add (xor a, -1), 1) -> (sub 0, a)
3097 if (isBitwiseNot(N0))
3098 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
3099 N0.getOperand(0));
3100
3101 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
3102 if (N0.getOpcode() == ISD::ADD) {
3103 SDValue A, Xor;
3104
3105 if (isBitwiseNot(N0.getOperand(0))) {
3106 A = N0.getOperand(1);
3107 Xor = N0.getOperand(0);
3108 } else if (isBitwiseNot(N0.getOperand(1))) {
3109 A = N0.getOperand(0);
3110 Xor = N0.getOperand(1);
3111 }
3112
3113 if (Xor)
3114 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
3115 }
3116
3117 // Look for:
3118 // add (add x, y), 1
3119 // And if the target does not like this form then turn into:
3120 // sub y, (xor x, -1)
3121 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3122 N0.hasOneUse() &&
3123 // Limit this to after legalization if the add has wrap flags
3124 (Level >= AfterLegalizeDAG || (!N->getFlags().hasNoUnsignedWrap() &&
3125 !N->getFlags().hasNoSignedWrap()))) {
3126 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3127 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
3128 }
3129 }
3130
3131 // (x - y) + -1 -> add (xor y, -1), x
3132 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
3133 isAllOnesOrAllOnesSplat(N1, /*AllowUndefs=*/true)) {
3134 SDValue Not = DAG.getNOT(DL, N0.getOperand(1), VT);
3135 return DAG.getNode(ISD::ADD, DL, VT, Not, N0.getOperand(0));
3136 }
3137
3138 // Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB).
3139 // This can help if the inner add has multiple uses.
3140 APInt CM, CA;
3141 if (ConstantSDNode *CB = dyn_cast<ConstantSDNode>(N1)) {
3142 if (VT.getScalarSizeInBits() <= 64) {
3144 m_ConstInt(CM)))) &&
3146 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3147 SDNodeFlags Flags;
3148 // If all the inputs are nuw, the outputs can be nuw. If all the input
3149 // are _also_ nsw the outputs can be too.
3150 if (N->getFlags().hasNoUnsignedWrap() &&
3151 N0->getFlags().hasNoUnsignedWrap() &&
3154 if (N->getFlags().hasNoSignedWrap() &&
3155 N0->getFlags().hasNoSignedWrap() &&
3158 }
3159 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3160 DAG.getConstant(CM, DL, VT), Flags);
3161 return DAG.getNode(
3162 ISD::ADD, DL, VT, Mul,
3163 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3164 }
3165 // Also look in case there is an intermediate add.
3166 if (sd_match(N0, m_OneUse(m_Add(
3168 m_ConstInt(CM))),
3169 m_Value(B)))) &&
3171 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3172 SDNodeFlags Flags;
3173 // If all the inputs are nuw, the outputs can be nuw. If all the input
3174 // are _also_ nsw the outputs can be too.
3175 SDValue OMul =
3176 N0.getOperand(0) == B ? N0.getOperand(1) : N0.getOperand(0);
3177 if (N->getFlags().hasNoUnsignedWrap() &&
3178 N0->getFlags().hasNoUnsignedWrap() &&
3179 OMul->getFlags().hasNoUnsignedWrap() &&
3180 OMul.getOperand(0)->getFlags().hasNoUnsignedWrap()) {
3182 if (N->getFlags().hasNoSignedWrap() &&
3183 N0->getFlags().hasNoSignedWrap() &&
3184 OMul->getFlags().hasNoSignedWrap() &&
3185 OMul.getOperand(0)->getFlags().hasNoSignedWrap())
3187 }
3188 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3189 DAG.getConstant(CM, DL, VT), Flags);
3190 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N1), VT, Mul, B, Flags);
3191 return DAG.getNode(
3192 ISD::ADD, DL, VT, Add,
3193 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3194 }
3195 }
3196 }
3197
3198 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
3199 return Combined;
3200
3201 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
3202 return Combined;
3203
3204 return SDValue();
3205}
3206
3207// Attempt to form avgfloor(A, B) from (A & B) + ((A ^ B) >> 1)
3208// Attempt to form avgfloor(A, B) from ((A >> 1) + (B >> 1)) + (A & B & 1)
3209// Attempt to form avgceil(A, B) from ((A >> 1) + (B >> 1)) + ((A | B) & 1)
3210SDValue DAGCombiner::foldAddToAvg(SDNode *N, const SDLoc &DL) {
3211 SDValue N0 = N->getOperand(0);
3212 EVT VT = N0.getValueType();
3213 SDValue A, B;
3214
3215 if ((!LegalOperations || hasOperation(ISD::AVGFLOORU, VT)) &&
3216 (sd_match(N,
3218 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3221 m_Srl(m_Deferred(A), m_One()),
3222 m_Srl(m_Deferred(B), m_One()))))) {
3223 return DAG.getNode(ISD::AVGFLOORU, DL, VT, A, B);
3224 }
3225 if ((!LegalOperations || hasOperation(ISD::AVGFLOORS, VT)) &&
3226 (sd_match(N,
3228 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3231 m_Sra(m_Deferred(A), m_One()),
3232 m_Sra(m_Deferred(B), m_One()))))) {
3233 return DAG.getNode(ISD::AVGFLOORS, DL, VT, A, B);
3234 }
3235
3236 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
3237 sd_match(N,
3239 m_Srl(m_Deferred(A), m_One()),
3240 m_Srl(m_Deferred(B), m_One())))) {
3241 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
3242 }
3243 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
3244 sd_match(N,
3246 m_Sra(m_Deferred(A), m_One()),
3247 m_Sra(m_Deferred(B), m_One())))) {
3248 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
3249 }
3250
3251 return SDValue();
3252}
3253
3254SDValue DAGCombiner::visitADD(SDNode *N) {
3255 SDValue N0 = N->getOperand(0);
3256 SDValue N1 = N->getOperand(1);
3257 EVT VT = N0.getValueType();
3258 SDLoc DL(N);
3259
3260 if (SDValue Combined = visitADDLike(N))
3261 return Combined;
3262
3263 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
3264 return V;
3265
3266 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
3267 return V;
3268
3269 if (SDValue V = MatchRotate(N0, N1, SDLoc(N), /*FromAdd=*/true))
3270 return V;
3271
3272 // Try to match AVGFLOOR fixedwidth pattern
3273 if (SDValue V = foldAddToAvg(N, DL))
3274 return V;
3275
3276 // fold (a+b) -> (a|b) iff a and b share no bits.
3277 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
3278 DAG.haveNoCommonBitsSet(N0, N1))
3279 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
3280
3281 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
3282 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
3283 const APInt &C0 = N0->getConstantOperandAPInt(0);
3284 const APInt &C1 = N1->getConstantOperandAPInt(0);
3285 return DAG.getVScale(DL, VT, C0 + C1);
3286 }
3287
3288 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
3289 if (N0.getOpcode() == ISD::ADD &&
3290 N0.getOperand(1).getOpcode() == ISD::VSCALE &&
3291 N1.getOpcode() == ISD::VSCALE) {
3292 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3293 const APInt &VS1 = N1->getConstantOperandAPInt(0);
3294 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
3295 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
3296 }
3297
3298 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
3299 if (N0.getOpcode() == ISD::STEP_VECTOR &&
3300 N1.getOpcode() == ISD::STEP_VECTOR) {
3301 const APInt &C0 = N0->getConstantOperandAPInt(0);
3302 const APInt &C1 = N1->getConstantOperandAPInt(0);
3303 APInt NewStep = C0 + C1;
3304 return DAG.getStepVector(DL, VT, NewStep);
3305 }
3306
3307 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
3308 if (N0.getOpcode() == ISD::ADD &&
3310 N1.getOpcode() == ISD::STEP_VECTOR) {
3311 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3312 const APInt &SV1 = N1->getConstantOperandAPInt(0);
3313 APInt NewStep = SV0 + SV1;
3314 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
3315 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
3316 }
3317
3318 return SDValue();
3319}
3320
3321SDValue DAGCombiner::visitADDSAT(SDNode *N) {
3322 unsigned Opcode = N->getOpcode();
3323 SDValue N0 = N->getOperand(0);
3324 SDValue N1 = N->getOperand(1);
3325 EVT VT = N0.getValueType();
3326 bool IsSigned = Opcode == ISD::SADDSAT;
3327 SDLoc DL(N);
3328
3329 // fold (add_sat x, undef) -> -1
3330 if (N0.isUndef() || N1.isUndef())
3331 return DAG.getAllOnesConstant(DL, VT);
3332
3333 // fold (add_sat c1, c2) -> c3
3334 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
3335 return C;
3336
3337 // canonicalize constant to RHS
3340 return DAG.getNode(Opcode, DL, VT, N1, N0);
3341
3342 // fold vector ops
3343 if (VT.isVector()) {
3344 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
3345 return FoldedVOp;
3346
3347 // fold (add_sat x, 0) -> x, vector edition
3349 return N0;
3350 }
3351
3352 // fold (add_sat x, 0) -> x
3353 if (isNullConstant(N1))
3354 return N0;
3355
3356 // If it cannot overflow, transform into an add.
3357 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3358 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
3359
3360 return SDValue();
3361}
3362
3364 bool ForceCarryReconstruction = false) {
3365 bool Masked = false;
3366
3367 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
3368 while (true) {
3369 if (ForceCarryReconstruction && V.getValueType() == MVT::i1)
3370 return V;
3371
3372 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
3373 V = V.getOperand(0);
3374 continue;
3375 }
3376
3377 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
3378 if (ForceCarryReconstruction)
3379 return V;
3380
3381 Masked = true;
3382 V = V.getOperand(0);
3383 continue;
3384 }
3385
3386 break;
3387 }
3388
3389 // If this is not a carry, return.
3390 if (V.getResNo() != 1)
3391 return SDValue();
3392
3393 if (V.getOpcode() != ISD::UADDO_CARRY && V.getOpcode() != ISD::USUBO_CARRY &&
3394 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
3395 return SDValue();
3396
3397 EVT VT = V->getValueType(0);
3398 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
3399 return SDValue();
3400
3401 // If the result is masked, then no matter what kind of bool it is we can
3402 // return. If it isn't, then we need to make sure the bool type is either 0 or
3403 // 1 and not other values.
3404 if (Masked ||
3405 TLI.getBooleanContents(V.getValueType()) ==
3407 return V;
3408
3409 return SDValue();
3410}
3411
3412/// Given the operands of an add/sub operation, see if the 2nd operand is a
3413/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
3414/// the opcode and bypass the mask operation.
3415static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
3416 SelectionDAG &DAG, const SDLoc &DL) {
3417 if (N1.getOpcode() == ISD::ZERO_EXTEND)
3418 N1 = N1.getOperand(0);
3419
3420 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
3421 return SDValue();
3422
3423 EVT VT = N0.getValueType();
3424 SDValue N10 = N1.getOperand(0);
3425 if (N10.getValueType() != VT && N10.getOpcode() == ISD::TRUNCATE)
3426 N10 = N10.getOperand(0);
3427
3428 if (N10.getValueType() != VT)
3429 return SDValue();
3430
3431 if (DAG.ComputeNumSignBits(N10) != VT.getScalarSizeInBits())
3432 return SDValue();
3433
3434 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
3435 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
3436 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N10);
3437}
3438
3439/// Helper for doing combines based on N0 and N1 being added to each other.
3440SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
3441 SDNode *LocReference) {
3442 EVT VT = N0.getValueType();
3443 SDLoc DL(LocReference);
3444
3445 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
3446 SDValue Y, N;
3447 if (sd_match(N1, m_Shl(m_Neg(m_Value(Y)), m_Value(N))))
3448 return DAG.getNode(ISD::SUB, DL, VT, N0,
3449 DAG.getNode(ISD::SHL, DL, VT, Y, N));
3450
3451 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
3452 return V;
3453
3454 // Look for:
3455 // add (add x, 1), y
3456 // And if the target does not like this form then turn into:
3457 // sub y, (xor x, -1)
3458 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3459 N0.hasOneUse() && isOneOrOneSplat(N0.getOperand(1)) &&
3460 // Limit this to after legalization if the add has wrap flags
3461 (Level >= AfterLegalizeDAG || (!N0->getFlags().hasNoUnsignedWrap() &&
3462 !N0->getFlags().hasNoSignedWrap()))) {
3463 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3464 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
3465 }
3466
3467 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse()) {
3468 // Hoist one-use subtraction by non-opaque constant:
3469 // (x - C) + y -> (x + y) - C
3470 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3471 if (isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3472 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
3473 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
3474 }
3475 // Hoist one-use subtraction from non-opaque constant:
3476 // (C - x) + y -> (y - x) + C
3477 if (isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3478 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
3479 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
3480 }
3481 }
3482
3483 // add (mul x, C), x -> mul x, C+1
3484 if (N0.getOpcode() == ISD::MUL && N0.getOperand(0) == N1 &&
3485 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true) &&
3486 N0.hasOneUse()) {
3487 SDValue NewC = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
3488 DAG.getConstant(1, DL, VT));
3489 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), NewC);
3490 }
3491
3492 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
3493 // rather than 'add 0/-1' (the zext should get folded).
3494 // add (sext i1 Y), X --> sub X, (zext i1 Y)
3495 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
3496 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
3498 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
3499 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
3500 }
3501
3502 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
3503 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3504 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3505 if (TN->getVT() == MVT::i1) {
3506 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3507 DAG.getConstant(1, DL, VT));
3508 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
3509 }
3510 }
3511
3512 // (add X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3513 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1)) &&
3514 N1.getResNo() == 0)
3515 return DAG.getNode(ISD::UADDO_CARRY, DL, N1->getVTList(),
3516 N0, N1.getOperand(0), N1.getOperand(2));
3517
3518 // (add X, Carry) -> (uaddo_carry X, 0, Carry)
3520 if (SDValue Carry = getAsCarry(TLI, N1))
3521 return DAG.getNode(ISD::UADDO_CARRY, DL,
3522 DAG.getVTList(VT, Carry.getValueType()), N0,
3523 DAG.getConstant(0, DL, VT), Carry);
3524
3525 return SDValue();
3526}
3527
3528SDValue DAGCombiner::visitADDC(SDNode *N) {
3529 SDValue N0 = N->getOperand(0);
3530 SDValue N1 = N->getOperand(1);
3531 EVT VT = N0.getValueType();
3532 SDLoc DL(N);
3533
3534 // If the flag result is dead, turn this into an ADD.
3535 if (!N->hasAnyUseOfValue(1))
3536 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3537 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3538
3539 // canonicalize constant to RHS.
3540 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3542 if (N0C && !N1C)
3543 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
3544
3545 // fold (addc x, 0) -> x + no carry out
3546 if (isNullConstant(N1))
3547 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
3548 DL, MVT::Glue));
3549
3550 // If it cannot overflow, transform into an add.
3552 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3553 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3554
3555 return SDValue();
3556}
3557
3558/**
3559 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
3560 * then the flip also occurs if computing the inverse is the same cost.
3561 * This function returns an empty SDValue in case it cannot flip the boolean
3562 * without increasing the cost of the computation. If you want to flip a boolean
3563 * no matter what, use DAG.getLogicalNOT.
3564 */
3566 const TargetLowering &TLI,
3567 bool Force) {
3568 if (Force && isa<ConstantSDNode>(V))
3569 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3570
3571 if (V.getOpcode() != ISD::XOR)
3572 return SDValue();
3573
3574 if (DAG.isBoolConstant(V.getOperand(1)) == true)
3575 return V.getOperand(0);
3576 if (Force && isConstOrConstSplat(V.getOperand(1), false))
3577 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3578 return SDValue();
3579}
3580
3581SDValue DAGCombiner::visitADDO(SDNode *N) {
3582 SDValue N0 = N->getOperand(0);
3583 SDValue N1 = N->getOperand(1);
3584 EVT VT = N0.getValueType();
3585 bool IsSigned = (ISD::SADDO == N->getOpcode());
3586
3587 EVT CarryVT = N->getValueType(1);
3588 SDLoc DL(N);
3589
3590 // If the flag result is dead, turn this into an ADD.
3591 if (!N->hasAnyUseOfValue(1))
3592 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3593 DAG.getUNDEF(CarryVT));
3594
3595 // canonicalize constant to RHS.
3598 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
3599
3600 // fold (addo x, 0) -> x + no carry out
3601 if (isNullOrNullSplat(N1))
3602 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3603
3604 // If it cannot overflow, transform into an add.
3605 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3606 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3607 DAG.getConstant(0, DL, CarryVT));
3608
3609 if (IsSigned) {
3610 // fold (saddo (xor a, -1), 1) -> (ssub 0, a).
3611 if (isBitwiseNot(N0) && isOneOrOneSplat(N1))
3612 return DAG.getNode(ISD::SSUBO, DL, N->getVTList(),
3613 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3614 } else {
3615 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
3616 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
3617 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
3618 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3619 return CombineTo(
3620 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3621 }
3622
3623 if (SDValue Combined = visitUADDOLike(N0, N1, N))
3624 return Combined;
3625
3626 if (SDValue Combined = visitUADDOLike(N1, N0, N))
3627 return Combined;
3628 }
3629
3630 return SDValue();
3631}
3632
3633SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
3634 EVT VT = N0.getValueType();
3635 if (VT.isVector())
3636 return SDValue();
3637
3638 // (uaddo X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3639 // If Y + 1 cannot overflow.
3640 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1))) {
3641 SDValue Y = N1.getOperand(0);
3642 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
3644 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0, Y,
3645 N1.getOperand(2));
3646 }
3647
3648 // (uaddo X, Carry) -> (uaddo_carry X, 0, Carry)
3650 if (SDValue Carry = getAsCarry(TLI, N1))
3651 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0,
3652 DAG.getConstant(0, SDLoc(N), VT), Carry);
3653
3654 return SDValue();
3655}
3656
3657SDValue DAGCombiner::visitADDE(SDNode *N) {
3658 SDValue N0 = N->getOperand(0);
3659 SDValue N1 = N->getOperand(1);
3660 SDValue CarryIn = N->getOperand(2);
3661
3662 // canonicalize constant to RHS
3663 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3664 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3665 if (N0C && !N1C)
3666 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
3667 N1, N0, CarryIn);
3668
3669 // fold (adde x, y, false) -> (addc x, y)
3670 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3671 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
3672
3673 return SDValue();
3674}
3675
3676SDValue DAGCombiner::visitUADDO_CARRY(SDNode *N) {
3677 SDValue N0 = N->getOperand(0);
3678 SDValue N1 = N->getOperand(1);
3679 SDValue CarryIn = N->getOperand(2);
3680 SDLoc DL(N);
3681
3682 // canonicalize constant to RHS
3683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685 if (N0C && !N1C)
3686 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
3687
3688 // fold (uaddo_carry x, y, false) -> (uaddo x, y)
3689 if (isNullConstant(CarryIn)) {
3690 if (!LegalOperations ||
3691 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
3692 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
3693 }
3694
3695 // fold (uaddo_carry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
3696 if (isNullConstant(N0) && isNullConstant(N1)) {
3697 EVT VT = N0.getValueType();
3698 EVT CarryVT = CarryIn.getValueType();
3699 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
3700 AddToWorklist(CarryExt.getNode());
3701 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
3702 DAG.getConstant(1, DL, VT)),
3703 DAG.getConstant(0, DL, CarryVT));
3704 }
3705
3706 if (SDValue Combined = visitUADDO_CARRYLike(N0, N1, CarryIn, N))
3707 return Combined;
3708
3709 if (SDValue Combined = visitUADDO_CARRYLike(N1, N0, CarryIn, N))
3710 return Combined;
3711
3712 // We want to avoid useless duplication.
3713 // TODO: This is done automatically for binary operations. As UADDO_CARRY is
3714 // not a binary operation, this is not really possible to leverage this
3715 // existing mechanism for it. However, if more operations require the same
3716 // deduplication logic, then it may be worth generalize.
3717 SDValue Ops[] = {N1, N0, CarryIn};
3718 SDNode *CSENode =
3719 DAG.getNodeIfExists(ISD::UADDO_CARRY, N->getVTList(), Ops, N->getFlags());
3720 if (CSENode)
3721 return SDValue(CSENode, 0);
3722
3723 return SDValue();
3724}
3725
3726/**
3727 * If we are facing some sort of diamond carry propagation pattern try to
3728 * break it up to generate something like:
3729 * (uaddo_carry X, 0, (uaddo_carry A, B, Z):Carry)
3730 *
3731 * The end result is usually an increase in operation required, but because the
3732 * carry is now linearized, other transforms can kick in and optimize the DAG.
3733 *
3734 * Patterns typically look something like
3735 * (uaddo A, B)
3736 * / \
3737 * Carry Sum
3738 * | \
3739 * | (uaddo_carry *, 0, Z)
3740 * | /
3741 * \ Carry
3742 * | /
3743 * (uaddo_carry X, *, *)
3744 *
3745 * But numerous variation exist. Our goal is to identify A, B, X and Z and
3746 * produce a combine with a single path for carry propagation.
3747 */
3749 SelectionDAG &DAG, SDValue X,
3750 SDValue Carry0, SDValue Carry1,
3751 SDNode *N) {
3752 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
3753 return SDValue();
3754 if (Carry1.getOpcode() != ISD::UADDO)
3755 return SDValue();
3756
3757 SDValue Z;
3758
3759 /**
3760 * First look for a suitable Z. It will present itself in the form of
3761 * (uaddo_carry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
3762 */
3763 if (Carry0.getOpcode() == ISD::UADDO_CARRY &&
3764 isNullConstant(Carry0.getOperand(1))) {
3765 Z = Carry0.getOperand(2);
3766 } else if (Carry0.getOpcode() == ISD::UADDO &&
3767 isOneConstant(Carry0.getOperand(1))) {
3768 EVT VT = Carry0->getValueType(1);
3769 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
3770 } else {
3771 // We couldn't find a suitable Z.
3772 return SDValue();
3773 }
3774
3775
3776 auto cancelDiamond = [&](SDValue A,SDValue B) {
3777 SDLoc DL(N);
3778 SDValue NewY =
3779 DAG.getNode(ISD::UADDO_CARRY, DL, Carry0->getVTList(), A, B, Z);
3780 Combiner.AddToWorklist(NewY.getNode());
3781 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), X,
3782 DAG.getConstant(0, DL, X.getValueType()),
3783 NewY.getValue(1));
3784 };
3785
3786 /**
3787 * (uaddo A, B)
3788 * |
3789 * Sum
3790 * |
3791 * (uaddo_carry *, 0, Z)
3792 */
3793 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3794 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3795 }
3796
3797 /**
3798 * (uaddo_carry A, 0, Z)
3799 * |
3800 * Sum
3801 * |
3802 * (uaddo *, B)
3803 */
3804 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3805 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3806 }
3807
3808 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3809 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3810 }
3811
3812 return SDValue();
3813}
3814
3815// If we are facing some sort of diamond carry/borrow in/out pattern try to
3816// match patterns like:
3817//
3818// (uaddo A, B) CarryIn
3819// | \ |
3820// | \ |
3821// PartialSum PartialCarryOutX /
3822// | | /
3823// | ____|____________/
3824// | / |
3825// (uaddo *, *) \________
3826// | \ \
3827// | \ |
3828// | PartialCarryOutY |
3829// | \ |
3830// | \ /
3831// AddCarrySum | ______/
3832// | /
3833// CarryOut = (or *, *)
3834//
3835// And generate UADDO_CARRY (or USUBO_CARRY) with two result values:
3836//
3837// {AddCarrySum, CarryOut} = (uaddo_carry A, B, CarryIn)
3838//
3839// Our goal is to identify A, B, and CarryIn and produce UADDO_CARRY/USUBO_CARRY
3840// with a single path for carry/borrow out propagation.
3842 SDValue N0, SDValue N1, SDNode *N) {
3843 SDValue Carry0 = getAsCarry(TLI, N0);
3844 if (!Carry0)
3845 return SDValue();
3846 SDValue Carry1 = getAsCarry(TLI, N1);
3847 if (!Carry1)
3848 return SDValue();
3849
3850 unsigned Opcode = Carry0.getOpcode();
3851 if (Opcode != Carry1.getOpcode())
3852 return SDValue();
3853 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3854 return SDValue();
3855 // Guarantee identical type of CarryOut
3856 EVT CarryOutType = N->getValueType(0);
3857 if (CarryOutType != Carry0.getValue(1).getValueType() ||
3858 CarryOutType != Carry1.getValue(1).getValueType())
3859 return SDValue();
3860
3861 // Canonicalize the add/sub of A and B (the top node in the above ASCII art)
3862 // as Carry0 and the add/sub of the carry in as Carry1 (the middle node).
3863 if (Carry1.getNode()->isOperandOf(Carry0.getNode()))
3864 std::swap(Carry0, Carry1);
3865
3866 // Check if nodes are connected in expected way.
3867 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3868 Carry1.getOperand(1) != Carry0.getValue(0))
3869 return SDValue();
3870
3871 // The carry in value must be on the righthand side for subtraction.
3872 unsigned CarryInOperandNum =
3873 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3874 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3875 return SDValue();
3876 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3877
3878 unsigned NewOp = Opcode == ISD::UADDO ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
3879 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3880 return SDValue();
3881
3882 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3883 CarryIn = getAsCarry(TLI, CarryIn, true);
3884 if (!CarryIn)
3885 return SDValue();
3886
3887 SDLoc DL(N);
3888 CarryIn = DAG.getBoolExtOrTrunc(CarryIn, DL, Carry1->getValueType(1),
3889 Carry1->getValueType(0));
3890 SDValue Merged =
3891 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3892 Carry0.getOperand(1), CarryIn);
3893
3894 // Please note that because we have proven that the result of the UADDO/USUBO
3895 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3896 // therefore prove that if the first UADDO/USUBO overflows, the second
3897 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3898 // maximum value.
3899 //
3900 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3901 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3902 //
3903 // This is important because it means that OR and XOR can be used to merge
3904 // carry flags; and that AND can return a constant zero.
3905 //
3906 // TODO: match other operations that can merge flags (ADD, etc)
3907 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3908 if (N->getOpcode() == ISD::AND)
3909 return DAG.getConstant(0, DL, CarryOutType);
3910 return Merged.getValue(1);
3911}
3912
3913// Reconstruct a subtract-with-borrow chain from its canonicalized icmp form:
3914// carry_out = or(icmp ult A, B, and(icmp eq A, B, carry_in))
3915// InstCombine folds usub.with.overflow chains into this, losing the
3916// USUBO_CARRY that lowers to sbb/sbcs.
3918 const TargetLowering &TLI) {
3919 SDValue A, B, CarryIn;
3924 m_Value(CarryIn)))))
3925 return SDValue();
3926
3927 EVT IntVT = A.getValueType();
3928 // Skip vectors: USUBO_CARRY on a vector type has no legalization path and
3929 // would crash.
3930 if (IntVT.isVector() || !TLI.isOperationLegalOrCustom(
3932 *DAG.getContext(), IntVT)))
3933 return SDValue();
3934
3935 SDLoc DL(N);
3936 SDVTList VTs = DAG.getVTList(IntVT, N->getValueType(0));
3937 return DAG.getNode(ISD::USUBO_CARRY, DL, VTs, A, B, CarryIn).getValue(1);
3938}
3939
3940SDValue DAGCombiner::visitUADDO_CARRYLike(SDValue N0, SDValue N1,
3941 SDValue CarryIn, SDNode *N) {
3942 // fold (uaddo_carry (xor a, -1), b, c) -> (usubo_carry b, a, !c) and flip
3943 // carry.
3944 if (isBitwiseNot(N0))
3945 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3946 SDLoc DL(N);
3947 SDValue Sub = DAG.getNode(ISD::USUBO_CARRY, DL, N->getVTList(), N1,
3948 N0.getOperand(0), NotC);
3949 return CombineTo(
3950 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3951 }
3952
3953 // Iff the flag result is dead:
3954 // (uaddo_carry (add|uaddo X, Y), 0, Carry) -> (uaddo_carry X, Y, Carry)
3955 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3956 // or the dependency between the instructions.
3957 if ((N0.getOpcode() == ISD::ADD ||
3958 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3959 N0.getValue(1) != CarryIn)) &&
3960 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3961 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(),
3962 N0.getOperand(0), N0.getOperand(1), CarryIn);
3963
3964 /**
3965 * When one of the uaddo_carry argument is itself a carry, we may be facing
3966 * a diamond carry propagation. In which case we try to transform the DAG
3967 * to ensure linear carry propagation if that is possible.
3968 */
3969 if (auto Y = getAsCarry(TLI, N1)) {
3970 // Because both are carries, Y and Z can be swapped.
3971 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
3972 return R;
3973 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
3974 return R;
3975 }
3976
3977 return SDValue();
3978}
3979
3980SDValue DAGCombiner::visitSADDO_CARRYLike(SDValue N0, SDValue N1,
3981 SDValue CarryIn, SDNode *N) {
3982 // fold (saddo_carry (xor a, -1), b, c) -> (ssubo_carry b, a, !c)
3983 if (isBitwiseNot(N0)) {
3984 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true))
3985 return DAG.getNode(ISD::SSUBO_CARRY, SDLoc(N), N->getVTList(), N1,
3986 N0.getOperand(0), NotC);
3987 }
3988
3989 return SDValue();
3990}
3991
3992SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
3993 SDValue N0 = N->getOperand(0);
3994 SDValue N1 = N->getOperand(1);
3995 SDValue CarryIn = N->getOperand(2);
3996 SDLoc DL(N);
3997
3998 // canonicalize constant to RHS
3999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4000 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4001 if (N0C && !N1C)
4002 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
4003
4004 // fold (saddo_carry x, y, false) -> (saddo x, y)
4005 if (isNullConstant(CarryIn)) {
4006 if (!LegalOperations ||
4007 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
4008 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
4009 }
4010
4011 if (SDValue Combined = visitSADDO_CARRYLike(N0, N1, CarryIn, N))
4012 return Combined;
4013
4014 if (SDValue Combined = visitSADDO_CARRYLike(N1, N0, CarryIn, N))
4015 return Combined;
4016
4017 return SDValue();
4018}
4019
4020// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
4021// clamp/truncation if necessary.
4023 SDValue RHS, SelectionDAG &DAG,
4024 const SDLoc &DL) {
4025 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
4026 "Illegal truncation");
4027
4028 if (DstVT == SrcVT)
4029 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4030
4031 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
4032 // clamping RHS.
4034 DstVT.getScalarSizeInBits());
4035 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
4036 return SDValue();
4037
4038 SDValue SatLimit =
4040 DstVT.getScalarSizeInBits()),
4041 DL, SrcVT);
4042 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
4043 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
4044 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
4045 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4046}
4047
4048// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
4049// usubsat(a,b), optionally as a truncated type.
4050SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL) {
4051 if (N->getOpcode() != ISD::SUB ||
4052 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
4053 return SDValue();
4054
4055 EVT SubVT = N->getValueType(0);
4056 SDValue Op0 = N->getOperand(0);
4057 SDValue Op1 = N->getOperand(1);
4058
4059 // Try to find umax(a,b) - b or a - umin(a,b) patterns
4060 // they may be converted to usubsat(a,b).
4061 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4062 SDValue MaxLHS = Op0.getOperand(0);
4063 SDValue MaxRHS = Op0.getOperand(1);
4064 if (MaxLHS == Op1)
4065 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, DL);
4066 if (MaxRHS == Op1)
4067 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, DL);
4068 }
4069
4070 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
4071 SDValue MinLHS = Op1.getOperand(0);
4072 SDValue MinRHS = Op1.getOperand(1);
4073 if (MinLHS == Op0)
4074 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, DL);
4075 if (MinRHS == Op0)
4076 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, DL);
4077 }
4078
4079 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
4080 if (Op1.getOpcode() == ISD::TRUNCATE &&
4081 Op1.getOperand(0).getOpcode() == ISD::UMIN &&
4082 Op1.getOperand(0).hasOneUse()) {
4083 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
4084 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
4085 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
4086 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
4087 DAG, DL);
4088 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
4089 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
4090 DAG, DL);
4091 }
4092
4093 return SDValue();
4094}
4095
4096// Refinement of DAG/Type Legalisation (promotion) when CTLZ is used for
4097// counting leading ones. Broadly, it replaces the substraction with a left
4098// shift.
4099//
4100// * DAG Legalisation Pattern:
4101//
4102// (sub (ctlz (zeroextend (not Src)))
4103// BitWidthDiff)
4104//
4105// if BitWidthDiff == BitWidth(Node) - BitWidth(Src)
4106// -->
4107//
4108// (ctlz_zero_poison (not (shl (anyextend Src)
4109// BitWidthDiff)))
4110//
4111// * Type Legalisation Pattern:
4112//
4113// (sub (ctlz (and (xor Src XorMask)
4114// AndMask))
4115// BitWidthDiff)
4116//
4117// if AndMask has only trailing ones
4118// and MaskBitWidth(AndMask) == BitWidth(Node) - BitWidthDiff
4119// and XorMask has more trailing ones than AndMask
4120// -->
4121//
4122// (ctlz_zero_poison (not (shl Src BitWidthDiff)))
4123template <class MatchContextClass>
4125 const SDLoc DL(N);
4126 SDValue N0 = N->getOperand(0);
4127 EVT VT = N0.getValueType();
4128 unsigned BitWidth = VT.getScalarSizeInBits();
4129
4130 MatchContextClass Matcher(DAG, DAG.getTargetLoweringInfo(), N);
4131
4132 APInt AndMask;
4133 APInt XorMask;
4134 uint64_t BitWidthDiff;
4135
4136 SDValue CtlzOp;
4137 SDValue Src;
4138
4139 if (!sd_context_match(
4140 N, Matcher, m_Sub(m_Ctlz(m_Value(CtlzOp)), m_ConstInt(BitWidthDiff))))
4141 return SDValue();
4142
4143 if (sd_context_match(CtlzOp, Matcher, m_ZExt(m_Not(m_Value(Src))))) {
4144 // DAG Legalisation Pattern:
4145 // (sub (ctlz (zero_extend (not Op)) BitWidthDiff))
4146 if ((BitWidth - Src.getValueType().getScalarSizeInBits()) != BitWidthDiff)
4147 return SDValue();
4148
4149 Src = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Src);
4150 } else if (sd_context_match(CtlzOp, Matcher,
4151 m_And(m_Xor(m_Value(Src), m_ConstInt(XorMask)),
4152 m_ConstInt(AndMask)))) {
4153 // Type Legalisation Pattern:
4154 // (sub (ctlz (and (xor Op XorMask) AndMask)) BitWidthDiff)
4155 if (BitWidthDiff >= BitWidth)
4156 return SDValue();
4157 unsigned AndMaskWidth = BitWidth - BitWidthDiff;
4158 if (!(AndMask.isMask(AndMaskWidth) && XorMask.countr_one() >= AndMaskWidth))
4159 return SDValue();
4160 } else
4161 return SDValue();
4162
4163 SDValue ShiftConst = DAG.getShiftAmountConstant(BitWidthDiff, VT, DL);
4164 SDValue LShift = Matcher.getNode(ISD::SHL, DL, VT, Src, ShiftConst);
4165 SDValue Not =
4166 Matcher.getNode(ISD::XOR, DL, VT, LShift, DAG.getAllOnesConstant(DL, VT));
4167
4168 return Matcher.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, Not);
4169}
4170
4171// Fold sub(x, mul(divrem(x,y)[0], y)) to divrem(x, y)[1]
4173 const SDLoc &DL) {
4174 assert(N->getOpcode() == ISD::SUB && "Node must be a SUB");
4175 SDValue Sub0 = N->getOperand(0);
4176 SDValue Sub1 = N->getOperand(1);
4177
4178 auto CheckAndFoldMulCase = [&](SDValue DivRem, SDValue MaybeY) -> SDValue {
4179 if ((DivRem.getOpcode() == ISD::SDIVREM ||
4180 DivRem.getOpcode() == ISD::UDIVREM) &&
4181 DivRem.getResNo() == 0 && DivRem.getOperand(0) == Sub0 &&
4182 DivRem.getOperand(1) == MaybeY) {
4183 return SDValue(DivRem.getNode(), 1);
4184 }
4185 return SDValue();
4186 };
4187
4188 if (Sub1.getOpcode() == ISD::MUL) {
4189 // (sub x, (mul divrem(x,y)[0], y))
4190 SDValue Mul0 = Sub1.getOperand(0);
4191 SDValue Mul1 = Sub1.getOperand(1);
4192
4193 if (SDValue Res = CheckAndFoldMulCase(Mul0, Mul1))
4194 return Res;
4195
4196 if (SDValue Res = CheckAndFoldMulCase(Mul1, Mul0))
4197 return Res;
4198
4199 } else if (Sub1.getOpcode() == ISD::SHL) {
4200 // Handle (sub x, (shl divrem(x,y)[0], C)) where y = 1 << C
4201 SDValue Shl0 = Sub1.getOperand(0);
4202 SDValue Shl1 = Sub1.getOperand(1);
4203 // Check if Shl0 is divrem(x, Y)[0]
4204 if ((Shl0.getOpcode() == ISD::SDIVREM ||
4205 Shl0.getOpcode() == ISD::UDIVREM) &&
4206 Shl0.getResNo() == 0 && Shl0.getOperand(0) == Sub0) {
4207
4208 SDValue Divisor = Shl0.getOperand(1);
4209
4210 ConstantSDNode *DivC = isConstOrConstSplat(Divisor);
4212 if (!DivC || !ShC)
4213 return SDValue();
4214
4215 if (DivC->getAPIntValue().isPowerOf2() &&
4216 DivC->getAPIntValue().logBase2() == ShC->getAPIntValue())
4217 return SDValue(Shl0.getNode(), 1);
4218 }
4219 }
4220 return SDValue();
4221}
4222
4223// Since it may not be valid to emit a fold to zero for vector initializers
4224// check if we can before folding.
4225static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
4226 SelectionDAG &DAG, bool LegalOperations) {
4227 if (!VT.isVector())
4228 return DAG.getConstant(0, DL, VT);
4229 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
4230 return DAG.getConstant(0, DL, VT);
4231 return SDValue();
4232}
4233
4234SDValue DAGCombiner::visitSUB(SDNode *N) {
4235 SDValue N0 = N->getOperand(0);
4236 SDValue N1 = N->getOperand(1);
4237 EVT VT = N0.getValueType();
4238 unsigned BitWidth = VT.getScalarSizeInBits();
4239 SDLoc DL(N);
4240
4242 return V;
4243
4244 // fold (sub x, x) -> 0
4245 if (N0 == N1)
4246 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4247
4248 // fold (sub c1, c2) -> c3
4249 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
4250 return C;
4251
4252 // fold vector ops
4253 if (VT.isVector()) {
4254 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4255 return FoldedVOp;
4256
4257 // fold (sub x, 0) -> x, vector edition
4259 return N0;
4260 }
4261
4262 // (sub x, ([v]select (ult x, y), 0, y)) -> (umin x, (sub x, y))
4263 // (sub x, ([v]select (uge x, y), y, 0)) -> (umin x, (sub x, y))
4264 if (N1.hasOneUse() && hasUMin(VT)) {
4265 SDValue Y;
4266 auto MS0 = m_Specific(N0);
4267 auto MVY = m_Value(Y);
4268 auto MZ = m_Zero();
4269 auto MCC1 = m_SpecificCondCode(ISD::SETULT);
4270 auto MCC2 = m_SpecificCondCode(ISD::SETUGE);
4271
4272 if (sd_match(N1, m_SelectCCLike(MS0, MVY, MZ, m_Deferred(Y), MCC1)) ||
4273 sd_match(N1, m_SelectCCLike(MS0, MVY, m_Deferred(Y), MZ, MCC2)) ||
4274 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC1), MZ, m_Deferred(Y))) ||
4275 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC2), m_Deferred(Y), MZ)))
4276
4277 return DAG.getNode(ISD::UMIN, DL, VT, N0,
4278 DAG.getNode(ISD::SUB, DL, VT, N0, Y));
4279 }
4280
4281 if (SDValue NewSel = foldBinOpIntoSelect(N))
4282 return NewSel;
4283
4284 // fold (sub x, c) -> (add x, -c)
4285 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4286 return DAG.getNode(ISD::ADD, DL, VT, N0,
4287 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4288
4289 if (isNullOrNullSplat(N0)) {
4290 // Right-shifting everything out but the sign bit followed by negation is
4291 // the same as flipping arithmetic/logical shift type without the negation:
4292 // -(X >>u 31) -> (X >>s 31)
4293 // -(X >>s 31) -> (X >>u 31)
4294 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
4295 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
4296 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
4297 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
4298 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
4299 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
4300 }
4301 }
4302
4303 // 0 - X --> 0 if the sub is NUW.
4304 if (N->getFlags().hasNoUnsignedWrap())
4305 return N0;
4306
4308 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
4309 // N1 must be 0 because negating the minimum signed value is undefined.
4310 if (N->getFlags().hasNoSignedWrap())
4311 return N0;
4312
4313 // 0 - X --> X if X is 0 or the minimum signed value.
4314 return N1;
4315 }
4316
4317 // Convert 0 - abs(x).
4318 if (ISD::isAbsOpcode(N1.getOpcode()) && N1.hasOneUse() &&
4319 !TLI.isOperationLegalOrCustom(N1.getOpcode(), VT))
4320 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
4321 return Result;
4322
4323 // Similar to the previous rule, but this time targeting an expanded abs.
4324 // (sub 0, (max X, (sub 0, X))) --> (min X, (sub 0, X))
4325 // as well as
4326 // (sub 0, (min X, (sub 0, X))) --> (max X, (sub 0, X))
4327 // Note that these two are applicable to both signed and unsigned min/max.
4328 SDValue X;
4329 SDValue S0;
4330 auto NegPat = m_AllOf(m_Neg(m_Deferred(X)), m_Value(S0));
4331 if (sd_match(N1, m_OneUse(m_AnyOf(m_SMax(m_Value(X), NegPat),
4332 m_UMax(m_Value(X), NegPat),
4333 m_SMin(m_Value(X), NegPat),
4334 m_UMin(m_Value(X), NegPat))))) {
4335 unsigned NewOpc = ISD::getInverseMinMaxOpcode(N1->getOpcode());
4336 if (hasOperation(NewOpc, VT))
4337 return DAG.getNode(NewOpc, DL, VT, X, S0);
4338 }
4339
4340 // Fold neg(splat(neg(x)) -> splat(x)
4341 if (VT.isVector()) {
4342 SDValue N1S = DAG.getSplatValue(N1, true);
4343 if (N1S && N1S.getOpcode() == ISD::SUB &&
4344 isNullConstant(N1S.getOperand(0)))
4345 return DAG.getSplat(VT, DL, N1S.getOperand(1));
4346 }
4347
4348 // sub 0, (and x, 1) --> SIGN_EXTEND_INREG x, i1
4349 if (N1.getOpcode() == ISD::AND && N1.hasOneUse() &&
4350 isOneOrOneSplat(N1->getOperand(1))) {
4351 EVT ExtVT = VT.changeElementType(*DAG.getContext(), MVT::i1);
4354 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N1->getOperand(0),
4355 DAG.getValueType(ExtVT));
4356 }
4357 }
4358 }
4359
4360 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
4362 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4363
4364 // fold (A - (0-B)) -> A+B
4365 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
4366 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
4367
4368 // fold A-(A-B) -> B
4369 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
4370 return N1.getOperand(1);
4371
4372 // fold (A+B)-A -> B
4373 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
4374 return N0.getOperand(1);
4375
4376 // fold (A+B)-B -> A
4377 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
4378 return N0.getOperand(0);
4379
4380 // fold (A+C1)-C2 -> A+(C1-C2)
4381 if (N0.getOpcode() == ISD::ADD) {
4382 SDValue N01 = N0.getOperand(1);
4383 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N01, N1}))
4384 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
4385 }
4386
4387 // fold C2-(A+C1) -> (C2-C1)-A
4388 if (N1.getOpcode() == ISD::ADD) {
4389 SDValue N11 = N1.getOperand(1);
4390 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}))
4391 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
4392 }
4393
4394 // fold (A-C1)-C2 -> A-(C1+C2)
4395 if (N0.getOpcode() == ISD::SUB) {
4396 SDValue N01 = N0.getOperand(1);
4397 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N01, N1}))
4398 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
4399 }
4400
4401 // fold (c1-A)-c2 -> (c1-c2)-A
4402 if (N0.getOpcode() == ISD::SUB) {
4403 SDValue N00 = N0.getOperand(0);
4404 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N00, N1}))
4405 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
4406 }
4407
4408 SDValue A, B, C;
4409
4410 // fold ((A+(B+C))-B) -> A+C
4411 if (sd_match(N0, m_Add(m_Value(A), m_Add(m_Specific(N1), m_Value(C)))))
4412 return DAG.getNode(ISD::ADD, DL, VT, A, C);
4413
4414 // fold ((A+(B-C))-B) -> A-C
4415 if (sd_match(N0, m_Add(m_Value(A), m_Sub(m_Specific(N1), m_Value(C)))))
4416 return DAG.getNode(ISD::SUB, DL, VT, A, C);
4417
4418 // fold ((A-(B-C))-C) -> A-B
4419 if (sd_match(N0, m_Sub(m_Value(A), m_Sub(m_Value(B), m_Specific(N1)))))
4420 return DAG.getNode(ISD::SUB, DL, VT, A, B);
4421
4422 // fold (A-(B-C)) -> A+(C-B)
4423 if (sd_match(N1, m_OneUse(m_Sub(m_Value(B), m_Value(C)))))
4424 return DAG.getNode(ISD::ADD, DL, VT, N0,
4425 DAG.getNode(ISD::SUB, DL, VT, C, B));
4426
4427 // A - (A & B) -> A & (~B)
4428 if (sd_match(N1, m_And(m_Specific(N0), m_Value(B))) &&
4429 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true)))
4430 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getNOT(DL, B, VT));
4431
4432 // fold (A - (-B * C)) -> (A + (B * C))
4433 if (sd_match(N1, m_OneUse(m_Mul(m_Neg(m_Value(B)), m_Value(C)))))
4434 return DAG.getNode(ISD::ADD, DL, VT, N0,
4435 DAG.getNode(ISD::MUL, DL, VT, B, C));
4436
4437 // If either operand of a sub is undef, the result is undef
4438 if (N0.isUndef())
4439 return N0;
4440 if (N1.isUndef())
4441 return N1;
4442
4443 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
4444 return V;
4445
4446 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
4447 return V;
4448
4449 // Try to match AVGCEIL fixedwidth pattern
4450 if (SDValue V = foldSubToAvg(N, DL))
4451 return V;
4452
4453 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, DL))
4454 return V;
4455
4456 if (SDValue V = foldSubToUSubSat(VT, N, DL))
4457 return V;
4458
4459 if (SDValue V = foldRemainderIdiom(N, DAG, DL))
4460 return V;
4461
4462 // (A - B) - 1 -> add (xor B, -1), A
4464 m_One(/*AllowUndefs=*/true))))
4465 return DAG.getNode(ISD::ADD, DL, VT, A, DAG.getNOT(DL, B, VT));
4466
4467 // Look for:
4468 // sub y, (xor x, -1)
4469 // And if the target does not like this form then turn into:
4470 // add (add x, y), 1
4471 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
4472 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
4473 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
4474 }
4475
4476 // Hoist one-use addition by non-opaque constant:
4477 // (x + C) - y -> (x - y) + C
4478 if (!reassociationCanBreakAddressingModePattern(ISD::SUB, DL, N, N0, N1) &&
4479 N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
4480 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4481 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4482 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
4483 }
4484 // y - (x + C) -> (y - x) - C
4485 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse() &&
4486 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
4487 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
4488 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
4489 }
4490 // (x - C) - y -> (x - y) - C
4491 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
4492 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4493 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4494 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4495 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
4496 }
4497 // (C - x) - y -> C - (x + y)
4498 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4499 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
4500 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
4501 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
4502 }
4503
4504 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
4505 // rather than 'sub 0/1' (the sext should get folded).
4506 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
4507 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
4508 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
4509 TLI.getBooleanContents(VT) ==
4511 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
4512 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
4513 }
4514
4515 // fold B = sra (A, size(A)-1); sub (xor (A, B), B) -> (abs A)
4516 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
4518 sd_match(N0, m_Xor(m_Specific(A), m_Specific(N1))))
4519 return DAG.getNode(ISD::ABS, DL, VT, A);
4520
4521 // If the relocation model supports it, consider symbol offsets.
4522 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
4523 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
4524 // fold (sub Sym+c1, Sym+c2) -> c1-c2
4525 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
4526 if (GA->getGlobal() == GB->getGlobal())
4527 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
4528 DL, VT);
4529 }
4530
4531 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
4532 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
4533 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
4534 if (TN->getVT() == MVT::i1) {
4535 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
4536 DAG.getConstant(1, DL, VT));
4537 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
4538 }
4539 }
4540
4541 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
4542 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
4543 if (N1.getOpcode() == ISD::VSCALE && N1.hasOneUse()) {
4544 const APInt &IntVal = N1.getConstantOperandAPInt(0);
4545 if (!IntVal.isPowerOf2() ||
4546 hasOperation(ISD::MUL, N1.getOperand(0).getValueType()))
4547 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
4548 }
4549
4550 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
4551 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
4552 APInt NewStep = -N1.getConstantOperandAPInt(0);
4553 return DAG.getNode(ISD::ADD, DL, VT, N0,
4554 DAG.getStepVector(DL, VT, NewStep));
4555 }
4556
4557 // Prefer an add for more folding potential and possibly better codegen:
4558 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
4559 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
4560 SDValue ShAmt = N1.getOperand(1);
4561 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
4562 if (ShAmtC && ShAmtC->getAPIntValue() == (BitWidth - 1)) {
4563 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
4564 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
4565 }
4566 }
4567
4568 // As with the previous fold, prefer add for more folding potential.
4569 // Subtracting SMIN/0 is the same as adding SMIN/0:
4570 // N0 - (X << BW-1) --> N0 + (X << BW-1)
4571 if (N1.getOpcode() == ISD::SHL) {
4572 ConstantSDNode *ShlC = isConstOrConstSplat(N1.getOperand(1));
4573 if (ShlC && ShlC->getAPIntValue() == (BitWidth - 1))
4574 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
4575 }
4576
4577 // (sub (usubo_carry X, 0, Carry), Y) -> (usubo_carry X, Y, Carry)
4578 if (N0.getOpcode() == ISD::USUBO_CARRY && isNullConstant(N0.getOperand(1)) &&
4579 N0.getResNo() == 0 && N0.hasOneUse())
4580 return DAG.getNode(ISD::USUBO_CARRY, DL, N0->getVTList(),
4581 N0.getOperand(0), N1, N0.getOperand(2));
4582
4584 // (sub Carry, X) -> (uaddo_carry (sub 0, X), 0, Carry)
4585 if (SDValue Carry = getAsCarry(TLI, N0)) {
4586 SDValue X = N1;
4587 SDValue Zero = DAG.getConstant(0, DL, VT);
4588 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
4589 return DAG.getNode(ISD::UADDO_CARRY, DL,
4590 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
4591 Carry);
4592 }
4593 }
4594
4595 if (ConstantSDNode *C0 = isConstOrConstSplat(N0)) {
4596 const APInt &C0Val = C0->getAPIntValue();
4597
4598 // sub nuw C, x --> xor x, C when C is a mask (2^k - 1)
4599 if (N->getFlags().hasNoUnsignedWrap() && C0Val.isMask())
4600 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4601
4602 // If there's no chance of borrowing from adjacent bits, then sub is xor:
4603 // sub C0, X --> xor X, C0
4604 if (!C0->isOpaque()) {
4605 const APInt &MaybeOnes = ~DAG.computeKnownBits(N1).Zero;
4606 if ((C0Val - MaybeOnes) == (C0Val ^ MaybeOnes))
4607 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4608 }
4609 }
4610
4611 // smax(a,b) - smin(a,b) --> abds(a,b)
4612 if ((!LegalOperations || hasOperation(ISD::ABDS, VT)) &&
4613 sd_match(N0, &DAG, m_SMaxLike(m_Value(A), m_Value(B))) &&
4614 sd_match(N1, &DAG, m_SMinLike(m_Specific(A), m_Specific(B))))
4615 return DAG.getNode(ISD::ABDS, DL, VT, A, B);
4616
4617 // smin(a,b) - smax(a,b) --> neg(abds(a,b))
4618 if (hasOperation(ISD::ABDS, VT) &&
4619 sd_match(N0, &DAG, m_SMinLike(m_Value(A), m_Value(B))) &&
4620 sd_match(N1, &DAG, m_SMaxLike(m_Specific(A), m_Specific(B))))
4621 return DAG.getNegative(DAG.getNode(ISD::ABDS, DL, VT, A, B), DL, VT);
4622
4623 // umax(a,b) - umin(a,b) --> abdu(a,b)
4624 if ((!LegalOperations || hasOperation(ISD::ABDU, VT)) &&
4625 sd_match(N0, &DAG, m_UMaxLike(m_Value(A), m_Value(B))) &&
4626 sd_match(N1, &DAG, m_UMinLike(m_Specific(A), m_Specific(B))))
4627 return DAG.getNode(ISD::ABDU, DL, VT, A, B);
4628
4629 // umin(a,b) - umax(a,b) --> neg(abdu(a,b))
4630 if (hasOperation(ISD::ABDU, VT) &&
4631 sd_match(N0, &DAG, m_UMinLike(m_Value(A), m_Value(B))) &&
4632 sd_match(N1, &DAG, m_UMaxLike(m_Specific(A), m_Specific(B))))
4633 return DAG.getNegative(DAG.getNode(ISD::ABDU, DL, VT, A, B), DL, VT);
4634
4635 return SDValue();
4636}
4637
4638SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
4639 unsigned Opcode = N->getOpcode();
4640 SDValue N0 = N->getOperand(0);
4641 SDValue N1 = N->getOperand(1);
4642 EVT VT = N0.getValueType();
4643 bool IsSigned = Opcode == ISD::SSUBSAT;
4644 SDLoc DL(N);
4645
4646 // fold (sub_sat x, undef) -> 0
4647 if (N0.isUndef() || N1.isUndef())
4648 return DAG.getConstant(0, DL, VT);
4649
4650 // fold (sub_sat x, x) -> 0
4651 if (N0 == N1)
4652 return DAG.getConstant(0, DL, VT);
4653
4654 // fold (sub_sat c1, c2) -> c3
4655 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4656 return C;
4657
4658 // fold vector ops
4659 if (VT.isVector()) {
4660 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4661 return FoldedVOp;
4662
4663 // fold (sub_sat x, 0) -> x, vector edition
4665 return N0;
4666 }
4667
4668 // fold (sub_sat x, 0) -> x
4669 if (isNullConstant(N1))
4670 return N0;
4671
4672 // If it cannot overflow, transform into an sub.
4673 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4674 return DAG.getNode(ISD::SUB, DL, VT, N0, N1);
4675
4676 return SDValue();
4677}
4678
4679SDValue DAGCombiner::visitSUBC(SDNode *N) {
4680 SDValue N0 = N->getOperand(0);
4681 SDValue N1 = N->getOperand(1);
4682 EVT VT = N0.getValueType();
4683 SDLoc DL(N);
4684
4685 // If the flag result is dead, turn this into an SUB.
4686 if (!N->hasAnyUseOfValue(1))
4687 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4688 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4689
4690 // fold (subc x, x) -> 0 + no borrow
4691 if (N0 == N1)
4692 return CombineTo(N, DAG.getConstant(0, DL, VT),
4693 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4694
4695 // fold (subc x, 0) -> x + no borrow
4696 if (isNullConstant(N1))
4697 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4698
4699 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4700 if (isAllOnesConstant(N0))
4701 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4702 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4703
4704 return SDValue();
4705}
4706
4707SDValue DAGCombiner::visitSUBO(SDNode *N) {
4708 SDValue N0 = N->getOperand(0);
4709 SDValue N1 = N->getOperand(1);
4710 EVT VT = N0.getValueType();
4711 bool IsSigned = (ISD::SSUBO == N->getOpcode());
4712
4713 EVT CarryVT = N->getValueType(1);
4714 SDLoc DL(N);
4715
4716 // If the flag result is dead, turn this into an SUB.
4717 if (!N->hasAnyUseOfValue(1))
4718 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4719 DAG.getUNDEF(CarryVT));
4720
4721 // fold (subo x, x) -> 0 + no borrow
4722 if (N0 == N1)
4723 return CombineTo(N, DAG.getConstant(0, DL, VT),
4724 DAG.getConstant(0, DL, CarryVT));
4725
4726 // fold (subox, c) -> (addo x, -c)
4727 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4728 if (IsSigned && !N1C->isMinSignedValue())
4729 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
4730 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4731
4732 // fold (subo x, 0) -> x + no borrow
4733 if (isNullOrNullSplat(N1))
4734 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
4735
4736 // If it cannot overflow, transform into an sub.
4737 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4738 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4739 DAG.getConstant(0, DL, CarryVT));
4740
4741 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4742 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
4743 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4744 DAG.getConstant(0, DL, CarryVT));
4745
4746 return SDValue();
4747}
4748
4749SDValue DAGCombiner::visitSUBE(SDNode *N) {
4750 SDValue N0 = N->getOperand(0);
4751 SDValue N1 = N->getOperand(1);
4752 SDValue CarryIn = N->getOperand(2);
4753
4754 // fold (sube x, y, false) -> (subc x, y)
4755 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
4756 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
4757
4758 return SDValue();
4759}
4760
4761SDValue DAGCombiner::visitUSUBO_CARRY(SDNode *N) {
4762 SDValue N0 = N->getOperand(0);
4763 SDValue N1 = N->getOperand(1);
4764 SDValue CarryIn = N->getOperand(2);
4765
4766 // fold (usubo_carry x, y, false) -> (usubo x, y)
4767 if (isNullConstant(CarryIn)) {
4768 if (!LegalOperations ||
4769 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
4770 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
4771 }
4772
4773 return SDValue();
4774}
4775
4776SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
4777 SDValue N0 = N->getOperand(0);
4778 SDValue N1 = N->getOperand(1);
4779 SDValue CarryIn = N->getOperand(2);
4780
4781 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
4782 if (isNullConstant(CarryIn)) {
4783 if (!LegalOperations ||
4784 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
4785 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
4786 }
4787
4788 return SDValue();
4789}
4790
4791// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
4792// UMULFIXSAT here.
4793SDValue DAGCombiner::visitMULFIX(SDNode *N) {
4794 SDValue N0 = N->getOperand(0);
4795 SDValue N1 = N->getOperand(1);
4796 SDValue Scale = N->getOperand(2);
4797 EVT VT = N0.getValueType();
4798
4799 // fold (mulfix x, undef, scale) -> 0
4800 if (N0.isUndef() || N1.isUndef())
4801 return DAG.getConstant(0, SDLoc(N), VT);
4802
4803 // Canonicalize constant to RHS (vector doesn't have to splat)
4806 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
4807
4808 // fold (mulfix x, 0, scale) -> 0
4809 if (isNullConstant(N1))
4810 return DAG.getConstant(0, SDLoc(N), VT);
4811
4812 return SDValue();
4813}
4814
4815SDValue DAGCombiner::visitMUL(SDNode *N) {
4816 SDValue N0 = N->getOperand(0);
4817 SDValue N1 = N->getOperand(1);
4818 EVT VT = N0.getValueType();
4819 unsigned BitWidth = VT.getScalarSizeInBits();
4820 SDLoc DL(N);
4821
4822 // fold (mul x, undef) -> 0
4823 if (N0.isUndef() || N1.isUndef())
4824 return DAG.getConstant(0, DL, VT);
4825
4826 // fold (mul c1, c2) -> c1*c2
4827 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, DL, VT, {N0, N1}))
4828 return C;
4829
4830 // canonicalize constant to RHS (vector doesn't have to splat)
4833 return DAG.getNode(ISD::MUL, DL, VT, N1, N0);
4834
4835 bool N1IsConst = false;
4836 bool N1IsOpaqueConst = false;
4837 APInt ConstValue1;
4838
4839 // fold vector ops
4840 if (VT.isVector()) {
4841 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4842 return FoldedVOp;
4843
4844 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
4845 assert((!N1IsConst || ConstValue1.getBitWidth() == BitWidth) &&
4846 "Splat APInt should be element width");
4847 } else {
4848 N1IsConst = isa<ConstantSDNode>(N1);
4849 if (N1IsConst) {
4850 ConstValue1 = N1->getAsAPIntVal();
4851 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
4852 }
4853 }
4854
4855 // fold (mul x, 0) -> 0
4856 if (N1IsConst && ConstValue1.isZero())
4857 return N1;
4858
4859 // fold (mul x, 1) -> x
4860 if (N1IsConst && ConstValue1.isOne())
4861 return N0;
4862
4863 if (SDValue NewSel = foldBinOpIntoSelect(N))
4864 return NewSel;
4865
4866 // fold (mul x, -1) -> 0-x
4867 if (N1IsConst && ConstValue1.isAllOnes())
4868 return DAG.getNegative(N0, DL, VT);
4869
4870 // fold (mul x, (1 << c)) -> x << c
4871 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4872 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
4873 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
4874 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4875 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4876 SDNodeFlags Flags;
4877 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap());
4878 // Preserve nsw when the shift amount is strictly less than BitWidth - 1,
4879 // i.e. the multiplier is not the signed minimum value.
4880 if (N->getFlags().hasNoSignedWrap() && N1IsConst &&
4881 ConstValue1.logBase2() < BitWidth - 1)
4882 Flags.setNoSignedWrap(true);
4883 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc, Flags);
4884 }
4885 }
4886
4887 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
4888 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
4889 unsigned Log2Val = (-ConstValue1).logBase2();
4890
4891 // FIXME: If the input is something that is easily negated (e.g. a
4892 // single-use add), we should put the negate there.
4893 return DAG.getNode(
4894 ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4895 DAG.getNode(ISD::SHL, DL, VT, N0,
4896 DAG.getShiftAmountConstant(Log2Val, VT, DL)));
4897 }
4898
4899 // Attempt to reuse an existing umul_lohi/smul_lohi node, but only if the
4900 // hi result is in use in case we hit this mid-legalization.
4901 for (unsigned LoHiOpc : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
4902 if (!LegalOperations || TLI.isOperationLegalOrCustom(LoHiOpc, VT)) {
4903 SDVTList LoHiVT = DAG.getVTList(VT, VT);
4904 // TODO: Can we match commutable operands with getNodeIfExists?
4905 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N0, N1}))
4906 if (LoHi->hasAnyUseOfValue(1))
4907 return SDValue(LoHi, 0);
4908 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N1, N0}))
4909 if (LoHi->hasAnyUseOfValue(1))
4910 return SDValue(LoHi, 0);
4911 }
4912 }
4913
4914 // Try to transform:
4915 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
4916 // mul x, (2^N + 1) --> add (shl x, N), x
4917 // mul x, (2^N - 1) --> sub (shl x, N), x
4918 // Examples: x * 33 --> (x << 5) + x
4919 // x * 15 --> (x << 4) - x
4920 // x * -33 --> -((x << 5) + x)
4921 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
4922 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
4923 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
4924 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
4925 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
4926 // x * 0xf800 --> (x << 16) - (x << 11)
4927 // x * -0x8800 --> -((x << 15) + (x << 11))
4928 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
4929 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
4930 // TODO: We could handle more general decomposition of any constant by
4931 // having the target set a limit on number of ops and making a
4932 // callback to determine that sequence (similar to sqrt expansion).
4933 unsigned MathOp = ISD::DELETED_NODE;
4934 APInt MulC = ConstValue1.abs();
4935 // The constant `2` should be treated as (2^0 + 1).
4936 unsigned TZeros = MulC == 2 ? 0 : MulC.countr_zero();
4937 MulC.lshrInPlace(TZeros);
4938 if ((MulC - 1).isPowerOf2())
4939 MathOp = ISD::ADD;
4940 else if ((MulC + 1).isPowerOf2())
4941 MathOp = ISD::SUB;
4942
4943 if (MathOp != ISD::DELETED_NODE) {
4944 unsigned ShAmt =
4945 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
4946 ShAmt += TZeros;
4947 assert(ShAmt < BitWidth &&
4948 "multiply-by-constant generated out of bounds shift");
4949 SDValue Shl =
4950 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
4951 SDValue R =
4952 TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
4953 DAG.getNode(ISD::SHL, DL, VT, N0,
4954 DAG.getConstant(TZeros, DL, VT)))
4955 : DAG.getNode(MathOp, DL, VT, Shl, N0);
4956 if (ConstValue1.isNegative())
4957 R = DAG.getNegative(R, DL, VT);
4958 return R;
4959 }
4960 }
4961
4962 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
4963 {
4964 SDValue X, C1;
4965 if (sd_match(N0, m_Shl(m_Value(X), m_Value(C1))))
4966 if (SDValue C3 = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N1, C1}))
4967 return DAG.getNode(ISD::MUL, DL, VT, X, C3);
4968 }
4969
4970 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
4971 // use.
4972 {
4973 SDValue X, C, Y;
4974 if (sd_match(N,
4977 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, X, Y);
4978 return DAG.getNode(ISD::SHL, DL, VT, Mul, C);
4979 }
4980 }
4981
4982 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
4986 return DAG.getNode(
4987 ISD::ADD, DL, VT,
4988 DAG.getNode(ISD::MUL, SDLoc(N0), VT, N0.getOperand(0), N1),
4989 DAG.getNode(ISD::MUL, SDLoc(N1), VT, N0.getOperand(1), N1));
4990
4991 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
4992 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
4993 ConstantSDNode *NC1 = isConstOrConstSplat(N1);
4994 if (N0.getOpcode() == ISD::VSCALE && NC1) {
4995 const APInt &C0 = N0.getConstantOperandAPInt(0);
4996 const APInt &C1 = NC1->getAPIntValue();
4997 if (!C0.isPowerOf2() || C1.isPowerOf2() ||
4998 hasOperation(ISD::MUL, NC1->getValueType(0)))
4999 return DAG.getVScale(DL, VT, C0 * C1);
5000 }
5001
5002 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5003 APInt MulVal;
5004 if (N0.getOpcode() == ISD::STEP_VECTOR &&
5005 ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
5006 const APInt &C0 = N0.getConstantOperandAPInt(0);
5007 APInt NewStep = C0 * MulVal;
5008 return DAG.getStepVector(DL, VT, NewStep);
5009 }
5010
5011 // Fold Y = sra (X, size(X)-1); mul (or (Y, 1), X) -> (abs X)
5012 SDValue X;
5013 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
5015 m_One()),
5016 m_Deferred(X)))) {
5017 return DAG.getNode(ISD::ABS, DL, VT, X);
5018 }
5019
5020 // Fold ((mul x, 0/undef) -> 0,
5021 // (mul x, 1) -> x) -> x)
5022 // -> and(x, mask)
5023 // We can replace vectors with '0' and '1' factors with a clearing mask.
5024 if (VT.isFixedLengthVector()) {
5025 unsigned NumElts = VT.getVectorNumElements();
5026 SmallBitVector ClearMask;
5027 ClearMask.reserve(NumElts);
5028 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
5029 if (!V || V->isZero()) {
5030 ClearMask.push_back(true);
5031 return true;
5032 }
5033 ClearMask.push_back(false);
5034 return V->isOne();
5035 };
5036 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
5037 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
5038 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
5039 EVT LegalSVT = N1.getOperand(0).getValueType();
5040 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
5041 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
5043 for (unsigned I = 0; I != NumElts; ++I)
5044 if (ClearMask[I])
5045 Mask[I] = Zero;
5046 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
5047 }
5048 }
5049
5050 // reassociate mul
5051 if (SDValue RMUL = reassociateOps(ISD::MUL, DL, N0, N1, N->getFlags()))
5052 return RMUL;
5053
5054 // Fold mul(vecreduce(x), vecreduce(y)) -> vecreduce(mul(x, y))
5055 if (SDValue SD =
5056 reassociateReduction(ISD::VECREDUCE_MUL, ISD::MUL, DL, VT, N0, N1))
5057 return SD;
5058
5059 // Simplify the operands using demanded-bits information.
5061 return SDValue(N, 0);
5062
5063 return SDValue();
5064}
5065
5066/// Return true if divmod libcall is available.
5068 const SelectionDAG &DAG) {
5069 RTLIB::Libcall LC;
5070 EVT NodeType = Node->getValueType(0);
5071 if (!NodeType.isSimple())
5072 return false;
5073 switch (NodeType.getSimpleVT().SimpleTy) {
5074 default: return false; // No libcall for vector types.
5075 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
5076 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
5077 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
5078 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
5079 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
5080 }
5081
5082 return DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported;
5083}
5084
5085/// Issue divrem if both quotient and remainder are needed.
5086SDValue DAGCombiner::useDivRem(SDNode *Node) {
5087 if (Node->use_empty())
5088 return SDValue(); // This is a dead node, leave it alone.
5089
5090 unsigned Opcode = Node->getOpcode();
5091 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
5092 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
5093
5094 // DivMod lib calls can still work on non-legal types if using lib-calls.
5095 EVT VT = Node->getValueType(0);
5096 if (VT.isVector() || !VT.isInteger())
5097 return SDValue();
5098
5099 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
5100 return SDValue();
5101
5102 // If DIVREM is going to get expanded into a libcall,
5103 // but there is no libcall available, then don't combine.
5104 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
5106 return SDValue();
5107
5108 // If div is legal, it's better to do the normal expansion
5109 unsigned OtherOpcode = 0;
5110 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
5111 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
5112 if (TLI.isOperationLegalOrCustom(Opcode, VT))
5113 return SDValue();
5114 } else {
5115 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5116 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
5117 return SDValue();
5118 }
5119
5120 SDValue Op0 = Node->getOperand(0);
5121 SDValue Op1 = Node->getOperand(1);
5122 SDValue combined;
5123 for (SDNode *User : Op0->users()) {
5124 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
5125 User->use_empty())
5126 continue;
5127 // Convert the other matching node(s), too;
5128 // otherwise, the DIVREM may get target-legalized into something
5129 // target-specific that we won't be able to recognize.
5130 unsigned UserOpc = User->getOpcode();
5131 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
5132 User->getOperand(0) == Op0 &&
5133 User->getOperand(1) == Op1) {
5134 if (!combined) {
5135 if (UserOpc == OtherOpcode) {
5136 SDVTList VTs = DAG.getVTList(VT, VT);
5137 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
5138 } else if (UserOpc == DivRemOpc) {
5139 combined = SDValue(User, 0);
5140 } else {
5141 assert(UserOpc == Opcode);
5142 continue;
5143 }
5144 }
5145 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
5146 CombineTo(User, combined);
5147 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
5148 CombineTo(User, combined.getValue(1));
5149 }
5150 }
5151 return combined;
5152}
5153
5155 SDValue N0 = N->getOperand(0);
5156 SDValue N1 = N->getOperand(1);
5157 EVT VT = N->getValueType(0);
5158 SDLoc DL(N);
5159
5160 unsigned Opc = N->getOpcode();
5161 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
5162
5163 // X / undef -> undef
5164 // X % undef -> undef
5165 // X / 0 -> undef
5166 // X % 0 -> undef
5167 // NOTE: This includes vectors where any divisor element is zero/undef.
5168 if (DAG.isUndef(Opc, {N0, N1}))
5169 return DAG.getUNDEF(VT);
5170
5171 // undef / X -> 0
5172 // undef % X -> 0
5173 if (N0.isUndef())
5174 return DAG.getConstant(0, DL, VT);
5175
5176 // 0 / X -> 0
5177 // 0 % X -> 0
5179 if (N0C && N0C->isZero())
5180 return N0;
5181
5182 // X / X -> 1
5183 // X % X -> 0
5184 if (N0 == N1)
5185 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
5186
5187 // X / 1 -> X
5188 // X % 1 -> 0
5189 // If this is a boolean op (single-bit element type), we can't have
5190 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
5191 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
5192 // it's a 1.
5193 if (isOneOrOneSplat(N1) || (VT.getScalarType() == MVT::i1))
5194 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
5195
5196 return SDValue();
5197}
5198
5199SDValue DAGCombiner::visitSDIV(SDNode *N) {
5200 SDValue N0 = N->getOperand(0);
5201 SDValue N1 = N->getOperand(1);
5202 EVT VT = N->getValueType(0);
5203 EVT CCVT = getSetCCResultType(VT);
5204 SDLoc DL(N);
5205
5206 // fold (sdiv c1, c2) -> c1/c2
5207 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
5208 return C;
5209
5210 // fold vector ops
5211 if (VT.isVector())
5212 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5213 return FoldedVOp;
5214
5215 // fold (sdiv X, -1) -> 0-X
5216 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5217 if (N1C && N1C->isAllOnes())
5218 return DAG.getNegative(N0, DL, VT);
5219
5220 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
5221 if (N1C && N1C->isMinSignedValue())
5222 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5223 DAG.getConstant(1, DL, VT),
5224 DAG.getConstant(0, DL, VT));
5225
5226 if (SDValue V = simplifyDivRem(N, DAG))
5227 return V;
5228
5229 if (SDValue NewSel = foldBinOpIntoSelect(N))
5230 return NewSel;
5231
5232 // If we know the sign bits of both operands are zero, strength reduce to a
5233 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
5234 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5235 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
5236
5237 if (SDValue V = visitSDIVLike(N0, N1, N)) {
5238 // If the corresponding remainder node exists, update its users with
5239 // (Dividend - (Quotient * Divisor).
5240 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
5241 { N0, N1 })) {
5242 // If the sdiv has the exact flag we shouldn't propagate it to the
5243 // remainder node.
5244 if (!N->getFlags().hasExact()) {
5245 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5246 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5247 AddToWorklist(Mul.getNode());
5248 AddToWorklist(Sub.getNode());
5249 CombineTo(RemNode, Sub);
5250 }
5251 }
5252 return V;
5253 }
5254
5255 // sdiv, srem -> sdivrem
5256 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5257 // true. Otherwise, we break the simplification logic in visitREM().
5258 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5259 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5260 if (SDValue DivRem = useDivRem(N))
5261 return DivRem;
5262
5263 return SDValue();
5264}
5265
5266static bool isDivisorPowerOfTwo(SDValue Divisor) {
5267 // Helper for determining whether a value is a power-2 constant scalar or a
5268 // vector of such elements.
5269 auto IsPowerOfTwo = [](ConstantSDNode *C) {
5270 if (C->isZero() || C->isOpaque())
5271 return false;
5272 if (C->getAPIntValue().isPowerOf2())
5273 return true;
5274 if (C->getAPIntValue().isNegatedPowerOf2())
5275 return true;
5276 return false;
5277 };
5278
5279 return ISD::matchUnaryPredicate(Divisor, IsPowerOfTwo, /*AllowUndefs=*/false,
5280 /*AllowTruncation=*/true);
5281}
5282
5283SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5284 SDLoc DL(N);
5285 EVT VT = N->getValueType(0);
5286 EVT CCVT = getSetCCResultType(VT);
5287 unsigned BitWidth = VT.getScalarSizeInBits();
5288 unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();
5289
5290 // fold (sdiv X, pow2) -> simple ops after legalize
5291 // FIXME: We check for the exact bit here because the generic lowering gives
5292 // better results in that case. The target-specific lowering should learn how
5293 // to handle exact sdivs efficiently. An exception is made for large bitwidths
5294 // exceeding what the target can natively support, as division expansion was
5295 // skipped in favor of this optimization.
5296 if ((!N->getFlags().hasExact() || BitWidth > MaxLegalDivRemBitWidth) &&
5297 isDivisorPowerOfTwo(N1)) {
5298 // Target-specific implementation of sdiv x, pow2.
5299 if (SDValue Res = BuildSDIVPow2(N))
5300 return Res;
5301
5302 // Create constants that are functions of the shift amount value.
5303 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
5304 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
5305 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
5306 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
5307 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
5308 if (!isConstantOrConstantVector(Inexact))
5309 return SDValue();
5310
5311 // Splat the sign bit into the register
5312 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
5313 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
5314 AddToWorklist(Sign.getNode());
5315
5316 // Add (N0 < 0) ? abs2 - 1 : 0;
5317 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
5318 AddToWorklist(Srl.getNode());
5319 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
5320 AddToWorklist(Add.getNode());
5321 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
5322 AddToWorklist(Sra.getNode());
5323
5324 // Special case: (sdiv X, 1) -> X
5325 // Special Case: (sdiv X, -1) -> 0-X
5326 SDValue One = DAG.getConstant(1, DL, VT);
5328 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
5329 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
5330 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
5331 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
5332
5333 // If dividing by a positive value, we're done. Otherwise, the result must
5334 // be negated.
5335 SDValue Zero = DAG.getConstant(0, DL, VT);
5336 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
5337
5338 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
5339 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
5340 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
5341 return Res;
5342 }
5343
5344 // If integer divide is expensive and we satisfy the requirements, emit an
5345 // alternate sequence. Targets may check function attributes for size/speed
5346 // trade-offs.
5347 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5348 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5349 /*AllowTruncation=*/true) &&
5350 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5351 if (SDValue Op = BuildSDIV(N))
5352 return Op;
5353
5354 return SDValue();
5355}
5356
5357SDValue DAGCombiner::visitUDIV(SDNode *N) {
5358 SDValue N0 = N->getOperand(0);
5359 SDValue N1 = N->getOperand(1);
5360 EVT VT = N->getValueType(0);
5361 EVT CCVT = getSetCCResultType(VT);
5362 SDLoc DL(N);
5363
5364 // fold (udiv c1, c2) -> c1/c2
5365 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
5366 return C;
5367
5368 // fold vector ops
5369 if (VT.isVector())
5370 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5371 return FoldedVOp;
5372
5373 // fold (udiv X, -1) -> select(X == -1, 1, 0)
5374 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5375 if (N1C && N1C->isAllOnes() && CCVT.isVector() == VT.isVector()) {
5376 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5377 DAG.getConstant(1, DL, VT),
5378 DAG.getConstant(0, DL, VT));
5379 }
5380
5381 if (SDValue V = simplifyDivRem(N, DAG))
5382 return V;
5383
5384 if (SDValue NewSel = foldBinOpIntoSelect(N))
5385 return NewSel;
5386
5387 if (SDValue V = visitUDIVLike(N0, N1, N)) {
5388 // If the corresponding remainder node exists, update its users with
5389 // (Dividend - (Quotient * Divisor).
5390 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
5391 { N0, N1 })) {
5392 // If the udiv has the exact flag we shouldn't propagate it to the
5393 // remainder node.
5394 if (!N->getFlags().hasExact()) {
5395 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5396 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5397 AddToWorklist(Mul.getNode());
5398 AddToWorklist(Sub.getNode());
5399 CombineTo(RemNode, Sub);
5400 }
5401 }
5402 return V;
5403 }
5404
5405 // sdiv, srem -> sdivrem
5406 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5407 // true. Otherwise, we break the simplification logic in visitREM().
5408 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5409 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5410 if (SDValue DivRem = useDivRem(N))
5411 return DivRem;
5412
5413 // Simplify the operands using demanded-bits information.
5414 // We don't have demanded bits support for UDIV so this just enables constant
5415 // folding based on known bits.
5417 return SDValue(N, 0);
5418
5419 return SDValue();
5420}
5421
5422SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5423 SDLoc DL(N);
5424 EVT VT = N->getValueType(0);
5425
5426 // fold (udiv x, (1 << c)) -> x >>u c
5427 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5428 /*AllowTruncation=*/true)) {
5429 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5430 AddToWorklist(LogBase2.getNode());
5431
5432 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5433 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
5434 AddToWorklist(Trunc.getNode());
5435 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5436 }
5437 }
5438
5439 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
5440 if (N1.getOpcode() == ISD::SHL) {
5441 SDValue N10 = N1.getOperand(0);
5442 if (isConstantOrConstantVector(N10, /*NoOpaques=*/true,
5443 /*AllowTruncation=*/true)) {
5444 if (SDValue LogBase2 = BuildLogBase2(N10, DL)) {
5445 AddToWorklist(LogBase2.getNode());
5446
5447 EVT ADDVT = N1.getOperand(1).getValueType();
5448 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
5449 AddToWorklist(Trunc.getNode());
5450 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
5451 AddToWorklist(Add.getNode());
5452 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
5453 }
5454 }
5455 }
5456
5457 // fold (udiv x, c) -> alternate
5458 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5459 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5460 /*AllowTruncation=*/true) &&
5461 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5462 if (SDValue Op = BuildUDIV(N))
5463 return Op;
5464
5465 return SDValue();
5466}
5467
5468SDValue DAGCombiner::buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N) {
5469 if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1) &&
5470 !DAG.doesNodeExist(ISD::SDIV, N->getVTList(), {N0, N1})) {
5471 // Target-specific implementation of srem x, pow2.
5472 if (SDValue Res = BuildSREMPow2(N))
5473 return Res;
5474 }
5475 return SDValue();
5476}
5477
5478// handles ISD::SREM and ISD::UREM
5479SDValue DAGCombiner::visitREM(SDNode *N) {
5480 unsigned Opcode = N->getOpcode();
5481 SDValue N0 = N->getOperand(0);
5482 SDValue N1 = N->getOperand(1);
5483 EVT VT = N->getValueType(0);
5484 EVT CCVT = getSetCCResultType(VT);
5485
5486 bool isSigned = (Opcode == ISD::SREM);
5487 SDLoc DL(N);
5488
5489 // fold (rem c1, c2) -> c1%c2
5490 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5491 return C;
5492
5493 // fold (urem X, -1) -> select(FX == -1, 0, FX)
5494 // Freeze the numerator to avoid a miscompile with an undefined value.
5495 if (!isSigned && llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false) &&
5496 CCVT.isVector() == VT.isVector()) {
5497 SDValue F0 = DAG.getFreeze(N0);
5498 SDValue EqualsNeg1 = DAG.getSetCC(DL, CCVT, F0, N1, ISD::SETEQ);
5499 return DAG.getSelect(DL, VT, EqualsNeg1, DAG.getConstant(0, DL, VT), F0);
5500 }
5501
5502 if (SDValue V = simplifyDivRem(N, DAG))
5503 return V;
5504
5505 if (SDValue NewSel = foldBinOpIntoSelect(N))
5506 return NewSel;
5507
5508 if (isSigned) {
5509 // If we know the sign bits of both operands are zero, strength reduce to a
5510 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
5511 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5512 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
5513 } else {
5514 if (DAG.isKnownToBeAPowerOfTwo(N1, /*OrZero=*/true)) {
5515 // fold (urem x, pow2) -> (and x, pow2-1)
5516 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
5517 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
5518 AddToWorklist(Add.getNode());
5519 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
5520 }
5521 }
5522
5523 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5524
5525 // If X/C can be simplified by the division-by-constant logic, lower
5526 // X%C to the equivalent of X-X/C*C.
5527 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
5528 // speculative DIV must not cause a DIVREM conversion. We guard against this
5529 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
5530 // combine will not return a DIVREM. Regardless, checking cheapness here
5531 // makes sense since the simplification results in fatter code.
5532 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
5533 if (isSigned) {
5534 // check if we can build faster implementation for srem
5535 if (SDValue OptimizedRem = buildOptimizedSREM(N0, N1, N))
5536 return OptimizedRem;
5537 }
5538
5539 SDValue OptimizedDiv =
5540 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
5541 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
5542 // If the equivalent Div node also exists, update its users.
5543 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5544 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
5545 { N0, N1 }))
5546 CombineTo(DivNode, OptimizedDiv);
5547 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
5548 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5549 AddToWorklist(OptimizedDiv.getNode());
5550 AddToWorklist(Mul.getNode());
5551 return Sub;
5552 }
5553 }
5554
5555 // sdiv, srem -> sdivrem
5556 if (SDValue DivRem = useDivRem(N))
5557 return DivRem.getValue(1);
5558
5559 // fold urem(urem(A, BCst), Op1Cst) -> urem(A, Op1Cst)
5560 // iff urem(BCst, Op1Cst) == 0
5561 SDValue A;
5562 APInt Op1Cst, BCst;
5563 if (sd_match(N, m_URem(m_URem(m_Value(A), m_ConstInt(BCst)),
5564 m_ConstInt(Op1Cst))) &&
5565 BCst.urem(Op1Cst).isZero()) {
5566 return DAG.getNode(ISD::UREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5567 }
5568
5569 // fold srem(srem(A, BCst), Op1Cst) -> srem(A, Op1Cst)
5570 // iff srem(BCst, Op1Cst) == 0 && Op1Cst != 1
5571 if (sd_match(N, m_SRem(m_SRem(m_Value(A), m_ConstInt(BCst)),
5572 m_ConstInt(Op1Cst))) &&
5573 BCst.srem(Op1Cst).isZero() && !Op1Cst.isAllOnes()) {
5574 return DAG.getNode(ISD::SREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5575 }
5576
5577 return SDValue();
5578}
5579
5580SDValue DAGCombiner::visitMULHS(SDNode *N) {
5581 SDValue N0 = N->getOperand(0);
5582 SDValue N1 = N->getOperand(1);
5583 EVT VT = N->getValueType(0);
5584 SDLoc DL(N);
5585
5586 // fold (mulhs c1, c2)
5587 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
5588 return C;
5589
5590 // canonicalize constant to RHS.
5593 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
5594
5595 if (VT.isVector()) {
5596 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5597 return FoldedVOp;
5598
5599 // fold (mulhs x, 0) -> 0
5600 // do not return N1, because undef node may exist.
5602 return DAG.getConstant(0, DL, VT);
5603 }
5604
5605 // fold (mulhs x, 0) -> 0
5606 if (isNullConstant(N1))
5607 return N1;
5608
5609 // fold (mulhs x, 1) -> (sra x, size(x)-1)
5610 if (isOneConstant(N1))
5611 return DAG.getNode(
5612 ISD::SRA, DL, VT, N0,
5614
5615 // fold (mulhs x, undef) -> 0
5616 if (N0.isUndef() || N1.isUndef())
5617 return DAG.getConstant(0, DL, VT);
5618
5619 // If the type twice as wide is legal, transform the mulhs to a wider multiply
5620 // plus a shift.
5621 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
5622 !VT.isVector()) {
5623 MVT Simple = VT.getSimpleVT();
5624 unsigned SimpleSize = Simple.getSizeInBits();
5625 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5626 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5627 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
5628 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
5629 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5630 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5631 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5632 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5633 }
5634 }
5635
5636 return SDValue();
5637}
5638
5639SDValue DAGCombiner::visitMULHU(SDNode *N) {
5640 SDValue N0 = N->getOperand(0);
5641 SDValue N1 = N->getOperand(1);
5642 EVT VT = N->getValueType(0);
5643 SDLoc DL(N);
5644
5645 // fold (mulhu c1, c2)
5646 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
5647 return C;
5648
5649 // canonicalize constant to RHS.
5652 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
5653
5654 if (VT.isVector()) {
5655 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5656 return FoldedVOp;
5657
5658 // fold (mulhu x, 0) -> 0
5659 // do not return N1, because undef node may exist.
5661 return DAG.getConstant(0, DL, VT);
5662 }
5663
5664 // fold (mulhu x, 0) -> 0
5665 if (isNullConstant(N1))
5666 return N1;
5667
5668 // fold (mulhu x, 1) -> 0
5669 if (isOneConstant(N1))
5670 return DAG.getConstant(0, DL, VT);
5671
5672 // fold (mulhu x, undef) -> 0
5673 if (N0.isUndef() || N1.isUndef())
5674 return DAG.getConstant(0, DL, VT);
5675
5676 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
5677 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5678 /*AllowTruncation=*/true) &&
5679 (!LegalOperations || hasOperation(ISD::SRL, VT))) {
5680 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5681 unsigned NumEltBits = VT.getScalarSizeInBits();
5682 SDValue SRLAmt = DAG.getNode(
5683 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
5684 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5685 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
5686 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5687 }
5688 }
5689
5690 // If the type twice as wide is legal, transform the mulhu to a wider multiply
5691 // plus a shift.
5692 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
5693 !VT.isVector()) {
5694 MVT Simple = VT.getSimpleVT();
5695 unsigned SimpleSize = Simple.getSizeInBits();
5696 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5697 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5698 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
5699 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
5700 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5701 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5702 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5703 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5704 }
5705 }
5706
5707 // Simplify the operands using demanded-bits information.
5708 // We don't have demanded bits support for MULHU so this just enables constant
5709 // folding based on known bits.
5711 return SDValue(N, 0);
5712
5713 return SDValue();
5714}
5715
5716SDValue DAGCombiner::visitAVG(SDNode *N) {
5717 unsigned Opcode = N->getOpcode();
5718 SDValue N0 = N->getOperand(0);
5719 SDValue N1 = N->getOperand(1);
5720 EVT VT = N->getValueType(0);
5721 SDLoc DL(N);
5722 bool IsSigned = Opcode == ISD::AVGCEILS || Opcode == ISD::AVGFLOORS;
5723
5724 // fold (avg c1, c2)
5725 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5726 return C;
5727
5728 // canonicalize constant to RHS.
5731 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5732
5733 if (VT.isVector())
5734 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5735 return FoldedVOp;
5736
5737 // fold (avg x, undef) -> x
5738 if (N0.isUndef())
5739 return N1;
5740 if (N1.isUndef())
5741 return N0;
5742
5743 // fold (avg x, x) --> x
5744 if (N0 == N1 && Level >= AfterLegalizeTypes)
5745 return N0;
5746
5747 // fold (avgfloor x, 0) -> x >> 1
5748 SDValue X, Y;
5750 return DAG.getNode(ISD::SRA, DL, VT, X,
5751 DAG.getShiftAmountConstant(1, VT, DL));
5753 return DAG.getNode(ISD::SRL, DL, VT, X,
5754 DAG.getShiftAmountConstant(1, VT, DL));
5755
5756 // fold avgu(zext(x), zext(y)) -> zext(avgu(x, y))
5757 // fold avgs(sext(x), sext(y)) -> sext(avgs(x, y))
5758 if (!IsSigned &&
5759 sd_match(N, m_BinOp(Opcode, m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
5760 X.getValueType() == Y.getValueType() &&
5761 hasOperation(Opcode, X.getValueType())) {
5762 SDValue AvgU = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5763 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, AvgU);
5764 }
5765 if (IsSigned &&
5766 sd_match(N, m_BinOp(Opcode, m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
5767 X.getValueType() == Y.getValueType() &&
5768 hasOperation(Opcode, X.getValueType())) {
5769 SDValue AvgS = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5770 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, AvgS);
5771 }
5772
5773 // Fold avgflooru(x,y) -> avgceilu(x,y-1) iff y != 0
5774 // Fold avgflooru(x,y) -> avgceilu(x-1,y) iff x != 0
5775 // Check if avgflooru isn't legal/custom but avgceilu is.
5776 if (Opcode == ISD::AVGFLOORU && !hasOperation(ISD::AVGFLOORU, VT) &&
5777 (!LegalOperations || hasOperation(ISD::AVGCEILU, VT))) {
5778 if (DAG.isKnownNeverZero(N1))
5779 return DAG.getNode(
5780 ISD::AVGCEILU, DL, VT, N0,
5781 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getAllOnesConstant(DL, VT)));
5782 if (DAG.isKnownNeverZero(N0))
5783 return DAG.getNode(
5784 ISD::AVGCEILU, DL, VT, N1,
5785 DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getAllOnesConstant(DL, VT)));
5786 }
5787
5788 // Fold avgfloor((add nw x,y), 1) -> avgceil(x,y)
5789 // Fold avgfloor((add nw x,1), y) -> avgceil(x,y)
5790 if ((Opcode == ISD::AVGFLOORU && hasOperation(ISD::AVGCEILU, VT)) ||
5791 (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGCEILS, VT))) {
5792 SDValue Add;
5793 if (sd_match(N,
5794 m_c_BinOp(Opcode,
5796 m_One())) ||
5797 sd_match(N, m_c_BinOp(Opcode,
5799 m_Value(Y)))) {
5800
5801 if (IsSigned && Add->getFlags().hasNoSignedWrap())
5802 return DAG.getNode(ISD::AVGCEILS, DL, VT, X, Y);
5803
5804 if (!IsSigned && Add->getFlags().hasNoUnsignedWrap())
5805 return DAG.getNode(ISD::AVGCEILU, DL, VT, X, Y);
5806 }
5807 }
5808
5809 // Fold avgfloors(x,y) -> avgflooru(x,y) if both x and y are non-negative
5810 if (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGFLOORU, VT)) {
5811 if (DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5812 return DAG.getNode(ISD::AVGFLOORU, DL, VT, N0, N1);
5813 }
5814
5815 return SDValue();
5816}
5817
5818SDValue DAGCombiner::visitABD(SDNode *N) {
5819 unsigned Opcode = N->getOpcode();
5820 SDValue N0 = N->getOperand(0);
5821 SDValue N1 = N->getOperand(1);
5822 EVT VT = N->getValueType(0);
5823 SDLoc DL(N);
5824
5825 // fold (abd c1, c2)
5826 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5827 return C;
5828
5829 // canonicalize constant to RHS.
5832 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5833
5834 if (VT.isVector())
5835 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5836 return FoldedVOp;
5837
5838 // fold (abd x, undef) -> 0
5839 if (N0.isUndef() || N1.isUndef())
5840 return DAG.getConstant(0, DL, VT);
5841
5842 // fold (abd x, x) -> 0
5843 if (N0 == N1)
5844 return DAG.getConstant(0, DL, VT);
5845
5846 SDValue X, Y;
5847
5848 // fold (abds x, 0) -> abs x
5850 (!LegalOperations || hasOperation(ISD::ABS, VT)))
5851 return DAG.getNode(ISD::ABS, DL, VT, X);
5852
5853 // fold (abdu x, 0) -> x
5855 return X;
5856
5857 // fold (abds x, y) -> (abdu x, y) iff both args are known positive
5858 if (Opcode == ISD::ABDS && hasOperation(ISD::ABDU, VT) &&
5859 DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5860 return DAG.getNode(ISD::ABDU, DL, VT, N1, N0);
5861
5862 // fold (abd? (?ext x), (?ext y)) -> (zext (abd? x, y))
5865 EVT SmallVT = X.getScalarValueSizeInBits() > Y.getScalarValueSizeInBits()
5866 ? X.getValueType()
5867 : Y.getValueType();
5868 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5869 SDValue ExtedX = DAG.getExtOrTrunc(X, SDLoc(X), SmallVT, N0->getOpcode());
5870 SDValue ExtedY = DAG.getExtOrTrunc(Y, SDLoc(Y), SmallVT, N0->getOpcode());
5871 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {ExtedX, ExtedY});
5872 SDValue ZExted = DAG.getZExtOrTrunc(SmallABD, DL, VT);
5873 return ZExted;
5874 }
5875 }
5876
5877 // fold (abd? (?ext ty:x), small_const:c) -> (zext (abd? x, c))
5880 EVT SmallVT = X.getValueType();
5881 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5882 uint64_t Bits = SmallVT.getScalarSizeInBits();
5883 unsigned RelevantBits =
5884 (Opcode == ISD::ABDS) ? DAG.ComputeMaxSignificantBits(Y)
5886 bool TruncatingYIsCheap = TLI.isTruncateFree(Y, SmallVT) ||
5888 Y,
5889 [&](auto *C) {
5890 const APInt &YConst = C->getAsAPIntVal();
5891 return (Opcode == ISD::ABDS)
5892 ? YConst.isSignedIntN(Bits)
5893 : YConst.isIntN(Bits);
5894 },
5895 /*AllowUndefs=*/true);
5896
5897 if (RelevantBits <= Bits && TruncatingYIsCheap) {
5898 SDValue NewY = DAG.getNode(ISD::TRUNCATE, SDLoc(Y), SmallVT, Y);
5899 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {X, NewY});
5900 return DAG.getZExtOrTrunc(SmallABD, DL, VT);
5901 }
5902 }
5903 }
5904
5905 return SDValue();
5906}
5907
5908/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
5909/// give the opcodes for the two computations that are being performed. Return
5910/// true if a simplification was made.
5911SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
5912 unsigned HiOp) {
5913 // If the high half is not needed, just compute the low half.
5914 bool HiExists = N->hasAnyUseOfValue(1);
5915 if (!HiExists && (!LegalOperations ||
5916 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
5917 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5918 return CombineTo(N, Res, Res);
5919 }
5920
5921 // If the low half is not needed, just compute the high half.
5922 bool LoExists = N->hasAnyUseOfValue(0);
5923 if (!LoExists && (!LegalOperations ||
5924 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
5925 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
5926 return CombineTo(N, Res, Res);
5927 }
5928
5929 // If both halves are used, return as it is.
5930 if (LoExists && HiExists)
5931 return SDValue();
5932
5933 // If the two computed results can be simplified separately, separate them.
5934 if (LoExists) {
5935 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5936 AddToWorklist(Lo.getNode());
5937 SDValue LoOpt = combine(Lo.getNode());
5938 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
5939 (!LegalOperations ||
5940 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
5941 return CombineTo(N, LoOpt, LoOpt);
5942 }
5943
5944 if (HiExists) {
5945 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
5946 AddToWorklist(Hi.getNode());
5947 SDValue HiOpt = combine(Hi.getNode());
5948 if (HiOpt.getNode() && HiOpt != Hi &&
5949 (!LegalOperations ||
5950 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
5951 return CombineTo(N, HiOpt, HiOpt);
5952 }
5953
5954 return SDValue();
5955}
5956
5957SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
5958 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
5959 return Res;
5960
5961 SDValue N0 = N->getOperand(0);
5962 SDValue N1 = N->getOperand(1);
5963 EVT VT = N->getValueType(0);
5964 SDLoc DL(N);
5965
5966 // Constant fold.
5968 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N0, N1);
5969
5970 // canonicalize constant to RHS (vector doesn't have to splat)
5973 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N1, N0);
5974
5975 // If the type is twice as wide is legal, transform the mulhu to a wider
5976 // multiply plus a shift.
5977 if (VT.isSimple() && !VT.isVector()) {
5978 MVT Simple = VT.getSimpleVT();
5979 unsigned SimpleSize = Simple.getSizeInBits();
5980 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5981 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5982 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
5983 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
5984 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
5985 // Compute the high part as N1.
5986 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
5987 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5988 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
5989 // Compute the low part as N0.
5990 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
5991 return CombineTo(N, Lo, Hi);
5992 }
5993 }
5994
5995 return SDValue();
5996}
5997
5998SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
5999 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
6000 return Res;
6001
6002 SDValue N0 = N->getOperand(0);
6003 SDValue N1 = N->getOperand(1);
6004 EVT VT = N->getValueType(0);
6005 SDLoc DL(N);
6006
6007 // Constant fold.
6009 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N0, N1);
6010
6011 // canonicalize constant to RHS (vector doesn't have to splat)
6014 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N1, N0);
6015
6016 // (umul_lohi N0, 0) -> (0, 0)
6017 if (isNullConstant(N1)) {
6018 SDValue Zero = DAG.getConstant(0, DL, VT);
6019 return CombineTo(N, Zero, Zero);
6020 }
6021
6022 // (umul_lohi N0, 1) -> (N0, 0)
6023 if (isOneConstant(N1)) {
6024 SDValue Zero = DAG.getConstant(0, DL, VT);
6025 return CombineTo(N, N0, Zero);
6026 }
6027
6028 // If the type is twice as wide is legal, transform the mulhu to a wider
6029 // multiply plus a shift.
6030 if (VT.isSimple() && !VT.isVector()) {
6031 MVT Simple = VT.getSimpleVT();
6032 unsigned SimpleSize = Simple.getSizeInBits();
6033 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6034 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6035 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
6036 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
6037 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6038 // Compute the high part as N1.
6039 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6040 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6041 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6042 // Compute the low part as N0.
6043 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6044 return CombineTo(N, Lo, Hi);
6045 }
6046 }
6047
6048 return SDValue();
6049}
6050
6051SDValue DAGCombiner::visitMULO(SDNode *N) {
6052 SDValue N0 = N->getOperand(0);
6053 SDValue N1 = N->getOperand(1);
6054 EVT VT = N0.getValueType();
6055 bool IsSigned = (ISD::SMULO == N->getOpcode());
6056
6057 EVT CarryVT = N->getValueType(1);
6058 SDLoc DL(N);
6059
6060 ConstantSDNode *N0C = isConstOrConstSplat(N0);
6061 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6062
6063 // fold operation with constant operands.
6064 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
6065 // multiple results.
6066 if (N0C && N1C) {
6067 bool Overflow;
6068 APInt Result =
6069 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
6070 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
6071 return CombineTo(N, DAG.getConstant(Result, DL, VT),
6072 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
6073 }
6074
6075 // canonicalize constant to RHS.
6078 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
6079
6080 // fold (mulo x, 0) -> 0 + no carry out
6081 if (isNullOrNullSplat(N1))
6082 return CombineTo(N, DAG.getConstant(0, DL, VT),
6083 DAG.getConstant(0, DL, CarryVT));
6084
6085 // (mulo x, 2) -> (addo x, x)
6086 // FIXME: This needs a freeze.
6087 if (N1C && N1C->getAPIntValue() == 2 &&
6088 (!IsSigned || VT.getScalarSizeInBits() > 2))
6089 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
6090 N->getVTList(), N0, N0);
6091
6092 // A 1 bit SMULO overflows if both inputs are 1.
6093 if (IsSigned && VT.getScalarSizeInBits() == 1) {
6094 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
6095 SDValue Cmp = DAG.getSetCC(DL, CarryVT, And,
6096 DAG.getConstant(0, DL, VT), ISD::SETNE);
6097 return CombineTo(N, And, Cmp);
6098 }
6099
6100 // If it cannot overflow, transform into a mul.
6101 if (DAG.willNotOverflowMul(IsSigned, N0, N1))
6102 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
6103 DAG.getConstant(0, DL, CarryVT));
6104 return SDValue();
6105}
6106
6107// Function to calculate whether the Min/Max pair of SDNodes (potentially
6108// swapped around) make a signed saturate pattern, clamping to between a signed
6109// saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
6110// Returns the node being clamped and the bitwidth of the clamp in BW. Should
6111// work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
6112// same as SimplifySelectCC. N0<N1 ? N2 : N3.
6114 SDValue N3, ISD::CondCode CC, unsigned &BW,
6115 bool &Unsigned, SelectionDAG &DAG) {
6116 auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
6117 ISD::CondCode CC) {
6118 // The compare and select operand should be the same or the select operands
6119 // should be truncated versions of the comparison.
6120 if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
6121 return 0;
6122 // The constants need to be the same or a truncated version of each other.
6125 if (!N1C || !N3C)
6126 return 0;
6127 const APInt &C1 = N1C->getAPIntValue().trunc(N1.getScalarValueSizeInBits());
6128 const APInt &C2 = N3C->getAPIntValue().trunc(N3.getScalarValueSizeInBits());
6129 if (C1.getBitWidth() < C2.getBitWidth() || C1 != C2.sext(C1.getBitWidth()))
6130 return 0;
6131 return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
6132 };
6133
6134 // Check the initial value is a SMIN/SMAX equivalent.
6135 unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
6136 if (!Opcode0)
6137 return SDValue();
6138
6139 // We could only need one range check, if the fptosi could never produce
6140 // the upper value.
6141 if (N0.getOpcode() == ISD::FP_TO_SINT && Opcode0 == ISD::SMAX) {
6142 if (isNullOrNullSplat(N3)) {
6143 EVT IntVT = N0.getValueType().getScalarType();
6144 EVT FPVT = N0.getOperand(0).getValueType().getScalarType();
6145 if (FPVT.isSimple()) {
6146 Type *InputTy = FPVT.getTypeForEVT(*DAG.getContext());
6147 const fltSemantics &Semantics = InputTy->getFltSemantics();
6148 uint32_t MinBitWidth =
6149 APFloatBase::semanticsIntSizeInBits(Semantics, /*isSigned*/ true);
6150 if (IntVT.getSizeInBits() >= MinBitWidth) {
6151 Unsigned = true;
6152 BW = PowerOf2Ceil(MinBitWidth);
6153 return N0;
6154 }
6155 }
6156 }
6157 }
6158
6159 SDValue N00, N01, N02, N03;
6160 ISD::CondCode N0CC;
6161 switch (N0.getOpcode()) {
6162 case ISD::SMIN:
6163 case ISD::SMAX:
6164 N00 = N02 = N0.getOperand(0);
6165 N01 = N03 = N0.getOperand(1);
6166 N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
6167 break;
6168 case ISD::SELECT_CC:
6169 N00 = N0.getOperand(0);
6170 N01 = N0.getOperand(1);
6171 N02 = N0.getOperand(2);
6172 N03 = N0.getOperand(3);
6173 N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
6174 break;
6175 case ISD::SELECT:
6176 case ISD::VSELECT:
6177 if (N0.getOperand(0).getOpcode() != ISD::SETCC)
6178 return SDValue();
6179 N00 = N0.getOperand(0).getOperand(0);
6180 N01 = N0.getOperand(0).getOperand(1);
6181 N02 = N0.getOperand(1);
6182 N03 = N0.getOperand(2);
6183 N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
6184 break;
6185 default:
6186 return SDValue();
6187 }
6188
6189 unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
6190 if (!Opcode1 || Opcode0 == Opcode1)
6191 return SDValue();
6192
6193 ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
6194 ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
6195 if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
6196 return SDValue();
6197
6198 const APInt &MinC = MinCOp->getAPIntValue();
6199 const APInt &MaxC = MaxCOp->getAPIntValue();
6200 APInt MinCPlus1 = MinC + 1;
6201 if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
6202 BW = MinCPlus1.exactLogBase2() + 1;
6203 Unsigned = false;
6204 return N02;
6205 }
6206
6207 if (MaxC == 0 && MinC != 0 && MinCPlus1.isPowerOf2()) {
6208 BW = MinCPlus1.exactLogBase2();
6209 Unsigned = true;
6210 return N02;
6211 }
6212
6213 return SDValue();
6214}
6215
6217 SDValue N3, ISD::CondCode CC,
6218 SelectionDAG &DAG) {
6219 unsigned BW;
6220 bool Unsigned;
6221 SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned, DAG);
6222 if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
6223 return SDValue();
6224 EVT FPVT = Fp.getOperand(0).getValueType();
6225 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6226 EVT::getIntegerVT(*DAG.getContext(), BW));
6227 unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
6228 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
6229 return SDValue();
6230 SDLoc DL(Fp);
6231 SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
6232 DAG.getValueType(NewVT.getScalarType()));
6233 return DAG.getExtOrTrunc(!Unsigned, Sat, DL, N2->getValueType(0));
6234}
6235
6237 SDValue N3, ISD::CondCode CC,
6238 SelectionDAG &DAG) {
6239 // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
6240 // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
6241 // be truncated versions of the setcc (N0/N1).
6242 if ((N0 != N2 &&
6243 (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
6244 N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
6245 return SDValue();
6248 if (!N1C || !N3C)
6249 return SDValue();
6250 const APInt &C1 = N1C->getAPIntValue();
6251 const APInt &C3 = N3C->getAPIntValue();
6252 if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
6253 C1 != C3.zext(C1.getBitWidth()))
6254 return SDValue();
6255
6256 unsigned BW = (C1 + 1).exactLogBase2();
6257 EVT FPVT = N0.getOperand(0).getValueType();
6258 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6259 EVT::getIntegerVT(*DAG.getContext(), BW));
6261 FPVT, NewVT))
6262 return SDValue();
6263
6264 SDValue Sat =
6265 DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
6266 DAG.getValueType(NewVT.getScalarType()));
6267 return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
6268}
6269
6270SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
6271 SDValue N0 = N->getOperand(0);
6272 SDValue N1 = N->getOperand(1);
6273 EVT VT = N0.getValueType();
6274 unsigned Opcode = N->getOpcode();
6275 SDLoc DL(N);
6276
6277 // fold operation with constant operands.
6278 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
6279 return C;
6280
6281 // If the operands are the same, this is a no-op.
6282 if (N0 == N1)
6283 return N0;
6284
6285 // canonicalize constant to RHS
6288 return DAG.getNode(Opcode, DL, VT, N1, N0);
6289
6290 // fold vector ops
6291 if (VT.isVector())
6292 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
6293 return FoldedVOp;
6294
6295 // reassociate minmax
6296 if (SDValue RMINMAX = reassociateOps(Opcode, DL, N0, N1, N->getFlags()))
6297 return RMINMAX;
6298
6299 // If both operands are known to have the same sign (both non-negative or both
6300 // negative), flip between UMIN/UMAX and SMIN/SMAX.
6301 // Only do this if:
6302 // 1. The current op isn't legal and the flipped is.
6303 // 2. The saturation pattern is broken by canonicalization in InstCombine.
6304 bool IsOpIllegal = !TLI.isOperationLegal(Opcode, VT);
6305 bool IsSatBroken = Opcode == ISD::UMIN && N0.getOpcode() == ISD::SMAX;
6306
6307 if (IsSatBroken || IsOpIllegal) {
6308 auto HasKnownSameSign = [&](SDValue A, SDValue B) {
6309 if (A.isUndef() || B.isUndef())
6310 return true;
6311
6312 KnownBits KA = DAG.computeKnownBits(A);
6313 if (!KA.isNonNegative() && !KA.isNegative())
6314 return false;
6315
6316 KnownBits KB = DAG.computeKnownBits(B);
6317 if (KA.isNonNegative())
6318 return KB.isNonNegative();
6319 return KB.isNegative();
6320 };
6321
6322 if (HasKnownSameSign(N0, N1)) {
6323 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
6324 if ((IsSatBroken && IsOpIllegal) || TLI.isOperationLegal(AltOpcode, VT))
6325 return DAG.getNode(AltOpcode, DL, VT, N0, N1);
6326 }
6327 }
6328
6329 if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
6331 N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
6332 return S;
6333 if (Opcode == ISD::UMIN)
6334 if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
6335 return S;
6336
6337 // Fold min/max(vecreduce(x), vecreduce(y)) -> vecreduce(min/max(x, y))
6338 auto ReductionOpcode = [](unsigned Opcode) {
6339 switch (Opcode) {
6340 case ISD::SMIN:
6341 return ISD::VECREDUCE_SMIN;
6342 case ISD::SMAX:
6343 return ISD::VECREDUCE_SMAX;
6344 case ISD::UMIN:
6345 return ISD::VECREDUCE_UMIN;
6346 case ISD::UMAX:
6347 return ISD::VECREDUCE_UMAX;
6348 default:
6349 llvm_unreachable("Unexpected opcode");
6350 }
6351 };
6352 if (SDValue SD = reassociateReduction(ReductionOpcode(Opcode), Opcode,
6353 SDLoc(N), VT, N0, N1))
6354 return SD;
6355
6356 // Fold operation with vscale operands.
6357 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
6358 uint64_t C0 = N0->getConstantOperandVal(0);
6359 uint64_t C1 = N1->getConstantOperandVal(0);
6360 if (Opcode == ISD::UMAX)
6361 return C0 > C1 ? N0 : N1;
6362 else if (Opcode == ISD::UMIN)
6363 return C0 > C1 ? N1 : N0;
6364 }
6365
6366 // If we know the range of vscale, see if we can fold it given a constant.
6367 if (N0.getOpcode() == ISD::VSCALE) {
6368 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
6369 bool ForSigned = (Opcode == ISD::SMAX || Opcode == ISD::SMIN);
6370 ConstantRange Range = DAG.computeConstantRange(N0, ForSigned);
6371
6372 const APInt &C1V = C1->getAPIntValue();
6373 if ((Opcode == ISD::UMAX && Range.getUnsignedMax().ule(C1V)) ||
6374 (Opcode == ISD::UMIN && Range.getUnsignedMin().uge(C1V)) ||
6375 (Opcode == ISD::SMAX && Range.getSignedMax().sle(C1V)) ||
6376 (Opcode == ISD::SMIN && Range.getSignedMin().sge(C1V))) {
6377 return N1;
6378 }
6379 }
6380 }
6381
6382 // Simplify the operands using demanded-bits information.
6384 return SDValue(N, 0);
6385
6386 return SDValue();
6387}
6388
6389/// If this is a bitwise logic instruction and both operands have the same
6390/// opcode, try to sink the other opcode after the logic instruction.
6391SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
6392 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
6393 EVT VT = N0.getValueType();
6394 unsigned LogicOpcode = N->getOpcode();
6395 unsigned HandOpcode = N0.getOpcode();
6396 assert(ISD::isBitwiseLogicOp(LogicOpcode) && "Expected logic opcode");
6397 assert(HandOpcode == N1.getOpcode() && "Bad input!");
6398
6399 // Bail early if none of these transforms apply.
6400 if (N0.getNumOperands() == 0)
6401 return SDValue();
6402
6403 // FIXME: We should check number of uses of the operands to not increase
6404 // the instruction count for all transforms.
6405
6406 // Handle size-changing casts (or sign_extend_inreg).
6407 SDValue X = N0.getOperand(0);
6408 SDValue Y = N1.getOperand(0);
6409 EVT XVT = X.getValueType();
6410 SDLoc DL(N);
6411 if (ISD::isExtOpcode(HandOpcode) || ISD::isExtVecInRegOpcode(HandOpcode) ||
6412 (HandOpcode == ISD::SIGN_EXTEND_INREG &&
6413 N0.getOperand(1) == N1.getOperand(1))) {
6414 // If both operands have other uses, this transform would create extra
6415 // instructions without eliminating anything.
6416 if (!N0.hasOneUse() && !N1.hasOneUse())
6417 return SDValue();
6418 // We need matching integer source types.
6419 if (XVT != Y.getValueType())
6420 return SDValue();
6421 // Don't create an illegal op during or after legalization. Don't ever
6422 // create an unsupported vector op.
6423 if ((VT.isVector() || LegalOperations) &&
6424 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
6425 return SDValue();
6426 // Avoid infinite looping with PromoteIntBinOp.
6427 // TODO: Should we apply desirable/legal constraints to all opcodes?
6428 if ((HandOpcode == ISD::ANY_EXTEND ||
6429 HandOpcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
6430 LegalTypes && !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
6431 return SDValue();
6432 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
6433 SDNodeFlags LogicFlags;
6434 LogicFlags.setDisjoint(N->getFlags().hasDisjoint() &&
6435 ISD::isExtOpcode(HandOpcode));
6436 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y, LogicFlags);
6437 if (HandOpcode == ISD::SIGN_EXTEND_INREG)
6438 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6439 return DAG.getNode(HandOpcode, DL, VT, Logic);
6440 }
6441
6442 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
6443 if (HandOpcode == ISD::TRUNCATE) {
6444 // If both operands have other uses, this transform would create extra
6445 // instructions without eliminating anything.
6446 if (!N0.hasOneUse() && !N1.hasOneUse())
6447 return SDValue();
6448 // We need matching source types.
6449 if (XVT != Y.getValueType())
6450 return SDValue();
6451 // Don't create an illegal op during or after legalization.
6452 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
6453 return SDValue();
6454 // Be extra careful sinking truncate. If it's free, there's no benefit in
6455 // widening a binop. Also, don't create a logic op on an illegal type.
6456 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
6457 return SDValue();
6458 if (!TLI.isTypeLegal(XVT))
6459 return SDValue();
6460 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6461 return DAG.getNode(HandOpcode, DL, VT, Logic);
6462 }
6463
6464 // For binops SHL/SRL/SRA/AND:
6465 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
6466 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
6467 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
6468 N0.getOperand(1) == N1.getOperand(1)) {
6469 // If either operand has other uses, this transform is not an improvement.
6470 if (!N0.hasOneUse() || !N1.hasOneUse())
6471 return SDValue();
6472 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6473 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6474 }
6475
6476 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
6477 if (HandOpcode == ISD::BSWAP) {
6478 // If either operand has other uses, this transform is not an improvement.
6479 if (!N0.hasOneUse() || !N1.hasOneUse())
6480 return SDValue();
6481 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6482 return DAG.getNode(HandOpcode, DL, VT, Logic);
6483 }
6484
6485 // For funnel shifts FSHL/FSHR:
6486 // logic_op (OP x, x1, s), (OP y, y1, s) -->
6487 // --> OP (logic_op x, y), (logic_op, x1, y1), s
6488 if ((HandOpcode == ISD::FSHL || HandOpcode == ISD::FSHR) &&
6489 N0.getOperand(2) == N1.getOperand(2)) {
6490 if (!N0.hasOneUse() || !N1.hasOneUse())
6491 return SDValue();
6492 SDValue X1 = N0.getOperand(1);
6493 SDValue Y1 = N1.getOperand(1);
6494 SDValue S = N0.getOperand(2);
6495 SDValue Logic0 = DAG.getNode(LogicOpcode, DL, VT, X, Y);
6496 SDValue Logic1 = DAG.getNode(LogicOpcode, DL, VT, X1, Y1);
6497 return DAG.getNode(HandOpcode, DL, VT, Logic0, Logic1, S);
6498 }
6499
6500 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
6501 // Only perform this optimization up until type legalization, before
6502 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
6503 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
6504 // we don't want to undo this promotion.
6505 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
6506 // on scalars.
6507 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
6508 Level <= AfterLegalizeTypes) {
6509 // Input types must be integer and the same.
6510 if (XVT.isInteger() && XVT == Y.getValueType() &&
6511 !(VT.isVector() && TLI.isTypeLegal(VT) &&
6512 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
6513 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6514 return DAG.getNode(HandOpcode, DL, VT, Logic);
6515 }
6516 }
6517
6518 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
6519 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
6520 // If both shuffles use the same mask, and both shuffle within a single
6521 // vector, then it is worthwhile to move the swizzle after the operation.
6522 // The type-legalizer generates this pattern when loading illegal
6523 // vector types from memory. In many cases this allows additional shuffle
6524 // optimizations.
6525 // There are other cases where moving the shuffle after the xor/and/or
6526 // is profitable even if shuffles don't perform a swizzle.
6527 // If both shuffles use the same mask, and both shuffles have the same first
6528 // or second operand, then it might still be profitable to move the shuffle
6529 // after the xor/and/or operation.
6530 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
6531 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
6532 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
6533 assert(X.getValueType() == Y.getValueType() &&
6534 "Inputs to shuffles are not the same type");
6535
6536 // Check that both shuffles use the same mask. The masks are known to be of
6537 // the same length because the result vector type is the same.
6538 // Check also that shuffles have only one use to avoid introducing extra
6539 // instructions.
6540 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
6541 !SVN0->getMask().equals(SVN1->getMask()))
6542 return SDValue();
6543
6544 // Don't try to fold this node if it requires introducing a
6545 // build vector of all zeros that might be illegal at this stage.
6546 SDValue ShOp = N0.getOperand(1);
6547 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6548 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6549
6550 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
6551 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
6552 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
6553 N0.getOperand(0), N1.getOperand(0));
6554 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
6555 }
6556
6557 // Don't try to fold this node if it requires introducing a
6558 // build vector of all zeros that might be illegal at this stage.
6559 ShOp = N0.getOperand(0);
6560 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6561 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6562
6563 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
6564 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
6565 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
6566 N1.getOperand(1));
6567 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
6568 }
6569 }
6570
6571 return SDValue();
6572}
6573
6574/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
6575SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
6576 const SDLoc &DL) {
6577 SDValue LL, LR, RL, RR, N0CC, N1CC;
6578 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
6579 !isSetCCEquivalent(N1, RL, RR, N1CC))
6580 return SDValue();
6581
6582 assert(N0.getValueType() == N1.getValueType() &&
6583 "Unexpected operand types for bitwise logic op");
6584 assert(LL.getValueType() == LR.getValueType() &&
6585 RL.getValueType() == RR.getValueType() &&
6586 "Unexpected operand types for setcc");
6587
6588 // If we're here post-legalization or the logic op type is not i1, the logic
6589 // op type must match a setcc result type. Also, all folds require new
6590 // operations on the left and right operands, so those types must match.
6591 EVT VT = N0.getValueType();
6592 EVT OpVT = LL.getValueType();
6593 if (LegalOperations || VT.getScalarType() != MVT::i1)
6594 if (VT != getSetCCResultType(OpVT))
6595 return SDValue();
6596 if (OpVT != RL.getValueType())
6597 return SDValue();
6598
6599 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
6600 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
6601 bool IsInteger = OpVT.isInteger();
6602 if (LR == RR && CC0 == CC1 && IsInteger) {
6603 bool IsZero = isNullOrNullSplat(LR);
6604 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
6605
6606 // All bits clear?
6607 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
6608 // All sign bits clear?
6609 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
6610 // Any bits set?
6611 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
6612 // Any sign bits set?
6613 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
6614
6615 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
6616 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
6617 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
6618 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
6619 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
6620 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
6621 AddToWorklist(Or.getNode());
6622 return DAG.getSetCC(DL, VT, Or, LR, CC1);
6623 }
6624
6625 // All bits set?
6626 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
6627 // All sign bits set?
6628 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
6629 // Any bits clear?
6630 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
6631 // Any sign bits clear?
6632 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
6633
6634 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
6635 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
6636 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
6637 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
6638 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
6639 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
6640 AddToWorklist(And.getNode());
6641 return DAG.getSetCC(DL, VT, And, LR, CC1);
6642 }
6643 }
6644
6645 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
6646 // (or (seteq X, 0), (seteq X, -1)) --> (setult (add X, 1), 2)
6647 if (LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && IsInteger &&
6648 ((IsAnd && CC0 == ISD::SETNE) || (!IsAnd && CC0 == ISD::SETEQ)) &&
6649 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
6650 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
6651 SDValue One = DAG.getConstant(1, DL, OpVT);
6652 SDValue Two = DAG.getConstant(2, DL, OpVT);
6653 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
6654 AddToWorklist(Add.getNode());
6655 return DAG.getSetCC(DL, VT, Add, Two, IsAnd ? ISD::SETUGE : ISD::SETULT);
6656 }
6657
6658 // Try more general transforms if the predicates match and the only user of
6659 // the compares is the 'and' or 'or'.
6660 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
6661 N0.hasOneUse() && N1.hasOneUse()) {
6662 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
6663 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
6664 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
6665 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
6666 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
6667 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
6668 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6669 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
6670 }
6671
6672 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
6673 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
6674 // Match a shared variable operand and 2 non-opaque constant operands.
6675 auto MatchDiffPow2 = [&](ConstantSDNode *C0, ConstantSDNode *C1) {
6676 // The difference of the constants must be a single bit.
6677 const APInt &CMax =
6678 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
6679 const APInt &CMin =
6680 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
6681 return !C0->isOpaque() && !C1->isOpaque() && (CMax - CMin).isPowerOf2();
6682 };
6683 if (LL == RL && ISD::matchBinaryPredicate(LR, RR, MatchDiffPow2)) {
6684 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
6685 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
6686 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
6687 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
6688 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
6689 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
6690 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
6691 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
6692 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6693 return DAG.getSetCC(DL, VT, And, Zero, CC0);
6694 }
6695 }
6696 }
6697
6698 // Canonicalize equivalent operands to LL == RL.
6699 if (LL == RR && LR == RL) {
6701 std::swap(RL, RR);
6702 }
6703
6704 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6705 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6706 if (LL == RL && LR == RR) {
6707 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
6708 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
6709 if (NewCC != ISD::SETCC_INVALID &&
6710 (!LegalOperations ||
6711 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
6712 TLI.isOperationLegal(ISD::SETCC, OpVT))))
6713 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
6714 }
6715
6716 return SDValue();
6717}
6718
6719static bool arebothOperandsNotSNan(SDValue Operand1, SDValue Operand2,
6720 SelectionDAG &DAG) {
6721 return DAG.isKnownNeverSNaN(Operand2) && DAG.isKnownNeverSNaN(Operand1);
6722}
6723
6724static bool arebothOperandsNotNan(SDValue Operand1, SDValue Operand2,
6725 SelectionDAG &DAG) {
6726 return DAG.isKnownNeverNaN(Operand2) && DAG.isKnownNeverNaN(Operand1);
6727}
6728
6729/// Returns an appropriate FP min/max opcode for clamping operations.
6730static unsigned getMinMaxOpcodeForClamp(bool IsMin, SDValue Operand1,
6731 SDValue Operand2, SelectionDAG &DAG,
6732 const TargetLowering &TLI) {
6733 EVT VT = Operand1.getValueType();
6734 unsigned IEEEOp = IsMin ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6735 if (TLI.isOperationLegalOrCustom(IEEEOp, VT) &&
6736 arebothOperandsNotNan(Operand1, Operand2, DAG))
6737 return IEEEOp;
6738 unsigned PreferredOp = IsMin ? ISD::FMINNUM : ISD::FMAXNUM;
6739 if (TLI.isOperationLegalOrCustom(PreferredOp, VT))
6740 return PreferredOp;
6741 return ISD::DELETED_NODE;
6742}
6743
6744// FIXME: use FMINIMUMNUM if possible, such as for RISC-V.
6746 SDValue Operand1, SDValue Operand2, bool SetCCNoNaNs, ISD::CondCode CC,
6747 unsigned OrAndOpcode, SelectionDAG &DAG, bool isFMAXNUMFMINNUM_IEEE,
6748 bool isFMAXNUMFMINNUM) {
6749 // The optimization cannot be applied for all the predicates because
6750 // of the way FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle
6751 // NaNs. For FMINNUM_IEEE/FMAXNUM_IEEE, the optimization cannot be
6752 // applied at all if one of the operands is a signaling NaN.
6753
6754 // It is safe to use FMINNUM_IEEE/FMAXNUM_IEEE if all the operands
6755 // are non NaN values.
6756 if (((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::OR)) ||
6757 ((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::AND))) {
6758 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6759 isFMAXNUMFMINNUM_IEEE
6762 }
6763
6764 if (((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::OR)) ||
6765 ((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::AND))) {
6766 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6767 isFMAXNUMFMINNUM_IEEE
6770 }
6771
6772 // Both FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle quiet
6773 // NaNs in the same way. But, FMINNUM/FMAXNUM and FMINNUM_IEEE/
6774 // FMAXNUM_IEEE handle signaling NaNs differently. If we cannot prove
6775 // that there are not any sNaNs, then the optimization is not valid
6776 // for FMINNUM_IEEE/FMAXNUM_IEEE. In the presence of sNaNs, we apply
6777 // the optimization using FMINNUM/FMAXNUM for the following cases. If
6778 // we can prove that we do not have any sNaNs, then we can do the
6779 // optimization using FMINNUM_IEEE/FMAXNUM_IEEE for the following
6780 // cases.
6781 if (((CC == ISD::SETOLT || CC == ISD::SETOLE) && (OrAndOpcode == ISD::OR)) ||
6782 ((CC == ISD::SETUGT || CC == ISD::SETUGE) && (OrAndOpcode == ISD::AND))) {
6783 return isFMAXNUMFMINNUM ? ISD::FMINNUM
6784 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6785 isFMAXNUMFMINNUM_IEEE
6788 }
6789
6790 if (((CC == ISD::SETOGT || CC == ISD::SETOGE) && (OrAndOpcode == ISD::OR)) ||
6791 ((CC == ISD::SETULT || CC == ISD::SETULE) && (OrAndOpcode == ISD::AND))) {
6792 return isFMAXNUMFMINNUM ? ISD::FMAXNUM
6793 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6794 isFMAXNUMFMINNUM_IEEE
6797 }
6798
6799 return ISD::DELETED_NODE;
6800}
6801
6804 assert(
6805 (LogicOp->getOpcode() == ISD::AND || LogicOp->getOpcode() == ISD::OR) &&
6806 "Invalid Op to combine SETCC with");
6807
6808 // TODO: Search past casts/truncates.
6809 SDValue LHS = LogicOp->getOperand(0);
6810 SDValue RHS = LogicOp->getOperand(1);
6811 if (LHS->getOpcode() != ISD::SETCC || RHS->getOpcode() != ISD::SETCC ||
6812 !LHS->hasOneUse() || !RHS->hasOneUse())
6813 return SDValue();
6814
6815 SDNodeFlags LHSSetCCFlags = LHS->getFlags();
6816 SDNodeFlags RHSSetCCFlags = RHS->getFlags();
6817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6819 LogicOp, LHS.getNode(), RHS.getNode());
6820
6821 SDValue LHS0 = LHS->getOperand(0);
6822 SDValue RHS0 = RHS->getOperand(0);
6823 SDValue LHS1 = LHS->getOperand(1);
6824 SDValue RHS1 = RHS->getOperand(1);
6825 // TODO: We don't actually need a splat here, for vectors we just need the
6826 // invariants to hold for each element.
6827 auto *LHS1C = isConstOrConstSplat(LHS1);
6828 auto *RHS1C = isConstOrConstSplat(RHS1);
6829 ISD::CondCode CCL = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6830 ISD::CondCode CCR = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6831 EVT VT = LogicOp->getValueType(0);
6832 EVT OpVT = LHS0.getValueType();
6833 SDLoc DL(LogicOp);
6834
6835 // Check if the operands of an and/or operation are comparisons and if they
6836 // compare against the same value. Replace the and/or-cmp-cmp sequence with
6837 // min/max cmp sequence. If LHS1 is equal to RHS1, then the or-cmp-cmp
6838 // sequence will be replaced with min-cmp sequence:
6839 // (LHS0 < LHS1) | (RHS0 < RHS1) -> min(LHS0, RHS0) < LHS1
6840 // and and-cmp-cmp will be replaced with max-cmp sequence:
6841 // (LHS0 < LHS1) & (RHS0 < RHS1) -> max(LHS0, RHS0) < LHS1
6842 // The optimization does not work for `==` or `!=` .
6843 // The two comparisons should have either the same predicate or the
6844 // predicate of one of the comparisons is the opposite of the other one.
6845 bool isFMAXNUMFMINNUM_IEEE = TLI.isOperationLegal(ISD::FMAXNUM_IEEE, OpVT) &&
6847 bool isFMAXNUMFMINNUM = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, OpVT) &&
6849 if (((OpVT.isInteger() && TLI.isOperationLegal(ISD::UMAX, OpVT) &&
6850 TLI.isOperationLegal(ISD::SMAX, OpVT) &&
6851 TLI.isOperationLegal(ISD::UMIN, OpVT) &&
6852 TLI.isOperationLegal(ISD::SMIN, OpVT)) ||
6853 (OpVT.isFloatingPoint() &&
6854 (isFMAXNUMFMINNUM_IEEE || isFMAXNUMFMINNUM))) &&
6856 CCL != ISD::SETFALSE && CCL != ISD::SETO && CCL != ISD::SETUO &&
6857 CCL != ISD::SETTRUE &&
6858 (CCL == CCR || CCL == ISD::getSetCCSwappedOperands(CCR))) {
6859
6860 SDValue CommonValue, Operand1, Operand2;
6862 if (CCL == CCR) {
6863 if (LHS0 == RHS0) {
6864 CommonValue = LHS0;
6865 Operand1 = LHS1;
6866 Operand2 = RHS1;
6868 } else if (LHS1 == RHS1) {
6869 CommonValue = LHS1;
6870 Operand1 = LHS0;
6871 Operand2 = RHS0;
6872 CC = CCL;
6873 }
6874 } else {
6875 assert(CCL == ISD::getSetCCSwappedOperands(CCR) && "Unexpected CC");
6876 if (LHS0 == RHS1) {
6877 CommonValue = LHS0;
6878 Operand1 = LHS1;
6879 Operand2 = RHS0;
6880 CC = CCR;
6881 } else if (RHS0 == LHS1) {
6882 CommonValue = LHS1;
6883 Operand1 = LHS0;
6884 Operand2 = RHS1;
6885 CC = CCL;
6886 }
6887 }
6888
6889 // Don't do this transform for sign bit tests. Let foldLogicOfSetCCs
6890 // handle it using OR/AND.
6891 if (CC == ISD::SETLT && isNullOrNullSplat(CommonValue))
6892 CC = ISD::SETCC_INVALID;
6893 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CommonValue))
6894 CC = ISD::SETCC_INVALID;
6895
6896 if (CC != ISD::SETCC_INVALID) {
6897 unsigned NewOpcode = ISD::DELETED_NODE;
6898 bool IsSigned = isSignedIntSetCC(CC);
6899 if (OpVT.isInteger()) {
6900 bool IsLess = (CC == ISD::SETLE || CC == ISD::SETULE ||
6901 CC == ISD::SETLT || CC == ISD::SETULT);
6902 bool IsOr = (LogicOp->getOpcode() == ISD::OR);
6903 if (IsLess == IsOr)
6904 NewOpcode = IsSigned ? ISD::SMIN : ISD::UMIN;
6905 else
6906 NewOpcode = IsSigned ? ISD::SMAX : ISD::UMAX;
6907 } else if (OpVT.isFloatingPoint())
6909 Operand1, Operand2,
6910 LHSSetCCFlags.hasNoNaNs() && RHSSetCCFlags.hasNoNaNs(), CC,
6911 LogicOp->getOpcode(), DAG, isFMAXNUMFMINNUM_IEEE, isFMAXNUMFMINNUM);
6912
6913 if (NewOpcode != ISD::DELETED_NODE) {
6914 // Propagate fast-math flags from setcc.
6915 SDNodeFlags Flags = LHS->getFlags() & RHS->getFlags();
6916 SDValue MinMaxValue =
6917 DAG.getNode(NewOpcode, DL, OpVT, Operand1, Operand2, Flags);
6918 return DAG.getSetCC(DL, VT, MinMaxValue, CommonValue, CC, /*Chain=*/{},
6919 /*IsSignaling=*/false, Flags);
6920 }
6921 }
6922 }
6923
6924 if (LHS0 == LHS1 && RHS0 == RHS1 && CCL == CCR &&
6925 LHS0.getValueType() == RHS0.getValueType() &&
6926 ((LogicOp->getOpcode() == ISD::AND && CCL == ISD::SETO) ||
6927 (LogicOp->getOpcode() == ISD::OR && CCL == ISD::SETUO)))
6928 return DAG.getSetCC(DL, VT, LHS0, RHS0, CCL);
6929
6930 if (TargetPreference == AndOrSETCCFoldKind::None)
6931 return SDValue();
6932
6933 if (CCL == CCR &&
6934 CCL == (LogicOp->getOpcode() == ISD::AND ? ISD::SETNE : ISD::SETEQ) &&
6935 LHS0 == RHS0 && LHS1C && RHS1C && OpVT.isInteger()) {
6936 const APInt &APLhs = LHS1C->getAPIntValue();
6937 const APInt &APRhs = RHS1C->getAPIntValue();
6938
6939 // Preference is to use ISD::ABS or we already have an ISD::ABS (in which
6940 // case this is just a compare).
6941 if (APLhs == (-APRhs) &&
6942 ((TargetPreference & AndOrSETCCFoldKind::ABS) ||
6943 DAG.doesNodeExist(ISD::ABS, DAG.getVTList(OpVT), {LHS0}))) {
6944 const APInt &C = APLhs.isNegative() ? APRhs : APLhs;
6945 // (icmp eq A, C) | (icmp eq A, -C)
6946 // -> (icmp eq Abs(A), C)
6947 // (icmp ne A, C) & (icmp ne A, -C)
6948 // -> (icmp ne Abs(A), C)
6949 SDValue AbsOp = DAG.getNode(ISD::ABS, DL, OpVT, LHS0);
6950 return DAG.getNode(ISD::SETCC, DL, VT, AbsOp,
6951 DAG.getConstant(C, DL, OpVT), LHS.getOperand(2));
6952 } else if (TargetPreference &
6954
6955 // AndOrSETCCFoldKind::AddAnd:
6956 // A == C0 | A == C1
6957 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
6958 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) == 0
6959 // A != C0 & A != C1
6960 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
6961 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) != 0
6962
6963 // AndOrSETCCFoldKind::NotAnd:
6964 // A == C0 | A == C1
6965 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
6966 // -> ~A & smin(C0, C1) == 0
6967 // A != C0 & A != C1
6968 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
6969 // -> ~A & smin(C0, C1) != 0
6970
6971 const APInt &MaxC = APIntOps::smax(APRhs, APLhs);
6972 const APInt &MinC = APIntOps::smin(APRhs, APLhs);
6973 APInt Dif = MaxC - MinC;
6974 if (!Dif.isZero() && Dif.isPowerOf2()) {
6975 if (MaxC.isAllOnes() &&
6976 (TargetPreference & AndOrSETCCFoldKind::NotAnd)) {
6977 SDValue NotOp = DAG.getNOT(DL, LHS0, OpVT);
6978 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, NotOp,
6979 DAG.getConstant(MinC, DL, OpVT));
6980 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
6981 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
6982 } else if (TargetPreference & AndOrSETCCFoldKind::AddAnd) {
6983
6984 SDValue AddOp = DAG.getNode(ISD::ADD, DL, OpVT, LHS0,
6985 DAG.getConstant(-MinC, DL, OpVT));
6986 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, AddOp,
6987 DAG.getConstant(~Dif, DL, OpVT));
6988 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
6989 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
6990 }
6991 }
6992 }
6993 }
6994
6995 return SDValue();
6996}
6997
6998// Combine `(select c, (X & 1), 0)` -> `(and (zext c), X)`.
6999// We canonicalize to the `select` form in the middle end, but the `and` form
7000// gets better codegen and all tested targets (arm, x86, riscv)
7002 const SDLoc &DL, SelectionDAG &DAG) {
7003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7004 if (!isNullConstant(F))
7005 return SDValue();
7006
7007 EVT CondVT = Cond.getValueType();
7008 if (TLI.getBooleanContents(CondVT) !=
7010 return SDValue();
7011
7012 if (T.getOpcode() != ISD::AND)
7013 return SDValue();
7014
7015 if (!isOneConstant(T.getOperand(1)))
7016 return SDValue();
7017
7018 EVT OpVT = T.getValueType();
7019
7020 SDValue CondMask =
7021 OpVT == CondVT ? Cond : DAG.getBoolExtOrTrunc(Cond, DL, OpVT, CondVT);
7022 return DAG.getNode(ISD::AND, DL, OpVT, CondMask, T.getOperand(0));
7023}
7024
7025/// This contains all DAGCombine rules which reduce two values combined by
7026/// an And operation to a single value. This makes them reusable in the context
7027/// of visitSELECT(). Rules involving constants are not included as
7028/// visitSELECT() already handles those cases.
7029SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
7030 EVT VT = N1.getValueType();
7031 SDLoc DL(N);
7032
7033 // fold (and x, undef) -> 0
7034 if (N0.isUndef() || N1.isUndef())
7035 return DAG.getConstant(0, DL, VT);
7036
7037 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
7038 return V;
7039
7040 // Canonicalize:
7041 // and(x, add) -> and(add, x)
7042 if (N1.getOpcode() == ISD::ADD)
7043 std::swap(N0, N1);
7044
7045 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
7046 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
7047 VT.isScalarInteger() && VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
7048 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7049 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
7050 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
7051 // immediate for an add, but it is legal if its top c2 bits are set,
7052 // transform the ADD so the immediate doesn't need to be materialized
7053 // in a register.
7054 APInt ADDC = ADDI->getAPIntValue();
7055 APInt SRLC = SRLI->getAPIntValue();
7056 if (ADDC.getSignificantBits() <= 64 && SRLC.ult(VT.getSizeInBits()) &&
7057 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7059 SRLC.getZExtValue());
7060 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
7061 ADDC |= Mask;
7062 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7063 SDLoc DL0(N0);
7064 SDValue NewAdd =
7065 DAG.getNode(ISD::ADD, DL0, VT,
7066 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
7067 CombineTo(N0.getNode(), NewAdd);
7068 // Return N so it doesn't get rechecked!
7069 return SDValue(N, 0);
7070 }
7071 }
7072 }
7073 }
7074 }
7075 }
7076
7077 return SDValue();
7078}
7079
7080bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
7081 EVT LoadResultTy, EVT &ExtVT) {
7082 if (!AndC->getAPIntValue().isMask())
7083 return false;
7084
7085 unsigned ActiveBits = AndC->getAPIntValue().countr_one();
7086
7087 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7088 EVT LoadedVT = LoadN->getMemoryVT();
7089
7090 if (ExtVT == LoadedVT &&
7091 (!LegalOperations ||
7092 TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7093 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))) {
7094 // ZEXTLOAD will match without needing to change the size of the value being
7095 // loaded.
7096 return true;
7097 }
7098
7099 // Do not change the width of a volatile or atomic loads.
7100 if (!LoadN->isSimple())
7101 return false;
7102
7103 // Do not generate loads of non-round integer types since these can
7104 // be expensive (and would be wrong if the type is not byte sized).
7105 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
7106 return false;
7107
7108 if (LegalOperations &&
7109 !TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7110 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))
7111 return false;
7112
7113 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT, /*ByteOffset=*/0))
7114 return false;
7115
7116 return true;
7117}
7118
7119bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
7120 ISD::LoadExtType ExtType, EVT &MemVT,
7121 unsigned ShAmt) {
7122 if (!LDST)
7123 return false;
7124
7125 // Only allow byte offsets.
7126 if (ShAmt % 8)
7127 return false;
7128 const unsigned ByteShAmt = ShAmt / 8;
7129
7130 // Do not generate loads of non-round integer types since these can
7131 // be expensive (and would be wrong if the type is not byte sized).
7132 if (!MemVT.isRound())
7133 return false;
7134
7135 // Don't change the width of a volatile or atomic loads.
7136 if (!LDST->isSimple())
7137 return false;
7138
7139 EVT LdStMemVT = LDST->getMemoryVT();
7140
7141 // Bail out when changing the scalable property, since we can't be sure that
7142 // we're actually narrowing here.
7143 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
7144 return false;
7145
7146 // Verify that we are actually reducing a load width here.
7147 if (LdStMemVT.bitsLT(MemVT))
7148 return false;
7149
7150 // Ensure that this isn't going to produce an unsupported memory access.
7151 if (ShAmt) {
7152 const Align LDSTAlign = LDST->getAlign();
7153 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
7154 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7155 LDST->getAddressSpace(), NarrowAlign,
7156 LDST->getMemOperand()->getFlags()))
7157 return false;
7158 }
7159
7160 // It's not possible to generate a constant of extended or untyped type.
7161 EVT PtrType = LDST->getBasePtr().getValueType();
7162 if (PtrType == MVT::Untyped || PtrType.isExtended())
7163 return false;
7164
7165 if (isa<LoadSDNode>(LDST)) {
7166 LoadSDNode *Load = cast<LoadSDNode>(LDST);
7167 // Don't transform one with multiple uses, this would require adding a new
7168 // load.
7169 if (!SDValue(Load, 0).hasOneUse())
7170 return false;
7171
7172 if (LegalOperations &&
7173 !TLI.isLoadLegal(Load->getValueType(0), MemVT, Load->getAlign(),
7174 Load->getAddressSpace(), ExtType, false))
7175 return false;
7176
7177 // For the transform to be legal, the load must produce only two values
7178 // (the value loaded and the chain). Don't transform a pre-increment
7179 // load, for example, which produces an extra value. Otherwise the
7180 // transformation is not equivalent, and the downstream logic to replace
7181 // uses gets things wrong.
7182 if (Load->getNumValues() > 2)
7183 return false;
7184
7185 // If the load that we're shrinking is an extload and we're not just
7186 // discarding the extension we can't simply shrink the load. Bail.
7187 // TODO: It would be possible to merge the extensions in some cases.
7188 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
7189 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7190 return false;
7191
7192 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT, ByteShAmt))
7193 return false;
7194 } else {
7195 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
7196 StoreSDNode *Store = cast<StoreSDNode>(LDST);
7197 // Can't write outside the original store
7198 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7199 return false;
7200
7201 if (LegalOperations &&
7202 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT,
7203 Store->getAlign(), Store->getAddressSpace()))
7204 return false;
7205 }
7206 return true;
7207}
7208
7209bool DAGCombiner::SearchForAndLoads(SDNode *N,
7210 SmallVectorImpl<LoadSDNode*> &Loads,
7211 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
7212 ConstantSDNode *Mask,
7213 SDNode *&NodeToMask) {
7214 // Recursively search for the operands, looking for loads which can be
7215 // narrowed.
7216 for (SDValue Op : N->op_values()) {
7217 if (Op.getValueType().isVector())
7218 return false;
7219
7220 // Some constants may need fixing up later if they are too large.
7221 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7222 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
7223 "Expected bitwise logic operation");
7224 if (!C->getAPIntValue().isSubsetOf(Mask->getAPIntValue()))
7225 NodesWithConsts.insert(N);
7226 continue;
7227 }
7228
7229 if (!Op.hasOneUse())
7230 return false;
7231
7232 switch(Op.getOpcode()) {
7233 case ISD::LOAD: {
7234 auto *Load = cast<LoadSDNode>(Op);
7235 EVT ExtVT;
7236 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
7237 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
7238
7239 // ZEXTLOAD is already small enough.
7240 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
7241 ExtVT.bitsGE(Load->getMemoryVT()))
7242 continue;
7243
7244 // Use LE to convert equal sized loads to zext.
7245 if (ExtVT.bitsLE(Load->getMemoryVT()))
7246 Loads.push_back(Load);
7247
7248 continue;
7249 }
7250 return false;
7251 }
7252 case ISD::ZERO_EXTEND:
7253 case ISD::AssertZext: {
7254 unsigned ActiveBits = Mask->getAPIntValue().countr_one();
7255 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7256 EVT VT = Op.getOpcode() == ISD::AssertZext ?
7257 cast<VTSDNode>(Op.getOperand(1))->getVT() :
7258 Op.getOperand(0).getValueType();
7259
7260 // We can accept extending nodes if the mask is wider or an equal
7261 // width to the original type.
7262 if (ExtVT.bitsGE(VT))
7263 continue;
7264 break;
7265 }
7266 case ISD::OR:
7267 case ISD::XOR:
7268 case ISD::AND:
7269 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
7270 NodeToMask))
7271 return false;
7272 continue;
7273 }
7274
7275 // Allow one node which will masked along with any loads found.
7276 if (NodeToMask)
7277 return false;
7278
7279 // Also ensure that the node to be masked only produces one data result.
7280 NodeToMask = Op.getNode();
7281 if (NodeToMask->getNumValues() > 1) {
7282 bool HasValue = false;
7283 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
7284 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
7285 if (VT != MVT::Glue && VT != MVT::Other) {
7286 if (HasValue) {
7287 NodeToMask = nullptr;
7288 return false;
7289 }
7290 HasValue = true;
7291 }
7292 }
7293 assert(HasValue && "Node to be masked has no data result?");
7294 }
7295 }
7296 return true;
7297}
7298
7299bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
7300 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
7301 if (!Mask)
7302 return false;
7303
7304 if (!Mask->getAPIntValue().isMask())
7305 return false;
7306
7307 // No need to do anything if the and directly uses a load.
7308 if (isa<LoadSDNode>(N->getOperand(0)))
7309 return false;
7310
7312 SmallPtrSet<SDNode*, 2> NodesWithConsts;
7313 SDNode *FixupNode = nullptr;
7314 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
7315 if (Loads.empty())
7316 return false;
7317
7318 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
7319 SDValue MaskOp = N->getOperand(1);
7320
7321 // If it exists, fixup the single node we allow in the tree that needs
7322 // masking.
7323 if (FixupNode) {
7324 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
7325 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
7326 FixupNode->getValueType(0),
7327 SDValue(FixupNode, 0), MaskOp);
7328 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
7329 if (And.getOpcode() == ISD ::AND)
7330 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
7331 }
7332
7333 // Narrow any constants that need it.
7334 for (auto *LogicN : NodesWithConsts) {
7335 SDValue Op0 = LogicN->getOperand(0);
7336 SDValue Op1 = LogicN->getOperand(1);
7337
7338 // We only need to fix AND if both inputs are constants. And we only need
7339 // to fix one of the constants.
7340 if (LogicN->getOpcode() == ISD::AND &&
7342 continue;
7343
7344 if (isa<ConstantSDNode>(Op0) && LogicN->getOpcode() != ISD::AND)
7345 Op0 =
7346 DAG.getNode(ISD::AND, SDLoc(Op0), Op0.getValueType(), Op0, MaskOp);
7347
7348 if (isa<ConstantSDNode>(Op1))
7349 Op1 =
7350 DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), Op1, MaskOp);
7351
7352 if (isa<ConstantSDNode>(Op0) && !isa<ConstantSDNode>(Op1))
7353 std::swap(Op0, Op1);
7354
7355 DAG.UpdateNodeOperands(LogicN, Op0, Op1);
7356 }
7357
7358 // Create narrow loads.
7359 for (auto *Load : Loads) {
7360 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
7361 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
7362 SDValue(Load, 0), MaskOp);
7363 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
7364 if (And.getOpcode() == ISD ::AND)
7365 And = SDValue(
7366 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
7367 SDValue NewLoad = reduceLoadWidth(And.getNode());
7368 assert(NewLoad &&
7369 "Shouldn't be masking the load if it can't be narrowed");
7370 CombineTo(Load, NewLoad, NewLoad.getValue(1));
7371 }
7372 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
7373 return true;
7374 }
7375 return false;
7376}
7377
7378// Unfold
7379// x & (-1 'logical shift' y)
7380// To
7381// (x 'opposite logical shift' y) 'logical shift' y
7382// if it is better for performance.
7383SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
7384 assert(N->getOpcode() == ISD::AND);
7385
7386 SDValue N0 = N->getOperand(0);
7387 SDValue N1 = N->getOperand(1);
7388
7389 // Do we actually prefer shifts over mask?
7391 return SDValue();
7392
7393 // Try to match (-1 '[outer] logical shift' y)
7394 unsigned OuterShift;
7395 unsigned InnerShift; // The opposite direction to the OuterShift.
7396 SDValue Y; // Shift amount.
7397 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
7398 if (!M.hasOneUse())
7399 return false;
7400 OuterShift = M->getOpcode();
7401 if (OuterShift == ISD::SHL)
7402 InnerShift = ISD::SRL;
7403 else if (OuterShift == ISD::SRL)
7404 InnerShift = ISD::SHL;
7405 else
7406 return false;
7407 if (!isAllOnesConstant(M->getOperand(0)))
7408 return false;
7409 Y = M->getOperand(1);
7410 return true;
7411 };
7412
7413 SDValue X;
7414 if (matchMask(N1))
7415 X = N0;
7416 else if (matchMask(N0))
7417 X = N1;
7418 else
7419 return SDValue();
7420
7421 SDLoc DL(N);
7422 EVT VT = N->getValueType(0);
7423
7424 // tmp = x 'opposite logical shift' y
7425 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
7426 // ret = tmp 'logical shift' y
7427 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
7428
7429 return T1;
7430}
7431
7432/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
7433/// For a target with a bit test, this is expected to become test + set and save
7434/// at least 1 instruction.
7436 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
7437
7438 // Look through an optional extension.
7439 SDValue And0 = And->getOperand(0), And1 = And->getOperand(1);
7440 if (And0.getOpcode() == ISD::ANY_EXTEND && And0.hasOneUse())
7441 And0 = And0.getOperand(0);
7442 if (!isOneConstant(And1) || !And0.hasOneUse())
7443 return SDValue();
7444
7445 SDValue Src = And0;
7446
7447 // Attempt to find a 'not' op.
7448 // TODO: Should we favor test+set even without the 'not' op?
7449 bool FoundNot = false;
7450 if (isBitwiseNot(Src)) {
7451 FoundNot = true;
7452 Src = Src.getOperand(0);
7453
7454 // Look though an optional truncation. The source operand may not be the
7455 // same type as the original 'and', but that is ok because we are masking
7456 // off everything but the low bit.
7457 if (Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse())
7458 Src = Src.getOperand(0);
7459 }
7460
7461 // Match a shift-right by constant.
7462 if (Src.getOpcode() != ISD::SRL || !Src.hasOneUse())
7463 return SDValue();
7464
7465 // This is probably not worthwhile without a supported type.
7466 EVT SrcVT = Src.getValueType();
7467 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7468 if (!TLI.isTypeLegal(SrcVT))
7469 return SDValue();
7470
7471 // We might have looked through casts that make this transform invalid.
7472 unsigned BitWidth = SrcVT.getScalarSizeInBits();
7473 SDValue ShiftAmt = Src.getOperand(1);
7474 auto *ShiftAmtC = dyn_cast<ConstantSDNode>(ShiftAmt);
7475 if (!ShiftAmtC || !ShiftAmtC->getAPIntValue().ult(BitWidth))
7476 return SDValue();
7477
7478 // Set source to shift source.
7479 Src = Src.getOperand(0);
7480
7481 // Try again to find a 'not' op.
7482 // TODO: Should we favor test+set even with two 'not' ops?
7483 if (!FoundNot) {
7484 if (!isBitwiseNot(Src))
7485 return SDValue();
7486 Src = Src.getOperand(0);
7487 }
7488
7489 if (!TLI.hasBitTest(Src, ShiftAmt))
7490 return SDValue();
7491
7492 // Turn this into a bit-test pattern using mask op + setcc:
7493 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
7494 // and (srl (not X), C)), 1 --> (and X, 1<<C) == 0
7495 SDLoc DL(And);
7496 SDValue X = DAG.getZExtOrTrunc(Src, DL, SrcVT);
7497 EVT CCVT =
7498 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7499 SDValue Mask = DAG.getConstant(
7500 APInt::getOneBitSet(BitWidth, ShiftAmtC->getZExtValue()), DL, SrcVT);
7501 SDValue NewAnd = DAG.getNode(ISD::AND, DL, SrcVT, X, Mask);
7502 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
7503 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
7504 return DAG.getZExtOrTrunc(Setcc, DL, And->getValueType(0));
7505}
7506
7507/// For targets that support usubsat, match a bit-hack form of that operation
7508/// that ends in 'and' and convert it.
7510 EVT VT = N->getValueType(0);
7511 unsigned BitWidth = VT.getScalarSizeInBits();
7512 APInt SignMask = APInt::getSignMask(BitWidth);
7513
7514 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
7515 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
7516 // xor/add with SMIN (signmask) are logically equivalent.
7517 SDValue X;
7518 if (!sd_match(N, m_And(m_OneUse(m_Xor(m_Value(X), m_SpecificInt(SignMask))),
7520 m_SpecificInt(BitWidth - 1))))) &&
7523 m_SpecificInt(BitWidth - 1))))))
7524 return SDValue();
7525
7526 return DAG.getNode(ISD::USUBSAT, DL, VT, X,
7527 DAG.getConstant(SignMask, DL, VT));
7528}
7529
7530/// Given a bitwise logic operation N with a matching bitwise logic operand,
7531/// fold a pattern where 2 of the source operands are identically shifted
7532/// values. For example:
7533/// ((X0 << Y) | Z) | (X1 << Y) --> ((X0 | X1) << Y) | Z
7535 SelectionDAG &DAG) {
7536 unsigned LogicOpcode = N->getOpcode();
7537 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7538 "Expected bitwise logic operation");
7539
7540 if (!LogicOp.hasOneUse() || !ShiftOp.hasOneUse())
7541 return SDValue();
7542
7543 // Match another bitwise logic op and a shift.
7544 unsigned ShiftOpcode = ShiftOp.getOpcode();
7545 if (LogicOp.getOpcode() != LogicOpcode ||
7546 !(ShiftOpcode == ISD::SHL || ShiftOpcode == ISD::SRL ||
7547 ShiftOpcode == ISD::SRA))
7548 return SDValue();
7549
7550 // Match another shift op inside the first logic operand. Handle both commuted
7551 // possibilities.
7552 // LOGIC (LOGIC (SH X0, Y), Z), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7553 // LOGIC (LOGIC Z, (SH X0, Y)), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7554 SDValue X1 = ShiftOp.getOperand(0);
7555 SDValue Y = ShiftOp.getOperand(1);
7556 SDValue X0, Z;
7557 if (LogicOp.getOperand(0).getOpcode() == ShiftOpcode &&
7558 LogicOp.getOperand(0).getOperand(1) == Y) {
7559 X0 = LogicOp.getOperand(0).getOperand(0);
7560 Z = LogicOp.getOperand(1);
7561 } else if (LogicOp.getOperand(1).getOpcode() == ShiftOpcode &&
7562 LogicOp.getOperand(1).getOperand(1) == Y) {
7563 X0 = LogicOp.getOperand(1).getOperand(0);
7564 Z = LogicOp.getOperand(0);
7565 } else {
7566 return SDValue();
7567 }
7568
7569 EVT VT = N->getValueType(0);
7570 SDLoc DL(N);
7571 SDValue LogicX = DAG.getNode(LogicOpcode, DL, VT, X0, X1);
7572 SDValue NewShift = DAG.getNode(ShiftOpcode, DL, VT, LogicX, Y);
7573 return DAG.getNode(LogicOpcode, DL, VT, NewShift, Z);
7574}
7575
7576/// Given a tree of logic operations with shape like
7577/// (LOGIC (LOGIC (X, Y), LOGIC (Z, Y)))
7578/// try to match and fold shift operations with the same shift amount.
7579/// For example:
7580/// LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W) -->
7581/// --> LOGIC (SH (LOGIC X0, X1), Y), (LOGIC Z, W)
7583 SDValue RightHand, SelectionDAG &DAG) {
7584 unsigned LogicOpcode = N->getOpcode();
7585 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7586 "Expected bitwise logic operation");
7587 if (LeftHand.getOpcode() != LogicOpcode ||
7588 RightHand.getOpcode() != LogicOpcode)
7589 return SDValue();
7590 if (!LeftHand.hasOneUse() || !RightHand.hasOneUse())
7591 return SDValue();
7592
7593 // Try to match one of following patterns:
7594 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W)
7595 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC W, (SH X1, Y))
7596 // Note that foldLogicOfShifts will handle commuted versions of the left hand
7597 // itself.
7598 SDValue CombinedShifts, W;
7599 SDValue R0 = RightHand.getOperand(0);
7600 SDValue R1 = RightHand.getOperand(1);
7601 if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R0, DAG)))
7602 W = R1;
7603 else if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R1, DAG)))
7604 W = R0;
7605 else
7606 return SDValue();
7607
7608 EVT VT = N->getValueType(0);
7609 SDLoc DL(N);
7610 return DAG.getNode(LogicOpcode, DL, VT, CombinedShifts, W);
7611}
7612
7613/// Fold "masked merge" expressions like `(m & x) | (~m & y)` and its DeMorgan
7614/// variant `(~m | x) & (m | y)` into the equivalent `((x ^ y) & m) ^ y)`
7615/// pattern. This is typically a better representation for targets without a
7616/// fused "and-not" operation.
7618 const TargetLowering &TLI, const SDLoc &DL) {
7619 // Note that masked-merge variants using XOR or ADD expressions are
7620 // normalized to OR by InstCombine so we only check for OR or AND.
7621 assert((Node->getOpcode() == ISD::OR || Node->getOpcode() == ISD::AND) &&
7622 "Must be called with ISD::OR or ISD::AND node");
7623
7624 // If the target supports and-not, don't fold this.
7625 if (TLI.hasAndNot(SDValue(Node, 0)))
7626 return SDValue();
7627
7628 SDValue M, X, Y;
7629
7630 if (sd_match(Node,
7632 m_OneUse(m_And(m_Deferred(M), m_Value(X))))) ||
7633 sd_match(Node,
7635 m_OneUse(m_Or(m_Deferred(M), m_Value(Y)))))) {
7636 EVT VT = M.getValueType();
7637 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, Y);
7638 SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor, M);
7639 return DAG.getNode(ISD::XOR, DL, VT, And, Y);
7640 }
7641 return SDValue();
7642}
7643
7644SDValue DAGCombiner::visitAND(SDNode *N) {
7645 SDValue N0 = N->getOperand(0);
7646 SDValue N1 = N->getOperand(1);
7647 EVT VT = N1.getValueType();
7648 SDLoc DL(N);
7649
7650 // x & x --> x
7651 if (N0 == N1)
7652 return N0;
7653
7654 // fold (and c1, c2) -> c1&c2
7655 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N0, N1}))
7656 return C;
7657
7658 // canonicalize constant to RHS
7661 return DAG.getNode(ISD::AND, DL, VT, N1, N0);
7662
7663 if (areBitwiseNotOfEachother(N0, N1))
7664 return DAG.getConstant(APInt::getZero(VT.getScalarSizeInBits()), DL, VT);
7665
7666 // fold vector ops
7667 if (VT.isVector()) {
7668 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
7669 return FoldedVOp;
7670
7671 // fold (and x, 0) -> 0, vector edition
7673 // do not return N1, because undef node may exist in N1
7675 N1.getValueType());
7676
7677 // fold (and x, -1) -> x, vector edition
7679 return N0;
7680
7681 // fold (and buildvector(x,0,-1,w), buildvector(0,y,z,w))
7682 // --> buildvector(0,0,z,w)
7683 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
7684 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7685 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
7686 N0.hasOneUse() && N1.hasOneUse() &&
7687 BV0->getOperand(0).getValueType() ==
7688 BV1->getOperand(0).getValueType()) {
7689 SmallVector<SDValue> MergedOps;
7690 unsigned NumElts = VT.getVectorNumElements();
7691 EVT EltVT = BV0->getOperand(0).getValueType();
7692 for (unsigned I = 0; I != NumElts; ++I) {
7693 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
7694 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
7695 if (C0 && C1)
7696 MergedOps.push_back(DAG.getConstant(
7697 C0->getAPIntValue() & C1->getAPIntValue(), DL, EltVT));
7698 else if (C0 && C0->isZero())
7699 MergedOps.push_back(BV0->getOperand(I));
7700 else if (C1 && C1->isZero())
7701 MergedOps.push_back(BV1->getOperand(I));
7702 else if (C0 && C0->isAllOnes())
7703 MergedOps.push_back(BV1->getOperand(I));
7704 else if (C1 && C1->isAllOnes())
7705 MergedOps.push_back(BV0->getOperand(I));
7706 else if (BV0->getOperand(I) == BV1->getOperand(I))
7707 MergedOps.push_back(BV0->getOperand(I));
7708 else
7709 break;
7710 }
7711 if (MergedOps.size() == NumElts)
7712 return DAG.getBuildVector(VT, DL, MergedOps);
7713 }
7714
7715 // fold (and (masked_load) (splat_vec (x, ...))) to zext_masked_load
7716 bool Frozen = N0.getOpcode() == ISD::FREEZE;
7717 auto *MLoad = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0);
7718 ConstantSDNode *Splat = isConstOrConstSplat(N1, true, true);
7719 if (MLoad && MLoad->getExtensionType() == ISD::EXTLOAD && Splat) {
7720 EVT MemVT = MLoad->getMemoryVT();
7721 if (TLI.isLoadLegal(VT, MemVT, MLoad->getAlign(),
7722 MLoad->getAddressSpace(), ISD::ZEXTLOAD, false)) {
7723 // For this AND to be a zero extension of the masked load the elements
7724 // of the BuildVec must mask the bottom bits of the extended element
7725 // type
7726 if (Splat->getAPIntValue().isMask(MemVT.getScalarSizeInBits())) {
7727 SDValue NewLoad = DAG.getMaskedLoad(
7728 VT, DL, MLoad->getChain(), MLoad->getBasePtr(),
7729 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), MemVT,
7730 MLoad->getMemOperand(), MLoad->getAddressingMode(), ISD::ZEXTLOAD,
7731 MLoad->isExpandingLoad());
7732 CombineTo(N, Frozen ? N0 : NewLoad);
7733 CombineTo(MLoad, NewLoad, NewLoad.getValue(1));
7734 return SDValue(N, 0);
7735 }
7736 }
7737 }
7738 }
7739
7740 // fold (and x, -1) -> x
7741 if (isAllOnesConstant(N1))
7742 return N0;
7743
7744 // if (and x, c) is known to be zero, return 0
7745 unsigned BitWidth = VT.getScalarSizeInBits();
7746 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7748 return DAG.getConstant(0, DL, VT);
7749
7750 if (SDValue R = foldAndOrOfSETCC(N, DAG))
7751 return R;
7752
7753 if (SDValue NewSel = foldBinOpIntoSelect(N))
7754 return NewSel;
7755
7756 // reassociate and
7757 if (SDValue RAND = reassociateOps(ISD::AND, DL, N0, N1, N->getFlags()))
7758 return RAND;
7759
7760 // Fold and(vecreduce(x), vecreduce(y)) -> vecreduce(and(x, y))
7761 if (SDValue SD =
7762 reassociateReduction(ISD::VECREDUCE_AND, ISD::AND, DL, VT, N0, N1))
7763 return SD;
7764
7765 // fold (and (or x, C), D) -> D if (C & D) == D
7766 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7767 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
7768 };
7769 if (N0.getOpcode() == ISD::OR &&
7770 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
7771 return N1;
7772
7773 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
7774 SDValue N0Op0 = N0.getOperand(0);
7775 EVT SrcVT = N0Op0.getValueType();
7776 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
7777 APInt Mask = ~N1C->getAPIntValue();
7778 Mask = Mask.trunc(SrcBitWidth);
7779
7780 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
7781 if (DAG.MaskedValueIsZero(N0Op0, Mask))
7782 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0Op0);
7783
7784 // fold (and (any_ext V), c) -> (zero_ext (and (trunc V), c)) if profitable.
7785 if (N1C->getAPIntValue().countLeadingZeros() >= (BitWidth - SrcBitWidth) &&
7786 TLI.isTruncateFree(VT, SrcVT) && TLI.isZExtFree(SrcVT, VT) &&
7787 TLI.isTypeDesirableForOp(ISD::AND, SrcVT) &&
7788 TLI.isNarrowingProfitable(N, VT, SrcVT))
7789 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT,
7790 DAG.getNode(ISD::AND, DL, SrcVT, N0Op0,
7791 DAG.getZExtOrTrunc(N1, DL, SrcVT)));
7792 }
7793
7794 // fold (and (ext (and V, c1)), c2) -> (and (ext V), (and c1, (ext c2)))
7795 if (ISD::isExtOpcode(N0.getOpcode())) {
7796 unsigned ExtOpc = N0.getOpcode();
7797 SDValue N0Op0 = N0.getOperand(0);
7798 if (N0Op0.getOpcode() == ISD::AND &&
7799 (ExtOpc != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0Op0, VT)) &&
7800 N0->hasOneUse() && N0Op0->hasOneUse()) {
7801 if (SDValue NewExt = DAG.FoldConstantArithmetic(ExtOpc, DL, VT,
7802 {N0Op0.getOperand(1)})) {
7803 if (SDValue NewMask =
7804 DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N1, NewExt})) {
7805 return DAG.getNode(ISD::AND, DL, VT,
7806 DAG.getNode(ExtOpc, DL, VT, N0Op0.getOperand(0)),
7807 NewMask);
7808 }
7809 }
7810 }
7811 }
7812
7813 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
7814 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
7815 // already be zero by virtue of the width of the base type of the load.
7816 //
7817 // the 'X' node here can either be nothing or an extract_vector_elt to catch
7818 // more cases.
7819 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7821 N0.getOperand(0).getOpcode() == ISD::LOAD &&
7822 N0.getOperand(0).getResNo() == 0) ||
7823 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
7824 auto *Load =
7825 cast<LoadSDNode>((N0.getOpcode() == ISD::LOAD) ? N0 : N0.getOperand(0));
7826
7827 // Get the constant (if applicable) the zero'th operand is being ANDed with.
7828 // This can be a pure constant or a vector splat, in which case we treat the
7829 // vector as a scalar and use the splat value.
7830 APInt Constant = APInt::getZero(1);
7831 if (const ConstantSDNode *C = isConstOrConstSplat(
7832 N1, /*AllowUndefs=*/false, /*AllowTruncation=*/true)) {
7833 Constant = C->getAPIntValue();
7834 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
7835 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
7836 APInt SplatValue, SplatUndef;
7837 unsigned SplatBitSize;
7838 bool HasAnyUndefs;
7839 // Endianness should not matter here. Code below makes sure that we only
7840 // use the result if the SplatBitSize is a multiple of the vector element
7841 // size. And after that we AND all element sized parts of the splat
7842 // together. So the end result should be the same regardless of in which
7843 // order we do those operations.
7844 const bool IsBigEndian = false;
7845 bool IsSplat =
7846 Vector->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7847 HasAnyUndefs, EltBitWidth, IsBigEndian);
7848
7849 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
7850 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
7851 if (IsSplat && (SplatBitSize % EltBitWidth) == 0) {
7852 // Undef bits can contribute to a possible optimisation if set, so
7853 // set them.
7854 SplatValue |= SplatUndef;
7855
7856 // The splat value may be something like "0x00FFFFFF", which means 0 for
7857 // the first vector value and FF for the rest, repeating. We need a mask
7858 // that will apply equally to all members of the vector, so AND all the
7859 // lanes of the constant together.
7860 Constant = APInt::getAllOnes(EltBitWidth);
7861 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
7862 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
7863 }
7864 }
7865
7866 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
7867 // actually legal and isn't going to get expanded, else this is a false
7868 // optimisation.
7869 bool CanZextLoadProfitably = TLI.isLoadLegal(
7870 Load->getValueType(0), Load->getMemoryVT(), Load->getAlign(),
7871 Load->getAddressSpace(), ISD::ZEXTLOAD, false);
7872
7873 // Resize the constant to the same size as the original memory access before
7874 // extension. If it is still the AllOnesValue then this AND is completely
7875 // unneeded.
7876 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
7877
7878 bool B;
7879 switch (Load->getExtensionType()) {
7880 default: B = false; break;
7881 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
7882 case ISD::ZEXTLOAD:
7883 case ISD::NON_EXTLOAD: B = true; break;
7884 }
7885
7886 if (B && Constant.isAllOnes()) {
7887 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
7888 // preserve semantics once we get rid of the AND.
7889 SDValue NewLoad(Load, 0);
7890
7891 // Fold the AND away. NewLoad may get replaced immediately.
7892 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
7893
7894 if (Load->getExtensionType() == ISD::EXTLOAD) {
7895 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
7896 Load->getValueType(0), SDLoc(Load),
7897 Load->getChain(), Load->getBasePtr(),
7898 Load->getOffset(), Load->getMemoryVT(),
7899 Load->getMemOperand());
7900 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
7901 if (Load->getNumValues() == 3) {
7902 // PRE/POST_INC loads have 3 values.
7903 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
7904 NewLoad.getValue(2) };
7905 CombineTo(Load, To, 3, true);
7906 } else {
7907 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
7908 }
7909 }
7910
7911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7912 }
7913 }
7914
7915 // Try to convert a constant mask AND into a shuffle clear mask.
7916 if (VT.isVector())
7917 if (SDValue Shuffle = XformToShuffleWithZero(N))
7918 return Shuffle;
7919
7920 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
7921 return Combined;
7922
7923 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() && N1C &&
7925 SDValue Ext = N0.getOperand(0);
7926 EVT ExtVT = Ext->getValueType(0);
7927 SDValue Extendee = Ext->getOperand(0);
7928
7929 unsigned ScalarWidth = Extendee.getValueType().getScalarSizeInBits();
7930 if (N1C->getAPIntValue().isMask(ScalarWidth) &&
7931 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, ExtVT))) {
7932 // (and (extract_subvector (zext|anyext|sext v) _) iN_mask)
7933 // => (extract_subvector (iN_zeroext v))
7934 SDValue ZeroExtExtendee =
7935 DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Extendee);
7936
7937 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ZeroExtExtendee,
7938 N0.getOperand(1));
7939 }
7940 }
7941
7942 // fold (and (masked_gather x)) -> (zext_masked_gather x)
7943 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
7944 EVT MemVT = GN0->getMemoryVT();
7945 EVT ScalarVT = MemVT.getScalarType();
7946
7947 if (SDValue(GN0, 0).hasOneUse() &&
7948 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
7950 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
7951 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
7952
7953 SDValue ZExtLoad = DAG.getMaskedGather(
7954 DAG.getVTList(VT, MVT::Other), MemVT, DL, Ops, GN0->getMemOperand(),
7955 GN0->getIndexType(), ISD::ZEXTLOAD);
7956
7957 CombineTo(N, ZExtLoad);
7958 AddToWorklist(ZExtLoad.getNode());
7959 // Avoid recheck of N.
7960 return SDValue(N, 0);
7961 }
7962 }
7963
7964 // fold (and (load x), 255) -> (zextload x, i8)
7965 // fold (and (extload x, i16), 255) -> (zextload x, i8)
7966 // fold (and (freeze (load x)), 255) -> (freeze (zextload x, i8))
7967 // fold (and (freeze (extload x, i16)), 255) -> (freeze (zextload x, i8))
7968 if (N1C && !VT.isVector()) {
7969 SDValue Inner = peekThroughFreeze(N0);
7970 if (Inner.getOpcode() == ISD::LOAD)
7971 if (SDValue Res = reduceLoadWidth(N))
7972 return Res;
7973 }
7974
7975 if (LegalTypes) {
7976 // Attempt to propagate the AND back up to the leaves which, if they're
7977 // loads, can be combined to narrow loads and the AND node can be removed.
7978 // Perform after legalization so that extend nodes will already be
7979 // combined into the loads.
7980 if (BackwardsPropagateMask(N))
7981 return SDValue(N, 0);
7982 }
7983
7984 if (SDValue Combined = visitANDLike(N0, N1, N))
7985 return Combined;
7986
7987 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
7988 if (N0.getOpcode() == N1.getOpcode())
7989 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
7990 return V;
7991
7992 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
7993 return R;
7994 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
7995 return R;
7996
7997 // Fold (and X, (bswap (not Y))) -> (and X, (not (bswap Y)))
7998 // Fold (and X, (bitreverse (not Y))) -> (and X, (not (bitreverse Y)))
7999 SDValue X, Y, Z, NotY;
8000 for (unsigned Opc : {ISD::BSWAP, ISD::BITREVERSE})
8001 if (sd_match(N,
8002 m_And(m_Value(X), m_OneUse(m_UnaryOp(Opc, m_Value(NotY))))) &&
8003 sd_match(NotY, m_Not(m_Value(Y))) &&
8004 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8005 return DAG.getNode(ISD::AND, DL, VT, X,
8006 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y), VT));
8007
8008 // Fold (and X, (rot (not Y), Z)) -> (and X, (not (rot Y, Z)))
8009 for (unsigned Opc : {ISD::ROTL, ISD::ROTR})
8010 if (sd_match(N, m_And(m_Value(X),
8011 m_OneUse(m_BinOp(Opc, m_Value(NotY), m_Value(Z))))) &&
8012 sd_match(NotY, m_Not(m_Value(Y))) &&
8013 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8014 return DAG.getNode(ISD::AND, DL, VT, X,
8015 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y, Z), VT));
8016
8017 // Fold (and X, (add (not Y), Z)) -> (and X, (not (sub Y, Z)))
8018 // Fold (and X, (sub (not Y), Z)) -> (and X, (not (add Y, Z)))
8019 if (TLI.hasAndNot(SDValue(N, 0)))
8020 if (SDValue Folded = foldBitwiseOpWithNeg(N, DL, VT))
8021 return Folded;
8022
8023 // Fold (and (srl X, C), 1) -> (srl X, BW-1) for signbit extraction
8024 // If we are shifting down an extended sign bit, see if we can simplify
8025 // this to shifting the MSB directly to expose further simplifications.
8026 // This pattern often appears after sext_inreg legalization.
8027 APInt Amt;
8028 if (sd_match(N, m_And(m_Srl(m_Value(X), m_ConstInt(Amt)), m_One())) &&
8029 Amt.ult(BitWidth - 1) && Amt.uge(BitWidth - DAG.ComputeNumSignBits(X)))
8030 return DAG.getNode(ISD::SRL, DL, VT, X,
8031 DAG.getShiftAmountConstant(BitWidth - 1, VT, DL));
8032
8033 // Masking the negated extension of a boolean is just the zero-extended
8034 // boolean:
8035 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
8036 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
8037 //
8038 // Note: the SimplifyDemandedBits fold below can make an information-losing
8039 // transform, and then we have no way to find this better fold.
8040 if (sd_match(N, m_And(m_Sub(m_Zero(), m_Value(X)), m_One()))) {
8041 if (X.getOpcode() == ISD::ZERO_EXTEND &&
8042 X.getOperand(0).getScalarValueSizeInBits() == 1)
8043 return X;
8044 if (X.getOpcode() == ISD::SIGN_EXTEND &&
8045 X.getOperand(0).getScalarValueSizeInBits() == 1)
8046 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, X.getOperand(0));
8047 }
8048
8049 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
8050 // fold (and (sra)) -> (and (srl)) when possible.
8052 return SDValue(N, 0);
8053
8054 // fold (zext_inreg (extload x)) -> (zextload x)
8055 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
8056 if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
8057 (ISD::isEXTLoad(N0.getNode()) ||
8058 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
8059 auto *LN0 = cast<LoadSDNode>(N0);
8060 EVT MemVT = LN0->getMemoryVT();
8061 // If we zero all the possible extended bits, then we can turn this into
8062 // a zextload if we are running before legalize or the operation is legal.
8063 unsigned ExtBitSize = N1.getScalarValueSizeInBits();
8064 unsigned MemBitSize = MemVT.getScalarSizeInBits();
8065 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
8066 if (DAG.MaskedValueIsZero(N1, ExtBits) &&
8067 ((!LegalOperations && LN0->isSimple()) ||
8068 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
8069 ISD::ZEXTLOAD, false))) {
8070 SDValue ExtLoad =
8071 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
8072 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
8073 AddToWorklist(N);
8074 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8075 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8076 }
8077 }
8078
8079 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
8080 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
8081 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8082 N0.getOperand(1), false))
8083 return BSwap;
8084 }
8085
8086 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
8087 return Shifts;
8088
8089 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
8090 return V;
8091
8092 // Recognize the following pattern:
8093 //
8094 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
8095 //
8096 // where bitmask is a mask that clears the upper bits of AndVT. The
8097 // number of bits in bitmask must be a power of two.
8098 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
8099 if (LHS->getOpcode() != ISD::SIGN_EXTEND)
8100 return false;
8101
8102 auto *C = isConstOrConstSplat(RHS, false, true);
8103 if (!C)
8104 return false;
8105
8106 if (!C->getAPIntValue().isMask(
8107 LHS.getOperand(0).getValueType().getScalarSizeInBits()))
8108 return false;
8109
8110 return true;
8111 };
8112
8113 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
8114 if (IsAndZeroExtMask(N0, N1) &&
8115 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)))
8116 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
8117
8118 if (hasOperation(ISD::USUBSAT, VT))
8119 if (SDValue V = foldAndToUsubsat(N, DAG, DL))
8120 return V;
8121
8122 // Postpone until legalization completed to avoid interference with bswap
8123 // folding
8124 if (LegalOperations || VT.isVector())
8125 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
8126 return R;
8127
8128 if (VT.isScalarInteger() && VT != MVT::i1)
8129 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
8130 return R;
8131
8132 return SDValue();
8133}
8134
8135/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
8136SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
8137 bool DemandHighBits) {
8138 if (!LegalOperations)
8139 return SDValue();
8140
8141 EVT VT = N->getValueType(0);
8142 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
8143 return SDValue();
8145 return SDValue();
8146
8147 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
8148 bool LookPassAnd0 = false;
8149 bool LookPassAnd1 = false;
8150 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
8151 std::swap(N0, N1);
8152 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
8153 std::swap(N0, N1);
8154 if (N0.getOpcode() == ISD::AND) {
8155 if (!N0->hasOneUse())
8156 return SDValue();
8157 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8158 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
8159 // This is needed for X86.
8160 if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
8161 N01C->getZExtValue() != 0xFFFF))
8162 return SDValue();
8163 N0 = N0.getOperand(0);
8164 LookPassAnd0 = true;
8165 }
8166
8167 if (N1.getOpcode() == ISD::AND) {
8168 if (!N1->hasOneUse())
8169 return SDValue();
8170 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8171 if (!N11C || N11C->getZExtValue() != 0xFF)
8172 return SDValue();
8173 N1 = N1.getOperand(0);
8174 LookPassAnd1 = true;
8175 }
8176
8177 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
8178 std::swap(N0, N1);
8179 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
8180 return SDValue();
8181 if (!N0->hasOneUse() || !N1->hasOneUse())
8182 return SDValue();
8183
8184 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8185 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8186 if (!N01C || !N11C)
8187 return SDValue();
8188 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
8189 return SDValue();
8190
8191 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
8192 SDValue N00 = N0->getOperand(0);
8193 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
8194 if (!N00->hasOneUse())
8195 return SDValue();
8196 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
8197 if (!N001C || N001C->getZExtValue() != 0xFF)
8198 return SDValue();
8199 N00 = N00.getOperand(0);
8200 LookPassAnd0 = true;
8201 }
8202
8203 SDValue N10 = N1->getOperand(0);
8204 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
8205 if (!N10->hasOneUse())
8206 return SDValue();
8207 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
8208 // Also allow 0xFFFF since the bits will be shifted out. This is needed
8209 // for X86.
8210 if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
8211 N101C->getZExtValue() != 0xFFFF))
8212 return SDValue();
8213 N10 = N10.getOperand(0);
8214 LookPassAnd1 = true;
8215 }
8216
8217 if (N00 != N10)
8218 return SDValue();
8219
8220 // Make sure everything beyond the low halfword gets set to zero since the SRL
8221 // 16 will clear the top bits.
8222 unsigned OpSizeInBits = VT.getSizeInBits();
8223 if (OpSizeInBits > 16) {
8224 // If the left-shift isn't masked out then the only way this is a bswap is
8225 // if all bits beyond the low 8 are 0. In that case the entire pattern
8226 // reduces to a left shift anyway: leave it for other parts of the combiner.
8227 if (DemandHighBits && !LookPassAnd0)
8228 return SDValue();
8229
8230 // However, if the right shift isn't masked out then it might be because
8231 // it's not needed. See if we can spot that too. If the high bits aren't
8232 // demanded, we only need bits 23:16 to be zero. Otherwise, we need all
8233 // upper bits to be zero.
8234 if (!LookPassAnd1) {
8235 unsigned HighBit = DemandHighBits ? OpSizeInBits : 24;
8236 if (!DAG.MaskedValueIsZero(N10,
8237 APInt::getBitsSet(OpSizeInBits, 16, HighBit)))
8238 return SDValue();
8239 }
8240 }
8241
8242 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
8243 if (OpSizeInBits > 16) {
8244 SDLoc DL(N);
8245 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
8246 DAG.getShiftAmountConstant(OpSizeInBits - 16, VT, DL));
8247 }
8248 return Res;
8249}
8250
8251/// Return true if the specified node is an element that makes up a 32-bit
8252/// packed halfword byteswap.
8253/// ((x & 0x000000ff) << 8) |
8254/// ((x & 0x0000ff00) >> 8) |
8255/// ((x & 0x00ff0000) << 8) |
8256/// ((x & 0xff000000) >> 8)
8258 if (!N->hasOneUse())
8259 return false;
8260
8261 unsigned Opc = N.getOpcode();
8262 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
8263 return false;
8264
8265 SDValue N0 = N.getOperand(0);
8266 unsigned Opc0 = N0.getOpcode();
8267 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
8268 return false;
8269
8270 ConstantSDNode *N1C = nullptr;
8271 // SHL or SRL: look upstream for AND mask operand
8272 if (Opc == ISD::AND)
8273 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8274 else if (Opc0 == ISD::AND)
8276 if (!N1C)
8277 return false;
8278
8279 unsigned MaskByteOffset;
8280 switch (N1C->getZExtValue()) {
8281 default:
8282 return false;
8283 case 0xFF: MaskByteOffset = 0; break;
8284 case 0xFF00: MaskByteOffset = 1; break;
8285 case 0xFFFF:
8286 // In case demanded bits didn't clear the bits that will be shifted out.
8287 // This is needed for X86.
8288 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
8289 MaskByteOffset = 1;
8290 break;
8291 }
8292 return false;
8293 case 0xFF0000: MaskByteOffset = 2; break;
8294 case 0xFF000000: MaskByteOffset = 3; break;
8295 }
8296
8297 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
8298 if (Opc == ISD::AND) {
8299 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
8300 // (x >> 8) & 0xff
8301 // (x >> 8) & 0xff0000
8302 if (Opc0 != ISD::SRL)
8303 return false;
8305 if (!C || C->getZExtValue() != 8)
8306 return false;
8307 } else {
8308 // (x << 8) & 0xff00
8309 // (x << 8) & 0xff000000
8310 if (Opc0 != ISD::SHL)
8311 return false;
8313 if (!C || C->getZExtValue() != 8)
8314 return false;
8315 }
8316 } else if (Opc == ISD::SHL) {
8317 // (x & 0xff) << 8
8318 // (x & 0xff0000) << 8
8319 if (MaskByteOffset != 0 && MaskByteOffset != 2)
8320 return false;
8321 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8322 if (!C || C->getZExtValue() != 8)
8323 return false;
8324 } else { // Opc == ISD::SRL
8325 // (x & 0xff00) >> 8
8326 // (x & 0xff000000) >> 8
8327 if (MaskByteOffset != 1 && MaskByteOffset != 3)
8328 return false;
8329 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8330 if (!C || C->getZExtValue() != 8)
8331 return false;
8332 }
8333
8334 if (Parts[MaskByteOffset])
8335 return false;
8336
8337 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
8338 return true;
8339}
8340
8341// Match 2 elements of a packed halfword bswap.
8343 if (N.getOpcode() == ISD::OR)
8344 return isBSwapHWordElement(N.getOperand(0), Parts) &&
8345 isBSwapHWordElement(N.getOperand(1), Parts);
8346
8347 if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
8348 ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
8349 if (!C || C->getAPIntValue() != 16)
8350 return false;
8351 Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
8352 return true;
8353 }
8354
8355 return false;
8356}
8357
8358// Match this pattern:
8359// (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
8360// And rewrite this to:
8361// (rotr (bswap A), 16)
8363 SelectionDAG &DAG, SDNode *N, SDValue N0,
8364 SDValue N1, EVT VT) {
8365 assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
8366 "MatchBSwapHWordOrAndAnd: expecting i32");
8367 if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
8368 return SDValue();
8369 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
8370 return SDValue();
8371 // TODO: this is too restrictive; lifting this restriction requires more tests
8372 if (!N0->hasOneUse() || !N1->hasOneUse())
8373 return SDValue();
8376 if (!Mask0 || !Mask1)
8377 return SDValue();
8378 if (Mask0->getAPIntValue() != 0xff00ff00 ||
8379 Mask1->getAPIntValue() != 0x00ff00ff)
8380 return SDValue();
8381 SDValue Shift0 = N0.getOperand(0);
8382 SDValue Shift1 = N1.getOperand(0);
8383 if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
8384 return SDValue();
8385 ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
8386 ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
8387 if (!ShiftAmt0 || !ShiftAmt1)
8388 return SDValue();
8389 if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
8390 return SDValue();
8391 if (Shift0.getOperand(0) != Shift1.getOperand(0))
8392 return SDValue();
8393
8394 SDLoc DL(N);
8395 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
8396 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8397 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8398}
8399
8400/// Match a 32-bit packed halfword bswap. That is
8401/// ((x & 0x000000ff) << 8) |
8402/// ((x & 0x0000ff00) >> 8) |
8403/// ((x & 0x00ff0000) << 8) |
8404/// ((x & 0xff000000) >> 8)
8405/// => (rotl (bswap x), 16)
8406SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
8407 if (!LegalOperations)
8408 return SDValue();
8409
8410 EVT VT = N->getValueType(0);
8411 if (VT != MVT::i32)
8412 return SDValue();
8414 return SDValue();
8415
8416 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT))
8417 return BSwap;
8418
8419 // Try again with commuted operands.
8420 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT))
8421 return BSwap;
8422
8423
8424 // Look for either
8425 // (or (bswaphpair), (bswaphpair))
8426 // (or (or (bswaphpair), (and)), (and))
8427 // (or (or (and), (bswaphpair)), (and))
8428 SDNode *Parts[4] = {};
8429
8430 if (isBSwapHWordPair(N0, Parts)) {
8431 // (or (or (and), (and)), (or (and), (and)))
8432 if (!isBSwapHWordPair(N1, Parts))
8433 return SDValue();
8434 } else if (N0.getOpcode() == ISD::OR) {
8435 // (or (or (or (and), (and)), (and)), (and))
8436 if (!isBSwapHWordElement(N1, Parts))
8437 return SDValue();
8438 SDValue N00 = N0.getOperand(0);
8439 SDValue N01 = N0.getOperand(1);
8440 if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
8441 !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
8442 return SDValue();
8443 } else {
8444 return SDValue();
8445 }
8446
8447 // Make sure the parts are all coming from the same node.
8448 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
8449 return SDValue();
8450
8451 SDLoc DL(N);
8452 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
8453 SDValue(Parts[0], 0));
8454
8455 // Result of the bswap should be rotated by 16. If it's not legal, then
8456 // do (x << 16) | (x >> 16).
8457 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8459 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
8461 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8462 return DAG.getNode(ISD::OR, DL, VT,
8463 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
8464 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
8465}
8466
8467/// This contains all DAGCombine rules which reduce two values combined by
8468/// an Or operation to a single value \see visitANDLike().
8469SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, const SDLoc &DL) {
8470 EVT VT = N1.getValueType();
8471
8472 // fold (or x, undef) -> -1
8473 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
8474 return DAG.getAllOnesConstant(DL, VT);
8475
8476 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
8477 return V;
8478
8479 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
8480 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
8481 // Don't increase # computations.
8482 (N0->hasOneUse() || N1->hasOneUse())) {
8483 // We can only do this xform if we know that bits from X that are set in C2
8484 // but not in C1 are already zero. Likewise for Y.
8485 if (const ConstantSDNode *N0O1C =
8487 if (const ConstantSDNode *N1O1C =
8489 // We can only do this xform if we know that bits from X that are set in
8490 // C2 but not in C1 are already zero. Likewise for Y.
8491 const APInt &LHSMask = N0O1C->getAPIntValue();
8492 const APInt &RHSMask = N1O1C->getAPIntValue();
8493
8494 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
8495 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
8496 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8497 N0.getOperand(0), N1.getOperand(0));
8498 return DAG.getNode(ISD::AND, DL, VT, X,
8499 DAG.getConstant(LHSMask | RHSMask, DL, VT));
8500 }
8501 }
8502 }
8503 }
8504
8505 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
8506 if (N0.getOpcode() == ISD::AND &&
8507 N1.getOpcode() == ISD::AND &&
8508 N0.getOperand(0) == N1.getOperand(0) &&
8509 // Don't increase # computations.
8510 (N0->hasOneUse() || N1->hasOneUse())) {
8511 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8512 N0.getOperand(1), N1.getOperand(1));
8513 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
8514 }
8515
8516 return SDValue();
8517}
8518
8519/// OR combines for which the commuted variant will be tried as well.
8521 SDNode *N) {
8522 EVT VT = N0.getValueType();
8523 unsigned BW = VT.getScalarSizeInBits();
8524 SDLoc DL(N);
8525
8526 auto peekThroughResize = [](SDValue V) {
8527 if (V->getOpcode() == ISD::ZERO_EXTEND || V->getOpcode() == ISD::TRUNCATE)
8528 return V->getOperand(0);
8529 return V;
8530 };
8531
8532 SDValue N0Resized = peekThroughResize(N0);
8533 if (N0Resized.getOpcode() == ISD::AND) {
8534 SDValue N1Resized = peekThroughResize(N1);
8535 SDValue N00 = N0Resized.getOperand(0);
8536 SDValue N01 = N0Resized.getOperand(1);
8537
8538 // fold or (and x, y), x --> x
8539 if (N00 == N1Resized || N01 == N1Resized)
8540 return N1;
8541
8542 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
8543 // TODO: Set AllowUndefs = true.
8544 if (SDValue NotOperand = getBitwiseNotOperand(N01, N00,
8545 /* AllowUndefs */ false)) {
8546 if (peekThroughResize(NotOperand) == N1Resized)
8547 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N00, DL, VT),
8548 N1);
8549 }
8550
8551 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
8552 if (SDValue NotOperand = getBitwiseNotOperand(N00, N01,
8553 /* AllowUndefs */ false)) {
8554 if (peekThroughResize(NotOperand) == N1Resized)
8555 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N01, DL, VT),
8556 N1);
8557 }
8558 }
8559
8560 SDValue X, Y;
8561
8562 // fold or (xor X, N1), N1 --> or X, N1
8563 if (sd_match(N0, m_Xor(m_Value(X), m_Specific(N1))))
8564 return DAG.getNode(ISD::OR, DL, VT, X, N1);
8565
8566 // fold or (xor x, y), (x and/or y) --> or x, y
8567 if (sd_match(N0, m_Xor(m_Value(X), m_Value(Y))) &&
8568 (sd_match(N1, m_And(m_Specific(X), m_Specific(Y))) ||
8570 return DAG.getNode(ISD::OR, DL, VT, X, Y);
8571
8572 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
8573 return R;
8574
8575 auto peekThroughZext = [](SDValue V) {
8576 if (V->getOpcode() == ISD::ZERO_EXTEND)
8577 return V->getOperand(0);
8578 return V;
8579 };
8580
8581 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::SHL &&
8582 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8583 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
8584 if (N0.getOperand(0) == N1.getOperand(0))
8585 return N0;
8586 // (fshl A, X, Y) | (shl X, Y) --> fshl (A|X), X, Y
8587 if (N0.getOperand(1) == N1.getOperand(0) && N0.hasOneUse() &&
8588 N1.hasOneUse()) {
8589 SDValue A = N0.getOperand(0);
8590 SDValue X = N1.getOperand(0);
8591 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, X);
8592 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, X, N0.getOperand(2));
8593 }
8594 }
8595
8596 if (N0.getOpcode() == ISD::FSHR && N1.getOpcode() == ISD::SRL &&
8597 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8598 // (fshr ?, X, Y) | (srl X, Y) --> fshr ?, X, Y
8599 if (N0.getOperand(1) == N1.getOperand(0))
8600 return N0;
8601 // (fshr X, B, Y) | (srl X, Y) --> fshr X, (X|B), Y
8602 if (N0.getOperand(0) == N1.getOperand(0) && N0.hasOneUse() &&
8603 N1.hasOneUse()) {
8604 SDValue X = N1.getOperand(0);
8605 SDValue B = N0.getOperand(1);
8606 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, X, B);
8607 return DAG.getNode(ISD::FSHR, DL, VT, X, NewRHS, N0.getOperand(2));
8608 }
8609 }
8610
8611 // (fshl A, B, S0) | (fshr C, D, S1) --> fshl (A|C), (B|D), S0
8612 // iff S0 + S1 == bitwidth(S1)
8613 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::FSHR &&
8614 N0.hasOneUse() && N1.hasOneUse()) {
8615 auto *S0 = dyn_cast<ConstantSDNode>(N0.getOperand(2));
8616 auto *S1 = dyn_cast<ConstantSDNode>(N1.getOperand(2));
8617 if (S0 && S1 && S0->getZExtValue() < BW && S1->getZExtValue() < BW &&
8618 S0->getZExtValue() == (BW - S1->getZExtValue())) {
8619 SDValue A = N0.getOperand(0);
8620 SDValue B = N0.getOperand(1);
8621 SDValue C = N1.getOperand(0);
8622 SDValue D = N1.getOperand(1);
8623 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, C);
8624 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, B, D);
8625 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, NewRHS, N0.getOperand(2));
8626 }
8627 }
8628
8629 // Attempt to match a legalized build_pair-esque pattern:
8630 // or(shl(aext(Hi),BW/2),zext(Lo))
8631 SDValue Lo, Hi;
8632 if (sd_match(N0,
8634 sd_match(N1, m_ZExt(m_Value(Lo))) &&
8635 Lo.getScalarValueSizeInBits() == (BW / 2) &&
8636 Lo.getValueType() == Hi.getValueType()) {
8637 // Fold build_pair(not(Lo),not(Hi)) -> not(build_pair(Lo,Hi)).
8638 SDValue NotLo, NotHi;
8639 if (sd_match(Lo, m_OneUse(m_Not(m_Value(NotLo)))) &&
8640 sd_match(Hi, m_OneUse(m_Not(m_Value(NotHi))))) {
8641 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotLo);
8642 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NotHi);
8643 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
8644 DAG.getShiftAmountConstant(BW / 2, VT, DL));
8645 return DAG.getNOT(DL, DAG.getNode(ISD::OR, DL, VT, Lo, Hi), VT);
8646 }
8647 }
8648
8649 return SDValue();
8650}
8651
8652SDValue DAGCombiner::visitOR(SDNode *N) {
8653 SDValue N0 = N->getOperand(0);
8654 SDValue N1 = N->getOperand(1);
8655 EVT VT = N1.getValueType();
8656 SDLoc DL(N);
8657
8658 // x | x --> x
8659 if (N0 == N1)
8660 return N0;
8661
8662 // fold (or c1, c2) -> c1|c2
8663 if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, DL, VT, {N0, N1}))
8664 return C;
8665
8666 // canonicalize constant to RHS
8669 return DAG.getNode(ISD::OR, DL, VT, N1, N0);
8670
8671 // fold vector ops
8672 if (VT.isVector()) {
8673 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
8674 return FoldedVOp;
8675
8676 // fold (or x, 0) -> x, vector edition
8678 return N0;
8679
8680 // fold (or x, -1) -> -1, vector edition
8682 // do not return N1, because undef node may exist in N1
8683 return DAG.getAllOnesConstant(DL, N1.getValueType());
8684
8685 // fold (or buildvector(x,0,-1,w), buildvector(0,y,z,w))
8686 // --> buildvector(x,y,-1,w)
8687 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
8688 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8689 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
8690 N0.hasOneUse() && N1.hasOneUse() &&
8691 BV0->getOperand(0).getValueType() ==
8692 BV1->getOperand(0).getValueType()) {
8693 SmallVector<SDValue> MergedOps;
8694 unsigned NumElts = VT.getVectorNumElements();
8695 EVT EltVT = BV0->getOperand(0).getValueType();
8696 for (unsigned I = 0; I != NumElts; ++I) {
8697 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
8698 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
8699 if (C0 && C1)
8700 MergedOps.push_back(DAG.getConstant(
8701 C0->getAPIntValue() | C1->getAPIntValue(), DL, EltVT));
8702 else if (C0 && C0->isZero())
8703 MergedOps.push_back(BV1->getOperand(I));
8704 else if (C1 && C1->isZero())
8705 MergedOps.push_back(BV0->getOperand(I));
8706 else if (C0 && C0->isAllOnes())
8707 MergedOps.push_back(BV0->getOperand(I));
8708 else if (C1 && C1->isAllOnes())
8709 MergedOps.push_back(BV1->getOperand(I));
8710 else if (BV0->getOperand(I) == BV1->getOperand(I))
8711 MergedOps.push_back(BV0->getOperand(I));
8712 else
8713 break;
8714 }
8715 if (MergedOps.size() == NumElts)
8716 return DAG.getBuildVector(VT, DL, MergedOps);
8717 }
8718
8719 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
8720 // Do this only if the resulting type / shuffle is legal.
8721 auto *SV0 = dyn_cast<ShuffleVectorSDNode>(N0);
8722 auto *SV1 = dyn_cast<ShuffleVectorSDNode>(N1);
8723 if (SV0 && SV1 && TLI.isTypeLegal(VT)) {
8724 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
8725 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
8726 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
8727 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
8728 // Ensure both shuffles have a zero input.
8729 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
8730 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
8731 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
8732 bool CanFold = true;
8733 int NumElts = VT.getVectorNumElements();
8734 SmallVector<int, 4> Mask(NumElts, -1);
8735
8736 for (int i = 0; i != NumElts; ++i) {
8737 int M0 = SV0->getMaskElt(i);
8738 int M1 = SV1->getMaskElt(i);
8739
8740 // Determine if either index is pointing to a zero vector.
8741 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
8742 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
8743
8744 // If one element is zero and the otherside is undef, keep undef.
8745 // This also handles the case that both are undef.
8746 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0))
8747 continue;
8748
8749 // Make sure only one of the elements is zero.
8750 if (M0Zero == M1Zero) {
8751 CanFold = false;
8752 break;
8753 }
8754
8755 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
8756
8757 // We have a zero and non-zero element. If the non-zero came from
8758 // SV0 make the index a LHS index. If it came from SV1, make it
8759 // a RHS index. We need to mod by NumElts because we don't care
8760 // which operand it came from in the original shuffles.
8761 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
8762 }
8763
8764 if (CanFold) {
8765 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
8766 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
8767 SDValue LegalShuffle =
8768 TLI.buildLegalVectorShuffle(VT, DL, NewLHS, NewRHS, Mask, DAG);
8769 if (LegalShuffle)
8770 return LegalShuffle;
8771 }
8772 }
8773 }
8774 }
8775
8776 // fold (or x, 0) -> x
8777 if (isNullConstant(N1))
8778 return N0;
8779
8780 // fold (or x, -1) -> -1
8781 if (isAllOnesConstant(N1))
8782 return N1;
8783
8784 if (SDValue NewSel = foldBinOpIntoSelect(N))
8785 return NewSel;
8786
8787 // fold (or x, c) -> c iff (x & ~c) == 0
8788 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8789 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
8790 return N1;
8791
8792 if (SDValue R = foldAndOrOfSETCC(N, DAG))
8793 return R;
8794
8795 if (SDValue Combined = visitORLike(N0, N1, DL))
8796 return Combined;
8797
8798 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
8799 return Combined;
8800
8801 if (SDValue Combined = combineOrOfSetCCToUSUBOCarry(N, DAG, TLI))
8802 return Combined;
8803
8804 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
8805 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
8806 return BSwap;
8807 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
8808 return BSwap;
8809
8810 // reassociate or
8811 if (SDValue ROR = reassociateOps(ISD::OR, DL, N0, N1, N->getFlags()))
8812 return ROR;
8813
8814 // Fold or(vecreduce(x), vecreduce(y)) -> vecreduce(or(x, y))
8815 if (SDValue SD =
8816 reassociateReduction(ISD::VECREDUCE_OR, ISD::OR, DL, VT, N0, N1))
8817 return SD;
8818
8819 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
8820 // iff (c1 & c2) != 0 or c1/c2 are undef.
8821 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
8822 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
8823 };
8824 if (N0.getOpcode() == ISD::AND && N0->hasOneUse() &&
8825 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
8826 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
8827 {N1, N0.getOperand(1)})) {
8828 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
8829 AddToWorklist(IOR.getNode());
8830 return DAG.getNode(ISD::AND, DL, VT, COR, IOR);
8831 }
8832 }
8833
8834 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
8835 return Combined;
8836 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
8837 return Combined;
8838
8839 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
8840 if (N0.getOpcode() == N1.getOpcode())
8841 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
8842 return V;
8843
8844 // See if this is some rotate idiom.
8845 if (SDValue Rot = MatchRotate(N0, N1, DL, /*FromAdd=*/false))
8846 return Rot;
8847
8848 if (SDValue Load = MatchLoadCombine(N))
8849 return Load;
8850
8851 // Simplify the operands using demanded-bits information.
8853 return SDValue(N, 0);
8854
8855 // If OR can be rewritten into ADD, try combines based on ADD.
8856 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
8857 DAG.isADDLike(SDValue(N, 0)))
8858 if (SDValue Combined = visitADDLike(N))
8859 return Combined;
8860
8861 // Postpone until legalization completed to avoid interference with bswap
8862 // folding
8863 if (LegalOperations || VT.isVector())
8864 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
8865 return R;
8866
8867 if (VT.isScalarInteger() && VT != MVT::i1)
8868 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
8869 return R;
8870
8871 return SDValue();
8872}
8873
8875 SDValue &Mask) {
8876 if (Op.getOpcode() == ISD::AND &&
8877 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
8878 Mask = Op.getOperand(1);
8879 return Op.getOperand(0);
8880 }
8881 return Op;
8882}
8883
8884/// Match "(X shl/srl V1) & V2" where V2 may not be present.
8885static bool matchRotateHalf(const SelectionDAG &DAG, SDValue Op, SDValue &Shift,
8886 SDValue &Mask) {
8887 Op = stripConstantMask(DAG, Op, Mask);
8888 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
8889 Shift = Op;
8890 return true;
8891 }
8892 return false;
8893}
8894
8895/// Helper function for visitOR to extract the needed side of a rotate idiom
8896/// from a shl/srl/mul/udiv. This is meant to handle cases where
8897/// InstCombine merged some outside op with one of the shifts from
8898/// the rotate pattern.
8899/// \returns An empty \c SDValue if the needed shift couldn't be extracted.
8900/// Otherwise, returns an expansion of \p ExtractFrom based on the following
8901/// patterns:
8902///
8903/// (or (add v v) (shrl v bitwidth-1)):
8904/// expands (add v v) -> (shl v 1)
8905///
8906/// (or (mul v c0) (shrl (mul v c1) c2)):
8907/// expands (mul v c0) -> (shl (mul v c1) c3)
8908///
8909/// (or (udiv v c0) (shl (udiv v c1) c2)):
8910/// expands (udiv v c0) -> (shrl (udiv v c1) c3)
8911///
8912/// (or (shl v c0) (shrl (shl v c1) c2)):
8913/// expands (shl v c0) -> (shl (shl v c1) c3)
8914///
8915/// (or (shrl v c0) (shl (shrl v c1) c2)):
8916/// expands (shrl v c0) -> (shrl (shrl v c1) c3)
8917///
8918/// Such that in all cases, c3+c2==bitwidth(op v c1).
8920 SDValue ExtractFrom, SDValue &Mask,
8921 const SDLoc &DL) {
8922 assert(OppShift && ExtractFrom && "Empty SDValue");
8923 if (OppShift.getOpcode() != ISD::SHL && OppShift.getOpcode() != ISD::SRL)
8924 return SDValue();
8925
8926 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
8927
8928 // Value and Type of the shift.
8929 SDValue OppShiftLHS = OppShift.getOperand(0);
8930 EVT ShiftedVT = OppShiftLHS.getValueType();
8931
8932 // Amount of the existing shift.
8933 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
8934
8935 // (add v v) -> (shl v 1)
8936 // TODO: Should this be a general DAG canonicalization?
8937 if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
8938 ExtractFrom.getOpcode() == ISD::ADD &&
8939 ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
8940 ExtractFrom.getOperand(0) == OppShiftLHS &&
8941 OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
8942 return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
8943 DAG.getShiftAmountConstant(1, ShiftedVT, DL));
8944
8945 // Preconditions:
8946 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
8947 //
8948 // Find opcode of the needed shift to be extracted from (op0 v c0).
8949 unsigned Opcode = ISD::DELETED_NODE;
8950 bool IsMulOrDiv = false;
8951 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
8952 // opcode or its arithmetic (mul or udiv) variant.
8953 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
8954 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
8955 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
8956 return false;
8957 Opcode = NeededShift;
8958 return true;
8959 };
8960 // op0 must be either the needed shift opcode or the mul/udiv equivalent
8961 // that the needed shift can be extracted from.
8962 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
8963 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
8964 return SDValue();
8965
8966 // op0 must be the same opcode on both sides, have the same LHS argument,
8967 // and produce the same value type.
8968 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
8969 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
8970 ShiftedVT != ExtractFrom.getValueType())
8971 return SDValue();
8972
8973 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
8974 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
8975 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
8976 ConstantSDNode *ExtractFromCst =
8977 isConstOrConstSplat(ExtractFrom.getOperand(1));
8978 // TODO: We should be able to handle non-uniform constant vectors for these values
8979 // Check that we have constant values.
8980 if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
8981 !OppLHSCst || !OppLHSCst->getAPIntValue() ||
8982 !ExtractFromCst || !ExtractFromCst->getAPIntValue())
8983 return SDValue();
8984
8985 // Compute the shift amount we need to extract to complete the rotate.
8986 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
8987 if (OppShiftCst->getAPIntValue().ugt(VTWidth))
8988 return SDValue();
8989 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
8990 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
8991 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
8992 APInt OppLHSAmt = OppLHSCst->getAPIntValue();
8993 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
8994
8995 // Now try extract the needed shift from the ExtractFrom op and see if the
8996 // result matches up with the existing shift's LHS op.
8997 if (IsMulOrDiv) {
8998 // Op to extract from is a mul or udiv by a constant.
8999 // Check:
9000 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
9001 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
9002 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
9003 NeededShiftAmt.getZExtValue());
9004 APInt ResultAmt;
9005 APInt Rem;
9006 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
9007 if (Rem != 0 || ResultAmt != OppLHSAmt)
9008 return SDValue();
9009 } else {
9010 // Op to extract from is a shift by a constant.
9011 // Check:
9012 // c2 - (bitwidth(op0 v c0) - c1) == c0
9013 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
9014 ExtractFromAmt.getBitWidth()))
9015 return SDValue();
9016 }
9017
9018 // Return the expanded shift op that should allow a rotate to be formed.
9019 EVT ShiftVT = OppShift.getOperand(1).getValueType();
9020 EVT ResVT = ExtractFrom.getValueType();
9021 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
9022 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
9023}
9024
9025// Return true if we can prove that, whenever Neg and Pos are both in the
9026// range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
9027// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
9028//
9029// (or (shift1 X, Neg), (shift2 X, Pos))
9030//
9031// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
9032// in direction shift1 by Neg. The range [0, EltSize) means that we only need
9033// to consider shift amounts with defined behavior.
9034//
9035// The IsRotate flag should be set when the LHS of both shifts is the same.
9036// Otherwise if matching a general funnel shift, it should be clear.
9037static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
9038 SelectionDAG &DAG, bool IsRotate, bool FromAdd) {
9039 const auto &TLI = DAG.getTargetLoweringInfo();
9040 // If EltSize is a power of 2 then:
9041 //
9042 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
9043 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
9044 //
9045 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
9046 // for the stronger condition:
9047 //
9048 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
9049 //
9050 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
9051 // we can just replace Neg with Neg' for the rest of the function.
9052 //
9053 // In other cases we check for the even stronger condition:
9054 //
9055 // Neg == EltSize - Pos [B]
9056 //
9057 // for all Neg and Pos. Note that the (or ...) then invokes undefined
9058 // behavior if Pos == 0 (and consequently Neg == EltSize).
9059 //
9060 // We could actually use [A] whenever EltSize is a power of 2, but the
9061 // only extra cases that it would match are those uninteresting ones
9062 // where Neg and Pos are never in range at the same time. E.g. for
9063 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
9064 // as well as (sub 32, Pos), but:
9065 //
9066 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
9067 //
9068 // always invokes undefined behavior for 32-bit X.
9069 //
9070 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
9071 // This allows us to peek through any operations that only affect Mask's
9072 // un-demanded bits.
9073 //
9074 // NOTE: We can only do this when matching operations which won't modify the
9075 // least Log2(EltSize) significant bits and not a general funnel shift.
9076 unsigned MaskLoBits = 0;
9077 if (IsRotate && !FromAdd && isPowerOf2_64(EltSize)) {
9078 unsigned Bits = Log2_64(EltSize);
9079 unsigned NegBits = Neg.getScalarValueSizeInBits();
9080 if (NegBits >= Bits) {
9081 APInt DemandedBits = APInt::getLowBitsSet(NegBits, Bits);
9082 if (SDValue Inner =
9084 Neg = Inner;
9085 MaskLoBits = Bits;
9086 }
9087 }
9088 }
9089
9090 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
9091 if (Neg.getOpcode() != ISD::SUB)
9092 return false;
9094 if (!NegC)
9095 return false;
9096 SDValue NegOp1 = Neg.getOperand(1);
9097
9098 // On the RHS of [A], if Pos is the result of operation on Pos' that won't
9099 // affect Mask's demanded bits, just replace Pos with Pos'. These operations
9100 // are redundant for the purpose of the equality.
9101 if (MaskLoBits) {
9102 unsigned PosBits = Pos.getScalarValueSizeInBits();
9103 if (PosBits >= MaskLoBits) {
9104 APInt DemandedBits = APInt::getLowBitsSet(PosBits, MaskLoBits);
9105 if (SDValue Inner =
9107 Pos = Inner;
9108 }
9109 }
9110 }
9111
9112 // The condition we need is now:
9113 //
9114 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
9115 //
9116 // If NegOp1 == Pos then we need:
9117 //
9118 // EltSize & Mask == NegC & Mask
9119 //
9120 // (because "x & Mask" is a truncation and distributes through subtraction).
9121 //
9122 // We also need to account for a potential truncation of NegOp1 if the amount
9123 // has already been legalized to a shift amount type.
9124 APInt Width;
9125 if ((Pos == NegOp1) ||
9126 (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
9127 Width = NegC->getAPIntValue();
9128
9129 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
9130 // Then the condition we want to prove becomes:
9131 //
9132 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
9133 //
9134 // which, again because "x & Mask" is a truncation, becomes:
9135 //
9136 // NegC & Mask == (EltSize - PosC) & Mask
9137 // EltSize & Mask == (NegC + PosC) & Mask
9138 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
9139 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
9140 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
9141 else
9142 return false;
9143 } else
9144 return false;
9145
9146 // Now we just need to check that EltSize & Mask == Width & Mask.
9147 if (MaskLoBits)
9148 // EltSize & Mask is 0 since Mask is EltSize - 1.
9149 return Width.getLoBits(MaskLoBits) == 0;
9150 return Width == EltSize;
9151}
9152
9153// A subroutine of MatchRotate used once we have found an OR of two opposite
9154// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
9155// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
9156// former being preferred if supported. InnerPos and InnerNeg are Pos and
9157// Neg with outer conversions stripped away.
9158SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
9159 SDValue Neg, SDValue InnerPos,
9160 SDValue InnerNeg, bool FromAdd,
9161 bool HasPos, unsigned PosOpcode,
9162 unsigned NegOpcode, const SDLoc &DL) {
9163 // fold (or/add (shl x, (*ext y)),
9164 // (srl x, (*ext (sub 32, y)))) ->
9165 // (rotl x, y) or (rotr x, (sub 32, y))
9166 //
9167 // fold (or/add (shl x, (*ext (sub 32, y))),
9168 // (srl x, (*ext y))) ->
9169 // (rotr x, y) or (rotl x, (sub 32, y))
9170 EVT VT = Shifted.getValueType();
9171 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG,
9172 /*IsRotate*/ true, FromAdd))
9173 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
9174 HasPos ? Pos : Neg);
9175
9176 return SDValue();
9177}
9178
9179// A subroutine of MatchRotate used once we have found an OR of two opposite
9180// shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces
9181// to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
9182// former being preferred if supported. InnerPos and InnerNeg are Pos and
9183// Neg with outer conversions stripped away.
9184// TODO: Merge with MatchRotatePosNeg.
9185SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
9186 SDValue Neg, SDValue InnerPos,
9187 SDValue InnerNeg, bool FromAdd,
9188 bool HasPos, unsigned PosOpcode,
9189 unsigned NegOpcode, const SDLoc &DL) {
9190 EVT VT = N0.getValueType();
9191 unsigned EltBits = VT.getScalarSizeInBits();
9192
9193 // fold (or/add (shl x0, (*ext y)),
9194 // (srl x1, (*ext (sub 32, y)))) ->
9195 // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
9196 //
9197 // fold (or/add (shl x0, (*ext (sub 32, y))),
9198 // (srl x1, (*ext y))) ->
9199 // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
9200 if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1,
9201 FromAdd))
9202 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
9203 HasPos ? Pos : Neg);
9204
9205 // Matching the shift+xor cases, we can't easily use the xor'd shift amount
9206 // so for now just use the PosOpcode case if its legal.
9207 // TODO: When can we use the NegOpcode case?
9208 if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
9209 SDValue X;
9210 // fold (or/add (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
9211 // -> (fshl x0, x1, y)
9212 if (sd_match(N1, m_Srl(m_Value(X), m_One())) &&
9213 sd_match(InnerNeg,
9214 m_Xor(m_Specific(InnerPos), m_SpecificInt(EltBits - 1))) &&
9216 return DAG.getNode(ISD::FSHL, DL, VT, N0, X, Pos);
9217 }
9218
9219 // fold (or/add (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
9220 // -> (fshr x0, x1, y)
9221 if (sd_match(N0, m_Shl(m_Value(X), m_One())) &&
9222 sd_match(InnerPos,
9223 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9225 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9226 }
9227
9228 // fold (or/add (shl (add x0, x0), (xor y, 31)), (srl x1, y))
9229 // -> (fshr x0, x1, y)
9230 // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
9231 if (sd_match(N0, m_Add(m_Value(X), m_Deferred(X))) &&
9232 sd_match(InnerPos,
9233 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9235 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9236 }
9237 }
9238
9239 return SDValue();
9240}
9241
9242// MatchRotate - Handle an 'or' or 'add' of two operands. If this is one of the
9243// many idioms for rotate, and if the target supports rotation instructions,
9244// generate a rot[lr]. This also matches funnel shift patterns, similar to
9245// rotation but with different shifted sources.
9246SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
9247 bool FromAdd) {
9248 EVT VT = LHS.getValueType();
9249
9250 // The target must have at least one rotate/funnel flavor.
9251 // We still try to match rotate by constant pre-legalization.
9252 // TODO: Support pre-legalization funnel-shift by constant.
9253 bool HasROTL = hasOperation(ISD::ROTL, VT);
9254 bool HasROTR = hasOperation(ISD::ROTR, VT);
9255 bool HasFSHL = hasOperation(ISD::FSHL, VT);
9256 bool HasFSHR = hasOperation(ISD::FSHR, VT);
9257
9258 // If the type is going to be promoted and the target has enabled custom
9259 // lowering for rotate, allow matching rotate by non-constants. Only allow
9260 // this for scalar types.
9261 if (VT.isScalarInteger() && TLI.getTypeAction(*DAG.getContext(), VT) ==
9265 }
9266
9267 if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9268 return SDValue();
9269
9270 // Check for truncated rotate.
9271 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
9272 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
9273 assert(LHS.getValueType() == RHS.getValueType());
9274 if (SDValue Rot =
9275 MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL, FromAdd))
9276 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
9277 }
9278
9279 // Match "(X shl/srl V1) & V2" where V2 may not be present.
9280 SDValue LHSShift; // The shift.
9281 SDValue LHSMask; // AND value if any.
9282 matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
9283
9284 SDValue RHSShift; // The shift.
9285 SDValue RHSMask; // AND value if any.
9286 matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
9287
9288 // If neither side matched a rotate half, bail
9289 if (!LHSShift && !RHSShift)
9290 return SDValue();
9291
9292 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
9293 // side of the rotate, so try to handle that here. In all cases we need to
9294 // pass the matched shift from the opposite side to compute the opcode and
9295 // needed shift amount to extract. We still want to do this if both sides
9296 // matched a rotate half because one half may be a potential overshift that
9297 // can be broken down (ie if InstCombine merged two shl or srl ops into a
9298 // single one).
9299
9300 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
9301 if (LHSShift)
9302 if (SDValue NewRHSShift =
9303 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
9304 RHSShift = NewRHSShift;
9305 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
9306 if (RHSShift)
9307 if (SDValue NewLHSShift =
9308 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
9309 LHSShift = NewLHSShift;
9310
9311 // If a side is still missing, nothing else we can do.
9312 if (!RHSShift || !LHSShift)
9313 return SDValue();
9314
9315 // At this point we've matched or extracted a shift op on each side.
9316
9317 if (LHSShift.getOpcode() == RHSShift.getOpcode())
9318 return SDValue(); // Shifts must disagree.
9319
9320 // Canonicalize shl to left side in a shl/srl pair.
9321 if (RHSShift.getOpcode() == ISD::SHL) {
9322 std::swap(LHS, RHS);
9323 std::swap(LHSShift, RHSShift);
9324 std::swap(LHSMask, RHSMask);
9325 }
9326
9327 // Something has gone wrong - we've lost the shl/srl pair - bail.
9328 if (LHSShift.getOpcode() != ISD::SHL || RHSShift.getOpcode() != ISD::SRL)
9329 return SDValue();
9330
9331 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9332 SDValue LHSShiftArg = LHSShift.getOperand(0);
9333 SDValue LHSShiftAmt = LHSShift.getOperand(1);
9334 SDValue RHSShiftArg = RHSShift.getOperand(0);
9335 SDValue RHSShiftAmt = RHSShift.getOperand(1);
9336
9337 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
9338 ConstantSDNode *RHS) {
9339 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
9340 };
9341
9342 auto ApplyMasks = [&](SDValue Res) {
9343 // If there is an AND of either shifted operand, apply it to the result.
9344 if (LHSMask.getNode() || RHSMask.getNode()) {
9347
9348 if (LHSMask.getNode()) {
9349 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
9350 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9351 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
9352 }
9353 if (RHSMask.getNode()) {
9354 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
9355 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9356 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
9357 }
9358
9359 Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
9360 }
9361
9362 return Res;
9363 };
9364
9365 // TODO: Support pre-legalization funnel-shift by constant.
9366 bool IsRotate = LHSShiftArg == RHSShiftArg;
9367 if (!IsRotate && !(HasFSHL || HasFSHR)) {
9368 if (TLI.isTypeLegal(VT) && LHS.hasOneUse() && RHS.hasOneUse() &&
9369 ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9370 // Look for a disguised rotate by constant.
9371 // The common shifted operand X may be hidden inside another 'or'.
9372 SDValue X, Y;
9373 auto matchOr = [&X, &Y](SDValue Or, SDValue CommonOp) {
9374 if (!Or.hasOneUse() || Or.getOpcode() != ISD::OR)
9375 return false;
9376 if (CommonOp == Or.getOperand(0)) {
9377 X = CommonOp;
9378 Y = Or.getOperand(1);
9379 return true;
9380 }
9381 if (CommonOp == Or.getOperand(1)) {
9382 X = CommonOp;
9383 Y = Or.getOperand(0);
9384 return true;
9385 }
9386 return false;
9387 };
9388
9389 SDValue Res;
9390 if (matchOr(LHSShiftArg, RHSShiftArg)) {
9391 // (shl (X | Y), C1) | (srl X, C2) --> (rotl X, C1) | (shl Y, C1)
9392 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9393 SDValue ShlY = DAG.getNode(ISD::SHL, DL, VT, Y, LHSShiftAmt);
9394 Res = DAG.getNode(ISD::OR, DL, VT, RotX, ShlY);
9395 } else if (matchOr(RHSShiftArg, LHSShiftArg)) {
9396 // (shl X, C1) | (srl (X | Y), C2) --> (rotl X, C1) | (srl Y, C2)
9397 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9398 SDValue SrlY = DAG.getNode(ISD::SRL, DL, VT, Y, RHSShiftAmt);
9399 Res = DAG.getNode(ISD::OR, DL, VT, RotX, SrlY);
9400 } else {
9401 return SDValue();
9402 }
9403
9404 return ApplyMasks(Res);
9405 }
9406
9407 return SDValue(); // Requires funnel shift support.
9408 }
9409
9410 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotl x, C1)
9411 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotr x, C2)
9412 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
9413 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
9414 // iff C1+C2 == EltSizeInBits
9415 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9416 SDValue Res;
9417 if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) {
9418 bool UseROTL = !LegalOperations || HasROTL;
9419 Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
9420 UseROTL ? LHSShiftAmt : RHSShiftAmt);
9421 } else {
9422 bool UseFSHL = !LegalOperations || HasFSHL;
9423 Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
9424 RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt);
9425 }
9426
9427 return ApplyMasks(Res);
9428 }
9429
9430 // Even pre-legalization, we can't easily rotate/funnel-shift by a variable
9431 // shift.
9432 if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9433 return SDValue();
9434
9435 // If there is a mask here, and we have a variable shift, we can't be sure
9436 // that we're masking out the right stuff.
9437 if (LHSMask.getNode() || RHSMask.getNode())
9438 return SDValue();
9439
9440 // If the shift amount is sign/zext/any-extended just peel it off.
9441 SDValue LExtOp0 = LHSShiftAmt;
9442 SDValue RExtOp0 = RHSShiftAmt;
9443 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9444 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9445 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9446 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
9447 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9448 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9449 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9450 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
9451 LExtOp0 = LHSShiftAmt.getOperand(0);
9452 RExtOp0 = RHSShiftAmt.getOperand(0);
9453 }
9454
9455 if (IsRotate && (HasROTL || HasROTR)) {
9456 if (SDValue TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
9457 LExtOp0, RExtOp0, FromAdd, HasROTL,
9459 return TryL;
9460
9461 if (SDValue TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
9462 RExtOp0, LExtOp0, FromAdd, HasROTR,
9464 return TryR;
9465 }
9466
9467 if (SDValue TryL = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt,
9468 RHSShiftAmt, LExtOp0, RExtOp0, FromAdd,
9469 HasFSHL, ISD::FSHL, ISD::FSHR, DL))
9470 return TryL;
9471
9472 if (SDValue TryR = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt,
9473 LHSShiftAmt, RExtOp0, LExtOp0, FromAdd,
9474 HasFSHR, ISD::FSHR, ISD::FSHL, DL))
9475 return TryR;
9476
9477 return SDValue();
9478}
9479
9480/// Recursively traverses the expression calculating the origin of the requested
9481/// byte of the given value. Returns std::nullopt if the provider can't be
9482/// calculated.
9483///
9484/// For all the values except the root of the expression, we verify that the
9485/// value has exactly one use and if not then return std::nullopt. This way if
9486/// the origin of the byte is returned it's guaranteed that the values which
9487/// contribute to the byte are not used outside of this expression.
9488
9489/// However, there is a special case when dealing with vector loads -- we allow
9490/// more than one use if the load is a vector type. Since the values that
9491/// contribute to the byte ultimately come from the ExtractVectorElements of the
9492/// Load, we don't care if the Load has uses other than ExtractVectorElements,
9493/// because those operations are independent from the pattern to be combined.
9494/// For vector loads, we simply care that the ByteProviders are adjacent
9495/// positions of the same vector, and their index matches the byte that is being
9496/// provided. This is captured by the \p VectorIndex algorithm. \p VectorIndex
9497/// is the index used in an ExtractVectorElement, and \p StartingIndex is the
9498/// byte position we are trying to provide for the LoadCombine. If these do
9499/// not match, then we can not combine the vector loads. \p Index uses the
9500/// byte position we are trying to provide for and is matched against the
9501/// shl and load size. The \p Index algorithm ensures the requested byte is
9502/// provided for by the pattern, and the pattern does not over provide bytes.
9503///
9504///
9505/// The supported LoadCombine pattern for vector loads is as follows
9506/// or
9507/// / \
9508/// or shl
9509/// / \ |
9510/// or shl zext
9511/// / \ | |
9512/// shl zext zext EVE*
9513/// | | | |
9514/// zext EVE* EVE* LOAD
9515/// | | |
9516/// EVE* LOAD LOAD
9517/// |
9518/// LOAD
9519///
9520/// *ExtractVectorElement
9522
9523static std::optional<SDByteProvider>
9524calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
9525 std::optional<uint64_t> VectorIndex,
9526 unsigned StartingIndex = 0) {
9527
9528 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
9529 if (Depth == 10)
9530 return std::nullopt;
9531
9532 // Only allow multiple uses if the instruction is a vector load (in which
9533 // case we will use the load for every ExtractVectorElement)
9534 if (Depth && !Op.hasOneUse() &&
9535 (Op.getOpcode() != ISD::LOAD || !Op.getValueType().isVector()))
9536 return std::nullopt;
9537
9538 // Fail to combine if we have encountered anything but a LOAD after handling
9539 // an ExtractVectorElement.
9540 if (Op.getOpcode() != ISD::LOAD && VectorIndex.has_value())
9541 return std::nullopt;
9542
9543 unsigned BitWidth = Op.getScalarValueSizeInBits();
9544 if (BitWidth % 8 != 0)
9545 return std::nullopt;
9546 unsigned ByteWidth = BitWidth / 8;
9547 assert(Index < ByteWidth && "invalid index requested");
9548 (void) ByteWidth;
9549
9550 switch (Op.getOpcode()) {
9551 case ISD::OR: {
9552 auto LHS =
9553 calculateByteProvider(Op->getOperand(0), Index, Depth + 1, VectorIndex);
9554 if (!LHS)
9555 return std::nullopt;
9556 auto RHS =
9557 calculateByteProvider(Op->getOperand(1), Index, Depth + 1, VectorIndex);
9558 if (!RHS)
9559 return std::nullopt;
9560
9561 if (LHS->isConstantZero())
9562 return RHS;
9563 if (RHS->isConstantZero())
9564 return LHS;
9565 return std::nullopt;
9566 }
9567 case ISD::SHL: {
9568 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9569 if (!ShiftOp)
9570 return std::nullopt;
9571
9572 uint64_t BitShift = ShiftOp->getZExtValue();
9573
9574 if (BitShift % 8 != 0)
9575 return std::nullopt;
9576 uint64_t ByteShift = BitShift / 8;
9577
9578 // If we are shifting by an amount greater than the index we are trying to
9579 // provide, then do not provide anything. Otherwise, subtract the index by
9580 // the amount we shifted by.
9581 return Index < ByteShift
9583 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
9584 Depth + 1, VectorIndex, Index);
9585 }
9586 case ISD::ANY_EXTEND:
9587 case ISD::SIGN_EXTEND:
9588 case ISD::ZERO_EXTEND: {
9589 SDValue NarrowOp = Op->getOperand(0);
9590 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9591 if (NarrowBitWidth % 8 != 0)
9592 return std::nullopt;
9593 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9594
9595 if (Index >= NarrowByteWidth)
9596 return Op.getOpcode() == ISD::ZERO_EXTEND
9597 ? std::optional<SDByteProvider>(
9599 : std::nullopt;
9600 return calculateByteProvider(NarrowOp, Index, Depth + 1, VectorIndex,
9601 StartingIndex);
9602 }
9603 case ISD::BSWAP:
9604 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
9605 Depth + 1, VectorIndex, StartingIndex);
9607 auto OffsetOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9608 if (!OffsetOp)
9609 return std::nullopt;
9610
9611 VectorIndex = OffsetOp->getZExtValue();
9612
9613 SDValue NarrowOp = Op->getOperand(0);
9614 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9615 if (NarrowBitWidth % 8 != 0)
9616 return std::nullopt;
9617 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9618 // EXTRACT_VECTOR_ELT can extend the element type to the width of the return
9619 // type, leaving the high bits undefined.
9620 if (Index >= NarrowByteWidth)
9621 return std::nullopt;
9622
9623 // Check to see if the position of the element in the vector corresponds
9624 // with the byte we are trying to provide for. In the case of a vector of
9625 // i8, this simply means the VectorIndex == StartingIndex. For non i8 cases,
9626 // the element will provide a range of bytes. For example, if we have a
9627 // vector of i16s, each element provides two bytes (V[1] provides byte 2 and
9628 // 3).
9629 if (*VectorIndex * NarrowByteWidth > StartingIndex)
9630 return std::nullopt;
9631 if ((*VectorIndex + 1) * NarrowByteWidth <= StartingIndex)
9632 return std::nullopt;
9633
9634 return calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
9635 VectorIndex, StartingIndex);
9636 }
9637 case ISD::LOAD: {
9638 auto L = cast<LoadSDNode>(Op.getNode());
9639 if (!L->isSimple() || L->isIndexed())
9640 return std::nullopt;
9641
9642 unsigned NarrowBitWidth = L->getMemoryVT().getScalarSizeInBits();
9643 if (NarrowBitWidth % 8 != 0)
9644 return std::nullopt;
9645 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9646
9647 // If the width of the load does not reach byte we are trying to provide for
9648 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
9649 // question
9650 if (Index >= NarrowByteWidth)
9651 return L->getExtensionType() == ISD::ZEXTLOAD
9652 ? std::optional<SDByteProvider>(
9654 : std::nullopt;
9655
9656 unsigned BPVectorIndex = VectorIndex.value_or(0U);
9657 return SDByteProvider::getSrc(L, Index, BPVectorIndex);
9658 }
9659 }
9660
9661 return std::nullopt;
9662}
9663
9664static unsigned littleEndianByteAt(unsigned BW, unsigned i) {
9665 return i;
9666}
9667
9668static unsigned bigEndianByteAt(unsigned BW, unsigned i) {
9669 return BW - i - 1;
9670}
9671
9672// Check if the bytes offsets we are looking at match with either big or
9673// little endian value loaded. Return true for big endian, false for little
9674// endian, and std::nullopt if match failed.
9675static std::optional<bool> isBigEndian(ArrayRef<int64_t> ByteOffsets,
9676 int64_t FirstOffset) {
9677 // The endian can be decided only when it is 2 bytes at least.
9678 unsigned Width = ByteOffsets.size();
9679 if (Width < 2)
9680 return std::nullopt;
9681
9682 bool BigEndian = true, LittleEndian = true;
9683 for (unsigned i = 0; i < Width; i++) {
9684 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
9685 LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i);
9686 BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i);
9687 if (!BigEndian && !LittleEndian)
9688 return std::nullopt;
9689 }
9690
9691 assert((BigEndian != LittleEndian) && "It should be either big endian or"
9692 "little endian");
9693 return BigEndian;
9694}
9695
9696// Look through one layer of truncate or extend.
9698 switch (Value.getOpcode()) {
9699 case ISD::TRUNCATE:
9700 case ISD::ZERO_EXTEND:
9701 case ISD::SIGN_EXTEND:
9702 case ISD::ANY_EXTEND:
9703 return Value.getOperand(0);
9704 }
9705 return SDValue();
9706}
9707
9708/// Match a pattern where a wide type scalar value is stored by several narrow
9709/// stores. Fold it into a single store or a BSWAP and a store if the targets
9710/// supports it.
9711///
9712/// Assuming little endian target:
9713/// i8 *p = ...
9714/// i32 val = ...
9715/// p[0] = (val >> 0) & 0xFF;
9716/// p[1] = (val >> 8) & 0xFF;
9717/// p[2] = (val >> 16) & 0xFF;
9718/// p[3] = (val >> 24) & 0xFF;
9719/// =>
9720/// *((i32)p) = val;
9721///
9722/// i8 *p = ...
9723/// i32 val = ...
9724/// p[0] = (val >> 24) & 0xFF;
9725/// p[1] = (val >> 16) & 0xFF;
9726/// p[2] = (val >> 8) & 0xFF;
9727/// p[3] = (val >> 0) & 0xFF;
9728/// =>
9729/// *((i32)p) = BSWAP(val);
9730SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) {
9731 // The matching looks for "store (trunc x)" patterns that appear early but are
9732 // likely to be replaced by truncating store nodes during combining.
9733 // TODO: If there is evidence that running this later would help, this
9734 // limitation could be removed. Legality checks may need to be added
9735 // for the created store and optional bswap/rotate.
9736 if (LegalOperations || OptLevel == CodeGenOptLevel::None)
9737 return SDValue();
9738
9739 // We only handle merging simple stores of 1-4 bytes.
9740 // TODO: Allow unordered atomics when wider type is legal (see D66309)
9741 EVT MemVT = N->getMemoryVT();
9742 if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) ||
9743 !N->isSimple() || N->isIndexed())
9744 return SDValue();
9745
9746 // Collect all of the stores in the chain, upto the maximum store width (i64).
9747 SDValue Chain = N->getChain();
9749 unsigned NarrowNumBits = MemVT.getScalarSizeInBits();
9750 unsigned MaxWideNumBits = 64;
9751 unsigned MaxStores = MaxWideNumBits / NarrowNumBits;
9752 while (auto *Store = dyn_cast<StoreSDNode>(Chain)) {
9753 // All stores must be the same size to ensure that we are writing all of the
9754 // bytes in the wide value.
9755 // This store should have exactly one use as a chain operand for another
9756 // store in the merging set. If there are other chain uses, then the
9757 // transform may not be safe because order of loads/stores outside of this
9758 // set may not be preserved.
9759 // TODO: We could allow multiple sizes by tracking each stored byte.
9760 if (Store->getMemoryVT() != MemVT || !Store->isSimple() ||
9761 Store->isIndexed() || !Store->hasOneUse())
9762 return SDValue();
9763 Stores.push_back(Store);
9764 Chain = Store->getChain();
9765 if (MaxStores < Stores.size())
9766 return SDValue();
9767 }
9768 // There is no reason to continue if we do not have at least a pair of stores.
9769 if (Stores.size() < 2)
9770 return SDValue();
9771
9772 // Handle simple types only.
9773 LLVMContext &Context = *DAG.getContext();
9774 unsigned NumStores = Stores.size();
9775 unsigned WideNumBits = NumStores * NarrowNumBits;
9776 if (WideNumBits != 16 && WideNumBits != 32 && WideNumBits != 64)
9777 return SDValue();
9778
9779 // Check if all bytes of the source value that we are looking at are stored
9780 // to the same base address. Collect offsets from Base address into OffsetMap.
9781 SDValue SourceValue;
9782 SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX);
9783 int64_t FirstOffset = INT64_MAX;
9784 StoreSDNode *FirstStore = nullptr;
9785 std::optional<BaseIndexOffset> Base;
9786 for (auto *Store : Stores) {
9787 // All the stores store different parts of the CombinedValue. A truncate is
9788 // required to get the partial value.
9789 SDValue Trunc = Store->getValue();
9790 if (Trunc.getOpcode() != ISD::TRUNCATE)
9791 return SDValue();
9792 // Other than the first/last part, a shift operation is required to get the
9793 // offset.
9794 int64_t Offset = 0;
9795 SDValue WideVal = Trunc.getOperand(0);
9796 if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) &&
9797 isa<ConstantSDNode>(WideVal.getOperand(1))) {
9798 // The shift amount must be a constant multiple of the narrow type.
9799 // It is translated to the offset address in the wide source value "y".
9800 //
9801 // x = srl y, ShiftAmtC
9802 // i8 z = trunc x
9803 // store z, ...
9804 uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1);
9805 if (ShiftAmtC % NarrowNumBits != 0)
9806 return SDValue();
9807
9808 // Make sure we aren't reading bits that are shifted in.
9809 if (ShiftAmtC > WideVal.getScalarValueSizeInBits() - NarrowNumBits)
9810 return SDValue();
9811
9812 Offset = ShiftAmtC / NarrowNumBits;
9813 WideVal = WideVal.getOperand(0);
9814 }
9815
9816 // Stores must share the same source value with different offsets.
9817 if (!SourceValue)
9818 SourceValue = WideVal;
9819 else if (SourceValue != WideVal) {
9820 // Truncate and extends can be stripped to see if the values are related.
9821 if (stripTruncAndExt(SourceValue) != WideVal &&
9822 stripTruncAndExt(WideVal) != SourceValue)
9823 return SDValue();
9824
9825 if (WideVal.getScalarValueSizeInBits() >
9826 SourceValue.getScalarValueSizeInBits())
9827 SourceValue = WideVal;
9828
9829 // Give up if the source value type is smaller than the store size.
9830 if (SourceValue.getScalarValueSizeInBits() < WideNumBits)
9831 return SDValue();
9832 }
9833
9834 // Stores must share the same base address.
9835 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
9836 int64_t ByteOffsetFromBase = 0;
9837 if (!Base)
9838 Base = Ptr;
9839 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
9840 return SDValue();
9841
9842 // Remember the first store.
9843 if (ByteOffsetFromBase < FirstOffset) {
9844 FirstStore = Store;
9845 FirstOffset = ByteOffsetFromBase;
9846 }
9847 // Map the offset in the store and the offset in the combined value, and
9848 // early return if it has been set before.
9849 if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX)
9850 return SDValue();
9851 OffsetMap[Offset] = ByteOffsetFromBase;
9852 }
9853
9854 EVT WideVT = EVT::getIntegerVT(Context, WideNumBits);
9855
9856 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
9857 assert(FirstStore && "First store must be set");
9858
9859 // Check that a store of the wide type is both allowed and fast on the target
9860 const DataLayout &Layout = DAG.getDataLayout();
9861 unsigned Fast = 0;
9862 bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT,
9863 *FirstStore->getMemOperand(), &Fast);
9864 if (!Allowed || !Fast)
9865 return SDValue();
9866
9867 // Check if the pieces of the value are going to the expected places in memory
9868 // to merge the stores.
9869 auto checkOffsets = [&](bool MatchLittleEndian) {
9870 if (MatchLittleEndian) {
9871 for (unsigned i = 0; i != NumStores; ++i)
9872 if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset)
9873 return false;
9874 } else { // MatchBigEndian by reversing loop counter.
9875 for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j)
9876 if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset)
9877 return false;
9878 }
9879 return true;
9880 };
9881
9882 // Check if the offsets line up for the native data layout of this target.
9883 bool NeedBswap = false;
9884 bool NeedRotate = false;
9885 if (!checkOffsets(Layout.isLittleEndian())) {
9886 // Special-case: check if byte offsets line up for the opposite endian.
9887 if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian()))
9888 NeedBswap = true;
9889 else if (NumStores == 2 && checkOffsets(Layout.isBigEndian()))
9890 NeedRotate = true;
9891 else
9892 return SDValue();
9893 }
9894
9895 SDLoc DL(N);
9896 if (WideVT != SourceValue.getValueType()) {
9897 assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&
9898 "Unexpected store value to merge");
9899 SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue);
9900 }
9901
9902 // Before legalize we can introduce illegal bswaps/rotates which will be later
9903 // converted to an explicit bswap sequence. This way we end up with a single
9904 // store and byte shuffling instead of several stores and byte shuffling.
9905 if (NeedBswap) {
9906 SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue);
9907 } else if (NeedRotate) {
9908 assert(WideNumBits % 2 == 0 && "Unexpected type for rotate");
9909 SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT);
9910 SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt);
9911 }
9912
9913 SDValue NewStore =
9914 DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(),
9915 FirstStore->getPointerInfo(), FirstStore->getAlign());
9916
9917 // Rely on other DAG combine rules to remove the other individual stores.
9918 DAG.ReplaceAllUsesWith(N, NewStore.getNode());
9919 return NewStore;
9920}
9921
9922/// Match a pattern where a wide type scalar value is loaded by several narrow
9923/// loads and combined by shifts and ors. Fold it into a single load or a load
9924/// and a BSWAP if the targets supports it.
9925///
9926/// Assuming little endian target:
9927/// i8 *a = ...
9928/// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
9929/// =>
9930/// i32 val = *((i32)a)
9931///
9932/// i8 *a = ...
9933/// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
9934/// =>
9935/// i32 val = BSWAP(*((i32)a))
9936///
9937/// TODO: This rule matches complex patterns with OR node roots and doesn't
9938/// interact well with the worklist mechanism. When a part of the pattern is
9939/// updated (e.g. one of the loads) its direct users are put into the worklist,
9940/// but the root node of the pattern which triggers the load combine is not
9941/// necessarily a direct user of the changed node. For example, once the address
9942/// of t28 load is reassociated load combine won't be triggered:
9943/// t25: i32 = add t4, Constant:i32<2>
9944/// t26: i64 = sign_extend t25
9945/// t27: i64 = add t2, t26
9946/// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
9947/// t29: i32 = zero_extend t28
9948/// t32: i32 = shl t29, Constant:i8<8>
9949/// t33: i32 = or t23, t32
9950/// As a possible fix visitLoad can check if the load can be a part of a load
9951/// combine pattern and add corresponding OR roots to the worklist.
9952SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
9953 assert(N->getOpcode() == ISD::OR &&
9954 "Can only match load combining against OR nodes");
9955
9956 // Handles simple types only
9957 EVT VT = N->getValueType(0);
9958 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9959 return SDValue();
9960 unsigned ByteWidth = VT.getSizeInBits() / 8;
9961
9962 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
9963 auto MemoryByteOffset = [&](SDByteProvider P) {
9964 assert(P.hasSrc() && "Must be a memory byte provider");
9965 auto *Load = cast<LoadSDNode>(P.Src.value());
9966
9967 unsigned LoadBitWidth = Load->getMemoryVT().getScalarSizeInBits();
9968
9969 assert(LoadBitWidth % 8 == 0 &&
9970 "can only analyze providers for individual bytes not bit");
9971 unsigned LoadByteWidth = LoadBitWidth / 8;
9972 return IsBigEndianTarget ? bigEndianByteAt(LoadByteWidth, P.DestOffset)
9973 : littleEndianByteAt(LoadByteWidth, P.DestOffset);
9974 };
9975
9976 std::optional<BaseIndexOffset> Base;
9977 SDValue Chain;
9978
9979 SmallPtrSet<LoadSDNode *, 8> Loads;
9980 std::optional<SDByteProvider> FirstByteProvider;
9981 int64_t FirstOffset = INT64_MAX;
9982
9983 // Check if all the bytes of the OR we are looking at are loaded from the same
9984 // base address. Collect bytes offsets from Base address in ByteOffsets.
9985 SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
9986 unsigned ZeroExtendedBytes = 0;
9987 for (int i = ByteWidth - 1; i >= 0; --i) {
9988 auto P =
9989 calculateByteProvider(SDValue(N, 0), i, 0, /*VectorIndex*/ std::nullopt,
9990 /*StartingIndex*/ i);
9991 if (!P)
9992 return SDValue();
9993
9994 if (P->isConstantZero()) {
9995 // It's OK for the N most significant bytes to be 0, we can just
9996 // zero-extend the load.
9997 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
9998 return SDValue();
9999 continue;
10000 }
10001 assert(P->hasSrc() && "provenance should either be memory or zero");
10002 auto *L = cast<LoadSDNode>(P->Src.value());
10003
10004 // All loads must share the same chain
10005 SDValue LChain = L->getChain();
10006 if (!Chain)
10007 Chain = LChain;
10008 else if (Chain != LChain)
10009 return SDValue();
10010
10011 // Loads must share the same base address
10012 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
10013 int64_t ByteOffsetFromBase = 0;
10014
10015 // For vector loads, the expected load combine pattern will have an
10016 // ExtractElement for each index in the vector. While each of these
10017 // ExtractElements will be accessing the same base address as determined
10018 // by the load instruction, the actual bytes they interact with will differ
10019 // due to different ExtractElement indices. To accurately determine the
10020 // byte position of an ExtractElement, we offset the base load ptr with
10021 // the index multiplied by the byte size of each element in the vector.
10022 if (L->getMemoryVT().isVector()) {
10023 unsigned LoadWidthInBit = L->getMemoryVT().getScalarSizeInBits();
10024 if (LoadWidthInBit % 8 != 0)
10025 return SDValue();
10026 unsigned ByteOffsetFromVector = P->SrcOffset * LoadWidthInBit / 8;
10027 Ptr.addToOffset(ByteOffsetFromVector);
10028 }
10029
10030 if (!Base)
10031 Base = Ptr;
10032
10033 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
10034 return SDValue();
10035
10036 // Calculate the offset of the current byte from the base address
10037 ByteOffsetFromBase += MemoryByteOffset(*P);
10038 ByteOffsets[i] = ByteOffsetFromBase;
10039
10040 // Remember the first byte load
10041 if (ByteOffsetFromBase < FirstOffset) {
10042 FirstByteProvider = P;
10043 FirstOffset = ByteOffsetFromBase;
10044 }
10045
10046 Loads.insert(L);
10047 }
10048
10049 assert(!Loads.empty() && "All the bytes of the value must be loaded from "
10050 "memory, so there must be at least one load which produces the value");
10051 assert(Base && "Base address of the accessed memory location must be set");
10052 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
10053
10054 bool NeedsZext = ZeroExtendedBytes > 0;
10055
10056 EVT MemVT =
10057 EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
10058
10059 if (!MemVT.isSimple())
10060 return SDValue();
10061
10062 // Check if the bytes of the OR we are looking at match with either big or
10063 // little endian value load
10064 std::optional<bool> IsBigEndian = isBigEndian(
10065 ArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
10066 if (!IsBigEndian)
10067 return SDValue();
10068
10069 assert(FirstByteProvider && "must be set");
10070
10071 // Ensure that the first byte is loaded from zero offset of the first load.
10072 // So the combined value can be loaded from the first load address.
10073 if (MemoryByteOffset(*FirstByteProvider) != 0)
10074 return SDValue();
10075 auto *FirstLoad = cast<LoadSDNode>(FirstByteProvider->Src.value());
10076
10077 // Before legalization we allow introducing loads that are wider than legal,
10078 // which will later be split into legally sized loads. This enables us to
10079 // combine, for example, i8 loads forming an i64 into an i64 load, which get
10080 // then gets split up into couple of i32 loads on 32 bit targets.
10081 if (LegalOperations &&
10082 !TLI.isLoadLegal(VT, MemVT, FirstLoad->getAlign(),
10083 FirstLoad->getAddressSpace(),
10084 NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, false))
10085 return SDValue();
10086
10087 // The node we are looking at matches with the pattern, check if we can
10088 // replace it with a single (possibly zero-extended) load and bswap + shift if
10089 // needed.
10090
10091 // If the load needs byte swap check if the target supports it
10092 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
10093
10094 // Before legalize we can introduce illegal bswaps which will be later
10095 // converted to an explicit bswap sequence. This way we end up with a single
10096 // load and byte shuffling instead of several loads and byte shuffling.
10097 // We do not introduce illegal bswaps when zero-extending as this tends to
10098 // introduce too many arithmetic instructions.
10099 if (NeedsBswap && (LegalOperations || NeedsZext) &&
10100 !TLI.isOperationLegal(ISD::BSWAP, VT))
10101 return SDValue();
10102
10103 // If we need to bswap and zero extend, we have to insert a shift. Check that
10104 // it is legal.
10105 if (NeedsBswap && NeedsZext && LegalOperations &&
10106 !TLI.isOperationLegal(ISD::SHL, VT))
10107 return SDValue();
10108
10109 // Check that a load of the wide type is both allowed and fast on the target
10110 unsigned Fast = 0;
10111 bool Allowed =
10112 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
10113 *FirstLoad->getMemOperand(), &Fast);
10114 if (!Allowed || !Fast)
10115 return SDValue();
10116
10117 SDValue NewLoad =
10118 DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT,
10119 Chain, FirstLoad->getBasePtr(),
10120 FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign());
10121
10122 // Transfer chain users from old loads to the new load.
10123 for (LoadSDNode *L : Loads)
10124 DAG.makeEquivalentMemoryOrdering(L, NewLoad);
10125
10126 if (!NeedsBswap)
10127 return NewLoad;
10128
10129 SDValue ShiftedLoad =
10130 NeedsZext ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
10131 DAG.getShiftAmountConstant(ZeroExtendedBytes * 8,
10132 VT, SDLoc(N)))
10133 : NewLoad;
10134 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
10135}
10136
10137// If the target has andn, bsl, or a similar bit-select instruction,
10138// we want to unfold masked merge, with canonical pattern of:
10139// | A | |B|
10140// ((x ^ y) & m) ^ y
10141// | D |
10142// Into:
10143// (x & m) | (y & ~m)
10144// If y is a constant, m is not a 'not', and the 'andn' does not work with
10145// immediates, we unfold into a different pattern:
10146// ~(~x & m) & (m | y)
10147// If x is a constant, m is a 'not', and the 'andn' does not work with
10148// immediates, we unfold into a different pattern:
10149// (x | ~m) & ~(~m & ~y)
10150// NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
10151// the very least that breaks andnpd / andnps patterns, and because those
10152// patterns are simplified in IR and shouldn't be created in the DAG
10153SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
10154 assert(N->getOpcode() == ISD::XOR);
10155
10156 // Don't touch 'not' (i.e. where y = -1).
10157 if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
10158 return SDValue();
10159
10160 EVT VT = N->getValueType(0);
10161
10162 // There are 3 commutable operators in the pattern,
10163 // so we have to deal with 8 possible variants of the basic pattern.
10164 SDValue X, Y, M;
10165 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
10166 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
10167 return false;
10168 SDValue Xor = And.getOperand(XorIdx);
10169 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
10170 return false;
10171 SDValue Xor0 = Xor.getOperand(0);
10172 SDValue Xor1 = Xor.getOperand(1);
10173 // Don't touch 'not' (i.e. where y = -1).
10174 if (isAllOnesOrAllOnesSplat(Xor1))
10175 return false;
10176 if (Other == Xor0)
10177 std::swap(Xor0, Xor1);
10178 if (Other != Xor1)
10179 return false;
10180 X = Xor0;
10181 Y = Xor1;
10182 M = And.getOperand(XorIdx ? 0 : 1);
10183 return true;
10184 };
10185
10186 SDValue N0 = N->getOperand(0);
10187 SDValue N1 = N->getOperand(1);
10188 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
10189 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
10190 return SDValue();
10191
10192 // Don't do anything if the mask is constant. This should not be reachable.
10193 // InstCombine should have already unfolded this pattern, and DAGCombiner
10194 // probably shouldn't produce it, too.
10195 if (isa<ConstantSDNode>(M.getNode()))
10196 return SDValue();
10197
10198 // We can transform if the target has AndNot
10199 if (!TLI.hasAndNot(M))
10200 return SDValue();
10201
10202 SDLoc DL(N);
10203
10204 // If Y is a constant, check that 'andn' works with immediates. Unless M is
10205 // a bitwise not that would already allow ANDN to be used.
10206 if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) {
10207 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
10208 // If not, we need to do a bit more work to make sure andn is still used.
10209 SDValue NotX = DAG.getNOT(DL, X, VT);
10210 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
10211 SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
10212 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
10213 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
10214 }
10215
10216 // If X is a constant and M is a bitwise not, check that 'andn' works with
10217 // immediates.
10218 if (!TLI.hasAndNot(X) && isBitwiseNot(M)) {
10219 assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable.");
10220 // If not, we need to do a bit more work to make sure andn is still used.
10221 SDValue NotM = M.getOperand(0);
10222 SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM);
10223 SDValue NotY = DAG.getNOT(DL, Y, VT);
10224 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY);
10225 SDValue NotRHS = DAG.getNOT(DL, RHS, VT);
10226 return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS);
10227 }
10228
10229 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
10230 SDValue NotM = DAG.getNOT(DL, M, VT);
10231 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
10232
10233 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
10234}
10235
10236SDValue DAGCombiner::visitXOR(SDNode *N) {
10237 SDValue N0 = N->getOperand(0);
10238 SDValue N1 = N->getOperand(1);
10239 EVT VT = N0.getValueType();
10240 SDLoc DL(N);
10241
10242 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
10243 if (N0.isUndef() && N1.isUndef())
10244 return DAG.getConstant(0, DL, VT);
10245
10246 // fold (xor x, undef) -> undef
10247 if (N0.isUndef())
10248 return N0;
10249 if (N1.isUndef())
10250 return N1;
10251
10252 // fold (xor c1, c2) -> c1^c2
10253 if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
10254 return C;
10255
10256 // canonicalize constant to RHS
10259 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
10260
10261 // fold vector ops
10262 if (VT.isVector()) {
10263 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
10264 return FoldedVOp;
10265
10266 // fold (xor x, 0) -> x, vector edition
10268 return N0;
10269 }
10270
10271 // fold (xor x, 0) -> x
10272 if (isNullConstant(N1))
10273 return N0;
10274
10275 if (SDValue NewSel = foldBinOpIntoSelect(N))
10276 return NewSel;
10277
10278 // reassociate xor
10279 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
10280 return RXOR;
10281
10282 // Fold xor(vecreduce(x), vecreduce(y)) -> vecreduce(xor(x, y))
10283 if (SDValue SD =
10284 reassociateReduction(ISD::VECREDUCE_XOR, ISD::XOR, DL, VT, N0, N1))
10285 return SD;
10286
10287 // fold (a^b) -> (a|b) iff a and b share no bits.
10288 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
10289 DAG.haveNoCommonBitsSet(N0, N1))
10290 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
10291
10292 // look for 'add-like' folds:
10293 // XOR(N0,MIN_SIGNED_VALUE) == ADD(N0,MIN_SIGNED_VALUE)
10294 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
10296 if (SDValue Combined = visitADDLike(N))
10297 return Combined;
10298
10299 // fold not (setcc x, y, cc) -> setcc x y !cc
10300 // Avoid breaking: and (not(setcc x, y, cc), z) -> andn for vec
10301 unsigned N0Opcode = N0.getOpcode();
10302 SDValue LHS, RHS, CC;
10303 if (TLI.isConstTrueVal(N1) &&
10304 isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/ true) &&
10305 !(VT.isVector() && TLI.hasAndNot(SDValue(N, 0)) && N->hasOneUse() &&
10306 N->use_begin()->getUser()->getOpcode() == ISD::AND)) {
10308 LHS.getValueType());
10309 if (!LegalOperations ||
10310 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
10311 // Propagate fast-math-flags.
10312 SDNodeFlags Flags = N0->getFlags();
10313 switch (N0Opcode) {
10314 default:
10315 llvm_unreachable("Unhandled SetCC Equivalent!");
10316 case ISD::SETCC:
10317 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, SDValue(),
10318 /*IsSignaling=*/false, Flags);
10319 case ISD::SELECT_CC:
10320 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
10321 N0.getOperand(3), NotCC, Flags);
10322 case ISD::STRICT_FSETCC:
10323 case ISD::STRICT_FSETCCS: {
10324 if (N0.hasOneUse()) {
10325 // FIXME Can we handle multiple uses? Could we token factor the chain
10326 // results from the new/old setcc?
10327 SDValue SetCC =
10328 DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, N0.getOperand(0),
10329 N0Opcode == ISD::STRICT_FSETCCS, Flags);
10330 CombineTo(N, SetCC);
10331 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
10332 recursivelyDeleteUnusedNodes(N0.getNode());
10333 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10334 }
10335 break;
10336 }
10337 }
10338 }
10339 }
10340
10341 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
10342 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
10343 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
10344 SDValue V = N0.getOperand(0);
10345 SDLoc DL0(N0);
10346 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
10347 DAG.getConstant(1, DL0, V.getValueType()));
10348 AddToWorklist(V.getNode());
10349 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
10350 }
10351
10352 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
10353 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are setcc
10354 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
10355 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10356 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10357 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
10358 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10359 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10360 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10361 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10362 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10363 }
10364 }
10365 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
10366 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are constants
10367 if (isAllOnesConstant(N1) && N0.hasOneUse() &&
10368 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10369 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10370 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
10371 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10372 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10373 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10374 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10375 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10376 }
10377 }
10378
10379 // fold (not (sub Y, X)) -> (add X, ~Y) if Y is a constant
10380 if (N0.getOpcode() == ISD::SUB && isAllOnesConstant(N1)) {
10381 SDValue Y = N0.getOperand(0);
10382 SDValue X = N0.getOperand(1);
10383
10384 if (auto *YConst = dyn_cast<ConstantSDNode>(Y)) {
10385 APInt NotYValue = ~YConst->getAPIntValue();
10386 SDValue NotY = DAG.getConstant(NotYValue, DL, VT);
10387 return DAG.getNode(ISD::ADD, DL, VT, X, NotY, N->getFlags());
10388 }
10389 }
10390
10391 // fold (not (add X, -1)) -> (neg X)
10392 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && isAllOnesConstant(N1) &&
10394 return DAG.getNegative(N0.getOperand(0), DL, VT);
10395 }
10396
10397 // fold (xor (and x, y), y) -> (and (not x), y)
10398 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
10399 SDValue X = N0.getOperand(0);
10400 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
10401 AddToWorklist(NotX.getNode());
10402 return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
10403 }
10404
10405 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
10406 if (!LegalOperations || hasOperation(ISD::ABS, VT)) {
10407 SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
10408 SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
10409 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
10410 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
10411 SDValue S0 = S.getOperand(0);
10412 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0))
10413 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
10414 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
10415 return DAG.getNode(ISD::ABS, DL, VT, S0);
10416 }
10417 }
10418
10419 // fold (xor x, x) -> 0
10420 if (N0 == N1)
10421 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
10422
10423 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
10424 // Here is a concrete example of this equivalence:
10425 // i16 x == 14
10426 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
10427 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
10428 //
10429 // =>
10430 //
10431 // i16 ~1 == 0b1111111111111110
10432 // i16 rol(~1, 14) == 0b1011111111111111
10433 //
10434 // Some additional tips to help conceptualize this transform:
10435 // - Try to see the operation as placing a single zero in a value of all ones.
10436 // - There exists no value for x which would allow the result to contain zero.
10437 // - Values of x larger than the bitwidth are undefined and do not require a
10438 // consistent result.
10439 // - Pushing the zero left requires shifting one bits in from the right.
10440 // A rotate left of ~1 is a nice way of achieving the desired result.
10441 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
10443 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getSignedConstant(~1, DL, VT),
10444 N0.getOperand(1));
10445 }
10446
10447 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
10448 if (N0Opcode == N1.getOpcode())
10449 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
10450 return V;
10451
10452 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
10453 return R;
10454 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
10455 return R;
10456 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
10457 return R;
10458
10459 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
10460 if (SDValue MM = unfoldMaskedMerge(N))
10461 return MM;
10462
10463 // Simplify the expression using non-local knowledge.
10465 return SDValue(N, 0);
10466
10467 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
10468 return Combined;
10469
10470 // fold (xor (smin(x, C), C)) -> select (x < C), xor(x, C), 0
10471 // fold (xor (smax(x, C), C)) -> select (x > C), xor(x, C), 0
10472 // fold (xor (umin(x, C), C)) -> select (x < C), xor(x, C), 0
10473 // fold (xor (umax(x, C), C)) -> select (x > C), xor(x, C), 0
10474 SDValue Op0;
10475 if (sd_match(N0, m_OneUse(m_AnyOf(m_SMin(m_Value(Op0), m_Specific(N1)),
10476 m_SMax(m_Value(Op0), m_Specific(N1)),
10477 m_UMin(m_Value(Op0), m_Specific(N1)),
10478 m_UMax(m_Value(Op0), m_Specific(N1)))))) {
10479
10480 if (isa<ConstantSDNode>(N1) ||
10482 // For vectors, only optimize when the constant is zero or all-ones to
10483 // avoid generating more instructions
10484 if (VT.isVector()) {
10485 ConstantSDNode *N1C = isConstOrConstSplat(N1);
10486 if (!N1C || (!N1C->isZero() && !N1C->isAllOnes()))
10487 return SDValue();
10488 }
10489
10490 // Avoid the fold if the minmax operation is legal and select is expensive
10491 if (TLI.isOperationLegal(N0.getOpcode(), VT) &&
10493 return SDValue();
10494
10495 EVT CCVT = getSetCCResultType(VT);
10496 ISD::CondCode CC;
10497 switch (N0.getOpcode()) {
10498 case ISD::SMIN:
10499 CC = ISD::SETLT;
10500 break;
10501 case ISD::SMAX:
10502 CC = ISD::SETGT;
10503 break;
10504 case ISD::UMIN:
10505 CC = ISD::SETULT;
10506 break;
10507 case ISD::UMAX:
10508 CC = ISD::SETUGT;
10509 break;
10510 }
10511 SDValue FN1 = DAG.getFreeze(N1);
10512 SDValue Cmp = DAG.getSetCC(DL, CCVT, Op0, FN1, CC);
10513 SDValue XorXC = DAG.getNode(ISD::XOR, DL, VT, Op0, FN1);
10514 SDValue Zero = DAG.getConstant(0, DL, VT);
10515 return DAG.getSelect(DL, VT, Cmp, XorXC, Zero);
10516 }
10517 }
10518
10519 return SDValue();
10520}
10521
10522/// If we have a shift-by-constant of a bitwise logic op that itself has a
10523/// shift-by-constant operand with identical opcode, we may be able to convert
10524/// that into 2 independent shifts followed by the logic op. This is a
10525/// throughput improvement.
10527 // Match a one-use bitwise logic op.
10528 SDValue LogicOp = Shift->getOperand(0);
10529 if (!LogicOp.hasOneUse())
10530 return SDValue();
10531
10532 unsigned LogicOpcode = LogicOp.getOpcode();
10533 if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
10534 LogicOpcode != ISD::XOR)
10535 return SDValue();
10536
10537 // Find a matching one-use shift by constant.
10538 unsigned ShiftOpcode = Shift->getOpcode();
10539 SDValue C1 = Shift->getOperand(1);
10540 ConstantSDNode *C1Node = isConstOrConstSplat(C1);
10541 assert(C1Node && "Expected a shift with constant operand");
10542 const APInt &C1Val = C1Node->getAPIntValue();
10543 auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
10544 const APInt *&ShiftAmtVal) {
10545 if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
10546 return false;
10547
10548 ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
10549 if (!ShiftCNode)
10550 return false;
10551
10552 // Capture the shifted operand and shift amount value.
10553 ShiftOp = V.getOperand(0);
10554 ShiftAmtVal = &ShiftCNode->getAPIntValue();
10555
10556 // Shift amount types do not have to match their operand type, so check that
10557 // the constants are the same width.
10558 if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
10559 return false;
10560
10561 // The fold is not valid if the sum of the shift values doesn't fit in the
10562 // given shift amount type.
10563 bool Overflow = false;
10564 APInt NewShiftAmt = C1Val.uadd_ov(*ShiftAmtVal, Overflow);
10565 if (Overflow)
10566 return false;
10567
10568 // The fold is not valid if the sum of the shift values exceeds bitwidth.
10569 if (NewShiftAmt.uge(V.getScalarValueSizeInBits()))
10570 return false;
10571
10572 return true;
10573 };
10574
10575 // Logic ops are commutative, so check each operand for a match.
10576 SDValue X, Y;
10577 const APInt *C0Val;
10578 if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
10579 Y = LogicOp.getOperand(1);
10580 else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
10581 Y = LogicOp.getOperand(0);
10582 else
10583 return SDValue();
10584
10585 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
10586 SDLoc DL(Shift);
10587 EVT VT = Shift->getValueType(0);
10588 EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
10589 SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
10590 SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
10591 SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
10592 return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2,
10593 LogicOp->getFlags());
10594}
10595
10596/// Handle transforms common to the three shifts, when the shift amount is a
10597/// constant.
10598/// We are looking for: (shift being one of shl/sra/srl)
10599/// shift (binop X, C0), C1
10600/// And want to transform into:
10601/// binop (shift X, C1), (shift C0, C1)
10602SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
10603 assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
10604
10605 // Do not turn a 'not' into a regular xor.
10606 if (isBitwiseNot(N->getOperand(0)))
10607 return SDValue();
10608
10609 // The inner binop must be one-use, since we want to replace it.
10610 SDValue LHS = N->getOperand(0);
10611 if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
10612 return SDValue();
10613
10614 // Fold shift(bitop(shift(x,c1),y), c2) -> bitop(shift(x,c1+c2),shift(y,c2)).
10615 if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
10616 return R;
10617
10618 // We want to pull some binops through shifts, so that we have (and (shift))
10619 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
10620 // thing happens with address calculations, so it's important to canonicalize
10621 // it.
10622 switch (LHS.getOpcode()) {
10623 default:
10624 return SDValue();
10625 case ISD::OR:
10626 case ISD::XOR:
10627 case ISD::AND:
10628 break;
10629 case ISD::ADD:
10630 if (N->getOpcode() != ISD::SHL)
10631 return SDValue(); // only shl(add) not sr[al](add).
10632 break;
10633 }
10634
10635 // FIXME: disable this unless the input to the binop is a shift by a constant
10636 // or is copy/select. Enable this in other cases when figure out it's exactly
10637 // profitable.
10638 SDValue BinOpLHSVal = LHS.getOperand(0);
10639 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
10640 BinOpLHSVal.getOpcode() == ISD::SRA ||
10641 BinOpLHSVal.getOpcode() == ISD::SRL) &&
10642 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
10643 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
10644 BinOpLHSVal.getOpcode() == ISD::SELECT;
10645
10646 if (!IsShiftByConstant && !IsCopyOrSelect)
10647 return SDValue();
10648
10649 if (IsCopyOrSelect && N->hasOneUse())
10650 return SDValue();
10651
10652 // Attempt to fold the constants, shifting the binop RHS by the shift amount.
10653 SDLoc DL(N);
10654 EVT VT = N->getValueType(0);
10655 if (SDValue NewRHS = DAG.FoldConstantArithmetic(
10656 N->getOpcode(), DL, VT, {LHS.getOperand(1), N->getOperand(1)})) {
10657 SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
10658 N->getOperand(1));
10659 return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
10660 }
10661
10662 return SDValue();
10663}
10664
10665SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
10666 assert(N->getOpcode() == ISD::TRUNCATE);
10667 assert(N->getOperand(0).getOpcode() == ISD::AND);
10668
10669 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
10670 EVT TruncVT = N->getValueType(0);
10671 if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
10672 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
10673 SDValue N01 = N->getOperand(0).getOperand(1);
10674 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
10675 SDLoc DL(N);
10676 SDValue N00 = N->getOperand(0).getOperand(0);
10677 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
10678 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
10679 AddToWorklist(Trunc00.getNode());
10680 AddToWorklist(Trunc01.getNode());
10681 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
10682 }
10683 }
10684
10685 return SDValue();
10686}
10687
10688SDValue DAGCombiner::visitRotate(SDNode *N) {
10689 SDLoc dl(N);
10690 SDValue N0 = N->getOperand(0);
10691 SDValue N1 = N->getOperand(1);
10692 EVT VT = N->getValueType(0);
10693 unsigned Bitsize = VT.getScalarSizeInBits();
10694
10695 // fold (rot x, 0) -> x
10696 if (isNullOrNullSplat(N1))
10697 return N0;
10698
10699 // fold (rot x, c) -> x iff (c % BitSize) == 0
10700 if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
10701 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
10702 if (DAG.MaskedValueIsZero(N1, ModuloMask))
10703 return N0;
10704 }
10705
10706 // fold (rot x, c) -> (rot x, c % BitSize)
10707 bool OutOfRange = false;
10708 auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
10709 OutOfRange |= C->getAPIntValue().uge(Bitsize);
10710 return true;
10711 };
10712 if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
10713 EVT AmtVT = N1.getValueType();
10714 SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
10715 if (SDValue Amt =
10716 DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
10717 return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
10718 }
10719
10720 // rot i16 X, 8 --> bswap X
10721 auto *RotAmtC = isConstOrConstSplat(N1);
10722 if (RotAmtC && RotAmtC->getAPIntValue() == 8 &&
10723 VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT))
10724 return DAG.getNode(ISD::BSWAP, dl, VT, N0);
10725
10726 // Simplify the operands using demanded-bits information.
10728 return SDValue(N, 0);
10729
10730 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
10731 if (N1.getOpcode() == ISD::TRUNCATE &&
10732 N1.getOperand(0).getOpcode() == ISD::AND) {
10733 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
10734 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
10735 }
10736
10737 unsigned NextOp = N0.getOpcode();
10738
10739 // fold (rot* (rot* x, c2), c1)
10740 // -> (rot* x, ((c1 % bitsize) +- (c2 % bitsize) + bitsize) % bitsize)
10741 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
10742 bool C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
10744 if (C1 && C2 && N1.getValueType() == N0.getOperand(1).getValueType()) {
10745 EVT ShiftVT = N1.getValueType();
10746 bool SameSide = (N->getOpcode() == NextOp);
10747 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
10748 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
10749 SDValue Norm1 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10750 {N1, BitsizeC});
10751 SDValue Norm2 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10752 {N0.getOperand(1), BitsizeC});
10753 if (Norm1 && Norm2)
10754 if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
10755 CombineOp, dl, ShiftVT, {Norm1, Norm2})) {
10756 CombinedShift = DAG.FoldConstantArithmetic(ISD::ADD, dl, ShiftVT,
10757 {CombinedShift, BitsizeC});
10758 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
10759 ISD::UREM, dl, ShiftVT, {CombinedShift, BitsizeC});
10760 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
10761 CombinedShiftNorm);
10762 }
10763 }
10764 }
10765 return SDValue();
10766}
10767
10768SDValue DAGCombiner::visitSHL(SDNode *N) {
10769 SDValue N0 = N->getOperand(0);
10770 SDValue N1 = N->getOperand(1);
10771 if (SDValue V = DAG.simplifyShift(N0, N1))
10772 return V;
10773
10774 SDLoc DL(N);
10775 EVT VT = N0.getValueType();
10776 EVT ShiftVT = N1.getValueType();
10777 unsigned OpSizeInBits = VT.getScalarSizeInBits();
10778
10779 // fold (shl c1, c2) -> c1<<c2
10780 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N0, N1}))
10781 return C;
10782
10783 // fold vector ops
10784 if (VT.isVector()) {
10785 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
10786 return FoldedVOp;
10787
10788 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
10789 // If setcc produces all-one true value then:
10790 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
10791 if (N1CV && N1CV->isConstant()) {
10792 if (N0.getOpcode() == ISD::AND) {
10793 SDValue N00 = N0->getOperand(0);
10794 SDValue N01 = N0->getOperand(1);
10795 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
10796
10797 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
10800 if (SDValue C =
10801 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N01, N1}))
10802 return DAG.getNode(ISD::AND, DL, VT, N00, C);
10803 }
10804 }
10805 }
10806 }
10807
10808 if (SDValue NewSel = foldBinOpIntoSelect(N))
10809 return NewSel;
10810
10811 // if (shl x, c) is known to be zero, return 0
10812 if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
10813 return DAG.getConstant(0, DL, VT);
10814
10815 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
10816 if (N1.getOpcode() == ISD::TRUNCATE &&
10817 N1.getOperand(0).getOpcode() == ISD::AND) {
10818 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
10819 return DAG.getNode(ISD::SHL, DL, VT, N0, NewOp1);
10820 }
10821
10822 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
10823 if (N0.getOpcode() == ISD::SHL) {
10824 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
10825 ConstantSDNode *RHS) {
10826 APInt c1 = LHS->getAPIntValue();
10827 APInt c2 = RHS->getAPIntValue();
10828 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10829 return (c1 + c2).uge(OpSizeInBits);
10830 };
10831 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
10832 return DAG.getConstant(0, DL, VT);
10833
10834 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
10835 ConstantSDNode *RHS) {
10836 APInt c1 = LHS->getAPIntValue();
10837 APInt c2 = RHS->getAPIntValue();
10838 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10839 return (c1 + c2).ult(OpSizeInBits);
10840 };
10841 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
10842 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
10843 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
10844 }
10845 }
10846
10847 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
10848 // For this to be valid, the second form must not preserve any of the bits
10849 // that are shifted out by the inner shift in the first form. This means
10850 // the outer shift size must be >= the number of bits added by the ext.
10851 // As a corollary, we don't care what kind of ext it is.
10852 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
10853 N0.getOpcode() == ISD::ANY_EXTEND ||
10854 N0.getOpcode() == ISD::SIGN_EXTEND) &&
10855 N0.getOperand(0).getOpcode() == ISD::SHL) {
10856 SDValue N0Op0 = N0.getOperand(0);
10857 SDValue InnerShiftAmt = N0Op0.getOperand(1);
10858 EVT InnerVT = N0Op0.getValueType();
10859 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
10860
10861 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
10862 ConstantSDNode *RHS) {
10863 APInt c1 = LHS->getAPIntValue();
10864 APInt c2 = RHS->getAPIntValue();
10865 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10866 return c2.uge(OpSizeInBits - InnerBitwidth) &&
10867 (c1 + c2).uge(OpSizeInBits);
10868 };
10869 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
10870 /*AllowUndefs*/ false,
10871 /*AllowTypeMismatch*/ true))
10872 return DAG.getConstant(0, DL, VT);
10873
10874 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
10875 ConstantSDNode *RHS) {
10876 APInt c1 = LHS->getAPIntValue();
10877 APInt c2 = RHS->getAPIntValue();
10878 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10879 return c2.uge(OpSizeInBits - InnerBitwidth) &&
10880 (c1 + c2).ult(OpSizeInBits);
10881 };
10882 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
10883 /*AllowUndefs*/ false,
10884 /*AllowTypeMismatch*/ true)) {
10885 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
10886 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
10887 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
10888 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
10889 }
10890 }
10891
10892 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
10893 // Only fold this if the inner zext has no other uses to avoid increasing
10894 // the total number of instructions.
10895 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
10896 N0.getOperand(0).getOpcode() == ISD::SRL) {
10897 SDValue N0Op0 = N0.getOperand(0);
10898 SDValue InnerShiftAmt = N0Op0.getOperand(1);
10899
10900 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
10901 APInt c1 = LHS->getAPIntValue();
10902 APInt c2 = RHS->getAPIntValue();
10903 zeroExtendToMatch(c1, c2);
10904 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
10905 };
10906 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
10907 /*AllowUndefs*/ false,
10908 /*AllowTypeMismatch*/ true)) {
10909 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
10910 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
10911 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
10912 AddToWorklist(NewSHL.getNode());
10913 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
10914 }
10915 }
10916
10917 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) {
10918 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
10919 ConstantSDNode *RHS) {
10920 const APInt &LHSC = LHS->getAPIntValue();
10921 const APInt &RHSC = RHS->getAPIntValue();
10922 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
10923 LHSC.getZExtValue() <= RHSC.getZExtValue();
10924 };
10925
10926 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
10927 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 >= C2
10928 if (N0->getFlags().hasExact()) {
10929 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
10930 /*AllowUndefs*/ false,
10931 /*AllowTypeMismatch*/ true)) {
10932 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
10933 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
10934 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
10935 }
10936 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
10937 /*AllowUndefs*/ false,
10938 /*AllowTypeMismatch*/ true)) {
10939 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
10940 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
10941 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Diff);
10942 }
10943 }
10944
10945 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
10946 // (and (srl x, (sub c1, c2), MASK)
10947 // Only fold this if the inner shift has no other uses -- if it does,
10948 // folding this will increase the total number of instructions.
10949 if (N0.getOpcode() == ISD::SRL &&
10950 (N0.getOperand(1) == N1 || N0.hasOneUse()) &&
10952 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
10953 /*AllowUndefs*/ false,
10954 /*AllowTypeMismatch*/ true)) {
10955 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
10956 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
10957 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
10958 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N01);
10959 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, Diff);
10960 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
10961 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
10962 }
10963 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
10964 /*AllowUndefs*/ false,
10965 /*AllowTypeMismatch*/ true)) {
10966 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
10967 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
10968 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
10969 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N1);
10970 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
10971 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
10972 }
10973 }
10974 }
10975
10976 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
10977 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
10978 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
10979 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
10980 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
10981 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
10982 }
10983
10984 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10985 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
10986 // Variant of version done on multiply, except mul by a power of 2 is turned
10987 // into a shift.
10988 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
10989 TLI.isDesirableToCommuteWithShift(N, Level)) {
10990 SDValue N01 = N0.getOperand(1);
10991 if (SDValue Shl1 =
10992 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1})) {
10993 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
10994 AddToWorklist(Shl0.getNode());
10995 SDNodeFlags Flags;
10996 // Preserve the disjoint flag for Or.
10997 if (N0.getOpcode() == ISD::OR && N0->getFlags().hasDisjoint())
10999 return DAG.getNode(N0.getOpcode(), DL, VT, Shl0, Shl1, Flags);
11000 }
11001 }
11002
11003 // fold (shl (sext (add_nsw x, c1)), c2) -> (add (shl (sext x), c2), c1 << c2)
11004 // TODO: Add zext/add_nuw variant with suitable test coverage
11005 // TODO: Should we limit this with isLegalAddImmediate?
11006 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
11007 N0.getOperand(0).getOpcode() == ISD::ADD &&
11008 N0.getOperand(0)->getFlags().hasNoSignedWrap() &&
11009 TLI.isDesirableToCommuteWithShift(N, Level)) {
11010 SDValue Add = N0.getOperand(0);
11011 SDLoc DL(N0);
11012 if (SDValue ExtC = DAG.FoldConstantArithmetic(N0.getOpcode(), DL, VT,
11013 {Add.getOperand(1)})) {
11014 if (SDValue ShlC =
11015 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {ExtC, N1})) {
11016 SDValue ExtX = DAG.getNode(N0.getOpcode(), DL, VT, Add.getOperand(0));
11017 SDValue ShlX = DAG.getNode(ISD::SHL, DL, VT, ExtX, N1);
11018 return DAG.getNode(ISD::ADD, DL, VT, ShlX, ShlC);
11019 }
11020 }
11021 }
11022
11023 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
11024 if (N0.getOpcode() == ISD::MUL && N0->hasOneUse()) {
11025 SDValue N01 = N0.getOperand(1);
11026 if (SDValue Shl =
11027 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1}))
11028 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), Shl);
11029 }
11030
11031 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11032 if (N1C && !N1C->isOpaque())
11033 if (SDValue NewSHL = visitShiftByConstant(N))
11034 return NewSHL;
11035
11036 // fold (shl X, cttz(Y)) -> (mul (Y & -Y), X) if cttz is unsupported on the
11037 // target.
11038 if (((N1.getOpcode() == ISD::CTTZ &&
11039 VT.getScalarSizeInBits() <= ShiftVT.getScalarSizeInBits()) ||
11041 N1.hasOneUse() && !TLI.isOperationLegalOrCustom(ISD::CTTZ, ShiftVT) &&
11043 SDValue Y = N1.getOperand(0);
11044 SDLoc DL(N);
11045 SDValue NegY = DAG.getNegative(Y, DL, ShiftVT);
11046 SDValue And =
11047 DAG.getZExtOrTrunc(DAG.getNode(ISD::AND, DL, ShiftVT, Y, NegY), DL, VT);
11048 return DAG.getNode(ISD::MUL, DL, VT, And, N0);
11049 }
11050
11052 return SDValue(N, 0);
11053
11054 // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
11055 if (N0.getOpcode() == ISD::VSCALE && N1C) {
11056 const APInt &C0 = N0.getConstantOperandAPInt(0);
11057 const APInt &C1 = N1C->getAPIntValue();
11058 return DAG.getVScale(DL, VT, C0 << C1);
11059 }
11060
11061 SDValue X;
11062 APInt VS0;
11063
11064 // fold (shl (X * vscale(VS0)), C1) -> (X * vscale(VS0 << C1))
11065 if (N1C && sd_match(N0, m_Mul(m_Value(X), m_VScale(m_ConstInt(VS0))))) {
11066 SDNodeFlags Flags;
11067 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
11068 N0->getFlags().hasNoUnsignedWrap());
11069
11070 SDValue VScale = DAG.getVScale(DL, VT, VS0 << N1C->getAPIntValue());
11071 return DAG.getNode(ISD::MUL, DL, VT, X, VScale, Flags);
11072 }
11073
11074 // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)).
11075 APInt ShlVal;
11076 if (N0.getOpcode() == ISD::STEP_VECTOR &&
11077 ISD::isConstantSplatVector(N1.getNode(), ShlVal)) {
11078 const APInt &C0 = N0.getConstantOperandAPInt(0);
11079 if (ShlVal.ult(C0.getBitWidth())) {
11080 APInt NewStep = C0 << ShlVal;
11081 return DAG.getStepVector(DL, VT, NewStep);
11082 }
11083 }
11084
11085 return SDValue();
11086}
11087
11088// Transform a right shift of a multiply into a multiply-high.
11089// Examples:
11090// (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b)
11091// (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b)
11093 const TargetLowering &TLI) {
11094 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
11095 "SRL or SRA node is required here!");
11096
11097 // Check the shift amount. Proceed with the transformation if the shift
11098 // amount is constant.
11099 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
11100 if (!ShiftAmtSrc)
11101 return SDValue();
11102
11103 // The operation feeding into the shift must be a multiply.
11104 SDValue ShiftOperand = N->getOperand(0);
11105 if (ShiftOperand.getOpcode() != ISD::MUL)
11106 return SDValue();
11107
11108 // Both operands must be equivalent extend nodes.
11109 SDValue LeftOp = ShiftOperand.getOperand(0);
11110 SDValue RightOp = ShiftOperand.getOperand(1);
11111
11112 if (LeftOp.getOpcode() != ISD::SIGN_EXTEND &&
11113 LeftOp.getOpcode() != ISD::ZERO_EXTEND)
11114 std::swap(LeftOp, RightOp);
11115
11116 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
11117 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
11118
11119 if (!IsSignExt && !IsZeroExt)
11120 return SDValue();
11121
11122 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
11123 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
11124
11125 // return true if U may use the lower bits of its operands
11126 auto UserOfLowerBits = [NarrowVTSize](SDNode *U) {
11127 if (U->getOpcode() != ISD::SRL && U->getOpcode() != ISD::SRA) {
11128 return true;
11129 }
11130 ConstantSDNode *UShiftAmtSrc = isConstOrConstSplat(U->getOperand(1));
11131 if (!UShiftAmtSrc) {
11132 return true;
11133 }
11134 unsigned UShiftAmt = UShiftAmtSrc->getZExtValue();
11135 return UShiftAmt < NarrowVTSize;
11136 };
11137
11138 // If the lower part of the MUL is also used and MUL_LOHI is supported
11139 // do not introduce the MULH in favor of MUL_LOHI
11140 unsigned MulLoHiOp = IsSignExt ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
11141 if (!ShiftOperand.hasOneUse() &&
11142 TLI.isOperationLegalOrCustom(MulLoHiOp, NarrowVT) &&
11143 llvm::any_of(ShiftOperand->users(), UserOfLowerBits)) {
11144 return SDValue();
11145 }
11146
11147 SDValue MulhRightOp;
11148 if (LeftOp.getOpcode() != RightOp.getOpcode()) {
11149 if (IsZeroExt && ShiftOperand.hasOneUse() &&
11150 DAG.computeKnownBits(RightOp).countMaxActiveBits() <= NarrowVTSize) {
11151 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11152 } else if (IsSignExt && ShiftOperand.hasOneUse() &&
11153 DAG.ComputeMaxSignificantBits(RightOp) <= NarrowVTSize) {
11154 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11155 } else {
11156 return SDValue();
11157 }
11158 } else {
11159 // Check that the two extend nodes are the same type.
11160 if (NarrowVT != RightOp.getOperand(0).getValueType())
11161 return SDValue();
11162 MulhRightOp = RightOp.getOperand(0);
11163 }
11164
11165 EVT WideVT = LeftOp.getValueType();
11166 // Proceed with the transformation if the wide types match.
11167 assert((WideVT == RightOp.getValueType()) &&
11168 "Cannot have a multiply node with two different operand types.");
11169
11170 // Proceed with the transformation if the wide type is twice as large
11171 // as the narrow type.
11172 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
11173 return SDValue();
11174
11175 // Check the shift amount with the narrow type size.
11176 // Proceed with the transformation if the shift amount is the width
11177 // of the narrow type.
11178 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
11179 if (ShiftAmt != NarrowVTSize)
11180 return SDValue();
11181
11182 // If the operation feeding into the MUL is a sign extend (sext),
11183 // we use mulhs. Othewise, zero extends (zext) use mulhu.
11184 unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU;
11185
11186 // Combine to mulh if mulh is legal/custom for the narrow type on the target
11187 // or if it is a vector type then we could transform to an acceptable type and
11188 // rely on legalization to split/combine the result.
11189 EVT TransformVT = NarrowVT;
11190 if (NarrowVT.isVector()) {
11191 TransformVT = TLI.getLegalTypeToTransformTo(*DAG.getContext(), NarrowVT);
11192 if (TransformVT.getScalarType() != NarrowVT.getScalarType())
11193 return SDValue();
11194 }
11195 if (!TLI.isOperationLegalOrCustom(MulhOpcode, TransformVT))
11196 return SDValue();
11197
11198 SDValue Result =
11199 DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp);
11200 bool IsSigned = N->getOpcode() == ISD::SRA;
11201 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
11202}
11203
11204// fold (bswap (logic_op(bswap(x),y))) -> logic_op(x,bswap(y))
11205// This helper function accept SDNode with opcode ISD::BSWAP and ISD::BITREVERSE
11207 unsigned Opcode = N->getOpcode();
11208 if (Opcode != ISD::BSWAP && Opcode != ISD::BITREVERSE)
11209 return SDValue();
11210
11211 SDValue N0 = N->getOperand(0);
11212 EVT VT = N->getValueType(0);
11213 SDLoc DL(N);
11214 SDValue X, Y;
11215
11216 // If both operands are bswap/bitreverse, ignore the multiuse
11218 m_UnaryOp(Opcode, m_Value(Y))))))
11219 return DAG.getNode(N0.getOpcode(), DL, VT, X, Y);
11220
11221 // Otherwise need to ensure logic_op and bswap/bitreverse(x) have one use.
11223 m_OneUse(m_UnaryOp(Opcode, m_Value(X))), m_Value(Y))))) {
11224 SDValue NewBitReorder = DAG.getNode(Opcode, DL, VT, Y);
11225 return DAG.getNode(N0.getOpcode(), DL, VT, X, NewBitReorder);
11226 }
11227
11228 return SDValue();
11229}
11230
11231SDValue DAGCombiner::visitSRA(SDNode *N) {
11232 SDValue N0 = N->getOperand(0);
11233 SDValue N1 = N->getOperand(1);
11234 if (SDValue V = DAG.simplifyShift(N0, N1))
11235 return V;
11236
11237 SDLoc DL(N);
11238 EVT VT = N0.getValueType();
11239 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11240
11241 // fold (sra c1, c2) -> (sra c1, c2)
11242 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, DL, VT, {N0, N1}))
11243 return C;
11244
11245 // Arithmetic shifting an all-sign-bit value is a no-op.
11246 // fold (sra 0, x) -> 0
11247 // fold (sra -1, x) -> -1
11248 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
11249 return N0;
11250
11251 // fold vector ops
11252 if (VT.isVector())
11253 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11254 return FoldedVOp;
11255
11256 if (SDValue NewSel = foldBinOpIntoSelect(N))
11257 return NewSel;
11258
11259 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11260
11261 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
11262 // clamp (add c1, c2) to max shift.
11263 if (N0.getOpcode() == ISD::SRA) {
11264 EVT ShiftVT = N1.getValueType();
11265 EVT ShiftSVT = ShiftVT.getScalarType();
11266 SmallVector<SDValue, 16> ShiftValues;
11267
11268 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
11269 APInt c1 = LHS->getAPIntValue();
11270 APInt c2 = RHS->getAPIntValue();
11271 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11272 APInt Sum = c1 + c2;
11273 unsigned ShiftSum =
11274 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
11275 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
11276 return true;
11277 };
11278 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
11279 SDValue ShiftValue;
11280 if (N1.getOpcode() == ISD::BUILD_VECTOR)
11281 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
11282 else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
11283 assert(ShiftValues.size() == 1 &&
11284 "Expected matchBinaryPredicate to return one element for "
11285 "SPLAT_VECTORs");
11286 ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]);
11287 } else
11288 ShiftValue = ShiftValues[0];
11289 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
11290 }
11291 }
11292
11293 // fold (sra (xor (sra x, c1), -1), c2) -> (xor (sra x, c3), -1)
11294 // This allows merging two arithmetic shifts even when there's a NOT in
11295 // between.
11296 SDValue X;
11297 APInt C1;
11298 if (N1C && sd_match(N0, m_OneUse(m_Not(
11299 m_OneUse(m_Sra(m_Value(X), m_ConstInt(C1))))))) {
11300 APInt C2 = N1C->getAPIntValue();
11301 zeroExtendToMatch(C1, C2, 1 /* Overflow Bit */);
11302 APInt Sum = C1 + C2;
11303 unsigned ShiftSum = Sum.getLimitedValue(OpSizeInBits - 1);
11304 SDValue NewShift = DAG.getNode(
11305 ISD::SRA, DL, VT, X, DAG.getShiftAmountConstant(ShiftSum, VT, DL));
11306 return DAG.getNOT(DL, NewShift, VT);
11307 }
11308
11309 // fold (sra (shl X, m), (sub result_size, n))
11310 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
11311 // result_size - n != m.
11312 // If truncate is free for the target sext(shl) is likely to result in better
11313 // code.
11314 if (N0.getOpcode() == ISD::SHL && N1C) {
11315 // Get the two constants of the shifts, CN0 = m, CN = n.
11316 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
11317 if (N01C) {
11318 LLVMContext &Ctx = *DAG.getContext();
11319 // Determine what the truncate's result bitsize and type would be.
11320 EVT TruncVT = VT.changeElementType(
11321 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()));
11322
11323 // Determine the residual right-shift amount.
11324 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
11325
11326 // If the shift is not a no-op (in which case this should be just a sign
11327 // extend already), the truncated to type is legal, sign_extend is legal
11328 // on that type, and the truncate to that type is both legal and free,
11329 // perform the transform.
11330 if ((ShiftAmt > 0) &&
11333 TLI.isTruncateFree(VT, TruncVT)) {
11334 SDValue Amt = DAG.getShiftAmountConstant(ShiftAmt, VT, DL);
11335 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
11336 N0.getOperand(0), Amt);
11337 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
11338 Shift);
11339 return DAG.getNode(ISD::SIGN_EXTEND, DL,
11340 N->getValueType(0), Trunc);
11341 }
11342 }
11343 }
11344
11345 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
11346 // sra (add (shl X, N1C), AddC), N1C -->
11347 // sext (add (trunc X to (width - N1C)), AddC')
11348 // sra (sub AddC, (shl X, N1C)), N1C -->
11349 // sext (sub AddC1',(trunc X to (width - N1C)))
11350 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB) && N1C &&
11351 N0.hasOneUse()) {
11352 bool IsAdd = N0.getOpcode() == ISD::ADD;
11353 SDValue Shl = N0.getOperand(IsAdd ? 0 : 1);
11354 if (Shl.getOpcode() == ISD::SHL && Shl.getOperand(1) == N1 &&
11355 Shl.hasOneUse()) {
11356 // TODO: AddC does not need to be a splat.
11357 if (ConstantSDNode *AddC =
11358 isConstOrConstSplat(N0.getOperand(IsAdd ? 1 : 0))) {
11359 // Determine what the truncate's type would be and ask the target if
11360 // that is a free operation.
11361 LLVMContext &Ctx = *DAG.getContext();
11362 unsigned ShiftAmt = N1C->getZExtValue();
11363 EVT TruncVT = VT.changeElementType(
11364 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt));
11365
11366 // TODO: The simple type check probably belongs in the default hook
11367 // implementation and/or target-specific overrides (because
11368 // non-simple types likely require masking when legalized), but
11369 // that restriction may conflict with other transforms.
11370 if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
11371 TLI.isTruncateFree(VT, TruncVT)) {
11372 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
11373 SDValue ShiftC =
11374 DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).trunc(
11375 TruncVT.getScalarSizeInBits()),
11376 DL, TruncVT);
11377 SDValue Add;
11378 if (IsAdd)
11379 Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
11380 else
11381 Add = DAG.getNode(ISD::SUB, DL, TruncVT, ShiftC, Trunc);
11382 return DAG.getSExtOrTrunc(Add, DL, VT);
11383 }
11384 }
11385 }
11386 }
11387
11388 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
11389 if (N1.getOpcode() == ISD::TRUNCATE &&
11390 N1.getOperand(0).getOpcode() == ISD::AND) {
11391 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11392 return DAG.getNode(ISD::SRA, DL, VT, N0, NewOp1);
11393 }
11394
11395 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
11396 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
11397 // if c1 is equal to the number of bits the trunc removes
11398 // TODO - support non-uniform vector shift amounts.
11399 if (N0.getOpcode() == ISD::TRUNCATE &&
11400 (N0.getOperand(0).getOpcode() == ISD::SRL ||
11401 N0.getOperand(0).getOpcode() == ISD::SRA) &&
11402 N0.getOperand(0).hasOneUse() &&
11403 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
11404 SDValue N0Op0 = N0.getOperand(0);
11405 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
11406 EVT LargeVT = N0Op0.getValueType();
11407 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
11408 if (LargeShift->getAPIntValue() == TruncBits) {
11409 EVT LargeShiftVT = getShiftAmountTy(LargeVT);
11410 SDValue Amt = DAG.getZExtOrTrunc(N1, DL, LargeShiftVT);
11411 Amt = DAG.getNode(ISD::ADD, DL, LargeShiftVT, Amt,
11412 DAG.getConstant(TruncBits, DL, LargeShiftVT));
11413 SDValue SRA =
11414 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
11415 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
11416 }
11417 }
11418 }
11419
11420 // fold (sra (add nsw X, C), D) -> (add nsw (sra X, D), C s>> D)
11421 // when C has D trailing zeros (so C s>> D is exact).
11422 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11423 N0->getFlags().hasNoSignedWrap()) {
11424 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11425 const APInt &ShAmt = N1C->getAPIntValue();
11426 const APInt &AddVal = AddC->getAPIntValue();
11427 if (ShAmt.ult(AddVal.countr_zero())) {
11428 SDNodeFlags ShiftFlags = N->getFlags();
11429 SDValue NewSra =
11430 DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11431 SDValue NewC = DAG.getConstant(AddVal.ashr(ShAmt), DL, VT);
11432 SDNodeFlags AddFlags = N0->getFlags();
11433 return DAG.getNode(ISD::ADD, DL, VT, NewSra, NewC, AddFlags);
11434 }
11435 }
11436 }
11437
11438 // Simplify, based on bits shifted out of the LHS.
11440 return SDValue(N, 0);
11441
11442 // If the sign bit is known to be zero, switch this to a SRL.
11443 if (DAG.SignBitIsZero(N0))
11444 return DAG.getNode(ISD::SRL, DL, VT, N0, N1);
11445
11446 if (N1C && !N1C->isOpaque())
11447 if (SDValue NewSRA = visitShiftByConstant(N))
11448 return NewSRA;
11449
11450 // Try to transform this shift into a multiply-high if
11451 // it matches the appropriate pattern detected in combineShiftToMULH.
11452 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
11453 return MULH;
11454
11455 // Attempt to convert a sra of a load into a narrower sign-extending load.
11456 if (SDValue NarrowLoad = reduceLoadWidth(N))
11457 return NarrowLoad;
11458
11459 if (SDValue AVG = foldShiftToAvg(N, DL))
11460 return AVG;
11461
11462 return SDValue();
11463}
11464
11465SDValue DAGCombiner::visitSRL(SDNode *N) {
11466 SDValue N0 = N->getOperand(0);
11467 SDValue N1 = N->getOperand(1);
11468 if (SDValue V = DAG.simplifyShift(N0, N1))
11469 return V;
11470
11471 SDLoc DL(N);
11472 EVT VT = N0.getValueType();
11473 EVT ShiftVT = N1.getValueType();
11474 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11475
11476 // fold (srl c1, c2) -> c1 >>u c2
11477 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, DL, VT, {N0, N1}))
11478 return C;
11479
11480 // fold vector ops
11481 if (VT.isVector())
11482 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11483 return FoldedVOp;
11484
11485 if (SDValue NewSel = foldBinOpIntoSelect(N))
11486 return NewSel;
11487
11488 // if (srl x, c) is known to be zero, return 0
11489 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11490 if (N1C &&
11491 DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
11492 return DAG.getConstant(0, DL, VT);
11493
11494 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
11495 if (N0.getOpcode() == ISD::SRL) {
11496 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
11497 ConstantSDNode *RHS) {
11498 APInt c1 = LHS->getAPIntValue();
11499 APInt c2 = RHS->getAPIntValue();
11500 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11501 return (c1 + c2).uge(OpSizeInBits);
11502 };
11503 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
11504 return DAG.getConstant(0, DL, VT);
11505
11506 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
11507 ConstantSDNode *RHS) {
11508 APInt c1 = LHS->getAPIntValue();
11509 APInt c2 = RHS->getAPIntValue();
11510 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11511 return (c1 + c2).ult(OpSizeInBits);
11512 };
11513 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
11514 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
11515 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
11516 }
11517 }
11518
11519 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
11520 N0.getOperand(0).getOpcode() == ISD::SRL) {
11521 SDValue InnerShift = N0.getOperand(0);
11522 // TODO - support non-uniform vector shift amounts.
11523 if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
11524 uint64_t c1 = N001C->getZExtValue();
11525 uint64_t c2 = N1C->getZExtValue();
11526 EVT InnerShiftVT = InnerShift.getValueType();
11527 EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
11528 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
11529 // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
11530 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
11531 if (c1 + OpSizeInBits == InnerShiftSize) {
11532 if (c1 + c2 >= InnerShiftSize)
11533 return DAG.getConstant(0, DL, VT);
11534 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11535 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11536 InnerShift.getOperand(0), NewShiftAmt);
11537 return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
11538 }
11539 // In the more general case, we can clear the high bits after the shift:
11540 // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
11541 if (N0.hasOneUse() && InnerShift.hasOneUse() &&
11542 c1 + c2 < InnerShiftSize) {
11543 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11544 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11545 InnerShift.getOperand(0), NewShiftAmt);
11546 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
11547 OpSizeInBits - c2),
11548 DL, InnerShiftVT);
11549 SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
11550 return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
11551 }
11552 }
11553 }
11554
11555 if (N0.getOpcode() == ISD::SHL) {
11556 // fold (srl (shl nuw x, c), c) -> x
11557 if (N0.getOperand(1) == N1 && N0->getFlags().hasNoUnsignedWrap())
11558 return N0.getOperand(0);
11559
11560 // fold (srl (shl x, c1), c2) -> (and (shl x, (sub c1, c2), MASK) or
11561 // (and (srl x, (sub c2, c1), MASK)
11562 if ((N0.getOperand(1) == N1 || N0->hasOneUse()) &&
11564 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
11565 ConstantSDNode *RHS) {
11566 const APInt &LHSC = LHS->getAPIntValue();
11567 const APInt &RHSC = RHS->getAPIntValue();
11568 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
11569 LHSC.getZExtValue() <= RHSC.getZExtValue();
11570 };
11571 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11572 /*AllowUndefs*/ false,
11573 /*AllowTypeMismatch*/ true)) {
11574 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11575 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11576 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11577 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N01);
11578 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, Diff);
11579 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11580 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11581 }
11582 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11583 /*AllowUndefs*/ false,
11584 /*AllowTypeMismatch*/ true)) {
11585 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11586 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11587 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11588 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N1);
11589 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
11590 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11591 }
11592 }
11593 }
11594
11595 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
11596 // TODO - support non-uniform vector shift amounts.
11597 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
11598 // Shifting in all undef bits?
11599 EVT SmallVT = N0.getOperand(0).getValueType();
11600 unsigned BitSize = SmallVT.getScalarSizeInBits();
11601 if (N1C->getAPIntValue().uge(BitSize))
11602 return DAG.getUNDEF(VT);
11603
11604 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
11605 uint64_t ShiftAmt = N1C->getZExtValue();
11606 SDLoc DL0(N0);
11607 SDValue SmallShift =
11608 DAG.getNode(ISD::SRL, DL0, SmallVT, N0.getOperand(0),
11609 DAG.getShiftAmountConstant(ShiftAmt, SmallVT, DL0));
11610 AddToWorklist(SmallShift.getNode());
11611 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
11612 return DAG.getNode(ISD::AND, DL, VT,
11613 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
11614 DAG.getConstant(Mask, DL, VT));
11615 }
11616 }
11617
11618 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
11619 // bit, which is unmodified by sra.
11620 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
11621 if (N0.getOpcode() == ISD::SRA)
11622 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
11623 }
11624
11625 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit), and x has a power
11626 // of two bitwidth. The "5" represents (log2 (bitwidth x)).
11627 if (N1C && N0.getOpcode() == ISD::CTLZ &&
11628 isPowerOf2_32(OpSizeInBits) &&
11629 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
11630 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
11631
11632 // If any of the input bits are KnownOne, then the input couldn't be all
11633 // zeros, thus the result of the srl will always be zero.
11634 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
11635
11636 // If all of the bits input the to ctlz node are known to be zero, then
11637 // the result of the ctlz is "32" and the result of the shift is one.
11638 APInt UnknownBits = ~Known.Zero;
11639 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
11640
11641 // Otherwise, check to see if there is exactly one bit input to the ctlz.
11642 if (UnknownBits.isPowerOf2()) {
11643 // Okay, we know that only that the single bit specified by UnknownBits
11644 // could be set on input to the CTLZ node. If this bit is set, the SRL
11645 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
11646 // to an SRL/XOR pair, which is likely to simplify more.
11647 unsigned ShAmt = UnknownBits.countr_zero();
11648 SDValue Op = N0.getOperand(0);
11649
11650 if (ShAmt) {
11651 SDLoc DL(N0);
11652 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
11653 DAG.getShiftAmountConstant(ShAmt, VT, DL));
11654 AddToWorklist(Op.getNode());
11655 }
11656 return DAG.getNode(ISD::XOR, DL, VT, Op, DAG.getConstant(1, DL, VT));
11657 }
11658 }
11659
11660 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
11661 if (N1.getOpcode() == ISD::TRUNCATE &&
11662 N1.getOperand(0).getOpcode() == ISD::AND) {
11663 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11664 return DAG.getNode(ISD::SRL, DL, VT, N0, NewOp1);
11665 }
11666
11667 // fold (srl (logic_op x, (shl (zext y), c1)), c1)
11668 // -> (logic_op (srl x, c1), (zext y))
11669 // c1 <= leadingzeros(zext(y))
11670 // TODO: Replace c1 with valuetracking?
11671 SDValue X, ZExtY;
11672 if (sd_match(
11673 N0,
11675 m_Value(X),
11677 m_Specific(N1))))))) {
11678 unsigned NumLeadingZeros = ZExtY.getScalarValueSizeInBits() -
11680 if (N1C && N1C->getZExtValue() <= NumLeadingZeros)
11681 return DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
11682 DAG.getNode(ISD::SRL, SDLoc(N0), VT, X, N1), ZExtY);
11683 }
11684
11685 // fold (srl (bitcast (build_vector e1, ..., eN)), (N-1) * eltsize)
11686 // -> (zext eN)
11687 if (N1C && VT.isScalarInteger() && DAG.getDataLayout().isLittleEndian()) {
11689 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
11690 EVT BVVT = BV.getValueType();
11691 unsigned EltSizeInBits = BVVT.getScalarSizeInBits();
11692 unsigned NumElts = BVVT.getVectorNumElements();
11693 if (N1C->getZExtValue() == (NumElts - 1) * EltSizeInBits) {
11694 SDValue LastElt = BV.getOperand(NumElts - 1);
11695 assert(LastElt.getScalarValueSizeInBits() >= EltSizeInBits &&
11696 "Expected BUILD_VECTOR operand as wide as element type");
11697 EVT IntEltVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits);
11698 LastElt = DAG.getBitcast(LastElt.getValueType().changeTypeToInteger(),
11699 LastElt);
11700 return DAG.getZExtOrTrunc(DAG.getZExtOrTrunc(LastElt, DL, IntEltVT), DL,
11701 VT);
11702 }
11703 }
11704 }
11705
11706 // fold (srl (add nuw X, C), D) -> (add nuw (srl X, D), C u>> D)
11707 // when C has D trailing zeros (so C >> D is exact).
11708 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11709 N0->getFlags().hasNoUnsignedWrap()) {
11710 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11711 const APInt &ShAmt = N1C->getAPIntValue();
11712 const APInt &AddVal = AddC->getAPIntValue();
11713 if (ShAmt.ult(AddVal.countr_zero())) {
11714 SDNodeFlags ShiftFlags = N->getFlags();
11715 SDValue NewSrl =
11716 DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11717 SDValue NewC = DAG.getConstant(AddVal.lshr(ShAmt), DL, VT);
11718 SDNodeFlags AddFlags = N0->getFlags();
11719 return DAG.getNode(ISD::ADD, DL, VT, NewSrl, NewC, AddFlags);
11720 }
11721 }
11722 }
11723
11724 // fold operands of srl based on knowledge that the low bits are not
11725 // demanded.
11727 return SDValue(N, 0);
11728
11729 if (N1C && !N1C->isOpaque())
11730 if (SDValue NewSRL = visitShiftByConstant(N))
11731 return NewSRL;
11732
11733 // Attempt to convert a srl of a load into a narrower zero-extending load.
11734 if (SDValue NarrowLoad = reduceLoadWidth(N))
11735 return NarrowLoad;
11736
11737 // Here is a common situation. We want to optimize:
11738 //
11739 // %a = ...
11740 // %b = and i32 %a, 2
11741 // %c = srl i32 %b, 1
11742 // brcond i32 %c ...
11743 //
11744 // into
11745 //
11746 // %a = ...
11747 // %b = and %a, 2
11748 // %c = setcc eq %b, 0
11749 // brcond %c ...
11750 //
11751 // However when after the source operand of SRL is optimized into AND, the SRL
11752 // itself may not be optimized further. Look for it and add the BRCOND into
11753 // the worklist.
11754 //
11755 // The also tends to happen for binary operations when SimplifyDemandedBits
11756 // is involved.
11757 //
11758 // FIXME: This is unecessary if we process the DAG in topological order,
11759 // which we plan to do. This workaround can be removed once the DAG is
11760 // processed in topological order.
11761 if (N->hasOneUse()) {
11762 SDNode *User = *N->user_begin();
11763
11764 // Look pass the truncate.
11765 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse())
11766 User = *User->user_begin();
11767
11768 if (User->getOpcode() == ISD::BRCOND || User->getOpcode() == ISD::AND ||
11769 User->getOpcode() == ISD::OR || User->getOpcode() == ISD::XOR)
11770 AddToWorklist(User);
11771 }
11772
11773 // Try to transform this shift into a multiply-high if
11774 // it matches the appropriate pattern detected in combineShiftToMULH.
11775 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
11776 return MULH;
11777
11778 if (SDValue AVG = foldShiftToAvg(N, DL))
11779 return AVG;
11780
11781 SDValue Y;
11782 if (VT.getScalarSizeInBits() % 2 == 0 && N1C) {
11783 // Fold clmul(zext(x), zext(y)) >> (BW - 1 | BW) -> clmul(r|h)(x, y).
11784 unsigned HalfBW = VT.getScalarSizeInBits() / 2;
11785 if (sd_match(N0, m_Clmul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
11786 X.getScalarValueSizeInBits() == HalfBW &&
11787 Y.getScalarValueSizeInBits() == HalfBW) {
11788 if (N1C->getZExtValue() == HalfBW - 1 &&
11789 (!LegalOperations ||
11790 TLI.isOperationLegalOrCustom(ISD::CLMULR, X.getValueType())))
11791 return DAG.getNode(
11792 ISD::ZERO_EXTEND, DL, VT,
11793 DAG.getNode(ISD::CLMULR, DL, X.getValueType(), X, Y));
11794 if (N1C->getZExtValue() == HalfBW &&
11795 (!LegalOperations ||
11796 TLI.isOperationLegalOrCustom(ISD::CLMULH, X.getValueType())))
11797 return DAG.getNode(
11798 ISD::ZERO_EXTEND, DL, VT,
11799 DAG.getNode(ISD::CLMULH, DL, X.getValueType(), X, Y));
11800 }
11801 }
11802
11803 // Fold bitreverse(clmul(bitreverse(x), bitreverse(y))) >> 1 ->
11804 // clmulh(x, y).
11805 if (N1C && N1C->getZExtValue() == 1 &&
11807 m_BitReverse(m_Value(Y))))))
11808 return DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
11809
11810 return SDValue();
11811}
11812
11813SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
11814 EVT VT = N->getValueType(0);
11815 SDValue N0 = N->getOperand(0);
11816 SDValue N1 = N->getOperand(1);
11817 SDValue N2 = N->getOperand(2);
11818 bool IsFSHL = N->getOpcode() == ISD::FSHL;
11819 unsigned BitWidth = VT.getScalarSizeInBits();
11820 SDLoc DL(N);
11821
11822 // fold (fshl/fshr C0, C1, C2) -> C3
11823 if (SDValue C =
11824 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
11825 return C;
11826
11827 // fold (fshl N0, N1, 0) -> N0
11828 // fold (fshr N0, N1, 0) -> N1
11830 if (DAG.MaskedValueIsZero(
11831 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
11832 return IsFSHL ? N0 : N1;
11833
11834 auto IsUndefOrZero = [](SDValue V) {
11835 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
11836 };
11837
11838 // TODO - support non-uniform vector shift amounts.
11839 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
11840 EVT ShAmtTy = N2.getValueType();
11841
11842 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
11843 if (Cst->getAPIntValue().uge(BitWidth)) {
11844 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
11845 return DAG.getNode(N->getOpcode(), DL, VT, N0, N1,
11846 DAG.getConstant(RotAmt, DL, ShAmtTy));
11847 }
11848
11849 unsigned ShAmt = Cst->getZExtValue();
11850 if (ShAmt == 0)
11851 return IsFSHL ? N0 : N1;
11852
11853 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
11854 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
11855 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
11856 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
11857 if (IsUndefOrZero(N0))
11858 return DAG.getNode(
11859 ISD::SRL, DL, VT, N1,
11860 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, DL, ShAmtTy));
11861 if (IsUndefOrZero(N1))
11862 return DAG.getNode(
11863 ISD::SHL, DL, VT, N0,
11864 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, DL, ShAmtTy));
11865
11866 // fold fshl(N0, N1, c) -> x and fshr(N0, N1, c) -> x
11867 // where N0 is any node that contributes "x >> C0" to the result:
11868 // lshr(x, C0) | fshr(_, x, C0) | fshl(_, x, C1)
11869 // and N1 is any node that contributes "x << C1" to the result:
11870 // shl(x, C1) | fshl(x, _, C1) | fshr(x, _, C0)
11871 // with C0 = IsFSHL ? amnt : BW-amnt, C1 = BW - C0
11872
11873 // ShAmt == 0 was handled above; uge(BitWidth) was reduced via modulo above.
11874 assert(ShAmt >= 1 && ShAmt < BitWidth &&
11875 "ShAmt must be in [1, BW-1] for the identity fold to be valid");
11876 SDValue Val;
11877 unsigned C0Expected = IsFSHL ? ShAmt : BitWidth - ShAmt;
11878 unsigned C1Expected = IsFSHL ? BitWidth - ShAmt : ShAmt;
11879
11880 if ((sd_match(N0, m_Srl(m_Value(Val), m_SpecificInt(C0Expected))) ||
11882 m_SpecificInt(C0Expected))) ||
11884 m_SpecificInt(C1Expected)))) &&
11885 (sd_match(N1, m_Shl(m_Specific(Val), m_SpecificInt(C1Expected))) ||
11887 m_SpecificInt(C1Expected))) ||
11889 m_SpecificInt(C0Expected)))))
11890 return Val;
11891
11892 // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
11893 // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
11894 // TODO - bigendian support once we have test coverage.
11895 // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
11896 // TODO - permit LHS EXTLOAD if extensions are shifted out.
11897 if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
11898 !DAG.getDataLayout().isBigEndian()) {
11899 auto *LHS = dyn_cast<LoadSDNode>(N0);
11900 auto *RHS = dyn_cast<LoadSDNode>(N1);
11901 if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
11902 LHS->getAddressSpace() == RHS->getAddressSpace() &&
11903 (LHS->hasNUsesOfValue(1, 0) || RHS->hasNUsesOfValue(1, 0)) &&
11905 if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
11906 SDLoc DL(RHS);
11907 uint64_t PtrOff =
11908 IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
11909 Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff);
11910 unsigned Fast = 0;
11911 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
11912 RHS->getAddressSpace(), NewAlign,
11913 RHS->getMemOperand()->getFlags(), &Fast) &&
11914 Fast) {
11915 SDValue NewPtr = DAG.getMemBasePlusOffset(
11916 RHS->getBasePtr(), TypeSize::getFixed(PtrOff), DL);
11917 AddToWorklist(NewPtr.getNode());
11918 SDValue Load = DAG.getLoad(
11919 VT, DL, RHS->getChain(), NewPtr,
11920 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11921 RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
11922 DAG.makeEquivalentMemoryOrdering(LHS, Load.getValue(1));
11923 DAG.makeEquivalentMemoryOrdering(RHS, Load.getValue(1));
11924 return Load;
11925 }
11926 }
11927 }
11928 }
11929 }
11930
11931 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
11932 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
11933 // iff We know the shift amount is in range.
11934 // TODO: when is it worth doing SUB(BW, N2) as well?
11935 if (isPowerOf2_32(BitWidth)) {
11936 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
11937 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
11938 return DAG.getNode(ISD::SRL, DL, VT, N1, N2);
11939 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
11940 return DAG.getNode(ISD::SHL, DL, VT, N0, N2);
11941 }
11942
11943 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
11944 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
11945 // TODO: Investigate flipping this rotate if only one is legal.
11946 // If funnel shift is legal as well we might be better off avoiding
11947 // non-constant (BW - N2).
11948 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
11949 if (N0 == N1 && hasOperation(RotOpc, VT))
11950 return DAG.getNode(RotOpc, DL, VT, N0, N2);
11951
11952 // Simplify, based on bits shifted out of N0/N1.
11954 return SDValue(N, 0);
11955
11956 return SDValue();
11957}
11958
11959SDValue DAGCombiner::visitSHLSAT(SDNode *N) {
11960 SDValue N0 = N->getOperand(0);
11961 SDValue N1 = N->getOperand(1);
11962 if (SDValue V = DAG.simplifyShift(N0, N1))
11963 return V;
11964
11965 SDLoc DL(N);
11966 EVT VT = N0.getValueType();
11967
11968 // fold (*shlsat c1, c2) -> c1<<c2
11969 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
11970 return C;
11971
11972 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11973
11974 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) {
11975 // fold (sshlsat x, c) -> (shl x, c)
11976 if (N->getOpcode() == ISD::SSHLSAT && N1C &&
11977 N1C->getAPIntValue().ult(DAG.ComputeNumSignBits(N0)))
11978 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
11979
11980 // fold (ushlsat x, c) -> (shl x, c)
11981 if (N->getOpcode() == ISD::USHLSAT && N1C &&
11982 N1C->getAPIntValue().ule(
11984 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
11985 }
11986
11987 return SDValue();
11988}
11989
11990// Given a ABS node, detect the following patterns:
11991// (ABS (SUB (EXTEND a), (EXTEND b))).
11992// (TRUNC (ABS (SUB (EXTEND a), (EXTEND b)))).
11993// Generates UABD/SABD instruction.
11994SDValue DAGCombiner::foldABSToABD(SDNode *N, const SDLoc &DL) {
11995 EVT SrcVT = N->getValueType(0);
11996
11997 if (N->getOpcode() == ISD::TRUNCATE)
11998 N = N->getOperand(0).getNode();
11999
12000 EVT VT = N->getValueType(0);
12001 SDValue Op0, Op1;
12002
12003 if (!sd_match(N, m_Abs(m_AnyOf(m_Sub(m_Value(Op0), m_Value(Op1)),
12004 m_Add(m_Value(Op0), m_Value(Op1))))))
12005 return SDValue();
12006
12007 SDValue AbsOp0 = N->getOperand(0);
12008 bool IsAdd = AbsOp0.getOpcode() == ISD::ADD;
12009 // Make sure (abs B) is positive.
12010 if (IsAdd) {
12011 // Elements of Op1 must be constant and != VT.minSignedValue() (or undef)
12012 auto IsNotMinSignedInt = [VT](ConstantSDNode *C) {
12013 if (C == nullptr)
12014 return true;
12015 return !C->getAPIntValue()
12016 .trunc(VT.getScalarSizeInBits())
12017 .isMinSignedValue();
12018 };
12019
12020 if (!ISD::matchUnaryPredicate(Op1, IsNotMinSignedInt, /*AllowUndefs=*/true,
12021 /*AllowTruncation=*/true))
12022 return SDValue();
12023 }
12024
12025 unsigned Opc0 = Op0.getOpcode();
12026
12027 // Check if the operands of the sub are (zero|sign)-extended, otherwise
12028 // fallback to ValueTracking.
12029 if (Opc0 != Op1.getOpcode() ||
12030 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND &&
12031 Opc0 != ISD::SIGN_EXTEND_INREG)) {
12032
12033 auto CreateZextedAbd = [&](unsigned AbdOpc) {
12034 if (IsAdd)
12035 Op1 = DAG.getNegative(Op1, SDLoc(Op1), VT);
12036 SDValue ABD = DAG.getNode(AbdOpc, DL, VT, Op0, Op1);
12037 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12038 };
12039
12040 // fold (abs (sub nsw x, y)) -> abds(x, y)
12041 // fold (abs (add nsw x, -y)) -> abds(x, y)
12042 bool AbsOpWillNSW =
12043 AbsOp0->getFlags().hasNoSignedWrap() ||
12044 (IsAdd ? DAG.willNotOverflowAdd(/*IsSigned=*/true, Op0, Op1)
12045 : DAG.willNotOverflowSub(/*IsSigned=*/true, Op0, Op1));
12046
12047 // Don't fold this for unsupported types as we lose the NSW handling.
12048 if (hasOperation(ISD::ABDS, VT) && TLI.preferABDSToABSWithNSW(VT) &&
12049 AbsOpWillNSW)
12050 return CreateZextedAbd(ISD::ABDS);
12051
12052 // fold (abs (sub x, y)) -> abdu(x, y)
12053 bool Op1SignBitIsOne = DAG.computeKnownBits(Op1).isNegative();
12054 bool AbsOpWillNUW = !IsAdd && DAG.SignBitIsZero(Op0) && Op1SignBitIsOne;
12055
12056 if (hasOperation(ISD::ABDU, VT) && AbsOpWillNUW)
12057 return CreateZextedAbd(ISD::ABDU);
12058
12059 return SDValue();
12060 }
12061
12062 // The IsAdd case explicitly checks for const/bv-of-const. This implies either
12063 // (Opc0 != Op1.getOpcode() || Opc0 is not in {zext/sext/sign_ext_inreg}. This
12064 // implies it was alrady handled by the above if statement.
12065 assert(!IsAdd && "Unexpected abs(add(x,y)) pattern");
12066
12067 EVT VT0, VT1;
12068 if (Opc0 == ISD::SIGN_EXTEND_INREG) {
12069 VT0 = cast<VTSDNode>(Op0.getOperand(1))->getVT();
12070 VT1 = cast<VTSDNode>(Op1.getOperand(1))->getVT();
12071 } else {
12072 VT0 = Op0.getOperand(0).getValueType();
12073 VT1 = Op1.getOperand(0).getValueType();
12074 }
12075 unsigned ABDOpcode = (Opc0 == ISD::ZERO_EXTEND) ? ISD::ABDU : ISD::ABDS;
12076
12077 // fold abs(sext(x) - sext(y)) -> zext(abds(x, y))
12078 // fold abs(zext(x) - zext(y)) -> zext(abdu(x, y))
12079 EVT MaxVT = VT0.bitsGT(VT1) ? VT0 : VT1;
12080 if ((VT0 == MaxVT || Op0->hasOneUse()) &&
12081 (VT1 == MaxVT || Op1->hasOneUse()) &&
12082 (!LegalTypes || hasOperation(ABDOpcode, MaxVT))) {
12083 SDValue ABD = DAG.getNode(ABDOpcode, DL, MaxVT,
12084 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op0),
12085 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op1));
12086 ABD = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ABD);
12087 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12088 }
12089
12090 // fold abs(sext(x) - sext(y)) -> abds(sext(x), sext(y))
12091 // fold abs(zext(x) - zext(y)) -> abdu(zext(x), zext(y))
12092 if (!LegalOperations || hasOperation(ABDOpcode, VT)) {
12093 SDValue ABD = DAG.getNode(ABDOpcode, DL, VT, Op0, Op1);
12094 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12095 }
12096
12097 return SDValue();
12098}
12099
12100SDValue DAGCombiner::visitABS(SDNode *N) {
12101 SDValue N0 = N->getOperand(0);
12102 EVT VT = N->getValueType(0);
12103 SDLoc DL(N);
12104
12105 // fold (abs c1) -> c2
12106 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ABS, DL, VT, {N0}))
12107 return C;
12108 // fold (abs (abs x)) -> (abs x)
12109 // fold (abs (abs_min_poison x)) -> (abs_min_poison x)
12110 if (ISD::isAbsOpcode(N0.getOpcode()))
12111 return N0;
12112 // fold (abs x) -> x iff not-negative
12113 if (DAG.SignBitIsZero(N0))
12114 return N0;
12115
12116 if (SDValue ABD = foldABSToABD(N, DL))
12117 return ABD;
12118
12119 // fold (abs (sign_extend_inreg x)) -> (zero_extend (abs (truncate x)))
12120 // iff zero_extend/truncate are free.
12121 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12122 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12123 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12124 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12125 hasOperation(ISD::ABS, ExtVT)) {
12126 return DAG.getNode(
12127 ISD::ZERO_EXTEND, DL, VT,
12128 DAG.getNode(ISD::ABS, DL, ExtVT,
12129 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12130 }
12131 }
12132
12133 return SDValue();
12134}
12135
12136SDValue DAGCombiner::visitABS_MIN_POISON(SDNode *N) {
12137 SDValue N0 = N->getOperand(0);
12138 EVT VT = N->getValueType(0);
12139 SDLoc DL(N);
12140
12141 // fold (abs_min_poison c1) -> c2 (or poison if c1 == INT_MIN)
12143 return C;
12144 // fold (abs_min_poison (abs_min_poison x)) -> (abs_min_poison x)
12145 // fold (abs_min_poison (abs x)) -> (abs x)
12146 // fold (abs_min_poison (freeze (abs x))) -> (freeze (abs x))
12147 // fold (abs_min_poison (freeze (abs_min_poison x))) ->
12148 // (freeze (abs_min_poison x))
12149 //
12150 // Freeze case is valid because: for x != INT_MIN both sides equal abs(x);
12151 // for x == INT_MIN both forms produce a non-deterministic but well-defined
12152 // value since freeze already consumed the poison.
12154 return N0;
12155 // fold (abs_min_poison x) -> x iff not-negative
12156 if (DAG.SignBitIsZero(N0))
12157 return N0;
12158
12159 if (SDValue ABD = foldABSToABD(N, DL))
12160 return ABD;
12161
12162 // fold (abs_min_poison (sign_extend_inreg x)) ->
12163 // (zero_extend (abs (truncate x)))
12164 // iff zero_extend/truncate are free. The sign_extend_inreg keeps the value
12165 // in the narrow type's range, so the wide abs_min_poison is never actually
12166 // poison.
12167 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12168 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12169 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12170 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12171 hasOperation(ISD::ABS, ExtVT)) {
12172 return DAG.getNode(
12173 ISD::ZERO_EXTEND, DL, VT,
12174 DAG.getNode(ISD::ABS, DL, ExtVT,
12175 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12176 }
12177 }
12178
12179 return SDValue();
12180}
12181
12182SDValue DAGCombiner::visitCLMUL(SDNode *N) {
12183 unsigned Opcode = N->getOpcode();
12184 SDValue N0 = N->getOperand(0);
12185 SDValue N1 = N->getOperand(1);
12186 EVT VT = N->getValueType(0);
12187 SDLoc DL(N);
12188
12189 // fold (clmul c1, c2)
12190 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
12191 return C;
12192
12193 // canonicalize constant to RHS
12196 return DAG.getNode(Opcode, DL, VT, N1, N0);
12197
12198 // fold (clmul x, 0) -> 0
12200 return DAG.getConstant(0, DL, VT);
12201
12202 // fold (clmul x, c_pow2) -> (shl x, log2(c_pow2))
12203 // This also handles (clmul x, 1) -> x since (shl x, 0) simplifies to x.
12204 if (Opcode == ISD::CLMUL) {
12205 if (ConstantSDNode *C = isConstOrConstSplat(N1)) {
12206 APInt CV = C->getAPIntValue().trunc(VT.getScalarSizeInBits());
12207 if (CV.isPowerOf2() &&
12208 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)))
12209 return DAG.getNode(ISD::SHL, DL, VT, N0,
12210 DAG.getShiftAmountConstant(CV.logBase2(), VT, DL));
12211 }
12212 }
12213
12214 return SDValue();
12215}
12216
12217SDValue DAGCombiner::visitBSWAP(SDNode *N) {
12218 SDValue N0 = N->getOperand(0);
12219 EVT VT = N->getValueType(0);
12220 SDLoc DL(N);
12221
12222 // fold (bswap c1) -> c2
12223 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BSWAP, DL, VT, {N0}))
12224 return C;
12225 // fold (bswap (bswap x)) -> x
12226 if (N0.getOpcode() == ISD::BSWAP)
12227 return N0.getOperand(0);
12228
12229 // Canonicalize bswap(bitreverse(x)) -> bitreverse(bswap(x)). If bitreverse
12230 // isn't supported, it will be expanded to bswap followed by a manual reversal
12231 // of bits in each byte. By placing bswaps before bitreverse, we can remove
12232 // the two bswaps if the bitreverse gets expanded.
12233 if (N0.getOpcode() == ISD::BITREVERSE && N0.hasOneUse()) {
12234 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12235 return DAG.getNode(ISD::BITREVERSE, DL, VT, BSwap);
12236 }
12237
12238 unsigned BW = VT.getScalarSizeInBits();
12239 // fold (bswap shl(x,c)) -> (zext(bswap(trunc(shl(x,sub(c,bw/2))))))
12240 // iff x >= bw/2 (i.e. lower half is known zero)
12241 if (BW >= 32 && N0.getOpcode() == ISD::SHL && N0.hasOneUse()) {
12242 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12243 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), BW / 2);
12244 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12245 ShAmt->getZExtValue() >= (BW / 2) && (ShAmt->getZExtValue() % 8) == 0 &&
12246 TLI.isTypeLegal(HalfVT) && TLI.isTruncateFree(VT, HalfVT) &&
12247 (!LegalOperations || hasOperation(ISD::BSWAP, HalfVT))) {
12248 SDValue Res = N0.getOperand(0);
12249 if (uint64_t NewShAmt = (ShAmt->getZExtValue() - (BW / 2)))
12250 Res = DAG.getNode(ISD::SHL, DL, VT, Res,
12251 DAG.getShiftAmountConstant(NewShAmt, VT, DL));
12252 Res = DAG.getZExtOrTrunc(Res, DL, HalfVT);
12253 Res = DAG.getNode(ISD::BSWAP, DL, HalfVT, Res);
12254 return DAG.getZExtOrTrunc(Res, DL, VT);
12255 }
12256 }
12257
12258 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
12259 // inverse-shift-of-bswap:
12260 // bswap (X u<< C) --> (bswap X) u>> C
12261 // bswap (X u>> C) --> (bswap X) u<< C
12262 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
12263 N0.hasOneUse()) {
12264 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12265 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12266 ShAmt->getZExtValue() % 8 == 0) {
12267 SDValue NewSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12268 unsigned InverseShift = N0.getOpcode() == ISD::SHL ? ISD::SRL : ISD::SHL;
12269 return DAG.getNode(InverseShift, DL, VT, NewSwap, N0.getOperand(1));
12270 }
12271 }
12272
12273 if (SDValue V = foldBitOrderCrossLogicOp(N, DAG))
12274 return V;
12275
12276 // Folds that depend on computeKnownBits of the operand.
12277 KnownBits Known = DAG.computeKnownBits(N0);
12278 // bswap(0) = 0. Catch cases that computeKnownBits can prove are zero but
12279 // that structural combines haven't simplified to a constant yet
12280 // (e.g. and of disjoint byte masks).
12281 if (Known.isZero())
12282 return DAG.getConstant(0, DL, VT);
12283 // If only one byte of the operand may be nonzero, bswap becomes a shift
12284 // to the mirror byte.
12285 unsigned TZ = alignDown(Known.countMinTrailingZeros(), 8);
12286 unsigned LZ = alignDown(Known.countMinLeadingZeros(), 8);
12287 if (BW - (LZ + TZ) == 8) {
12288 unsigned Opc = LZ > TZ ? ISD::SHL : ISD::SRL;
12289 // Skip if the target would re-expand the produced shift post-legalize.
12290 // Targets that custom-lower byte-multiple shifts via bswap (e.g. MSP430
12291 // for shl i16) would loop with this combine.
12292 if (!LegalOperations || hasOperation(Opc, VT)) {
12293 unsigned Amt = AbsoluteDifference(LZ, TZ);
12294 SDNodeFlags Flags =
12296 return DAG.getNode(Opc, DL, VT, N0,
12297 DAG.getShiftAmountConstant(Amt, VT, DL), Flags);
12298 }
12299 }
12300
12301 return SDValue();
12302}
12303
12304SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
12305 SDValue N0 = N->getOperand(0);
12306 EVT VT = N->getValueType(0);
12307 SDLoc DL(N);
12308
12309 // fold (bitreverse c1) -> c2
12310 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BITREVERSE, DL, VT, {N0}))
12311 return C;
12312
12313 // fold (bitreverse (bitreverse x)) -> x
12314 if (N0.getOpcode() == ISD::BITREVERSE)
12315 return N0.getOperand(0);
12316
12317 SDValue X, Y;
12318
12319 // fold (bitreverse (lshr (bitreverse x), y)) -> (shl x, y)
12320 if ((!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
12322 return DAG.getNode(ISD::SHL, DL, VT, X, Y);
12323
12324 // fold (bitreverse (shl (bitreverse x), y)) -> (lshr x, y)
12325 if ((!LegalOperations || TLI.isOperationLegal(ISD::SRL, VT)) &&
12327 return DAG.getNode(ISD::SRL, DL, VT, X, Y);
12328
12329 // fold bitreverse(clmul(bitreverse(x), bitreverse(y))) -> clmulr(x, y)
12330 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::CLMULR, VT)) &&
12332 return DAG.getNode(ISD::CLMULR, DL, VT, X, Y);
12333
12334 return SDValue();
12335}
12336
12337// Fold (ctlz (xor x, (sra x, bitwidth-1))) -> (add (ctls x), 1).
12338// Fold (ctlz (or (shl (xor x, (sra x, bitwidth-1)), 1), 1) -> (ctls x)
12339SDValue DAGCombiner::foldCTLZToCTLS(SDValue Src, const SDLoc &DL) {
12340 EVT VT = Src.getValueType();
12341
12342 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
12343 if ((LK.first != TargetLoweringBase::TypeLegal &&
12345 !TLI.isOperationLegalOrCustom(ISD::CTLS, LK.second))
12346 return SDValue();
12347
12348 unsigned BitWidth = VT.getScalarSizeInBits();
12349
12350 bool NeedAdd = true;
12351
12352 SDValue X;
12353 if (sd_match(Src,
12355 NeedAdd = false;
12356 Src = X;
12357 }
12358
12359 if (!sd_match(Src,
12362 m_SpecificInt(BitWidth - 1)))))))
12363 return SDValue();
12364
12365 SDValue Res = DAG.getNode(ISD::CTLS, DL, VT, X);
12366 if (!NeedAdd)
12367 return Res;
12368
12369 return DAG.getNode(ISD::ADD, DL, VT, Res, DAG.getConstant(1, DL, VT));
12370}
12371
12372SDValue DAGCombiner::visitCTLZ(SDNode *N) {
12373 SDValue N0 = N->getOperand(0);
12374 EVT VT = N->getValueType(0);
12375 SDLoc DL(N);
12376
12377 // fold (ctlz c1) -> c2
12378 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTLZ, DL, VT, {N0}))
12379 return C;
12380
12381 // If the value is known never to be zero, switch to the poison version.
12382 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_POISON, VT))
12383 if (DAG.isKnownNeverZero(N0))
12384 return DAG.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, N0);
12385
12386 if (SDValue V = foldCTLZToCTLS(N0, DL))
12387 return V;
12388
12389 return SDValue();
12390}
12391
12392SDValue DAGCombiner::visitCTLZ_ZERO_POISON(SDNode *N) {
12393 SDValue N0 = N->getOperand(0);
12394 EVT VT = N->getValueType(0);
12395 SDLoc DL(N);
12396
12397 // fold (ctlz_zero_poison c1) -> c2
12398 if (SDValue C =
12400 return C;
12401
12402 if (SDValue V = foldCTLZToCTLS(N0, DL))
12403 return V;
12404
12405 return SDValue();
12406}
12407
12408SDValue DAGCombiner::visitCTTZ(SDNode *N) {
12409 SDValue N0 = N->getOperand(0);
12410 EVT VT = N->getValueType(0);
12411 SDLoc DL(N);
12412
12413 // fold (cttz c1) -> c2
12414 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTTZ, DL, VT, {N0}))
12415 return C;
12416
12417 // If the value is known never to be zero, switch to the poison version.
12418 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_POISON, VT))
12419 if (DAG.isKnownNeverZero(N0))
12420 return DAG.getNode(ISD::CTTZ_ZERO_POISON, DL, VT, N0);
12421
12422 return SDValue();
12423}
12424
12425SDValue DAGCombiner::visitCTTZ_ZERO_POISON(SDNode *N) {
12426 SDValue N0 = N->getOperand(0);
12427 EVT VT = N->getValueType(0);
12428 SDLoc DL(N);
12429
12430 // fold (cttz_zero_poison c1) -> c2
12431 if (SDValue C =
12433 return C;
12434 return SDValue();
12435}
12436
12437SDValue DAGCombiner::visitCTPOP(SDNode *N) {
12438 SDValue N0 = N->getOperand(0);
12439 EVT VT = N->getValueType(0);
12440 unsigned NumBits = VT.getScalarSizeInBits();
12441 SDLoc DL(N);
12442
12443 // fold (ctpop c1) -> c2
12444 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTPOP, DL, VT, {N0}))
12445 return C;
12446
12447 // If the source is being shifted, but doesn't affect any active bits,
12448 // then we can call CTPOP on the shift source directly.
12449 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SHL) {
12450 if (ConstantSDNode *AmtC = isConstOrConstSplat(N0.getOperand(1))) {
12451 const APInt &Amt = AmtC->getAPIntValue();
12452 if (Amt.ult(NumBits)) {
12453 KnownBits KnownSrc = DAG.computeKnownBits(N0.getOperand(0));
12454 if ((N0.getOpcode() == ISD::SRL &&
12455 Amt.ule(KnownSrc.countMinTrailingZeros())) ||
12456 (N0.getOpcode() == ISD::SHL &&
12457 Amt.ule(KnownSrc.countMinLeadingZeros()))) {
12458 return DAG.getNode(ISD::CTPOP, DL, VT, N0.getOperand(0));
12459 }
12460 }
12461 }
12462 }
12463
12464 // If the upper bits are known to be zero, then see if its profitable to
12465 // only count the lower bits.
12466 if (VT.isScalarInteger() && NumBits > 8 && (NumBits & 1) == 0) {
12467 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), NumBits / 2);
12468 if (hasOperation(ISD::CTPOP, HalfVT) &&
12469 TLI.isTypeDesirableForOp(ISD::CTPOP, HalfVT) &&
12470 TLI.isTruncateFree(N0, HalfVT) && TLI.isZExtFree(HalfVT, VT)) {
12471 APInt UpperBits = APInt::getHighBitsSet(NumBits, NumBits / 2);
12472 if (DAG.MaskedValueIsZero(N0, UpperBits)) {
12473 SDValue PopCnt = DAG.getNode(ISD::CTPOP, DL, HalfVT,
12474 DAG.getZExtOrTrunc(N0, DL, HalfVT));
12475 return DAG.getZExtOrTrunc(PopCnt, DL, VT);
12476 }
12477 }
12478 }
12479
12480 return SDValue();
12481}
12482
12484 SDValue RHS, const SDNodeFlags Flags,
12485 const TargetLowering &TLI) {
12486 EVT VT = LHS.getValueType();
12487 if (!VT.isFloatingPoint())
12488 return false;
12489
12490 return Flags.hasNoSignedZeros() &&
12492 (Flags.hasNoNaNs() ||
12493 (DAG.isKnownNeverNaN(RHS) && DAG.isKnownNeverNaN(LHS)));
12494}
12495
12497 SDValue RHS, SDValue True, SDValue False,
12498 ISD::CondCode CC,
12499 const TargetLowering &TLI,
12500 SelectionDAG &DAG) {
12501 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12502 switch (CC) {
12503 case ISD::SETOLT:
12504 case ISD::SETOLE:
12505 case ISD::SETLT:
12506 case ISD::SETLE:
12507 case ISD::SETULT:
12508 case ISD::SETULE: {
12509 // Since it's known never nan to get here already, either fminnum or
12510 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
12511 // expanded in terms of it.
12512 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
12513 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12514 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
12515
12516 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
12517 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12518 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
12519 return SDValue();
12520 }
12521 case ISD::SETOGT:
12522 case ISD::SETOGE:
12523 case ISD::SETGT:
12524 case ISD::SETGE:
12525 case ISD::SETUGT:
12526 case ISD::SETUGE: {
12527 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
12528 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12529 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
12530
12531 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
12532 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12533 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
12534 return SDValue();
12535 }
12536 default:
12537 return SDValue();
12538 }
12539}
12540
12541// Convert (sr[al] (add n[su]w x, y)) -> (avgfloor[su] x, y)
12542SDValue DAGCombiner::foldShiftToAvg(SDNode *N, const SDLoc &DL) {
12543 const unsigned Opcode = N->getOpcode();
12544 if (Opcode != ISD::SRA && Opcode != ISD::SRL)
12545 return SDValue();
12546
12547 EVT VT = N->getValueType(0);
12548 bool IsUnsigned = Opcode == ISD::SRL;
12549
12550 // Captured values.
12551 SDValue A, B;
12552
12553 // Match floor average as it is common to both floor/ceil avgs, ensure the add
12554 // doesn't wrap.
12555 SDNodeFlags Flags =
12557 if (sd_match(N, m_BinOp(Opcode,
12558 m_c_BinOp(ISD::ADD, m_Value(A), m_Value(B), Flags),
12559 m_One()))) {
12560 // Decide whether signed or unsigned.
12561 unsigned FloorISD = IsUnsigned ? ISD::AVGFLOORU : ISD::AVGFLOORS;
12562 if (hasOperation(FloorISD, VT))
12563 return DAG.getNode(FloorISD, DL, VT, {A, B});
12564 }
12565
12566 return SDValue();
12567}
12568
12569SDValue DAGCombiner::foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT) {
12570 unsigned Opc = N->getOpcode();
12571 SDValue X, Y, Z;
12572 if (sd_match(
12574 return DAG.getNode(Opc, DL, VT, X,
12575 DAG.getNOT(DL, DAG.getNode(ISD::SUB, DL, VT, Y, Z), VT));
12576
12578 m_Value(Z)))))
12579 return DAG.getNode(Opc, DL, VT, X,
12580 DAG.getNOT(DL, DAG.getNode(ISD::ADD, DL, VT, Y, Z), VT));
12581
12582 return SDValue();
12583}
12584
12585/// Generate Min/Max node
12586SDValue DAGCombiner::combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
12587 SDValue RHS, SDValue True,
12588 SDValue False, ISD::CondCode CC) {
12589 if ((LHS == True && RHS == False) || (LHS == False && RHS == True))
12590 return combineMinNumMaxNumImpl(DL, VT, LHS, RHS, True, False, CC, TLI, DAG);
12591
12592 // If we can't directly match this, try to see if we can pull an fneg out of
12593 // the select.
12595 True, DAG, LegalOperations, ForCodeSize);
12596 if (!NegTrue)
12597 return SDValue();
12598
12599 HandleSDNode NegTrueHandle(NegTrue);
12600
12601 // Try to unfold an fneg from the select if we are comparing the negated
12602 // constant.
12603 //
12604 // select (setcc x, K) (fneg x), -K -> fneg(minnum(x, K))
12605 //
12606 // TODO: Handle fabs
12607 if (LHS == NegTrue) {
12608 // If we can't directly match this, try to see if we can pull an fneg out of
12609 // the select.
12611 RHS, DAG, LegalOperations, ForCodeSize);
12612 if (NegRHS) {
12613 HandleSDNode NegRHSHandle(NegRHS);
12614 if (NegRHS == False) {
12615 SDValue Combined = combineMinNumMaxNumImpl(DL, VT, LHS, RHS, NegTrue,
12616 False, CC, TLI, DAG);
12617 if (Combined)
12618 return DAG.getNode(ISD::FNEG, DL, VT, Combined);
12619 }
12620 }
12621 }
12622
12623 return SDValue();
12624}
12625
12626/// If a (v)select has a condition value that is a sign-bit test, try to smear
12627/// the condition operand sign-bit across the value width and use it as a mask.
12629 SelectionDAG &DAG) {
12630 SDValue Cond = N->getOperand(0);
12631 SDValue C1 = N->getOperand(1);
12632 SDValue C2 = N->getOperand(2);
12634 return SDValue();
12635
12636 EVT VT = N->getValueType(0);
12637 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
12638 VT != Cond.getOperand(0).getValueType())
12639 return SDValue();
12640
12641 // The inverted-condition + commuted-select variants of these patterns are
12642 // canonicalized to these forms in IR.
12643 SDValue X = Cond.getOperand(0);
12644 SDValue CondC = Cond.getOperand(1);
12645 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12646 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
12648 // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
12649 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12650 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12651 return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
12652 }
12653 if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
12654 // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
12655 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12656 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12657 return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
12658 }
12659 return SDValue();
12660}
12661
12663 const TargetLowering &TLI) {
12664 if (!TLI.convertSelectOfConstantsToMath(VT))
12665 return false;
12666
12667 if (Cond.getOpcode() != ISD::SETCC || !Cond->hasOneUse())
12668 return true;
12670 return true;
12671
12672 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12673 if (CC == ISD::SETLT && isNullOrNullSplat(Cond.getOperand(1)))
12674 return true;
12675 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond.getOperand(1)))
12676 return true;
12677
12678 return false;
12679}
12680
12681SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
12682 SDValue Cond = N->getOperand(0);
12683 SDValue N1 = N->getOperand(1);
12684 SDValue N2 = N->getOperand(2);
12685 EVT VT = N->getValueType(0);
12686 EVT CondVT = Cond.getValueType();
12687 SDLoc DL(N);
12688
12689 if (!VT.isInteger())
12690 return SDValue();
12691
12692 auto *C1 = dyn_cast<ConstantSDNode>(N1);
12693 auto *C2 = dyn_cast<ConstantSDNode>(N2);
12694 if (!C1 || !C2)
12695 return SDValue();
12696
12697 if (CondVT != MVT::i1 || LegalOperations) {
12698 // We can't do this reliably if integer based booleans have different contents
12699 // to floating point based booleans. This is because we can't tell whether we
12700 // have an integer-based boolean or a floating-point-based boolean unless we
12701 // can find the SETCC that produced it and inspect its operands. This is
12702 // fairly easy if C is the SETCC node, but it can potentially be
12703 // undiscoverable (or not reasonably discoverable). For example, it could be
12704 // in another basic block or it could require searching a complicated
12705 // expression.
12706 if (CondVT.isInteger() &&
12707 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
12709 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
12711 // fold (select Cond, 0, 1) -> (xor Cond, 1)
12712 if (C1->isZero() && C2->isOne()) {
12713 SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
12714 DAG.getConstant(1, DL, CondVT));
12715 if (VT.bitsEq(CondVT))
12716 return NotCond;
12717 return DAG.getZExtOrTrunc(NotCond, DL, VT);
12718 }
12719
12720 // fold (select Cond, 1, 0) -> Cond
12721 if (C1->isOne() && C2->isZero() && CondVT == VT)
12722 return Cond;
12723 }
12724
12725 return SDValue();
12726 }
12727
12728 // Only do this before legalization to avoid conflicting with target-specific
12729 // transforms in the other direction (create a select from a zext/sext). There
12730 // is also a target-independent combine here in DAGCombiner in the other
12731 // direction for (select Cond, -1, 0) when the condition is not i1.
12732 assert(CondVT == MVT::i1 && !LegalOperations);
12733
12734 // select Cond, 1, 0 --> zext (Cond)
12735 if (C1->isOne() && C2->isZero())
12736 return DAG.getZExtOrTrunc(Cond, DL, VT);
12737
12738 // select Cond, -1, 0 --> sext (Cond)
12739 if (C1->isAllOnes() && C2->isZero())
12740 return DAG.getSExtOrTrunc(Cond, DL, VT);
12741
12742 // select Cond, 0, 1 --> zext (!Cond)
12743 if (C1->isZero() && C2->isOne()) {
12744 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12745 NotCond = DAG.getZExtOrTrunc(NotCond, DL, VT);
12746 return NotCond;
12747 }
12748
12749 // select Cond, 0, -1 --> sext (!Cond)
12750 if (C1->isZero() && C2->isAllOnes()) {
12751 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12752 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
12753 return NotCond;
12754 }
12755
12756 // Use a target hook because some targets may prefer to transform in the
12757 // other direction.
12759 return SDValue();
12760
12761 // For any constants that differ by 1, we can transform the select into
12762 // an extend and add.
12763 const APInt &C1Val = C1->getAPIntValue();
12764 const APInt &C2Val = C2->getAPIntValue();
12765
12766 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
12767 if (C1Val - 1 == C2Val) {
12768 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
12769 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
12770 }
12771
12772 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
12773 if (C1Val + 1 == C2Val) {
12774 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
12775 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
12776 }
12777
12778 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
12779 if (C1Val.isPowerOf2() && C2Val.isZero()) {
12780 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
12781 SDValue ShAmtC =
12782 DAG.getShiftAmountConstant(C1Val.exactLogBase2(), VT, DL);
12783 return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
12784 }
12785
12786 // select Cond, -1, C --> or (sext Cond), C
12787 if (C1->isAllOnes()) {
12788 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
12789 return DAG.getNode(ISD::OR, DL, VT, Cond, N2);
12790 }
12791
12792 // select Cond, C, -1 --> or (sext (not Cond)), C
12793 if (C2->isAllOnes()) {
12794 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12795 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
12796 return DAG.getNode(ISD::OR, DL, VT, NotCond, N1);
12797 }
12798
12800 return V;
12801
12802 return SDValue();
12803}
12804
12805template <class MatchContextClass>
12807 SelectionDAG &DAG) {
12808 assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT ||
12809 N->getOpcode() == ISD::VP_SELECT) &&
12810 "Expected a (v)(vp.)select");
12811 SDValue Cond = N->getOperand(0);
12812 SDValue T = N->getOperand(1), F = N->getOperand(2);
12813 EVT VT = N->getValueType(0);
12814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12815 MatchContextClass matcher(DAG, TLI, N);
12816
12817 if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1)
12818 return SDValue();
12819
12820 // select Cond, Cond, F --> or Cond, freeze(F)
12821 // select Cond, 1, F --> or Cond, freeze(F)
12822 if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true))
12823 return matcher.getNode(ISD::OR, DL, VT, Cond, DAG.getFreeze(F));
12824
12825 // select Cond, T, Cond --> and Cond, freeze(T)
12826 // select Cond, T, 0 --> and Cond, freeze(T)
12827 if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true))
12828 return matcher.getNode(ISD::AND, DL, VT, Cond, DAG.getFreeze(T));
12829
12830 // select Cond, T, 1 --> or (not Cond), freeze(T)
12831 if (isOneOrOneSplat(F, /* AllowUndefs */ true)) {
12832 SDValue NotCond =
12833 matcher.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
12834 return matcher.getNode(ISD::OR, DL, VT, NotCond, DAG.getFreeze(T));
12835 }
12836
12837 // select Cond, 0, F --> and (not Cond), freeze(F)
12838 if (isNullOrNullSplat(T, /* AllowUndefs */ true)) {
12839 SDValue NotCond =
12840 matcher.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
12841 return matcher.getNode(ISD::AND, DL, VT, NotCond, DAG.getFreeze(F));
12842 }
12843
12844 return SDValue();
12845}
12846
12848 SDValue N0 = N->getOperand(0);
12849 SDValue N1 = N->getOperand(1);
12850 SDValue N2 = N->getOperand(2);
12851 EVT VT = N->getValueType(0);
12852 unsigned EltSizeInBits = VT.getScalarSizeInBits();
12853
12854 SDValue Cond0, Cond1;
12855 ISD::CondCode CC;
12856 if (!sd_match(N0, m_OneUse(m_SetCC(m_Value(Cond0), m_Value(Cond1),
12857 m_CondCode(CC)))) ||
12858 VT != Cond0.getValueType())
12859 return SDValue();
12860
12861 // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the
12862 // compare is inverted from that pattern ("Cond0 s> -1").
12863 if (CC == ISD::SETLT && isNullOrNullSplat(Cond1))
12864 ; // This is the pattern we are looking for.
12865 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1))
12866 std::swap(N1, N2);
12867 else
12868 return SDValue();
12869
12870 // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & freeze(N1)
12871 if (isNullOrNullSplat(N2)) {
12872 SDLoc DL(N);
12873 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
12874 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
12875 return DAG.getNode(ISD::AND, DL, VT, Sra, DAG.getFreeze(N1));
12876 }
12877
12878 // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | freeze(N2)
12879 if (isAllOnesOrAllOnesSplat(N1)) {
12880 SDLoc DL(N);
12881 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
12882 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
12883 return DAG.getNode(ISD::OR, DL, VT, Sra, DAG.getFreeze(N2));
12884 }
12885
12886 // If we have to invert the sign bit mask, only do that transform if the
12887 // target has a bitwise 'and not' instruction (the invert is free).
12888 // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & freeze(N2)
12889 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12890 if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) {
12891 SDLoc DL(N);
12892 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
12893 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
12894 SDValue Not = DAG.getNOT(DL, Sra, VT);
12895 return DAG.getNode(ISD::AND, DL, VT, Not, DAG.getFreeze(N2));
12896 }
12897
12898 // TODO: There's another pattern in this family, but it may require
12899 // implementing hasOrNot() to check for profitability:
12900 // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | freeze(N2)
12901
12902 return SDValue();
12903}
12904
12905// Match SELECTs with absolute difference patterns.
12906// (select (setcc a, b, set?gt), (sub a, b), (sub b, a)) --> (abd? a, b)
12907// (select (setcc a, b, set?ge), (sub a, b), (sub b, a)) --> (abd? a, b)
12908// (select (setcc a, b, set?lt), (sub b, a), (sub a, b)) --> (abd? a, b)
12909// (select (setcc a, b, set?le), (sub b, a), (sub a, b)) --> (abd? a, b)
12910SDValue DAGCombiner::foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
12911 SDValue False, ISD::CondCode CC,
12912 const SDLoc &DL) {
12913 bool IsSigned = isSignedIntSetCC(CC);
12914 unsigned ABDOpc = IsSigned ? ISD::ABDS : ISD::ABDU;
12915 EVT VT = LHS.getValueType();
12916
12917 if (LegalOperations && !hasOperation(ABDOpc, VT))
12918 return SDValue();
12919
12920 // (setcc 0, b set???) --> (setcc b, 0, set???)
12921 if (isZeroOrZeroSplat(LHS)) {
12922 std::swap(LHS, RHS);
12924 }
12925
12926 // (setcc (add nsw A, Const), 0, sets??) --> (setcc A, -Const, sets??)
12927 SDValue A, B;
12928 if (ISD::isSignedIntSetCC(CC) && LHS->getFlags().hasNoSignedWrap() &&
12931 RHS = DAG.getNegative(B, LHS, B.getValueType());
12932 LHS = A;
12933 }
12934
12935 bool IsTypeLegalOrPromote =
12936 TLI.isTypeLegal(VT) || TLI.getTypeAction(*DAG.getContext(), VT) ==
12938
12939 switch (CC) {
12940 case ISD::SETGT:
12941 case ISD::SETGE:
12942 case ISD::SETUGT:
12943 case ISD::SETUGE:
12948 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
12953 IsTypeLegalOrPromote)
12954 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
12955 break;
12956 case ISD::SETLT:
12957 case ISD::SETLE:
12958 case ISD::SETULT:
12959 case ISD::SETULE:
12964 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
12969 IsTypeLegalOrPromote)
12970 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
12971 break;
12972 default:
12973 break;
12974 }
12975
12976 return SDValue();
12977}
12978
12979// ([v]select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
12980// ([v]select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
12981SDValue DAGCombiner::foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
12982 SDValue False, ISD::CondCode CC,
12983 const SDLoc &DL) {
12984 APInt C;
12985 EVT VT = True.getValueType();
12986 if (sd_match(RHS, m_ConstInt(C)) && hasUMin(VT)) {
12987 if (CC == ISD::SETUGT && LHS == False &&
12988 sd_match(True, m_Add(m_Specific(False), m_SpecificInt(~C)))) {
12989 SDValue AddC = DAG.getConstant(~C, DL, VT);
12990 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, False, AddC);
12991 return DAG.getNode(ISD::UMIN, DL, VT, Add, False);
12992 }
12993 if (CC == ISD::SETULT && LHS == True &&
12994 sd_match(False, m_Add(m_Specific(True), m_SpecificInt(-C)))) {
12995 SDValue AddC = DAG.getConstant(-C, DL, VT);
12996 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, True, AddC);
12997 return DAG.getNode(ISD::UMIN, DL, VT, True, Add);
12998 }
12999 }
13000 return SDValue();
13001}
13002
13003SDValue DAGCombiner::visitSELECT(SDNode *N) {
13004 SDValue N0 = N->getOperand(0);
13005 SDValue N1 = N->getOperand(1);
13006 SDValue N2 = N->getOperand(2);
13007 EVT VT = N->getValueType(0);
13008 EVT VT0 = N0.getValueType();
13009 SDLoc DL(N);
13010 SDNodeFlags Flags = N->getFlags();
13011
13012 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
13013 return V;
13014
13016 return V;
13017
13018 // select (not Cond), N1, N2 -> select Cond, N2, N1
13019 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
13020 return DAG.getSelect(DL, VT, F, N2, N1, Flags);
13021
13022 if (SDValue V = foldSelectOfConstants(N))
13023 return V;
13024
13025 // If we can fold this based on the true/false value, do so.
13026 if (SimplifySelectOps(N, N1, N2))
13027 return SDValue(N, 0); // Don't revisit N.
13028
13029 if (VT0 == MVT::i1) {
13030 // The code in this block deals with the following 2 equivalences:
13031 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
13032 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
13033 // The target can specify its preferred form with the
13034 // shouldNormalizeToSelectSequence() callback. However we always transform
13035 // to the right anyway if we find the inner select exists in the DAG anyway
13036 // and we always transform to the left side if we know that we can further
13037 // optimize the combination of the conditions.
13038 bool normalizeToSequence =
13040 // select (and Cond0, Cond1), X, Y
13041 // -> select Cond0, (select Cond1, X, Y), Y
13042 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
13043 SDValue Cond0 = N0->getOperand(0);
13044 SDValue Cond1 = N0->getOperand(1);
13045 SDValue InnerSelect =
13046 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
13047 if (normalizeToSequence || !InnerSelect.use_empty())
13048 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
13049 InnerSelect, N2, Flags);
13050 // Cleanup on failure.
13051 if (InnerSelect.use_empty())
13052 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13053 }
13054 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
13055 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
13056 SDValue Cond0 = N0->getOperand(0);
13057 SDValue Cond1 = N0->getOperand(1);
13058 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
13059 Cond1, N1, N2, Flags);
13060 if (normalizeToSequence || !InnerSelect.use_empty())
13061 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
13062 InnerSelect, Flags);
13063 // Cleanup on failure.
13064 if (InnerSelect.use_empty())
13065 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13066 }
13067
13068 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
13069 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
13070 SDValue N1_0 = N1->getOperand(0);
13071 SDValue N1_1 = N1->getOperand(1);
13072 SDValue N1_2 = N1->getOperand(2);
13073 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
13074 // Create the actual and node if we can generate good code for it.
13075 if (!normalizeToSequence) {
13076 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
13077 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
13078 N2, Flags);
13079 }
13080 // Otherwise see if we can optimize the "and" to a better pattern.
13081 if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
13082 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
13083 N2, Flags);
13084 }
13085 }
13086 }
13087 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
13088 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
13089 SDValue N2_0 = N2->getOperand(0);
13090 SDValue N2_1 = N2->getOperand(1);
13091 SDValue N2_2 = N2->getOperand(2);
13092 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
13093 // Create the actual or node if we can generate good code for it.
13094 if (!normalizeToSequence) {
13095 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
13096 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
13097 N2_2, Flags);
13098 }
13099 // Otherwise see if we can optimize to a better pattern.
13100 if (SDValue Combined = visitORLike(N0, N2_0, DL))
13101 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
13102 N2_2, Flags);
13103 }
13104 }
13105
13106 // select usubo(x, y).overflow, (sub y, x), (usubo x, y) -> abdu(x, y)
13107 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13108 N2.getNode() == N0.getNode() && N2.getResNo() == 0 &&
13109 N1.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13110 N2.getOperand(1) == N1.getOperand(0) &&
13111 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13112 return DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1));
13113
13114 // select usubo(x, y).overflow, (usubo x, y), (sub y, x) -> neg (abdu x, y)
13115 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13116 N1.getNode() == N0.getNode() && N1.getResNo() == 0 &&
13117 N2.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13118 N2.getOperand(1) == N1.getOperand(0) &&
13119 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13120 return DAG.getNegative(
13121 DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1)),
13122 DL, VT);
13123 }
13124
13125 // Fold selects based on a setcc into other things, such as min/max/abs.
13126 if (N0.getOpcode() == ISD::SETCC) {
13127 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
13129
13130 // select (fcmp lt x, y), x, y -> fminnum x, y
13131 // select (fcmp gt x, y), x, y -> fmaxnum x, y
13132 //
13133 // This is OK if we don't care what happens if either operand is a NaN.
13134 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, Flags, TLI))
13135 if (SDValue FMinMax =
13136 combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, CC))
13137 return FMinMax;
13138
13139 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
13140 // This is conservatively limited to pre-legal-operations to give targets
13141 // a chance to reverse the transform if they want to do that. Also, it is
13142 // unlikely that the pattern would be formed late, so it's probably not
13143 // worth going through the other checks.
13144 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
13145 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
13146 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
13147 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
13148 auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
13149 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
13150 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
13151 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
13152 //
13153 // The IR equivalent of this transform would have this form:
13154 // %a = add %x, C
13155 // %c = icmp ugt %x, ~C
13156 // %r = select %c, -1, %a
13157 // =>
13158 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
13159 // %u0 = extractvalue %u, 0
13160 // %u1 = extractvalue %u, 1
13161 // %r = select %u1, -1, %u0
13162 SDVTList VTs = DAG.getVTList(VT, VT0);
13163 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
13164 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
13165 }
13166 }
13167
13168 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
13169 (!LegalOperations &&
13171 // Any flags available in a select/setcc fold will be on the setcc as they
13172 // migrated from fcmp
13173 return DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, N2,
13174 N0.getOperand(2), N0->getFlags());
13175 }
13176
13177 if (SDValue ABD = foldSelectToABD(Cond0, Cond1, N1, N2, CC, DL))
13178 return ABD;
13179
13180 if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
13181 return NewSel;
13182
13183 // (select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
13184 // (select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
13185 if (SDValue UMin = foldSelectToUMin(Cond0, Cond1, N1, N2, CC, DL))
13186 return UMin;
13187 }
13188
13189 if (!VT.isVector())
13190 if (SDValue BinOp = foldSelectOfBinops(N))
13191 return BinOp;
13192
13193 if (SDValue R = combineSelectAsExtAnd(N0, N1, N2, DL, DAG))
13194 return R;
13195
13196 return SDValue();
13197}
13198
13199// This function assumes all the vselect's arguments are CONCAT_VECTOR
13200// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
13202 SDLoc DL(N);
13203 SDValue Cond = N->getOperand(0);
13204 SDValue LHS = N->getOperand(1);
13205 SDValue RHS = N->getOperand(2);
13206 EVT VT = N->getValueType(0);
13207 int NumElems = VT.getVectorNumElements();
13208 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
13209 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
13210 Cond.getOpcode() == ISD::BUILD_VECTOR);
13211
13212 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
13213 // binary ones here.
13214 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
13215 return SDValue();
13216
13217 // We're sure we have an even number of elements due to the
13218 // concat_vectors we have as arguments to vselect.
13219 // Skip BV elements until we find one that's not an UNDEF
13220 // After we find an UNDEF element, keep looping until we get to half the
13221 // length of the BV and see if all the non-undef nodes are the same.
13222 ConstantSDNode *BottomHalf = nullptr;
13223 for (int i = 0; i < NumElems / 2; ++i) {
13224 if (Cond->getOperand(i)->isUndef())
13225 continue;
13226
13227 if (BottomHalf == nullptr)
13228 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13229 else if (Cond->getOperand(i).getNode() != BottomHalf)
13230 return SDValue();
13231 }
13232
13233 // Do the same for the second half of the BuildVector
13234 ConstantSDNode *TopHalf = nullptr;
13235 for (int i = NumElems / 2; i < NumElems; ++i) {
13236 if (Cond->getOperand(i)->isUndef())
13237 continue;
13238
13239 if (TopHalf == nullptr)
13240 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13241 else if (Cond->getOperand(i).getNode() != TopHalf)
13242 return SDValue();
13243 }
13244
13245 assert(TopHalf && BottomHalf &&
13246 "One half of the selector was all UNDEFs and the other was all the "
13247 "same value. This should have been addressed before this function.");
13248 return DAG.getNode(
13250 BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0),
13251 TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1));
13252}
13253
13254bool refineUniformBase(SDValue &BasePtr, SDValue &Index, bool IndexIsScaled,
13255 SelectionDAG &DAG, const SDLoc &DL) {
13256
13257 // Only perform the transformation when existing operands can be reused.
13258 if (IndexIsScaled)
13259 return false;
13260
13261 if (!isNullConstant(BasePtr) && !Index.hasOneUse())
13262 return false;
13263
13264 EVT VT = BasePtr.getValueType();
13265
13266 if (SDValue SplatVal = DAG.getSplatValue(Index);
13267 SplatVal && !isNullConstant(SplatVal) &&
13268 SplatVal.getValueType() == VT) {
13269 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13270 Index = DAG.getSplat(Index.getValueType(), DL, DAG.getConstant(0, DL, VT));
13271 return true;
13272 }
13273
13274 if (Index.getOpcode() != ISD::ADD)
13275 return false;
13276
13277 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(0));
13278 SplatVal && SplatVal.getValueType() == VT) {
13279 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13280 Index = Index.getOperand(1);
13281 return true;
13282 }
13283 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(1));
13284 SplatVal && SplatVal.getValueType() == VT) {
13285 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13286 Index = Index.getOperand(0);
13287 return true;
13288 }
13289 return false;
13290}
13291
13292// Fold sext/zext of index into index type.
13293bool refineIndexType(SDValue &Index, ISD::MemIndexType &IndexType, EVT DataVT,
13294 SelectionDAG &DAG) {
13295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13296
13297 // It's always safe to look through zero extends.
13298 if (Index.getOpcode() == ISD::ZERO_EXTEND) {
13299 if (TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13300 IndexType = ISD::UNSIGNED_SCALED;
13301 Index = Index.getOperand(0);
13302 return true;
13303 }
13304 if (ISD::isIndexTypeSigned(IndexType)) {
13305 IndexType = ISD::UNSIGNED_SCALED;
13306 return true;
13307 }
13308 }
13309
13310 // It's only safe to look through sign extends when Index is signed.
13311 if (Index.getOpcode() == ISD::SIGN_EXTEND &&
13312 ISD::isIndexTypeSigned(IndexType) &&
13313 TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13314 Index = Index.getOperand(0);
13315 return true;
13316 }
13317
13318 return false;
13319}
13320
13321SDValue DAGCombiner::visitVPSCATTER(SDNode *N) {
13322 VPScatterSDNode *MSC = cast<VPScatterSDNode>(N);
13323 SDValue Mask = MSC->getMask();
13324 SDValue Chain = MSC->getChain();
13325 SDValue Index = MSC->getIndex();
13326 SDValue Scale = MSC->getScale();
13327 SDValue StoreVal = MSC->getValue();
13328 SDValue BasePtr = MSC->getBasePtr();
13329 SDValue VL = MSC->getVectorLength();
13330 ISD::MemIndexType IndexType = MSC->getIndexType();
13331 SDLoc DL(N);
13332
13333 // Zap scatters with a zero mask.
13335 return Chain;
13336
13337 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13338 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13339 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13340 DL, Ops, MSC->getMemOperand(), IndexType);
13341 }
13342
13343 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13344 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13345 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13346 DL, Ops, MSC->getMemOperand(), IndexType);
13347 }
13348
13349 return SDValue();
13350}
13351
13352SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
13353 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
13354 SDValue Mask = MSC->getMask();
13355 SDValue Chain = MSC->getChain();
13356 SDValue Index = MSC->getIndex();
13357 SDValue Scale = MSC->getScale();
13358 SDValue StoreVal = MSC->getValue();
13359 SDValue BasePtr = MSC->getBasePtr();
13360 ISD::MemIndexType IndexType = MSC->getIndexType();
13361 SDLoc DL(N);
13362
13363 // Zap scatters with a zero mask.
13365 return Chain;
13366
13367 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13368 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13369 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13370 DL, Ops, MSC->getMemOperand(), IndexType,
13371 MSC->isTruncatingStore());
13372 }
13373
13374 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13375 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13376 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13377 DL, Ops, MSC->getMemOperand(), IndexType,
13378 MSC->isTruncatingStore());
13379 }
13380
13381 return SDValue();
13382}
13383
13384SDValue DAGCombiner::visitMSTORE(SDNode *N) {
13385 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
13386 SDValue Mask = MST->getMask();
13387 SDValue Chain = MST->getChain();
13388 SDValue Value = MST->getValue();
13389 SDValue Ptr = MST->getBasePtr();
13390
13391 // Zap masked stores with a zero mask.
13393 return Chain;
13394
13395 // Remove a masked store if base pointers and masks are equal.
13396 if (MaskedStoreSDNode *MST1 = dyn_cast<MaskedStoreSDNode>(Chain)) {
13397 if (MST->isUnindexed() && MST->isSimple() && MST1->isUnindexed() &&
13398 MST1->isSimple() && MST1->getBasePtr() == Ptr &&
13399 !MST->getBasePtr().isUndef() &&
13400 ((Mask == MST1->getMask() && MST->getMemoryVT().getStoreSize() ==
13401 MST1->getMemoryVT().getStoreSize()) ||
13403 TypeSize::isKnownLE(MST1->getMemoryVT().getStoreSize(),
13404 MST->getMemoryVT().getStoreSize())) {
13405 CombineTo(MST1, MST1->getChain());
13406 if (N->getOpcode() != ISD::DELETED_NODE)
13407 AddToWorklist(N);
13408 return SDValue(N, 0);
13409 }
13410 }
13411
13412 // If this is a masked load with an all ones mask, we can use a unmasked load.
13413 // FIXME: Can we do this for indexed, compressing, or truncating stores?
13414 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MST->isUnindexed() &&
13415 !MST->isCompressingStore() && !MST->isTruncatingStore())
13416 return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(),
13417 MST->getBasePtr(), MST->getPointerInfo(),
13418 MST->getBaseAlign(), MST->getMemOperand()->getFlags(),
13419 MST->getAAInfo());
13420
13421 // Try transforming N to an indexed store.
13422 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13423 return SDValue(N, 0);
13424
13425 if (MST->isTruncatingStore() && MST->isUnindexed() &&
13426 Value.getValueType().isInteger() &&
13428 !cast<ConstantSDNode>(Value)->isOpaque())) {
13429 APInt TruncDemandedBits =
13430 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13432
13433 // See if we can simplify the operation with
13434 // SimplifyDemandedBits, which only works if the value has a single use.
13435 if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
13436 // Re-visit the store if anything changed and the store hasn't been merged
13437 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13438 // node back to the worklist if necessary, but we also need to re-visit
13439 // the Store node itself.
13440 if (N->getOpcode() != ISD::DELETED_NODE)
13441 AddToWorklist(N);
13442 return SDValue(N, 0);
13443 }
13444 }
13445
13446 // If this is a TRUNC followed by a masked store, fold this into a masked
13447 // truncating store. We can do this even if this is already a masked
13448 // truncstore.
13449 // TODO: Try combine to masked compress store if possiable.
13450 if ((Value.getOpcode() == ISD::TRUNCATE) && Value->hasOneUse() &&
13451 MST->isUnindexed() && !MST->isCompressingStore() &&
13452 TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
13453 MST->getMemoryVT(), MST->getAlign(),
13454 MST->getAddressSpace(), LegalOperations)) {
13455 auto Mask = TLI.promoteTargetBoolean(DAG, MST->getMask(),
13456 Value.getOperand(0).getValueType());
13457 return DAG.getMaskedStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13458 MST->getOffset(), Mask, MST->getMemoryVT(),
13459 MST->getMemOperand(), MST->getAddressingMode(),
13460 /*IsTruncating=*/true);
13461 }
13462
13463 return SDValue();
13464}
13465
13466SDValue DAGCombiner::visitVP_STRIDED_STORE(SDNode *N) {
13467 auto *SST = cast<VPStridedStoreSDNode>(N);
13468 EVT EltVT = SST->getValue().getValueType().getVectorElementType();
13469 // Combine strided stores with unit-stride to a regular VP store.
13470 if (auto *CStride = dyn_cast<ConstantSDNode>(SST->getStride());
13471 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
13472 return DAG.getStoreVP(SST->getChain(), SDLoc(N), SST->getValue(),
13473 SST->getBasePtr(), SST->getOffset(), SST->getMask(),
13474 SST->getVectorLength(), SST->getMemoryVT(),
13475 SST->getMemOperand(), SST->getAddressingMode(),
13476 SST->isTruncatingStore(), SST->isCompressingStore());
13477 }
13478 return SDValue();
13479}
13480
13481SDValue DAGCombiner::visitVECTOR_COMPRESS(SDNode *N) {
13482 SDLoc DL(N);
13483 SDValue Vec = N->getOperand(0);
13484 SDValue Mask = N->getOperand(1);
13485 SDValue Passthru = N->getOperand(2);
13486 EVT VecVT = Vec.getValueType();
13487
13488 bool HasPassthru = !Passthru.isUndef();
13489
13490 APInt SplatVal;
13491 if (ISD::isConstantSplatVector(Mask.getNode(), SplatVal))
13492 return TLI.isConstTrueVal(Mask) ? Vec : Passthru;
13493
13494 if (Vec.isUndef() || Mask.isUndef())
13495 return Passthru;
13496
13497 // No need for potentially expensive compress if the mask is constant.
13500 EVT ScalarVT = VecVT.getVectorElementType();
13501 unsigned NumSelected = 0;
13502 unsigned NumElmts = VecVT.getVectorNumElements();
13503 for (unsigned I = 0; I < NumElmts; ++I) {
13504 SDValue MaskI = Mask.getOperand(I);
13505 // We treat undef mask entries as "false".
13506 if (MaskI.isUndef())
13507 continue;
13508
13509 if (TLI.isConstTrueVal(MaskI)) {
13510 SDValue VecI = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Vec,
13511 DAG.getVectorIdxConstant(I, DL));
13512 Ops.push_back(VecI);
13513 NumSelected++;
13514 }
13515 }
13516 for (unsigned Rest = NumSelected; Rest < NumElmts; ++Rest) {
13517 SDValue Val =
13518 HasPassthru
13519 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Passthru,
13520 DAG.getVectorIdxConstant(Rest, DL))
13521 : DAG.getUNDEF(ScalarVT);
13522 Ops.push_back(Val);
13523 }
13524 return DAG.getBuildVector(VecVT, DL, Ops);
13525 }
13526
13527 return SDValue();
13528}
13529
13530SDValue DAGCombiner::visitVPGATHER(SDNode *N) {
13531 VPGatherSDNode *MGT = cast<VPGatherSDNode>(N);
13532 SDValue Mask = MGT->getMask();
13533 SDValue Chain = MGT->getChain();
13534 SDValue Index = MGT->getIndex();
13535 SDValue Scale = MGT->getScale();
13536 SDValue BasePtr = MGT->getBasePtr();
13537 SDValue VL = MGT->getVectorLength();
13538 ISD::MemIndexType IndexType = MGT->getIndexType();
13539 SDLoc DL(N);
13540
13541 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
13542 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
13543 return DAG.getGatherVP(
13544 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13545 Ops, MGT->getMemOperand(), IndexType);
13546 }
13547
13548 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
13549 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
13550 return DAG.getGatherVP(
13551 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13552 Ops, MGT->getMemOperand(), IndexType);
13553 }
13554
13555 return SDValue();
13556}
13557
13558SDValue DAGCombiner::visitMGATHER(SDNode *N) {
13559 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
13560 SDValue Mask = MGT->getMask();
13561 SDValue Chain = MGT->getChain();
13562 SDValue Index = MGT->getIndex();
13563 SDValue Scale = MGT->getScale();
13564 SDValue PassThru = MGT->getPassThru();
13565 SDValue BasePtr = MGT->getBasePtr();
13566 ISD::MemIndexType IndexType = MGT->getIndexType();
13567 SDLoc DL(N);
13568
13569 // Zap gathers with a zero mask.
13571 return CombineTo(N, PassThru, MGT->getChain());
13572
13573 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
13574 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
13575 return DAG.getMaskedGather(
13576 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13577 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
13578 }
13579
13580 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
13581 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
13582 return DAG.getMaskedGather(
13583 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13584 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
13585 }
13586
13587 return SDValue();
13588}
13589
13590SDValue DAGCombiner::visitMLOAD(SDNode *N) {
13591 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
13592 SDValue Mask = MLD->getMask();
13593
13594 // Zap masked loads with a zero mask.
13596 return CombineTo(N, MLD->getPassThru(), MLD->getChain());
13597
13598 // If this is a masked load with an all ones mask, we can use a unmasked load.
13599 // FIXME: Can we do this for indexed, expanding, or extending loads?
13600 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MLD->isUnindexed() &&
13601 !MLD->isExpandingLoad() && MLD->getExtensionType() == ISD::NON_EXTLOAD) {
13602 SDValue NewLd = DAG.getLoad(
13603 N->getValueType(0), SDLoc(N), MLD->getChain(), MLD->getBasePtr(),
13604 MLD->getPointerInfo(), MLD->getBaseAlign(),
13605 MLD->getMemOperand()->getFlags(), MLD->getAAInfo(), MLD->getRanges());
13606 return CombineTo(N, NewLd, NewLd.getValue(1));
13607 }
13608
13609 // Try transforming N to an indexed load.
13610 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13611 return SDValue(N, 0);
13612
13613 return SDValue();
13614}
13615
13616SDValue DAGCombiner::visitMHISTOGRAM(SDNode *N) {
13617 MaskedHistogramSDNode *HG = cast<MaskedHistogramSDNode>(N);
13618 SDValue Chain = HG->getChain();
13619 SDValue Inc = HG->getInc();
13620 SDValue Mask = HG->getMask();
13621 SDValue BasePtr = HG->getBasePtr();
13622 SDValue Index = HG->getIndex();
13623 SDLoc DL(HG);
13624
13625 EVT MemVT = HG->getMemoryVT();
13626 EVT DataVT = Index.getValueType();
13627 MachineMemOperand *MMO = HG->getMemOperand();
13628 ISD::MemIndexType IndexType = HG->getIndexType();
13629
13631 return Chain;
13632
13633 if (refineUniformBase(BasePtr, Index, HG->isIndexScaled(), DAG, DL) ||
13634 refineIndexType(Index, IndexType, DataVT, DAG)) {
13635 SDValue Ops[] = {Chain, Inc, Mask, BasePtr, Index,
13636 HG->getScale(), HG->getIntID()};
13637 return DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), MemVT, DL, Ops,
13638 MMO, IndexType);
13639 }
13640
13641 return SDValue();
13642}
13643
13644SDValue DAGCombiner::visitPARTIAL_REDUCE_MLA(SDNode *N) {
13645 if (SDValue Res = foldPartialReduceMLAMulOp(N))
13646 return Res;
13647 if (SDValue Res = foldPartialReduceAdd(N))
13648 return Res;
13649 return SDValue();
13650}
13651
13652// partial_reduce_*mla(acc, mul(*ext(a), *ext(b)), splat(1))
13653// -> partial_reduce_*mla(acc, a, b)
13654//
13655// partial_reduce_*mla(acc, mul(*ext(x), splat(C)), splat(1))
13656// -> partial_reduce_*mla(acc, x, splat(C))
13657//
13658// partial_reduce_*mla(acc, sel(p, mul(*ext(a), *ext(b)), splat(0)), splat(1))
13659// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), b)
13660//
13661// partial_reduce_*mla(acc, sel(p, mul(*ext(a), splat(C)), splat(0)), splat(1))
13662// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), splat(C))
13663SDValue DAGCombiner::foldPartialReduceMLAMulOp(SDNode *N) {
13664 SDLoc DL(N);
13665 auto *Context = DAG.getContext();
13666 SDValue Tmp;
13667 SDValue Acc = N->getOperand(0);
13668 SDValue Op1 = N->getOperand(1);
13669 SDValue Op2 = N->getOperand(2);
13670 unsigned Opc = Op1->getOpcode();
13671
13672 // Handle predication by moving the SELECT into the operand of the MUL.
13673 SDValue Pred;
13674 if (Opc == ISD::VSELECT && (isZeroOrZeroSplat(Op1->getOperand(2)) ||
13675 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
13676 Pred = Op1->getOperand(0);
13677 Op1 = Op1->getOperand(1);
13678 Opc = Op1->getOpcode();
13679 }
13680
13681 // Handle negation (sub-reduction).
13682 bool IsMLS = false;
13683 if (sd_match(Op1, m_Neg(m_Value(Tmp)))) {
13684 Op1 = Tmp;
13685 Opc = Op1->getOpcode();
13686 IsMLS = true;
13687 }
13688
13689 if (Opc != ISD::MUL && Opc != ISD::FMUL && Opc != ISD::SHL)
13690 return SDValue();
13691
13692 SDValue LHS = Op1->getOperand(0);
13693 SDValue RHS = Op1->getOperand(1);
13694
13695 // After instcombine, negation for FP operations is on the RHS, so implement:
13696 // fmul(fpext(a), fneg(fpext(b)))
13697 //-> fmul(fpext(a), fpext(fneg(b)))
13698 if (sd_match(RHS, m_FNeg(m_Value(Tmp)))) {
13699 RHS = Tmp;
13700 IsMLS = true;
13701 }
13702
13703 // Try to treat (shl %a, %c) as (mul %a, (1 << %c)) for constant %c.
13704 if (Opc == ISD::SHL) {
13705 APInt C;
13706 if (!ISD::isConstantSplatVector(RHS.getNode(), C))
13707 return SDValue();
13708
13709 RHS =
13710 DAG.getSplatVector(RHS.getValueType(), DL,
13711 DAG.getConstant(APInt(C.getBitWidth(), 1).shl(C), DL,
13712 RHS.getValueType().getScalarType()));
13713 Opc = ISD::MUL;
13714 }
13715
13716 if (!(Opc == ISD::MUL && llvm::isOneOrOneSplat(Op2)) &&
13718 return SDValue();
13719
13720 auto IsIntOrFPExtOpcode = [](unsigned int Opcode) {
13721 return (ISD::isExtOpcode(Opcode) || Opcode == ISD::FP_EXTEND);
13722 };
13723
13724 unsigned LHSOpcode = LHS->getOpcode();
13725 if (!IsIntOrFPExtOpcode(LHSOpcode))
13726 return SDValue();
13727
13728 SDValue LHSExtOp = LHS->getOperand(0);
13729 EVT LHSExtOpVT = LHSExtOp.getValueType();
13730
13731 // When Pred is non-zero, set Op = select(Pred, Op, splat(0)) and freeze
13732 // OtherOp to keep the same semantics when moving the selects into the MUL
13733 // operands.
13734 auto ApplyPredicate = [&](SDValue &Op, SDValue &OtherOp) {
13735 if (Pred) {
13736 EVT OpVT = Op.getValueType();
13737 SDValue Zero = OpVT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, OpVT)
13738 : DAG.getConstant(0, DL, OpVT);
13739 Op = DAG.getSelect(DL, OpVT, Pred, Op, Zero);
13740 OtherOp = DAG.getFreeze(OtherOp);
13741 }
13742 };
13743
13744 // Generate an MLA or MLS.
13745 auto GetMLA = [&](unsigned Opc, SDValue Acc, SDValue LHS,
13746 SDValue RHS) -> SDValue {
13747 EVT AccVT = Acc.getValueType();
13748 return IsMLS ? DAG.getPartialReduceMLS(Opc, DL, Acc, LHS, RHS)
13749 : DAG.getNode(Opc, DL, AccVT, Acc, LHS, RHS);
13750 };
13751
13752 // partial_reduce_*mla(acc, mul(ext(x), splat(C)), splat(1))
13753 // -> partial_reduce_*mla(acc, x, C)
13754 APInt C;
13755 if (ISD::isConstantSplatVector(RHS.getNode(), C)) {
13756 // TODO: Make use of partial_reduce_sumla here
13757 APInt CTrunc = C.trunc(LHSExtOpVT.getScalarSizeInBits());
13758 unsigned LHSBits = LHS.getValueType().getScalarSizeInBits();
13759 if ((LHSOpcode != ISD::ZERO_EXTEND || CTrunc.zext(LHSBits) != C) &&
13760 (LHSOpcode != ISD::SIGN_EXTEND || CTrunc.sext(LHSBits) != C))
13761 return SDValue();
13762
13763 unsigned NewOpcode = LHSOpcode == ISD::SIGN_EXTEND
13766
13767 // Only perform these combines if the target supports folding
13768 // the extends into the operation.
13770 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
13771 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
13772 return SDValue();
13773
13774 SDValue C = DAG.getConstant(CTrunc, DL, LHSExtOpVT);
13775 ApplyPredicate(C, LHSExtOp);
13776 return GetMLA(NewOpcode, Acc, LHSExtOp, C);
13777 }
13778
13779 unsigned RHSOpcode = RHS->getOpcode();
13780 if (!IsIntOrFPExtOpcode(RHSOpcode))
13781 return SDValue();
13782
13783 SDValue RHSExtOp = RHS->getOperand(0);
13784 if (LHSExtOpVT != RHSExtOp.getValueType())
13785 return SDValue();
13786
13787 unsigned NewOpc;
13788 if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::SIGN_EXTEND)
13789 NewOpc = ISD::PARTIAL_REDUCE_SMLA;
13790 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
13791 NewOpc = ISD::PARTIAL_REDUCE_UMLA;
13792 else if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
13794 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::SIGN_EXTEND) {
13796 std::swap(LHSExtOp, RHSExtOp);
13797 } else if (LHSOpcode == ISD::FP_EXTEND && RHSOpcode == ISD::FP_EXTEND) {
13798 NewOpc = ISD::PARTIAL_REDUCE_FMLA;
13799 } else
13800 return SDValue();
13801 // For a 2-stage extend the signedness of both of the extends must match
13802 // If the mul has the same type, there is no outer extend, and thus we
13803 // can simply use the inner extends to pick the result node.
13804 // TODO: extend to handle nonneg zext as sext
13805 EVT AccElemVT = Acc.getValueType().getVectorElementType();
13806 if (Op1.getValueType().getVectorElementType() != AccElemVT &&
13807 NewOpc != N->getOpcode())
13808 return SDValue();
13809
13810 // Only perform these combines if the target supports folding
13811 // the extends into the operation.
13813 NewOpc, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
13814 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
13815 return SDValue();
13816
13817 ApplyPredicate(RHSExtOp, LHSExtOp);
13818 return GetMLA(NewOpc, Acc, LHSExtOp, RHSExtOp);
13819}
13820
13821// partial.reduce.*mla(acc, *ext(op), splat(1))
13822// -> partial.reduce.*mla(acc, op, splat(trunc(1)))
13823// partial.reduce.sumla(acc, sext(op), splat(1))
13824// -> partial.reduce.smla(acc, op, splat(trunc(1)))
13825//
13826// partial.reduce.*mla(acc, sel(p, *ext(op), splat(0)), splat(1))
13827// -> partial.reduce.*mla(acc, sel(p, op, splat(0)), splat(trunc(1)))
13828SDValue DAGCombiner::foldPartialReduceAdd(SDNode *N) {
13829 SDLoc DL(N);
13830 SDValue Tmp;
13831 SDValue Acc = N->getOperand(0);
13832 SDValue Op1 = N->getOperand(1);
13833 SDValue Op2 = N->getOperand(2);
13834
13836 return SDValue();
13837
13838 SDValue Pred;
13839 unsigned Op1Opcode = Op1.getOpcode();
13840 if (Op1Opcode == ISD::VSELECT && (isZeroOrZeroSplat(Op1->getOperand(2)) ||
13841 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
13842 Pred = Op1->getOperand(0);
13843 Op1 = Op1->getOperand(1);
13844 Op1Opcode = Op1->getOpcode();
13845 }
13846
13847 // Handle negation (sub-reduction).
13848 bool IsMLS = false;
13849 if (sd_match(Op1, m_AnyOf(m_Neg(m_Value(Tmp)), m_FNeg(m_Value(Tmp))))) {
13850 Op1 = Tmp;
13851 Op1Opcode = Op1.getOpcode();
13852 IsMLS = true;
13853 }
13854
13855 if (!ISD::isExtOpcode(Op1Opcode) && Op1Opcode != ISD::FP_EXTEND)
13856 return SDValue();
13857
13858 bool Op1IsSigned =
13859 Op1Opcode == ISD::SIGN_EXTEND || Op1Opcode == ISD::FP_EXTEND;
13860 bool NodeIsSigned = N->getOpcode() != ISD::PARTIAL_REDUCE_UMLA;
13861 EVT AccElemVT = Acc.getValueType().getVectorElementType();
13862 if (Op1IsSigned != NodeIsSigned &&
13863 Op1.getValueType().getVectorElementType() != AccElemVT)
13864 return SDValue();
13865
13866 unsigned NewOpcode = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
13868 : Op1IsSigned ? ISD::PARTIAL_REDUCE_SMLA
13870
13871 SDValue UnextOp1 = Op1.getOperand(0);
13872 EVT UnextOp1VT = UnextOp1.getValueType();
13873 auto *Context = DAG.getContext();
13875 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
13876 TLI.getTypeToTransformTo(*Context, UnextOp1VT)))
13877 return SDValue();
13878
13879 SDValue Constant = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
13880 ? DAG.getConstantFP(1, DL, UnextOp1VT)
13881 : DAG.getConstant(1, DL, UnextOp1VT);
13882
13883 if (Pred) {
13884 SDValue Zero = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
13885 ? DAG.getConstantFP(0, DL, UnextOp1VT)
13886 : DAG.getConstant(0, DL, UnextOp1VT);
13887 Constant = DAG.getSelect(DL, UnextOp1VT, Pred, Constant, Zero);
13888 }
13889 EVT AccVT = Acc.getValueType();
13890 return IsMLS ? DAG.getPartialReduceMLS(NewOpcode, DL, Acc, UnextOp1, Constant)
13891 : DAG.getNode(NewOpcode, DL, AccVT, Acc, UnextOp1, Constant);
13892}
13893
13894SDValue DAGCombiner::visitVP_STRIDED_LOAD(SDNode *N) {
13895 auto *SLD = cast<VPStridedLoadSDNode>(N);
13896 EVT EltVT = SLD->getValueType(0).getVectorElementType();
13897 // Combine strided loads with unit-stride to a regular VP load.
13898 if (auto *CStride = dyn_cast<ConstantSDNode>(SLD->getStride());
13899 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
13900 SDValue NewLd = DAG.getLoadVP(
13901 SLD->getAddressingMode(), SLD->getExtensionType(), SLD->getValueType(0),
13902 SDLoc(N), SLD->getChain(), SLD->getBasePtr(), SLD->getOffset(),
13903 SLD->getMask(), SLD->getVectorLength(), SLD->getMemoryVT(),
13904 SLD->getMemOperand(), SLD->isExpandingLoad());
13905 return CombineTo(N, NewLd, NewLd.getValue(1));
13906 }
13907 return SDValue();
13908}
13909
13910/// A vector select of 2 constant vectors can be simplified to math/logic to
13911/// avoid a variable select instruction and possibly avoid constant loads.
13912SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
13913 SDValue Cond = N->getOperand(0);
13914 SDValue N1 = N->getOperand(1);
13915 SDValue N2 = N->getOperand(2);
13916 EVT VT = N->getValueType(0);
13917 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
13921 return SDValue();
13922
13923 // Check if we can use the condition value to increment/decrement a single
13924 // constant value. This simplifies a select to an add and removes a constant
13925 // load/materialization from the general case.
13926 bool AllAddOne = true;
13927 bool AllSubOne = true;
13928 unsigned Elts = VT.getVectorNumElements();
13929 for (unsigned i = 0; i != Elts; ++i) {
13930 SDValue N1Elt = N1.getOperand(i);
13931 SDValue N2Elt = N2.getOperand(i);
13932 if (N1Elt.isUndef())
13933 continue;
13934 // N2 should not contain undef values since it will be reused in the fold.
13935 if (N2Elt.isUndef() || N1Elt.getValueType() != N2Elt.getValueType()) {
13936 AllAddOne = false;
13937 AllSubOne = false;
13938 break;
13939 }
13940
13941 const APInt &C1 = N1Elt->getAsAPIntVal();
13942 const APInt &C2 = N2Elt->getAsAPIntVal();
13943 if (C1 != C2 + 1)
13944 AllAddOne = false;
13945 if (C1 != C2 - 1)
13946 AllSubOne = false;
13947 }
13948
13949 // Further simplifications for the extra-special cases where the constants are
13950 // all 0 or all -1 should be implemented as folds of these patterns.
13951 SDLoc DL(N);
13952 if (AllAddOne || AllSubOne) {
13953 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
13954 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
13955 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13956 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
13957 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
13958 }
13959
13960 // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
13961 APInt Pow2C;
13962 if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
13963 isNullOrNullSplat(N2)) {
13964 SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
13965 SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
13966 return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
13967 }
13968
13970 return V;
13971
13972 // The general case for select-of-constants:
13973 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
13974 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
13975 // leave that to a machine-specific pass.
13976 return SDValue();
13977}
13978
13979SDValue DAGCombiner::visitVP_SELECT(SDNode *N) {
13980 SDValue N0 = N->getOperand(0);
13981 SDValue N1 = N->getOperand(1);
13982 SDValue N2 = N->getOperand(2);
13983 SDLoc DL(N);
13984
13985 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
13986 return V;
13987
13989 return V;
13990
13991 return SDValue();
13992}
13993
13995 SDValue FVal,
13996 const TargetLowering &TLI,
13997 SelectionDAG &DAG,
13998 const SDLoc &DL) {
13999 EVT VT = TVal.getValueType();
14000 if (!TLI.isTypeLegal(VT))
14001 return SDValue();
14002
14003 EVT CondVT = Cond.getValueType();
14004 assert(CondVT.isVector() && "Vector select expects a vector selector!");
14005
14006 bool IsTAllZero = ISD::isConstantSplatVectorAllZeros(TVal.getNode());
14007 bool IsTAllOne = ISD::isConstantSplatVectorAllOnes(TVal.getNode());
14008 bool IsFAllZero = ISD::isConstantSplatVectorAllZeros(FVal.getNode());
14009 bool IsFAllOne = ISD::isConstantSplatVectorAllOnes(FVal.getNode());
14010
14011 // no vselect(cond, 0/-1, X) or vselect(cond, X, 0/-1), return
14012 if (!IsTAllZero && !IsTAllOne && !IsFAllZero && !IsFAllOne)
14013 return SDValue();
14014
14015 // select Cond, 0, 0 → 0
14016 if (IsTAllZero && IsFAllZero) {
14017 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, VT)
14018 : DAG.getConstant(0, DL, VT);
14019 }
14020
14021 // check select(setgt lhs, -1), 1, -1 --> or (sra lhs, bitwidth - 1), 1
14022 APInt TValAPInt;
14023 if (Cond.getOpcode() == ISD::SETCC &&
14024 Cond.getOperand(2) == DAG.getCondCode(ISD::SETGT) &&
14025 Cond.getOperand(0).getValueType() == VT && VT.isSimple() &&
14026 ISD::isConstantSplatVector(TVal.getNode(), TValAPInt) &&
14027 TValAPInt.isOne() &&
14028 ISD::isConstantSplatVectorAllOnes(Cond.getOperand(1).getNode()) &&
14031 SDValue LHS = Cond.getOperand(0);
14032 SDValue ShiftC =
14034 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, ShiftC);
14035 return DAG.getNode(ISD::OR, DL, VT, Shift, TVal);
14036 }
14037
14038 // To use the condition operand as a bitwise mask, it must have elements that
14039 // are the same size as the select elements. i.e, the condition operand must
14040 // have already been promoted from the IR select condition type <N x i1>.
14041 // Don't check if the types themselves are equal because that excludes
14042 // vector floating-point selects.
14043 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
14044 return SDValue();
14045
14046 // Cond value must be 'sign splat' to be converted to a logical op.
14047 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
14048 return SDValue();
14049
14050 // Try inverting Cond and swapping T/F if it gives all-ones/all-zeros form
14051 if (!IsTAllOne && !IsFAllZero && Cond.hasOneUse() &&
14052 Cond.getOpcode() == ISD::SETCC &&
14053 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
14054 CondVT) {
14055 if (IsTAllZero || IsFAllOne) {
14056 SDValue CC = Cond.getOperand(2);
14058 cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
14059 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
14060 InverseCC);
14061 std::swap(TVal, FVal);
14062 std::swap(IsTAllOne, IsFAllOne);
14063 std::swap(IsTAllZero, IsFAllZero);
14064 }
14065 }
14066
14068 "Select condition no longer all-sign bits");
14069
14070 // select Cond, -1, 0 → bitcast Cond
14071 if (IsTAllOne && IsFAllZero)
14072 return DAG.getBitcast(VT, Cond);
14073
14074 // select Cond, -1, x → or Cond, x
14075 if (IsTAllOne) {
14076 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14077 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, X);
14078 return DAG.getBitcast(VT, Or);
14079 }
14080
14081 // select Cond, x, 0 → and Cond, x
14082 if (IsFAllZero) {
14083 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(TVal));
14084 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, X);
14085 return DAG.getBitcast(VT, And);
14086 }
14087
14088 // select Cond, 0, x -> and not(Cond), x
14089 if (IsTAllZero &&
14091 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14092 SDValue And =
14093 DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT), X);
14094 return DAG.getBitcast(VT, And);
14095 }
14096
14097 return SDValue();
14098}
14099
14100SDValue DAGCombiner::visitVSELECT(SDNode *N) {
14101 SDValue N0 = N->getOperand(0);
14102 SDValue N1 = N->getOperand(1);
14103 SDValue N2 = N->getOperand(2);
14104 EVT VT = N->getValueType(0);
14105 SDLoc DL(N);
14106
14107 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
14108 return V;
14109
14111 return V;
14112
14113 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
14114 if (!TLI.isTargetCanonicalSelect(N))
14115 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
14116 return DAG.getSelect(DL, VT, F, N2, N1, N->getFlags());
14117
14118 // select (sext m), (add X, C), X --> (add X, (and C, (sext m))))
14119 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N2 && N1->hasOneUse() &&
14122 TLI.getBooleanContents(N0.getValueType()) ==
14124 return DAG.getNode(
14125 ISD::ADD, DL, N1.getValueType(), N2,
14126 DAG.getNode(ISD::AND, DL, N0.getValueType(), N1.getOperand(1), N0));
14127 }
14128
14129 // Canonicalize integer abs.
14130 // vselect (setg[te] X, 0), X, -X ->
14131 // vselect (setgt X, -1), X, -X ->
14132 // vselect (setl[te] X, 0), -X, X ->
14133 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14134 if (N0.getOpcode() == ISD::SETCC) {
14135 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
14137 bool isAbs = false;
14138 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
14139
14140 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14141 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
14142 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
14144 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
14145 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
14147
14148 if (isAbs) {
14150 return DAG.getNode(ISD::ABS, DL, VT, LHS);
14151
14152 SDValue Shift = DAG.getNode(
14153 ISD::SRA, DL, VT, LHS,
14154 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, DL));
14155 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
14156 AddToWorklist(Shift.getNode());
14157 AddToWorklist(Add.getNode());
14158 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
14159 }
14160
14161 // vselect x, y (fcmp lt x, y) -> fminnum x, y
14162 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
14163 //
14164 // This is OK if we don't care about what happens if either operand is a
14165 // NaN.
14166 //
14167 if (N0.hasOneUse() &&
14168 isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, N->getFlags(), TLI)) {
14169 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC))
14170 return FMinMax;
14171 }
14172
14173 if (SDValue S = PerformMinMaxFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14174 return S;
14175 if (SDValue S = PerformUMinFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14176 return S;
14177
14178 // If this select has a condition (setcc) with narrower operands than the
14179 // select, try to widen the compare to match the select width.
14180 // TODO: This should be extended to handle any constant.
14181 // TODO: This could be extended to handle non-loading patterns, but that
14182 // requires thorough testing to avoid regressions.
14183 if (isNullOrNullSplat(RHS)) {
14184 EVT NarrowVT = LHS.getValueType();
14186 EVT SetCCVT = getSetCCResultType(LHS.getValueType());
14187 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
14188 unsigned WideWidth = WideVT.getScalarSizeInBits();
14189 bool IsSigned = isSignedIntSetCC(CC);
14190 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14191 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && SetCCWidth != 1 &&
14192 SetCCWidth < WideWidth &&
14193 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
14194 LoadSDNode *Ld = cast<LoadSDNode>(LHS);
14195
14196 if (TLI.isLoadLegalOrCustom(WideVT, NarrowVT, Ld->getAlign(),
14197 Ld->getAddressSpace(), LoadExtOpcode,
14198 false)) {
14199 // Both compare operands can be widened for free. The LHS can use an
14200 // extended load, and the RHS is a constant:
14201 // vselect (ext (setcc load(X), C)), N1, N2 -->
14202 // vselect (setcc extload(X), C'), N1, N2
14203 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14204 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
14205 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
14206 EVT WideSetCCVT = getSetCCResultType(WideVT);
14207 SDValue WideSetCC =
14208 DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
14209 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
14210 }
14211 }
14212 }
14213
14214 if (SDValue ABD = foldSelectToABD(LHS, RHS, N1, N2, CC, DL))
14215 return ABD;
14216
14217 // Match VSELECTs into add with unsigned saturation.
14218 if (hasOperation(ISD::UADDSAT, VT)) {
14219 // Check if one of the arms of the VSELECT is vector with all bits set.
14220 // If it's on the left side invert the predicate to simplify logic below.
14221 SDValue Other;
14222 ISD::CondCode SatCC = CC;
14224 Other = N2;
14225 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14226 } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) {
14227 Other = N1;
14228 }
14229
14230 if (Other && Other.getOpcode() == ISD::ADD) {
14231 SDValue CondLHS = LHS, CondRHS = RHS;
14232 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14233
14234 // Canonicalize condition operands.
14235 if (SatCC == ISD::SETUGE) {
14236 std::swap(CondLHS, CondRHS);
14237 SatCC = ISD::SETULE;
14238 }
14239
14240 // We can test against either of the addition operands.
14241 // x <= x+y ? x+y : ~0 --> uaddsat x, y
14242 // x+y >= x ? x+y : ~0 --> uaddsat x, y
14243 if (SatCC == ISD::SETULE && Other == CondRHS &&
14244 (OpLHS == CondLHS || OpRHS == CondLHS))
14245 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14246
14247 if (OpRHS.getOpcode() == CondRHS.getOpcode() &&
14248 (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14249 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) &&
14250 CondLHS == OpLHS) {
14251 // If the RHS is a constant we have to reverse the const
14252 // canonicalization.
14253 // x >= ~C ? x+C : ~0 --> uaddsat x, C
14254 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14255 return Cond->getAPIntValue() == ~Op->getAPIntValue();
14256 };
14257 if (SatCC == ISD::SETULE &&
14258 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
14259 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14260 }
14261 }
14262 }
14263
14264 // Match VSELECTs into sub with unsigned saturation.
14265 if (hasOperation(ISD::USUBSAT, VT)) {
14266 // Check if one of the arms of the VSELECT is a zero vector. If it's on
14267 // the left side invert the predicate to simplify logic below.
14268 SDValue Other;
14269 ISD::CondCode SatCC = CC;
14271 Other = N2;
14272 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14274 Other = N1;
14275 }
14276
14277 // zext(x) >= y ? trunc(zext(x) - y) : 0
14278 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14279 // zext(x) > y ? trunc(zext(x) - y) : 0
14280 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14281 if (Other && Other.getOpcode() == ISD::TRUNCATE &&
14282 Other.getOperand(0).getOpcode() == ISD::SUB &&
14283 (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT)) {
14284 SDValue OpLHS = Other.getOperand(0).getOperand(0);
14285 SDValue OpRHS = Other.getOperand(0).getOperand(1);
14286 if (LHS == OpLHS && RHS == OpRHS && LHS.getOpcode() == ISD::ZERO_EXTEND)
14287 if (SDValue R = getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS,
14288 DAG, DL))
14289 return R;
14290 }
14291
14292 if (Other && Other.getNumOperands() == 2) {
14293 SDValue CondRHS = RHS;
14294 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14295
14296 if (OpLHS == LHS) {
14297 // Look for a general sub with unsigned saturation first.
14298 // x >= y ? x-y : 0 --> usubsat x, y
14299 // x > y ? x-y : 0 --> usubsat x, y
14300 if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) &&
14301 Other.getOpcode() == ISD::SUB && OpRHS == CondRHS)
14302 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14303
14304 if (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14305 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14306 if (CondRHS.getOpcode() == ISD::BUILD_VECTOR ||
14307 CondRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14308 // If the RHS is a constant we have to reverse the const
14309 // canonicalization.
14310 // x > C-1 ? x+-C : 0 --> usubsat x, C
14311 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14312 return (!Op && !Cond) ||
14313 (Op && Cond &&
14314 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
14315 };
14316 if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD &&
14317 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
14318 /*AllowUndefs*/ true)) {
14319 OpRHS = DAG.getNegative(OpRHS, DL, VT);
14320 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14321 }
14322
14323 // Another special case: If C was a sign bit, the sub has been
14324 // canonicalized into a xor.
14325 // FIXME: Would it be better to use computeKnownBits to
14326 // determine whether it's safe to decanonicalize the xor?
14327 // x s< 0 ? x^C : 0 --> usubsat x, C
14328 APInt SplatValue;
14329 if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
14330 ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) &&
14332 SplatValue.isSignMask()) {
14333 // Note that we have to rebuild the RHS constant here to
14334 // ensure we don't rely on particular values of undef lanes.
14335 OpRHS = DAG.getConstant(SplatValue, DL, VT);
14336 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14337 }
14338 }
14339 }
14340 }
14341 }
14342 }
14343
14344 // (vselect (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
14345 // (vselect (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
14346 if (SDValue UMin = foldSelectToUMin(LHS, RHS, N1, N2, CC, DL))
14347 return UMin;
14348 }
14349
14350 if (SimplifySelectOps(N, N1, N2))
14351 return SDValue(N, 0); // Don't revisit N.
14352
14353 // Fold (vselect all_ones, N1, N2) -> N1
14355 return N1;
14356 // Fold (vselect all_zeros, N1, N2) -> N2
14358 return N2;
14359
14360 // The ConvertSelectToConcatVector function is assuming both the above
14361 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
14362 // and addressed.
14363 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14366 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
14367 return CV;
14368 }
14369
14370 if (SDValue V = foldVSelectOfConstants(N))
14371 return V;
14372
14373 if (hasOperation(ISD::SRA, VT))
14375 return V;
14376
14378 return SDValue(N, 0);
14379
14380 if (SDValue V = combineVSelectWithAllOnesOrZeros(N0, N1, N2, TLI, DAG, DL))
14381 return V;
14382
14383 return SDValue();
14384}
14385
14386SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
14387 SDValue N0 = N->getOperand(0);
14388 SDValue N1 = N->getOperand(1);
14389 SDValue N2 = N->getOperand(2);
14390 SDValue N3 = N->getOperand(3);
14391 SDValue N4 = N->getOperand(4);
14392 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
14393 SDLoc DL(N);
14394
14395 // fold select_cc lhs, rhs, x, x, cc -> x
14396 if (N2 == N3)
14397 return N2;
14398
14399 // select_cc bool, 0, x, y, seteq -> select bool, y, x
14400 if (CC == ISD::SETEQ && !LegalTypes && N0.getValueType() == MVT::i1 &&
14401 isNullConstant(N1))
14402 return DAG.getSelect(DL, N2.getValueType(), N0, N3, N2);
14403
14404 // Determine if the condition we're dealing with is constant
14405 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
14406 CC, DL, false)) {
14407 AddToWorklist(SCC.getNode());
14408
14409 // cond always true -> true val
14410 // cond always false -> false val
14411 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode()))
14412 return SCCC->isZero() ? N3 : N2;
14413
14414 // When the condition is UNDEF, just return the first operand. This is
14415 // coherent the DAG creation, no setcc node is created in this case
14416 if (SCC->isUndef())
14417 return N2;
14418
14419 // Fold to a simpler select_cc
14420 if (SCC.getOpcode() == ISD::SETCC) {
14421 return DAG.getNode(ISD::SELECT_CC, DL, N2.getValueType(),
14422 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
14423 SCC.getOperand(2), SCC->getFlags());
14424 }
14425 }
14426
14427 // If we can fold this based on the true/false value, do so.
14428 if (SimplifySelectOps(N, N2, N3))
14429 return SDValue(N, 0); // Don't revisit N.
14430
14431 // fold select_cc into other things, such as min/max/abs
14432 return SimplifySelectCC(DL, N0, N1, N2, N3, CC);
14433}
14434
14435SDValue DAGCombiner::visitSETCC(SDNode *N) {
14436 // setcc is very commonly used as an argument to brcond or cond_loop. This
14437 // pattern also lend itself to numerous combines and, as a result, it is
14438 // desired we keep the argument to a brcond as a setcc as much as possible.
14439 bool PreferSetCC =
14440 N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::BRCOND ||
14441 N->user_begin()->getOpcode() == ISD::COND_LOOP);
14442
14443 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
14444 EVT VT = N->getValueType(0);
14445 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
14446 SDLoc DL(N);
14447
14448 if (SDValue Combined = SimplifySetCC(VT, N0, N1, Cond, DL, !PreferSetCC)) {
14449 // If we prefer to have a setcc, and we don't, we'll try our best to
14450 // recreate one using rebuildSetCC.
14451 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
14452 SDValue NewSetCC = rebuildSetCC(Combined);
14453
14454 // We don't have anything interesting to combine to.
14455 if (NewSetCC.getNode() == N)
14456 return SDValue();
14457
14458 if (NewSetCC)
14459 return NewSetCC;
14460 }
14461 return Combined;
14462 }
14463
14464 // Optimize
14465 // 1) (icmp eq/ne (and X, C0), (shift X, C1))
14466 // or
14467 // 2) (icmp eq/ne X, (rotate X, C1))
14468 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
14469 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
14470 // Then:
14471 // If C1 is a power of 2, then the rotate and shift+and versions are
14472 // equivilent, so we can interchange them depending on target preference.
14473 // Otherwise, if we have the shift+and version we can interchange srl/shl
14474 // which inturn affects the constant C0. We can use this to get better
14475 // constants again determined by target preference.
14476 if (Cond == ISD::SETNE || Cond == ISD::SETEQ) {
14477 auto IsAndWithShift = [](SDValue A, SDValue B) {
14478 return A.getOpcode() == ISD::AND &&
14479 (B.getOpcode() == ISD::SRL || B.getOpcode() == ISD::SHL) &&
14480 A.getOperand(0) == B.getOperand(0);
14481 };
14482 auto IsRotateWithOp = [](SDValue A, SDValue B) {
14483 return (B.getOpcode() == ISD::ROTL || B.getOpcode() == ISD::ROTR) &&
14484 B.getOperand(0) == A;
14485 };
14486 SDValue AndOrOp = SDValue(), ShiftOrRotate = SDValue();
14487 bool IsRotate = false;
14488
14489 // Find either shift+and or rotate pattern.
14490 if (IsAndWithShift(N0, N1)) {
14491 AndOrOp = N0;
14492 ShiftOrRotate = N1;
14493 } else if (IsAndWithShift(N1, N0)) {
14494 AndOrOp = N1;
14495 ShiftOrRotate = N0;
14496 } else if (IsRotateWithOp(N0, N1)) {
14497 IsRotate = true;
14498 AndOrOp = N0;
14499 ShiftOrRotate = N1;
14500 } else if (IsRotateWithOp(N1, N0)) {
14501 IsRotate = true;
14502 AndOrOp = N1;
14503 ShiftOrRotate = N0;
14504 }
14505
14506 if (AndOrOp && ShiftOrRotate && ShiftOrRotate.hasOneUse() &&
14507 (IsRotate || AndOrOp.hasOneUse())) {
14508 EVT OpVT = N0.getValueType();
14509 // Get constant shift/rotate amount and possibly mask (if its shift+and
14510 // variant).
14511 auto GetAPIntValue = [](SDValue Op) -> std::optional<APInt> {
14512 ConstantSDNode *CNode = isConstOrConstSplat(Op, /*AllowUndefs*/ false,
14513 /*AllowTrunc*/ false);
14514 if (CNode == nullptr)
14515 return std::nullopt;
14516 return CNode->getAPIntValue();
14517 };
14518 std::optional<APInt> AndCMask =
14519 IsRotate ? std::nullopt : GetAPIntValue(AndOrOp.getOperand(1));
14520 std::optional<APInt> ShiftCAmt =
14521 GetAPIntValue(ShiftOrRotate.getOperand(1));
14522 unsigned NumBits = OpVT.getScalarSizeInBits();
14523
14524 // We found constants.
14525 if (ShiftCAmt && (IsRotate || AndCMask) && ShiftCAmt->ult(NumBits)) {
14526 unsigned ShiftOpc = ShiftOrRotate.getOpcode();
14527 // Check that the constants meet the constraints.
14528 bool CanTransform = IsRotate;
14529 if (!CanTransform) {
14530 // Check that mask and shift compliment eachother
14531 CanTransform = *ShiftCAmt == (~*AndCMask).popcount();
14532 // Check that we are comparing all bits
14533 CanTransform &= (*ShiftCAmt + AndCMask->popcount()) == NumBits;
14534 // Check that the and mask is correct for the shift
14535 CanTransform &=
14536 ShiftOpc == ISD::SHL ? (~*AndCMask).isMask() : AndCMask->isMask();
14537 }
14538
14539 // See if target prefers another shift/rotate opcode.
14540 unsigned NewShiftOpc = TLI.preferedOpcodeForCmpEqPiecesOfOperand(
14541 OpVT, ShiftOpc, ShiftCAmt->isPowerOf2(), *ShiftCAmt, AndCMask);
14542 // Transform is valid and we have a new preference.
14543 if (CanTransform && NewShiftOpc != ShiftOpc) {
14544 SDValue NewShiftOrRotate =
14545 DAG.getNode(NewShiftOpc, DL, OpVT, ShiftOrRotate.getOperand(0),
14546 ShiftOrRotate.getOperand(1));
14547 SDValue NewAndOrOp = SDValue();
14548
14549 if (NewShiftOpc == ISD::SHL || NewShiftOpc == ISD::SRL) {
14550 APInt NewMask =
14551 NewShiftOpc == ISD::SHL
14552 ? APInt::getHighBitsSet(NumBits,
14553 NumBits - ShiftCAmt->getZExtValue())
14554 : APInt::getLowBitsSet(NumBits,
14555 NumBits - ShiftCAmt->getZExtValue());
14556 NewAndOrOp =
14557 DAG.getNode(ISD::AND, DL, OpVT, ShiftOrRotate.getOperand(0),
14558 DAG.getConstant(NewMask, DL, OpVT));
14559 } else {
14560 NewAndOrOp = ShiftOrRotate.getOperand(0);
14561 }
14562
14563 return DAG.getSetCC(DL, VT, NewAndOrOp, NewShiftOrRotate, Cond);
14564 }
14565 }
14566 }
14567 }
14568 return SDValue();
14569}
14570
14571SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
14572 SDValue LHS = N->getOperand(0);
14573 SDValue RHS = N->getOperand(1);
14574 SDValue Carry = N->getOperand(2);
14575 SDValue Cond = N->getOperand(3);
14576
14577 // If Carry is false, fold to a regular SETCC.
14578 if (isNullConstant(Carry))
14579 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
14580
14581 return SDValue();
14582}
14583
14584/// Check if N satisfies:
14585/// N is used once.
14586/// N is a Load.
14587/// The load is compatible with ExtOpcode. It means
14588/// If load has explicit zero/sign extension, ExpOpcode must have the same
14589/// extension.
14590/// Otherwise returns true.
14591static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) {
14592 if (!N.hasOneUse())
14593 return false;
14594
14595 if (!isa<LoadSDNode>(N))
14596 return false;
14597
14598 LoadSDNode *Load = cast<LoadSDNode>(N);
14599 ISD::LoadExtType LoadExt = Load->getExtensionType();
14600 if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD)
14601 return true;
14602
14603 // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same
14604 // extension.
14605 if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) ||
14606 (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND))
14607 return false;
14608
14609 return true;
14610}
14611
14612/// Fold
14613/// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y)
14614/// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y)
14615/// (aext (select c, load x, load y)) -> (select c, extload x, extload y)
14616/// This function is called by the DAGCombiner when visiting sext/zext/aext
14617/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
14619 SelectionDAG &DAG, const SDLoc &DL,
14620 CombineLevel Level) {
14621 unsigned Opcode = N->getOpcode();
14622 SDValue N0 = N->getOperand(0);
14623 EVT VT = N->getValueType(0);
14624 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
14625 Opcode == ISD::ANY_EXTEND) &&
14626 "Expected EXTEND dag node in input!");
14627
14628 SDValue Cond, Op1, Op2;
14630 m_Value(Op2)))))
14631 return SDValue();
14632
14633 if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode))
14634 return SDValue();
14635
14636 auto ExtLoadOpcode = ISD::EXTLOAD;
14637 if (Opcode == ISD::SIGN_EXTEND)
14638 ExtLoadOpcode = ISD::SEXTLOAD;
14639 else if (Opcode == ISD::ZERO_EXTEND)
14640 ExtLoadOpcode = ISD::ZEXTLOAD;
14641
14642 // Illegal VSELECT may ISel fail if happen after legalization (DAG
14643 // Combine2), so we should conservatively check the OperationAction.
14644 LoadSDNode *Load1 = cast<LoadSDNode>(Op1);
14645 LoadSDNode *Load2 = cast<LoadSDNode>(Op2);
14646 if (!TLI.isLoadLegal(VT, Load1->getMemoryVT(), Load1->getAlign(),
14647 Load1->getAddressSpace(), ExtLoadOpcode, false) ||
14648 !TLI.isLoadLegal(VT, Load2->getMemoryVT(), Load2->getAlign(),
14649 Load2->getAddressSpace(), ExtLoadOpcode, false) ||
14650 (N0->getOpcode() == ISD::VSELECT && Level >= AfterLegalizeTypes &&
14652 return SDValue();
14653
14654 SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1);
14655 SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2);
14656 return DAG.getSelect(DL, VT, Cond, Ext1, Ext2);
14657}
14658
14659/// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
14660/// a build_vector of constants.
14661/// This function is called by the DAGCombiner when visiting sext/zext/aext
14662/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
14663/// Vector extends are not folded if operations are legal; this is to
14664/// avoid introducing illegal build_vector dag nodes.
14666 const TargetLowering &TLI,
14667 SelectionDAG &DAG, bool LegalTypes) {
14668 unsigned Opcode = N->getOpcode();
14669 SDValue N0 = N->getOperand(0);
14670 EVT VT = N->getValueType(0);
14671
14672 assert((ISD::isExtOpcode(Opcode) || ISD::isExtVecInRegOpcode(Opcode)) &&
14673 "Expected EXTEND dag node in input!");
14674
14675 // fold (sext c1) -> c1
14676 // fold (zext c1) -> c1
14677 // fold (aext c1) -> c1
14678 if (isa<ConstantSDNode>(N0))
14679 return DAG.getNode(Opcode, DL, VT, N0);
14680
14681 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
14682 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
14683 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
14684 if (N0->getOpcode() == ISD::SELECT) {
14685 SDValue Op1 = N0->getOperand(1);
14686 SDValue Op2 = N0->getOperand(2);
14687 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
14688 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
14689 // For any_extend, choose sign extension of the constants to allow a
14690 // possible further transform to sign_extend_inreg.i.e.
14691 //
14692 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
14693 // t2: i64 = any_extend t1
14694 // -->
14695 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
14696 // -->
14697 // t4: i64 = sign_extend_inreg t3
14698 unsigned FoldOpc = Opcode;
14699 if (FoldOpc == ISD::ANY_EXTEND)
14700 FoldOpc = ISD::SIGN_EXTEND;
14701 return DAG.getSelect(DL, VT, N0->getOperand(0),
14702 DAG.getNode(FoldOpc, DL, VT, Op1),
14703 DAG.getNode(FoldOpc, DL, VT, Op2));
14704 }
14705 }
14706
14707 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
14708 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
14709 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
14710 EVT SVT = VT.getScalarType();
14711 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
14713 return SDValue();
14714
14715 // We can fold this node into a build_vector.
14716 unsigned VTBits = SVT.getSizeInBits();
14717 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
14719 unsigned NumElts = VT.getVectorNumElements();
14720
14721 for (unsigned i = 0; i != NumElts; ++i) {
14722 SDValue Op = N0.getOperand(i);
14723 if (Op.isUndef()) {
14724 if (Opcode == ISD::ANY_EXTEND || Opcode == ISD::ANY_EXTEND_VECTOR_INREG)
14725 Elts.push_back(DAG.getUNDEF(SVT));
14726 else
14727 Elts.push_back(DAG.getConstant(0, DL, SVT));
14728 continue;
14729 }
14730
14731 SDLoc DL(Op);
14732 // Get the constant value and if needed trunc it to the size of the type.
14733 // Nodes like build_vector might have constants wider than the scalar type.
14734 APInt C = Op->getAsAPIntVal().zextOrTrunc(EVTBits);
14735 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
14736 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
14737 else
14738 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
14739 }
14740
14741 return DAG.getBuildVector(VT, DL, Elts);
14742}
14743
14744// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
14745// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
14746// transformation. Returns true if extension are possible and the above
14747// mentioned transformation is profitable.
14749 unsigned ExtOpc,
14750 SmallVectorImpl<SDNode *> &ExtendNodes,
14751 const TargetLowering &TLI) {
14752 bool HasCopyToRegUses = false;
14753 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
14754 for (SDUse &Use : N0->uses()) {
14755 SDNode *User = Use.getUser();
14756 if (User == N)
14757 continue;
14758 if (Use.getResNo() != N0.getResNo())
14759 continue;
14760 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
14761 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
14763 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
14764 // Sign bits will be lost after a zext.
14765 return false;
14766 bool Add = false;
14767 for (unsigned i = 0; i != 2; ++i) {
14768 SDValue UseOp = User->getOperand(i);
14769 if (UseOp == N0)
14770 continue;
14771 if (!isa<ConstantSDNode>(UseOp))
14772 return false;
14773 Add = true;
14774 }
14775 if (Add)
14776 ExtendNodes.push_back(User);
14777 continue;
14778 }
14779 // If truncates aren't free and there are users we can't
14780 // extend, it isn't worthwhile.
14781 if (!isTruncFree)
14782 return false;
14783 // Remember if this value is live-out.
14784 if (User->getOpcode() == ISD::CopyToReg)
14785 HasCopyToRegUses = true;
14786 }
14787
14788 if (HasCopyToRegUses) {
14789 bool BothLiveOut = false;
14790 for (SDUse &Use : N->uses()) {
14791 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
14792 BothLiveOut = true;
14793 break;
14794 }
14795 }
14796 if (BothLiveOut)
14797 // Both unextended and extended values are live out. There had better be
14798 // a good reason for the transformation.
14799 return !ExtendNodes.empty();
14800 }
14801 return true;
14802}
14803
14804void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
14805 SDValue OrigLoad, SDValue ExtLoad,
14806 ISD::NodeType ExtType) {
14807 // Extend SetCC uses if necessary.
14808 SDLoc DL(ExtLoad);
14809 for (SDNode *SetCC : SetCCs) {
14811
14812 for (unsigned j = 0; j != 2; ++j) {
14813 SDValue SOp = SetCC->getOperand(j);
14814 if (SOp == OrigLoad)
14815 Ops.push_back(ExtLoad);
14816 else
14817 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
14818 }
14819
14820 Ops.push_back(SetCC->getOperand(2));
14821 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
14822 }
14823}
14824
14825// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
14826SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
14827 SDValue N0 = N->getOperand(0);
14828 EVT DstVT = N->getValueType(0);
14829 EVT SrcVT = N0.getValueType();
14830
14831 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
14832 N->getOpcode() == ISD::ZERO_EXTEND) &&
14833 "Unexpected node type (not an extend)!");
14834
14835 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
14836 // For example, on a target with legal v4i32, but illegal v8i32, turn:
14837 // (v8i32 (sext (v8i16 (load x))))
14838 // into:
14839 // (v8i32 (concat_vectors (v4i32 (sextload x)),
14840 // (v4i32 (sextload (x + 16)))))
14841 // Where uses of the original load, i.e.:
14842 // (v8i16 (load x))
14843 // are replaced with:
14844 // (v8i16 (truncate
14845 // (v8i32 (concat_vectors (v4i32 (sextload x)),
14846 // (v4i32 (sextload (x + 16)))))))
14847 //
14848 // This combine is only applicable to illegal, but splittable, vectors.
14849 // All legal types, and illegal non-vector types, are handled elsewhere.
14850 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
14851 //
14852 if (N0->getOpcode() != ISD::LOAD)
14853 return SDValue();
14854
14855 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
14856
14857 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
14858 !N0.hasOneUse() || !LN0->isSimple() ||
14859 !DstVT.isVector() || !DstVT.isPow2VectorType() ||
14861 return SDValue();
14862
14864 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
14865 return SDValue();
14866
14867 ISD::LoadExtType ExtType =
14868 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14869
14870 // Try to split the vector types to get down to legal types.
14871 EVT SplitSrcVT = SrcVT;
14872 EVT SplitDstVT = DstVT;
14873 while (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
14874 LN0->getAddressSpace(), ExtType, false) &&
14875 SplitSrcVT.getVectorNumElements() > 1) {
14876 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
14877 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
14878 }
14879
14880 if (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
14881 LN0->getAddressSpace(), ExtType, false))
14882 return SDValue();
14883
14884 assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
14885
14886 SDLoc DL(N);
14887 const unsigned NumSplits =
14888 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
14889 const unsigned Stride = SplitSrcVT.getStoreSize();
14892
14893 SDValue BasePtr = LN0->getBasePtr();
14894 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
14895 const unsigned Offset = Idx * Stride;
14896
14898 DAG.getExtLoad(ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(),
14899 BasePtr, LN0->getPointerInfo().getWithOffset(Offset),
14900 SplitSrcVT, LN0->getBaseAlign(),
14901 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
14902
14903 BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::getFixed(Stride), DL);
14904
14905 Loads.push_back(SplitLoad.getValue(0));
14906 Chains.push_back(SplitLoad.getValue(1));
14907 }
14908
14909 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14910 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
14911
14912 // Simplify TF.
14913 AddToWorklist(NewChain.getNode());
14914
14915 CombineTo(N, NewValue);
14916
14917 // Replace uses of the original load (before extension)
14918 // with a truncate of the concatenated sextloaded vectors.
14919 SDValue Trunc =
14920 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
14921 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
14922 CombineTo(N0.getNode(), Trunc, NewChain);
14923 return SDValue(N, 0); // Return N so it doesn't get rechecked!
14924}
14925
14926// fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
14927// (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
14928SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
14929 assert(N->getOpcode() == ISD::ZERO_EXTEND);
14930 EVT VT = N->getValueType(0);
14931 EVT OrigVT = N->getOperand(0).getValueType();
14932 if (TLI.isZExtFree(OrigVT, VT))
14933 return SDValue();
14934
14935 // and/or/xor
14936 SDValue N0 = N->getOperand(0);
14937 if (!ISD::isBitwiseLogicOp(N0.getOpcode()) ||
14938 N0.getOperand(1).getOpcode() != ISD::Constant ||
14939 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
14940 return SDValue();
14941
14942 // shl/shr
14943 SDValue N1 = N0->getOperand(0);
14944 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
14945 N1.getOperand(1).getOpcode() != ISD::Constant ||
14946 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
14947 return SDValue();
14948
14949 // load
14950 if (!isa<LoadSDNode>(N1.getOperand(0)))
14951 return SDValue();
14952 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
14953 EVT MemVT = Load->getMemoryVT();
14954 if (!TLI.isLoadLegal(VT, MemVT, Load->getAlign(), Load->getAddressSpace(),
14955 ISD::ZEXTLOAD, false) ||
14956 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
14957 return SDValue();
14958
14959
14960 // If the shift op is SHL, the logic op must be AND, otherwise the result
14961 // will be wrong.
14962 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
14963 return SDValue();
14964
14965 if (!N0.hasOneUse() || !N1.hasOneUse())
14966 return SDValue();
14967
14969 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
14970 ISD::ZERO_EXTEND, SetCCs, TLI))
14971 return SDValue();
14972
14973 // Actually do the transformation.
14974 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
14975 Load->getChain(), Load->getBasePtr(),
14976 Load->getMemoryVT(), Load->getMemOperand());
14977
14978 SDLoc DL1(N1);
14979 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
14980 N1.getOperand(1));
14981
14982 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
14983 SDLoc DL0(N0);
14984 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
14985 DAG.getConstant(Mask, DL0, VT));
14986
14987 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
14988 CombineTo(N, And);
14989 if (SDValue(Load, 0).hasOneUse()) {
14990 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
14991 } else {
14992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
14993 Load->getValueType(0), ExtLoad);
14994 CombineTo(Load, Trunc, ExtLoad.getValue(1));
14995 }
14996
14997 // N0 is dead at this point.
14998 recursivelyDeleteUnusedNodes(N0.getNode());
14999
15000 return SDValue(N,0); // Return N so it doesn't get rechecked!
15001}
15002
15003/// If we're narrowing or widening the result of a vector select and the final
15004/// size is the same size as a setcc (compare) feeding the select, then try to
15005/// apply the cast operation to the select's operands because matching vector
15006/// sizes for a select condition and other operands should be more efficient.
15007SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
15008 unsigned CastOpcode = Cast->getOpcode();
15009 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
15010 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
15011 CastOpcode == ISD::FP_ROUND) &&
15012 "Unexpected opcode for vector select narrowing/widening");
15013
15014 // We only do this transform before legal ops because the pattern may be
15015 // obfuscated by target-specific operations after legalization. Do not create
15016 // an illegal select op, however, because that may be difficult to lower.
15017 EVT VT = Cast->getValueType(0);
15018 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
15019 return SDValue();
15020
15021 SDValue VSel = Cast->getOperand(0);
15022 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
15023 VSel.getOperand(0).getOpcode() != ISD::SETCC)
15024 return SDValue();
15025
15026 // Does the setcc have the same vector size as the casted select?
15027 SDValue SetCC = VSel.getOperand(0);
15028 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
15029 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
15030 return SDValue();
15031
15032 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
15033 SDValue A = VSel.getOperand(1);
15034 SDValue B = VSel.getOperand(2);
15035 SDValue CastA, CastB;
15036 SDLoc DL(Cast);
15037 if (CastOpcode == ISD::FP_ROUND) {
15038 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
15039 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
15040 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
15041 } else {
15042 CastA = DAG.getNode(CastOpcode, DL, VT, A);
15043 CastB = DAG.getNode(CastOpcode, DL, VT, B);
15044 }
15045 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
15046}
15047
15048// fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15049// fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15051 const TargetLowering &TLI, EVT VT,
15052 bool LegalOperations, SDNode *N,
15053 SDValue N0, ISD::LoadExtType ExtLoadType) {
15054 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15055 auto *OldExtLoad = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15056 if (!OldExtLoad)
15057 return SDValue();
15058
15059 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD)
15060 ? ISD::isSEXTLoad(OldExtLoad)
15061 : ISD::isZEXTLoad(OldExtLoad);
15062 if ((!isAExtLoad && !ISD::isEXTLoad(OldExtLoad)) ||
15063 !ISD::isUNINDEXEDLoad(OldExtLoad) || !OldExtLoad->hasNUsesOfValue(1, 0))
15064 return SDValue();
15065
15066 EVT MemVT = OldExtLoad->getMemoryVT();
15067 if ((LegalOperations || !OldExtLoad->isSimple() || VT.isVector()) &&
15068 !TLI.isLoadLegal(VT, MemVT, OldExtLoad->getAlign(),
15069 OldExtLoad->getAddressSpace(), ExtLoadType, false))
15070 return SDValue();
15071
15072 SDLoc DL(OldExtLoad);
15073 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, DL, VT, OldExtLoad->getChain(),
15074 OldExtLoad->getBasePtr(), MemVT,
15075 OldExtLoad->getMemOperand());
15076 SDValue Res = ExtLoad;
15077 if (Frozen) {
15078 Res = DAG.getFreeze(ExtLoad);
15079 Res = DAG.getNode(
15080 ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext : ISD::AssertZext, DL,
15081 Res.getValueType(), Res,
15082 DAG.getValueType(OldExtLoad->getValueType(0).getScalarType()));
15083 }
15084 Combiner.CombineTo(N, Res);
15085 DAG.ReplaceAllUsesOfValueWith(SDValue(OldExtLoad, 1), ExtLoad.getValue(1));
15086 if (N0->use_empty())
15087 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15088 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15089}
15090
15091// fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15092// Only generate vector extloads when 1) they're legal, and 2) they are
15093// deemed desirable by the target. NonNegZExt can be set to true if a zero
15094// extend has the nonneg flag to allow use of sextload if profitable.
15096 const TargetLowering &TLI, EVT VT,
15097 bool LegalOperations, SDNode *N, SDValue N0,
15098 ISD::LoadExtType ExtLoadType,
15099 ISD::NodeType ExtOpc,
15100 bool NonNegZExt = false) {
15101
15102 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15103 SDValue Freeze = Frozen ? N0 : SDValue();
15104 auto *Load = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15105 // TODO: Support multiple uses of the load when frozen.
15106 if (!Load || !ISD::isNON_EXTLoad(Load) || !ISD::isUNINDEXEDLoad(Load) ||
15107 (Frozen && !Load->hasNUsesOfValue(1, 0)))
15108 return {};
15109
15110 // If this is zext nneg, see if it would make sense to treat it as a sext.
15111 if (NonNegZExt) {
15112 assert(ExtLoadType == ISD::ZEXTLOAD && ExtOpc == ISD::ZERO_EXTEND &&
15113 "Unexpected load type or opcode");
15114 for (SDNode *User : Load->users()) {
15115 if (User->getOpcode() == ISD::SETCC) {
15117 if (ISD::isSignedIntSetCC(CC)) {
15118 ExtLoadType = ISD::SEXTLOAD;
15119 ExtOpc = ISD::SIGN_EXTEND;
15120 break;
15121 }
15122 }
15123 }
15124 }
15125
15126 // TODO: isFixedLengthVector() should be removed and any negative effects on
15127 // code generation being the result of that target's implementation of
15128 // isVectorLoadExtDesirable().
15129 if ((LegalOperations || VT.isFixedLengthVector() || !Load->isSimple()) &&
15130 !TLI.isLoadLegal(VT, Load->getValueType(0), Load->getAlign(),
15131 Load->getAddressSpace(), ExtLoadType, false))
15132 return {};
15133
15134 bool DoXform = true;
15136 if (!N0->hasOneUse())
15137 DoXform = ExtendUsesToFormExtLoad(VT, N, Frozen ? Freeze : SDValue(Load, 0),
15138 ExtOpc, SetCCs, TLI);
15139 if (VT.isVector())
15140 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
15141 if (!DoXform)
15142 return {};
15143
15144 SDLoc DL(Load);
15145
15146 auto SalvageDbgValue = [&](SDDbgValue *Dbg, SDValue Old, SDValue New,
15147 unsigned OldBits, unsigned NewBits,
15148 bool IsSigned) {
15149 SmallVector<SDDbgOperand> Locs = Dbg->copyLocationOps();
15150 bool Changed = false;
15151
15152 bool IsVariadic = Dbg->isVariadic();
15153 SmallVector<unsigned, 2> AffectedArgs;
15154
15155 for (unsigned I = 0, E = Locs.size(); I != E; ++I) {
15156 SDDbgOperand &Op = Locs[I];
15157 if (Op.getKind() != SDDbgOperand::SDNODE)
15158 continue;
15159
15160 if (Op.getSDNode() == Old.getNode() && Op.getResNo() == Old.getResNo()) {
15161 Op = SDDbgOperand::fromNode(New.getNode(), New.getResNo());
15162 Changed = true;
15163
15164 if (IsVariadic)
15165 AffectedArgs.push_back(I);
15166 }
15167 }
15168
15169 if (!Changed)
15170 return;
15171
15172 const DIExpression *OldExpr = Dbg->getExpression();
15173 const DIExpression *NewExpr = nullptr;
15174
15175 if (!IsVariadic) {
15176 // Do not introduce DW_OP_LLVM_arg into ordinary single-location
15177 // DBG_VALUEs.
15178 NewExpr = DIExpression::appendExt(OldExpr, NewBits, OldBits, IsSigned);
15179 } else {
15180 auto ExtOps = DIExpression::getExtOps(NewBits, OldBits, IsSigned);
15181
15183
15184 for (unsigned ArgNo : AffectedArgs)
15186 /*StackValue=*/false);
15187 }
15188
15189 SDDbgValue *NewDV = DAG.getDbgValueList(
15190 Dbg->getVariable(), const_cast<DIExpression *>(NewExpr), Locs,
15191 Dbg->getAdditionalDependencies(), Dbg->isIndirect(), Dbg->getDebugLoc(),
15192 Dbg->getOrder(), Dbg->isVariadic());
15193
15194 Dbg->setIsInvalidated();
15195 Dbg->setIsEmitted();
15196 DAG.AddDbgValue(NewDV, /*isParameter=*/false);
15197 };
15198
15199 // Because we are replacing a load and a s|z ext with a load-s|z ext
15200 // instruction, the dbg_value attached to the load will be of a smaller bit
15201 // width, and we have to add a DW_OP_LLVM_convert expression to get the
15202 // correct size.
15203 auto SalvageToOldLoadSize = [&](SDValue Old, SDValue New, bool IsSigned) {
15205 DAG.GetDbgValues(Old.getNode()).begin(),
15206 DAG.GetDbgValues(Old.getNode()).end());
15207
15208 unsigned VarBitsOld = Old.getValueSizeInBits();
15209 unsigned VarBitsNew = New.getValueSizeInBits();
15210
15211 for (SDDbgValue *Dbg : DbgVals) {
15212 if (Dbg->isInvalidated())
15213 continue;
15214
15215 SalvageDbgValue(Dbg, Old, New, VarBitsOld, VarBitsNew, IsSigned);
15216 }
15217 };
15218
15219 SDValue ExtLoad =
15220 DAG.getExtLoad(ExtLoadType, DL, VT, Load->getChain(), Load->getBasePtr(),
15221 Load->getValueType(0), Load->getMemOperand());
15222 SDValue Res = ExtLoad;
15223 if (Frozen) {
15224 Res = DAG.getFreeze(ExtLoad);
15225 Res = DAG.getNode(ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext
15227 DL, Res.getValueType(), Res,
15228 DAG.getValueType(Load->getValueType(0).getScalarType()));
15229 }
15230 Combiner.ExtendSetCCUses(SetCCs, N0, Res, ExtOpc);
15231 // If the load value is used only by N, replace it via CombineTo N.
15232 bool NoReplaceTrunc = N0.hasOneUse();
15233 if (N->getHasDebugValue()) {
15234 SDValue OldExtValue(N, 0);
15235 DAG.transferDbgValues(OldExtValue, ExtLoad);
15236 }
15237 if (NoReplaceTrunc) {
15238 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
15239 if (Load->getHasDebugValue()) {
15240 SDValue OldLoadVal(Load, 0);
15241 SalvageToOldLoadSize(OldLoadVal, ExtLoad, IsSigned);
15242 }
15243 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15244 Combiner.CombineTo(N, Res);
15245 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15246 } else {
15247 Combiner.CombineTo(N, Res);
15248 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Load->getValueType(0), Res);
15249 if (Frozen) {
15250 Combiner.CombineTo(Freeze.getNode(), Trunc);
15251 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15252 } else {
15253 Combiner.CombineTo(Load, Trunc, ExtLoad.getValue(1));
15254 }
15255 }
15256 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15257}
15258
15259static SDValue
15261 bool LegalOperations, SDNode *N, SDValue N0,
15262 ISD::LoadExtType ExtLoadType, ISD::NodeType ExtOpc) {
15263 if (!N0.hasOneUse())
15264 return SDValue();
15265
15267 if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
15268 return SDValue();
15269
15270 if ((LegalOperations || !cast<MaskedLoadSDNode>(N0)->isSimple()) &&
15271 !TLI.isLoadLegalOrCustom(VT, Ld->getValueType(0), Ld->getAlign(),
15272 Ld->getAddressSpace(), ExtLoadType, false))
15273 return SDValue();
15274
15275 if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
15276 return SDValue();
15277
15278 SDLoc dl(Ld);
15279 SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
15280 SDValue NewLoad = DAG.getMaskedLoad(
15281 VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
15282 PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
15283 ExtLoadType, Ld->isExpandingLoad());
15284 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
15285 return NewLoad;
15286}
15287
15288// fold ([s|z]ext (atomic_load)) -> ([s|z]ext (truncate ([s|z]ext atomic_load)))
15290 const TargetLowering &TLI, EVT VT,
15291 SDValue N0,
15292 ISD::LoadExtType ExtLoadType) {
15293 auto *ALoad = dyn_cast<AtomicSDNode>(N0);
15294 if (!ALoad || ALoad->getOpcode() != ISD::ATOMIC_LOAD)
15295 return {};
15296 EVT MemoryVT = ALoad->getMemoryVT();
15297 if (!TLI.isLoadLegal(VT, MemoryVT, ALoad->getAlign(),
15298 ALoad->getAddressSpace(), ExtLoadType, true))
15299 return {};
15300 // Can't fold into ALoad if it is already extending differently.
15301 ISD::LoadExtType ALoadExtTy = ALoad->getExtensionType();
15302 if ((ALoadExtTy == ISD::ZEXTLOAD && ExtLoadType == ISD::SEXTLOAD) ||
15303 (ALoadExtTy == ISD::SEXTLOAD && ExtLoadType == ISD::ZEXTLOAD))
15304 return {};
15305
15306 EVT OrigVT = ALoad->getValueType(0);
15307 assert(OrigVT.getSizeInBits() < VT.getSizeInBits() && "VT should be wider.");
15308 auto *NewALoad = cast<AtomicSDNode>(DAG.getAtomicLoad(
15309 ExtLoadType, SDLoc(ALoad), MemoryVT, VT, ALoad->getChain(),
15310 ALoad->getBasePtr(), ALoad->getMemOperand()));
15312 SDValue(ALoad, 0),
15313 DAG.getNode(ISD::TRUNCATE, SDLoc(ALoad), OrigVT, SDValue(NewALoad, 0)));
15314 // Update the chain uses.
15315 DAG.ReplaceAllUsesOfValueWith(SDValue(ALoad, 1), SDValue(NewALoad, 1));
15316 return SDValue(NewALoad, 0);
15317}
15318
15320 bool LegalOperations) {
15321 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
15322 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
15323
15324 SDValue SetCC = N->getOperand(0);
15325 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
15326 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
15327 return SDValue();
15328
15329 SDValue X = SetCC.getOperand(0);
15330 SDValue Ones = SetCC.getOperand(1);
15331 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
15332 EVT VT = N->getValueType(0);
15333 EVT XVT = X.getValueType();
15334 // setge X, C is canonicalized to setgt, so we do not need to match that
15335 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
15336 // not require the 'not' op.
15337 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
15338 // Invert and smear/shift the sign bit:
15339 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
15340 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
15341 SDLoc DL(N);
15342 unsigned ShCt = VT.getSizeInBits() - 1;
15343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15344 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
15345 SDValue NotX = DAG.getNOT(DL, X, VT);
15346 SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
15347 auto ShiftOpcode =
15348 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
15349 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
15350 }
15351 }
15352 return SDValue();
15353}
15354
15355SDValue DAGCombiner::foldSextSetcc(SDNode *N) {
15356 SDValue N0 = N->getOperand(0);
15357 if (N0.getOpcode() != ISD::SETCC)
15358 return SDValue();
15359
15360 SDValue N00 = N0.getOperand(0);
15361 SDValue N01 = N0.getOperand(1);
15363 EVT VT = N->getValueType(0);
15364 EVT N00VT = N00.getValueType();
15365 SDLoc DL(N);
15366
15367 // Propagate fast-math-flags.
15368 SDNodeFlags Flags = N0->getFlags();
15369
15370 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
15371 // the same size as the compared operands. Try to optimize sext(setcc())
15372 // if this is the case.
15373 if (VT.isVector() && !LegalOperations &&
15374 TLI.getBooleanContents(N00VT) ==
15376 EVT SVT = getSetCCResultType(N00VT);
15377
15378 // If we already have the desired type, don't change it.
15379 if (SVT != N0.getValueType()) {
15380 // We know that the # elements of the results is the same as the
15381 // # elements of the compare (and the # elements of the compare result
15382 // for that matter). Check to see that they are the same size. If so,
15383 // we know that the element size of the sext'd result matches the
15384 // element size of the compare operands.
15385 if (VT.getSizeInBits() == SVT.getSizeInBits())
15386 return DAG.getSetCC(DL, VT, N00, N01, CC, /*Chain=*/{},
15387 /*Signaling=*/false, Flags);
15388
15389 // If the desired elements are smaller or larger than the source
15390 // elements, we can use a matching integer vector type and then
15391 // truncate/sign extend.
15392 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
15393 if (SVT == MatchingVecType) {
15394 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC,
15395 /*Chain=*/{}, /*Signaling=*/false, Flags);
15396 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
15397 }
15398 }
15399
15400 // Try to eliminate the sext of a setcc by zexting the compare operands.
15401 if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) &&
15403 bool IsSignedCmp = ISD::isSignedIntSetCC(CC);
15404 unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15405 unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15406
15407 // We have an unsupported narrow vector compare op that would be legal
15408 // if extended to the destination type. See if the compare operands
15409 // can be freely extended to the destination type.
15410 auto IsFreeToExtend = [&](SDValue V) {
15411 if (isConstantOrConstantVector(V, /*NoOpaques*/ true))
15412 return true;
15413 // Match a simple, non-extended load that can be converted to a
15414 // legal {z/s}ext-load.
15415 // TODO: Allow widening of an existing {z/s}ext-load?
15416 if (!(ISD::isNON_EXTLoad(V.getNode()) &&
15417 ISD::isUNINDEXEDLoad(V.getNode())))
15418 return false;
15419
15420 LoadSDNode *Ld = cast<LoadSDNode>(V.getNode());
15421
15422 if (!Ld->isSimple() ||
15423 !TLI.isLoadLegal(VT, V.getValueType(), Ld->getAlign(),
15424 Ld->getAddressSpace(), LoadOpcode, false))
15425 return false;
15426
15427 // Non-chain users of this value must either be the setcc in this
15428 // sequence or extends that can be folded into the new {z/s}ext-load.
15429 for (SDUse &Use : V->uses()) {
15430 // Skip uses of the chain and the setcc.
15431 SDNode *User = Use.getUser();
15432 if (Use.getResNo() != 0 || User == N0.getNode())
15433 continue;
15434 // Extra users must have exactly the same cast we are about to create.
15435 // TODO: This restriction could be eased if ExtendUsesToFormExtLoad()
15436 // is enhanced similarly.
15437 if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT)
15438 return false;
15439 }
15440 return true;
15441 };
15442
15443 if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) {
15444 SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00);
15445 SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01);
15446 return DAG.getSetCC(DL, VT, Ext0, Ext1, CC, /*Chain=*/{},
15447 /*Signaling=*/false, Flags);
15448 }
15449 }
15450 }
15451
15452 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
15453 // Here, T can be 1 or -1, depending on the type of the setcc and
15454 // getBooleanContents().
15455 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
15456
15457 // To determine the "true" side of the select, we need to know the high bit
15458 // of the value returned by the setcc if it evaluates to true.
15459 // If the type of the setcc is i1, then the true case of the select is just
15460 // sext(i1 1), that is, -1.
15461 // If the type of the setcc is larger (say, i8) then the value of the high
15462 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
15463 // of the appropriate width.
15464 SDValue ExtTrueVal = (SetCCWidth == 1)
15465 ? DAG.getAllOnesConstant(DL, VT)
15466 : DAG.getBoolConstant(true, DL, VT, N00VT);
15467 SDValue Zero = DAG.getConstant(0, DL, VT);
15468 if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
15469 return SCC;
15470
15471 if (!VT.isVector() && !shouldConvertSelectOfConstantsToMath(N0, VT, TLI)) {
15472 EVT SetCCVT = getSetCCResultType(N00VT);
15473 // Don't do this transform for i1 because there's a select transform
15474 // that would reverse it.
15475 // TODO: We should not do this transform at all without a target hook
15476 // because a sext is likely cheaper than a select?
15477 if (SetCCVT.getScalarSizeInBits() != 1 &&
15478 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
15479 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC, /*Chain=*/{},
15480 /*Signaling=*/false, Flags);
15481 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero, Flags);
15482 }
15483 }
15484
15485 return SDValue();
15486}
15487
15488SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
15489 SDValue N0 = N->getOperand(0);
15490 EVT VT = N->getValueType(0);
15491 SDLoc DL(N);
15492
15493 if (VT.isVector())
15494 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
15495 return FoldedVOp;
15496
15497 // sext(undef) = 0 because the top bit will all be the same.
15498 if (N0.isUndef())
15499 return DAG.getConstant(0, DL, VT);
15500
15501 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
15502 return Res;
15503
15504 // fold (sext (sext x)) -> (sext x)
15505 // fold (sext (aext x)) -> (sext x)
15506 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
15507 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
15508
15509 // fold (sext (aext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
15510 // fold (sext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
15513 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT,
15514 N0.getOperand(0));
15515
15516 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
15517 SDValue N00 = N0.getOperand(0);
15518 EVT ExtVT = cast<VTSDNode>(N0->getOperand(1))->getVT();
15519 if (N00.getOpcode() == ISD::TRUNCATE || TLI.isTruncateFree(N00, ExtVT)) {
15520 // fold (sext (sext_inreg x)) -> (sext (trunc x))
15521 if ((!LegalTypes || TLI.isTypeLegal(ExtVT))) {
15522 SDValue T = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N00);
15523 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, T);
15524 }
15525
15526 // If the trunc wasn't legal, try to fold to (sext_inreg (anyext x))
15527 if (!LegalTypes || TLI.isTypeLegal(VT)) {
15528 SDValue ExtSrc = DAG.getAnyExtOrTrunc(N00, DL, VT);
15529 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ExtSrc,
15530 N0->getOperand(1));
15531 }
15532 }
15533 }
15534
15535 if (N0.getOpcode() == ISD::TRUNCATE) {
15536 // fold (sext (truncate (load x))) -> (sext (smaller load x))
15537 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
15538 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
15539 SDNode *oye = N0.getOperand(0).getNode();
15540 if (NarrowLoad.getNode() != N0.getNode()) {
15541 CombineTo(N0.getNode(), NarrowLoad);
15542 // CombineTo deleted the truncate, if needed, but not what's under it.
15543 AddToWorklist(oye);
15544 }
15545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15546 }
15547
15548 // See if the value being truncated is already sign extended. If so, just
15549 // eliminate the trunc/sext pair.
15550 SDValue Op = N0.getOperand(0);
15551 unsigned OpBits = Op.getScalarValueSizeInBits();
15552 unsigned MidBits = N0.getScalarValueSizeInBits();
15553 unsigned DestBits = VT.getScalarSizeInBits();
15554
15555 if (N0->getFlags().hasNoSignedWrap() ||
15556 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
15557 if (OpBits == DestBits) {
15558 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
15559 // bits, it is already ready.
15560 return Op;
15561 }
15562
15563 if (OpBits < DestBits) {
15564 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
15565 // bits, just sext from i32.
15566 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
15567 }
15568
15569 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
15570 // bits, just truncate to i32.
15571 SDNodeFlags Flags;
15572 Flags.setNoSignedWrap(true);
15573 Flags.setNoUnsignedWrap(N0->getFlags().hasNoUnsignedWrap());
15574 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
15575 }
15576
15577 // fold (sext (truncate x)) -> (sextinreg x).
15578 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
15579 N0.getValueType())) {
15580 if (OpBits < DestBits)
15581 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
15582 else if (OpBits > DestBits)
15583 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
15584 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
15585 DAG.getValueType(N0.getValueType()));
15586 }
15587 }
15588
15589 // Try to simplify (sext (load x)).
15590 if (SDValue foldedExt =
15591 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
15593 return foldedExt;
15594
15595 if (SDValue foldedExt =
15596 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
15598 return foldedExt;
15599
15600 // fold (sext (load x)) to multiple smaller sextloads.
15601 // Only on illegal but splittable vectors.
15602 if (SDValue ExtLoad = CombineExtLoad(N))
15603 return ExtLoad;
15604
15605 // Try to simplify (sext (sextload x)).
15606 if (SDValue foldedExt = tryToFoldExtOfExtload(
15607 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
15608 return foldedExt;
15609
15610 // Try to simplify (sext (atomic_load x)).
15611 if (SDValue foldedExt =
15612 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::SEXTLOAD))
15613 return foldedExt;
15614
15615 // fold (sext (and/or/xor (load x), cst)) ->
15616 // (and/or/xor (sextload x), (sext cst))
15617 if (ISD::isBitwiseLogicOp(N0.getOpcode()) &&
15618 isa<LoadSDNode>(N0.getOperand(0)) &&
15619 N0.getOperand(1).getOpcode() == ISD::Constant &&
15620 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
15621 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
15622 EVT MemVT = LN00->getMemoryVT();
15623 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
15624 ISD::SEXTLOAD, false) &&
15625 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
15627 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
15628 ISD::SIGN_EXTEND, SetCCs, TLI);
15629 if (DoXform) {
15630 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
15631 LN00->getChain(), LN00->getBasePtr(),
15632 LN00->getMemoryVT(),
15633 LN00->getMemOperand());
15634 APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
15635 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
15636 ExtLoad, DAG.getConstant(Mask, DL, VT));
15637 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
15638 bool NoReplaceTruncAnd = !N0.hasOneUse();
15639 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
15640 CombineTo(N, And);
15641 // If N0 has multiple uses, change other uses as well.
15642 if (NoReplaceTruncAnd) {
15643 SDValue TruncAnd =
15645 CombineTo(N0.getNode(), TruncAnd);
15646 }
15647 if (NoReplaceTrunc) {
15648 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
15649 } else {
15650 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
15651 LN00->getValueType(0), ExtLoad);
15652 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
15653 }
15654 return SDValue(N,0); // Return N so it doesn't get rechecked!
15655 }
15656 }
15657 }
15658
15659 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
15660 return V;
15661
15662 if (SDValue V = foldSextSetcc(N))
15663 return V;
15664
15665 // fold (sext x) -> (zext x) if the sign bit is known zero.
15666 if (!TLI.isSExtCheaperThanZExt(N0.getValueType(), VT) &&
15667 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
15668 DAG.SignBitIsZero(N0))
15669 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0, SDNodeFlags::NonNeg);
15670
15671 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
15672 return NewVSel;
15673
15674 // Eliminate this sign extend by doing a negation in the destination type:
15675 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
15676 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
15680 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
15681 return DAG.getNegative(Zext, DL, VT);
15682 }
15683 // Eliminate this sign extend by doing a decrement in the destination type:
15684 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
15685 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
15689 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
15690 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
15691 }
15692
15693 // fold sext (not i1 X) -> add (zext i1 X), -1
15694 // TODO: This could be extended to handle bool vectors.
15695 if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() &&
15696 (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) &&
15697 TLI.isOperationLegal(ISD::ADD, VT)))) {
15698 // If we can eliminate the 'not', the sext form should be better
15699 if (SDValue NewXor = visitXOR(N0.getNode())) {
15700 // Returning N0 is a form of in-visit replacement that may have
15701 // invalidated N0.
15702 if (NewXor.getNode() == N0.getNode()) {
15703 // Return SDValue here as the xor should have already been replaced in
15704 // this sext.
15705 return SDValue();
15706 }
15707
15708 // Return a new sext with the new xor.
15709 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor);
15710 }
15711
15712 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
15713 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
15714 }
15715
15716 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
15717 return Res;
15718
15719 return SDValue();
15720}
15721
15722/// Given an extending node with a pop-count operand, if the target does not
15723/// support a pop-count in the narrow source type but does support it in the
15724/// destination type, widen the pop-count to the destination type.
15725static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG, const SDLoc &DL) {
15726 assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
15727 Extend->getOpcode() == ISD::ANY_EXTEND) &&
15728 "Expected extend op");
15729
15730 SDValue CtPop = Extend->getOperand(0);
15731 if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
15732 return SDValue();
15733
15734 EVT VT = Extend->getValueType(0);
15735 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15738 return SDValue();
15739
15740 // zext (ctpop X) --> ctpop (zext X)
15741 SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
15742 return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
15743}
15744
15745// If we have (zext (abs X)) where X is a type that will be promoted by type
15746// legalization, convert to (abs_min_poison (sext X)). But do not extend
15747// past a legal type.
15748static SDValue widenAbs(SDNode *Extend, SelectionDAG &DAG) {
15749 assert(Extend->getOpcode() == ISD::ZERO_EXTEND && "Expected zero extend.");
15750
15751 EVT VT = Extend->getValueType(0);
15752 if (VT.isVector())
15753 return SDValue();
15754
15755 SDValue Abs = Extend->getOperand(0);
15756 if (!ISD::isAbsOpcode(Abs.getOpcode()) || !Abs.hasOneUse())
15757 return SDValue();
15758
15759 EVT AbsVT = Abs.getValueType();
15760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15761 if (TLI.getTypeAction(*DAG.getContext(), AbsVT) !=
15763 return SDValue();
15764
15765 EVT LegalVT = TLI.getTypeToTransformTo(*DAG.getContext(), AbsVT);
15766
15767 SDValue SExt =
15768 DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Abs), LegalVT, Abs.getOperand(0));
15769 SDValue NewAbs = DAG.getNode(ISD::ABS_MIN_POISON, SDLoc(Abs), LegalVT, SExt);
15770 return DAG.getZExtOrTrunc(NewAbs, SDLoc(Extend), VT);
15771}
15772
15773SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
15774 SDValue N0 = N->getOperand(0);
15775 EVT VT = N->getValueType(0);
15776 SDLoc DL(N);
15777
15778 if (VT.isVector())
15779 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
15780 return FoldedVOp;
15781
15782 // zext(undef) = 0
15783 if (N0.isUndef())
15784 return DAG.getConstant(0, DL, VT);
15785
15786 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
15787 return Res;
15788
15789 // fold (zext (zext x)) -> (zext x)
15790 // fold (zext (aext x)) -> (zext x)
15791 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
15792 SDNodeFlags Flags;
15793 if (N0.getOpcode() == ISD::ZERO_EXTEND)
15794 Flags.setNonNeg(N0->getFlags().hasNonNeg());
15795 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0), Flags);
15796 }
15797
15798 // fold (zext (aext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
15799 // fold (zext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
15802 return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, N0.getOperand(0));
15803
15804 // fold (zext (truncate x)) -> (zext x) or
15805 // (zext (truncate x)) -> (truncate x)
15806 // This is valid when the truncated bits of x are already zero.
15807 SDValue Op;
15808 KnownBits Known;
15809 if (isTruncateOf(DAG, N0, Op, Known)) {
15810 APInt TruncatedBits =
15811 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
15812 APInt(Op.getScalarValueSizeInBits(), 0) :
15813 APInt::getBitsSet(Op.getScalarValueSizeInBits(),
15814 N0.getScalarValueSizeInBits(),
15815 std::min(Op.getScalarValueSizeInBits(),
15816 VT.getScalarSizeInBits()));
15817 if (TruncatedBits.isSubsetOf(Known.Zero)) {
15818 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
15819 DAG.salvageDebugInfo(*N0.getNode());
15820
15821 return ZExtOrTrunc;
15822 }
15823 }
15824
15825 // fold (zext (truncate x)) -> (and x, mask)
15826 if (N0.getOpcode() == ISD::TRUNCATE) {
15827 // fold (zext (truncate (load x))) -> (zext (smaller load x))
15828 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
15829 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
15830 SDNode *oye = N0.getOperand(0).getNode();
15831 if (NarrowLoad.getNode() != N0.getNode()) {
15832 CombineTo(N0.getNode(), NarrowLoad);
15833 // CombineTo deleted the truncate, if needed, but not what's under it.
15834 AddToWorklist(oye);
15835 }
15836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15837 }
15838
15839 EVT SrcVT = N0.getOperand(0).getValueType();
15840 EVT MinVT = N0.getValueType();
15841
15842 if (N->getFlags().hasNonNeg()) {
15843 SDValue Op = N0.getOperand(0);
15844 unsigned OpBits = SrcVT.getScalarSizeInBits();
15845 unsigned MidBits = MinVT.getScalarSizeInBits();
15846 unsigned DestBits = VT.getScalarSizeInBits();
15847
15848 if (N0->getFlags().hasNoSignedWrap() ||
15849 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
15850 if (OpBits == DestBits) {
15851 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
15852 // bits, it is already ready.
15853 return Op;
15854 }
15855
15856 if (OpBits < DestBits) {
15857 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
15858 // bits, just sext from i32.
15859 // FIXME: This can probably be ZERO_EXTEND nneg?
15860 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
15861 }
15862
15863 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
15864 // bits, just truncate to i32.
15865 SDNodeFlags Flags;
15866 Flags.setNoSignedWrap(true);
15867 Flags.setNoUnsignedWrap(true);
15868 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
15869 }
15870 }
15871
15872 // Try to mask before the extension to avoid having to generate a larger mask,
15873 // possibly over several sub-vectors.
15874 if (SrcVT.bitsLT(VT) && VT.isVector()) {
15875 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
15877 SDValue Op = N0.getOperand(0);
15878 Op = DAG.getZeroExtendInReg(Op, DL, MinVT);
15879 AddToWorklist(Op.getNode());
15880 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
15881 // Transfer the debug info; the new node is equivalent to N0.
15882 DAG.transferDbgValues(N0, ZExtOrTrunc);
15883 return ZExtOrTrunc;
15884 }
15885 }
15886
15887 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
15888 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
15889 AddToWorklist(Op.getNode());
15890 SDValue And = DAG.getZeroExtendInReg(Op, DL, MinVT);
15891 // We may safely transfer the debug info describing the truncate node over
15892 // to the equivalent and operation.
15893 DAG.transferDbgValues(N0, And);
15894 return And;
15895 }
15896 }
15897
15898 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
15899 // if either of the casts is not free.
15900 // Also handles (zext (and (bitcast (extract_subvector vNi1, 0)) cst))
15901 // by treating the bitcast+extract as equivalent to a truncate of the
15902 // wider bitcast, e.g. on AVX512DQ where v8i1 extract replaces truncate.
15903 if (N0.getOpcode() == ISD::AND &&
15904 N0.getOperand(1).getOpcode() == ISD::Constant) {
15905 SDValue AndSrc = N0.getOperand(0);
15906 SDValue X;
15907 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
15908 X = AndSrc.getOperand(0);
15909 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
15911 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
15912 // (bitcast (extract_subvector vNi1, 0) -> iK) is equivalent to
15913 // (truncate (bitcast vNi1 -> iN) -> iK); use the wider vNi1 as X.
15914 SDValue Src = AndSrc.getOperand(0).getOperand(0);
15915 EVT SrcVT = Src.getValueType();
15916 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
15917 EVT WideIntVT =
15919 if (TLI.isTypeLegal(WideIntVT))
15920 X = DAG.getBitcast(WideIntVT, Src);
15921 }
15922 }
15923 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
15924 !TLI.isZExtFree(N0.getValueType(), VT))) {
15925 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
15926 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
15927 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
15928 }
15929 }
15930
15931 // Try to simplify (zext (load x)).
15932 if (SDValue foldedExt = tryToFoldExtOfLoad(
15933 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD,
15934 ISD::ZERO_EXTEND, N->getFlags().hasNonNeg()))
15935 return foldedExt;
15936
15937 if (SDValue foldedExt =
15938 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
15940 return foldedExt;
15941
15942 // fold (zext (load x)) to multiple smaller zextloads.
15943 // Only on illegal but splittable vectors.
15944 if (SDValue ExtLoad = CombineExtLoad(N))
15945 return ExtLoad;
15946
15947 // Try to simplify (zext (atomic_load x)).
15948 if (SDValue foldedExt =
15949 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::ZEXTLOAD))
15950 return foldedExt;
15951
15952 // fold (zext (and/or/xor (load x), cst)) ->
15953 // (and/or/xor (zextload x), (zext cst))
15954 // Unless (and (load x) cst) will match as a zextload already and has
15955 // additional users, or the zext is already free.
15956 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && !TLI.isZExtFree(N0, VT) &&
15957 isa<LoadSDNode>(N0.getOperand(0)) &&
15958 N0.getOperand(1).getOpcode() == ISD::Constant &&
15959 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
15960 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
15961 EVT MemVT = LN00->getMemoryVT();
15962 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
15963 ISD::ZEXTLOAD, false) &&
15964 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
15965 bool DoXform = true;
15967 if (!N0.hasOneUse()) {
15968 if (N0.getOpcode() == ISD::AND) {
15969 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
15970 EVT LoadResultTy = AndC->getValueType(0);
15971 EVT ExtVT;
15972 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
15973 DoXform = false;
15974 }
15975 }
15976 if (DoXform)
15977 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
15978 ISD::ZERO_EXTEND, SetCCs, TLI);
15979 if (DoXform) {
15980 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
15981 LN00->getChain(), LN00->getBasePtr(),
15982 LN00->getMemoryVT(),
15983 LN00->getMemOperand());
15984 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
15985 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
15986 ExtLoad, DAG.getConstant(Mask, DL, VT));
15987 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
15988 bool NoReplaceTruncAnd = !N0.hasOneUse();
15989 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
15990 CombineTo(N, And);
15991 // If N0 has multiple uses, change other uses as well.
15992 if (NoReplaceTruncAnd) {
15993 SDValue TruncAnd =
15995 CombineTo(N0.getNode(), TruncAnd);
15996 }
15997 if (NoReplaceTrunc) {
15998 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
15999 } else {
16000 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
16001 LN00->getValueType(0), ExtLoad);
16002 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
16003 }
16004 return SDValue(N,0); // Return N so it doesn't get rechecked!
16005 }
16006 }
16007 }
16008
16009 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
16010 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
16011 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
16012 return ZExtLoad;
16013
16014 // Try to simplify (zext (zextload x)).
16015 if (SDValue foldedExt = tryToFoldExtOfExtload(
16016 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
16017 return foldedExt;
16018
16019 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
16020 return V;
16021
16022 if (N0.getOpcode() == ISD::SETCC) {
16023 // Propagate fast-math-flags.
16024 SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
16025
16026 // Only do this before legalize for now.
16027 if (!LegalOperations && VT.isVector() &&
16028 N0.getValueType().getVectorElementType() == MVT::i1) {
16029 EVT N00VT = N0.getOperand(0).getValueType();
16030 if (getSetCCResultType(N00VT) == N0.getValueType())
16031 return SDValue();
16032
16033 // We know that the # elements of the results is the same as the #
16034 // elements of the compare (and the # elements of the compare result for
16035 // that matter). Check to see that they are the same size. If so, we know
16036 // that the element size of the sext'd result matches the element size of
16037 // the compare operands.
16038 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
16039 // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
16040 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
16041 N0.getOperand(1), N0.getOperand(2));
16042 return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
16043 }
16044
16045 // If the desired elements are smaller or larger than the source
16046 // elements we can use a matching integer vector type and then
16047 // truncate/any extend followed by zext_in_reg.
16048 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16049 SDValue VsetCC =
16050 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
16051 N0.getOperand(1), N0.getOperand(2));
16052 return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
16053 N0.getValueType());
16054 }
16055
16056 // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc)
16057 EVT N0VT = N0.getValueType();
16058 EVT N00VT = N0.getOperand(0).getValueType();
16059 if (SDValue SCC = SimplifySelectCC(
16060 DL, N0.getOperand(0), N0.getOperand(1),
16061 DAG.getBoolConstant(true, DL, N0VT, N00VT),
16062 DAG.getBoolConstant(false, DL, N0VT, N00VT),
16063 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16064 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC);
16065 }
16066
16067 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
16068 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
16069 !TLI.isZExtFree(N0, VT)) {
16070 SDValue ShVal = N0.getOperand(0);
16071 SDValue ShAmt = N0.getOperand(1);
16072 if (auto *ShAmtC = dyn_cast<ConstantSDNode>(ShAmt)) {
16073 if (ShVal.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse()) {
16074 if (N0.getOpcode() == ISD::SHL) {
16075 // If the original shl may be shifting out bits, do not perform this
16076 // transformation.
16077 unsigned KnownZeroBits = ShVal.getValueSizeInBits() -
16078 ShVal.getOperand(0).getValueSizeInBits();
16079 if (ShAmtC->getAPIntValue().ugt(KnownZeroBits)) {
16080 // If the shift is too large, then see if we can deduce that the
16081 // shift is safe anyway.
16082
16083 // Check if the bits being shifted out are known to be zero.
16084 KnownBits KnownShVal = DAG.computeKnownBits(ShVal);
16085 if (ShAmtC->getAPIntValue().ugt(KnownShVal.countMinLeadingZeros()))
16086 return SDValue();
16087 }
16088 }
16089
16090 // Ensure that the shift amount is wide enough for the shifted value.
16091 if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
16092 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
16093
16094 return DAG.getNode(N0.getOpcode(), DL, VT,
16095 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ShVal), ShAmt);
16096 }
16097 }
16098 }
16099
16100 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
16101 return NewVSel;
16102
16103 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16104 return NewCtPop;
16105
16106 if (SDValue V = widenAbs(N, DAG))
16107 return V;
16108
16109 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16110 return Res;
16111
16112 // CSE zext nneg with sext if the zext is not free.
16113 if (N->getFlags().hasNonNeg() && !TLI.isZExtFree(N0.getValueType(), VT)) {
16114 SDNode *CSENode = DAG.getNodeIfExists(ISD::SIGN_EXTEND, N->getVTList(), N0);
16115 if (CSENode)
16116 return SDValue(CSENode, 0);
16117 }
16118
16119 return SDValue();
16120}
16121
16122SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
16123 SDValue N0 = N->getOperand(0);
16124 EVT VT = N->getValueType(0);
16125 SDLoc DL(N);
16126
16127 // aext(undef) = undef
16128 if (N0.isUndef())
16129 return DAG.getUNDEF(VT);
16130
16131 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16132 return Res;
16133
16134 // fold (aext (aext x)) -> (aext x)
16135 // fold (aext (zext x)) -> (zext x)
16136 // fold (aext (sext x)) -> (sext x)
16137 if (N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::ZERO_EXTEND ||
16138 N0.getOpcode() == ISD::SIGN_EXTEND) {
16139 SDNodeFlags Flags;
16140 if (N0.getOpcode() == ISD::ZERO_EXTEND)
16141 Flags.setNonNeg(N0->getFlags().hasNonNeg());
16142 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
16143 }
16144
16145 // fold (aext (aext_extend_vector_inreg x)) -> (aext_extend_vector_inreg x)
16146 // fold (aext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16147 // fold (aext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
16151 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
16152
16153 // fold (aext (truncate (load x))) -> (aext (smaller load x))
16154 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
16155 if (N0.getOpcode() == ISD::TRUNCATE) {
16156 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16157 SDNode *oye = N0.getOperand(0).getNode();
16158 if (NarrowLoad.getNode() != N0.getNode()) {
16159 CombineTo(N0.getNode(), NarrowLoad);
16160 // CombineTo deleted the truncate, if needed, but not what's under it.
16161 AddToWorklist(oye);
16162 }
16163 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16164 }
16165 }
16166
16167 // fold (aext (truncate x))
16168 if (N0.getOpcode() == ISD::TRUNCATE)
16169 return DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
16170
16171 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
16172 // if either of the casts is not free, and sign-extending the narrow type is
16173 // not cheaper than zero-extending it (which would indicate the target prefers
16174 // to keep operations at the narrower width).
16175 // Also handles (aext (and (bitcast (extract_subvector vNi1, 0)) cst))
16176 // which arises on AVX512DQ where v8i1 extract replaces truncate.
16177 if (N0.getOpcode() == ISD::AND &&
16178 N0.getOperand(1).getOpcode() == ISD::Constant) {
16179 SDValue AndSrc = N0.getOperand(0);
16180 SDValue X;
16181 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
16182 X = AndSrc.getOperand(0);
16183 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
16185 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
16186 SDValue Src = AndSrc.getOperand(0).getOperand(0);
16187 EVT SrcVT = Src.getValueType();
16188 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
16189 EVT WideIntVT =
16191 if (TLI.isTypeLegal(WideIntVT))
16192 X = DAG.getBitcast(WideIntVT, Src);
16193 }
16194 }
16195 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
16196 (!TLI.isZExtFree(N0.getValueType(), VT) &&
16197 !TLI.isSExtCheaperThanZExt(N0.getValueType(), VT)))) {
16198 X = DAG.getAnyExtOrTrunc(X, DL, VT);
16199 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16200 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
16201 }
16202 }
16203
16204 // fold (aext (load x)) -> (aext (truncate (extload x)))
16205 // None of the supported targets knows how to perform load and any_ext
16206 // on vectors in one instruction, so attempt to fold to zext instead.
16207 if (VT.isVector()) {
16208 // Try to simplify (zext (load x)).
16209 if (SDValue foldedExt =
16210 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
16212 return foldedExt;
16213 } else if (ISD::isNON_EXTLoad(N0.getNode()) &&
16215 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16216 if (TLI.isLoadLegalOrCustom(VT, N0.getValueType(), LN0->getAlign(),
16217 LN0->getAddressSpace(), ISD::EXTLOAD, false)) {
16218 bool DoXform = true;
16220 if (!N0.hasOneUse())
16221 DoXform =
16222 ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
16223 if (DoXform) {
16224 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, DL, VT, LN0->getChain(),
16225 LN0->getBasePtr(), N0.getValueType(),
16226 LN0->getMemOperand());
16227 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
16228 // If the load value is used only by N, replace it via CombineTo N.
16229 bool NoReplaceTrunc = N0.hasOneUse();
16230 CombineTo(N, ExtLoad);
16231 if (NoReplaceTrunc) {
16232 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16233 recursivelyDeleteUnusedNodes(LN0);
16234 } else {
16235 SDValue Trunc =
16236 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
16237 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
16238 }
16239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16240 }
16241 }
16242 }
16243
16244 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
16245 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
16246 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
16247 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
16248 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
16249 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16250 ISD::LoadExtType ExtType = LN0->getExtensionType();
16251 EVT MemVT = LN0->getMemoryVT();
16252 if (!LegalOperations ||
16253 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
16254 ExtType, false)) {
16255 SDValue ExtLoad =
16256 DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), LN0->getBasePtr(),
16257 MemVT, LN0->getMemOperand());
16258 CombineTo(N, ExtLoad);
16259 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16260 recursivelyDeleteUnusedNodes(LN0);
16261 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16262 }
16263 }
16264
16265 if (N0.getOpcode() == ISD::SETCC) {
16266 // Propagate fast-math-flags.
16267 SDNodeFlags Flags = N0->getFlags();
16268 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
16269
16270 // For vectors:
16271 // aext(setcc) -> vsetcc
16272 // aext(setcc) -> truncate(vsetcc)
16273 // aext(setcc) -> aext(vsetcc)
16274 // Only do this before legalize for now.
16275 if (VT.isVector() && !LegalOperations) {
16276 EVT N00VT = N0.getOperand(0).getValueType();
16277 if (getSetCCResultType(N00VT) == N0.getValueType())
16278 return SDValue();
16279
16280 // We know that the # elements of the results is the same as the
16281 // # elements of the compare (and the # elements of the compare result
16282 // for that matter). Check to see that they are the same size. If so,
16283 // we know that the element size of the sext'd result matches the
16284 // element size of the compare operands.
16285 if (VT.getSizeInBits() == N00VT.getSizeInBits())
16286 return DAG.getSetCC(DL, VT, N0.getOperand(0), N0.getOperand(1),
16287 cast<CondCodeSDNode>(N0.getOperand(2))->get(),
16288 /*Chain=*/{}, /*Signaling=*/false, Flags);
16289
16290 // If the desired elements are smaller or larger than the source
16291 // elements we can use a matching integer vector type and then
16292 // truncate/any extend
16293 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16294 SDValue VsetCC = DAG.getSetCC(
16295 DL, MatchingVectorType, N0.getOperand(0), N0.getOperand(1),
16296 cast<CondCodeSDNode>(N0.getOperand(2))->get(), /*Chain=*/{},
16297 /*Signaling=*/false, Flags);
16298 return DAG.getAnyExtOrTrunc(VsetCC, DL, VT);
16299 }
16300
16301 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
16302 if (SDValue SCC = SimplifySelectCC(
16303 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
16304 DAG.getConstant(0, DL, VT),
16305 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16306 return SCC;
16307 }
16308
16309 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16310 return NewCtPop;
16311
16312 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16313 return Res;
16314
16315 return SDValue();
16316}
16317
16318SDValue DAGCombiner::visitAssertExt(SDNode *N) {
16319 unsigned Opcode = N->getOpcode();
16320 SDValue N0 = N->getOperand(0);
16321 SDValue N1 = N->getOperand(1);
16322 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
16323
16324 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
16325 if (N0.getOpcode() == Opcode &&
16326 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
16327 return N0;
16328
16329 // fold (assert?ext c, vt) -> c
16330 if (isa<ConstantSDNode>(N0))
16331 return N0;
16332
16333 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16334 N0.getOperand(0).getOpcode() == Opcode) {
16335 // We have an assert, truncate, assert sandwich. Make one stronger assert
16336 // by asserting on the smallest asserted type to the larger source type.
16337 // This eliminates the later assert:
16338 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
16339 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
16340 SDLoc DL(N);
16341 SDValue BigA = N0.getOperand(0);
16342 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16343 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
16344 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
16345 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16346 BigA.getOperand(0), MinAssertVTVal);
16347 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16348 }
16349
16350 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
16351 // than X. Just move the AssertZext in front of the truncate and drop the
16352 // AssertSExt.
16353 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16355 Opcode == ISD::AssertZext) {
16356 SDValue BigA = N0.getOperand(0);
16357 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16358 if (AssertVT.bitsLT(BigA_AssertVT)) {
16359 SDLoc DL(N);
16360 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16361 BigA.getOperand(0), N1);
16362 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16363 }
16364 }
16365
16366 if (Opcode == ISD::AssertZext && N0.getOpcode() == ISD::AND &&
16368 const APInt &Mask = N0.getConstantOperandAPInt(1);
16369
16370 // If we have (AssertZext (and (AssertSext X, iX), M), iY) and Y is smaller
16371 // than X, and the And doesn't change the lower iX bits, we can move the
16372 // AssertZext in front of the And and drop the AssertSext.
16373 if (N0.getOperand(0).getOpcode() == ISD::AssertSext && N0.hasOneUse()) {
16374 SDValue BigA = N0.getOperand(0);
16375 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16376 if (AssertVT.bitsLT(BigA_AssertVT) &&
16377 Mask.countr_one() >= BigA_AssertVT.getScalarSizeInBits()) {
16378 SDLoc DL(N);
16379 SDValue NewAssert =
16380 DAG.getNode(Opcode, DL, N->getValueType(0), BigA.getOperand(0), N1);
16381 return DAG.getNode(ISD::AND, DL, N->getValueType(0), NewAssert,
16382 N0.getOperand(1));
16383 }
16384 }
16385
16386 // Remove AssertZext entirely if the mask guarantees the assertion cannot
16387 // fail.
16388 // TODO: Use KB countMinLeadingZeros to handle non-constant masks?
16389 if (Mask.isIntN(AssertVT.getScalarSizeInBits()))
16390 return N0;
16391 }
16392
16393 return SDValue();
16394}
16395
16396SDValue DAGCombiner::visitAssertAlign(SDNode *N) {
16397 SDLoc DL(N);
16398
16399 Align AL = cast<AssertAlignSDNode>(N)->getAlign();
16400 SDValue N0 = N->getOperand(0);
16401
16402 // Fold (assertalign (assertalign x, AL0), AL1) ->
16403 // (assertalign x, max(AL0, AL1))
16404 if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0))
16405 return DAG.getAssertAlign(DL, N0.getOperand(0),
16406 std::max(AL, AAN->getAlign()));
16407
16408 // In rare cases, there are trivial arithmetic ops in source operands. Sink
16409 // this assert down to source operands so that those arithmetic ops could be
16410 // exposed to the DAG combining.
16411 switch (N0.getOpcode()) {
16412 default:
16413 break;
16414 case ISD::ADD:
16415 case ISD::PTRADD:
16416 case ISD::SUB: {
16417 unsigned AlignShift = Log2(AL);
16418 SDValue LHS = N0.getOperand(0);
16419 SDValue RHS = N0.getOperand(1);
16420 unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros();
16421 unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros();
16422 if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) {
16423 if (LHSAlignShift < AlignShift)
16424 LHS = DAG.getAssertAlign(DL, LHS, AL);
16425 if (RHSAlignShift < AlignShift)
16426 RHS = DAG.getAssertAlign(DL, RHS, AL);
16427 return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS);
16428 }
16429 break;
16430 }
16431 }
16432
16433 return SDValue();
16434}
16435
16436SDValue DAGCombiner::visitIS_FPCLASS(SDNode *N) {
16437 SDValue Src = N->getOperand(0);
16438 FPClassTest Mask = static_cast<FPClassTest>(N->getConstantOperandVal(1));
16439 EVT VT = N->getValueType(0);
16440 SDLoc DL(N);
16441
16442 // is.fpclass(poison, mask) -> poison
16443 if (Src.getOpcode() == ISD::POISON)
16444 return DAG.getPOISON(VT);
16445
16446 KnownFPClass Known = DAG.computeKnownFPClass(Src, Mask);
16447
16448 // All possible classes are within the mask: result is always true.
16449 if ((~Mask & Known.KnownFPClasses) == fcNone)
16450 return DAG.getBoolConstant(true, DL, VT, Src.getValueType());
16451
16452 // Clear test bits we know must be false from the source value.
16453 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
16454 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
16455 if ((Mask & Known.KnownFPClasses) != Mask) {
16456 return DAG.getNode(
16457 ISD::IS_FPCLASS, DL, VT, Src,
16458 DAG.getTargetConstant(Mask & Known.KnownFPClasses, DL, MVT::i32),
16459 N->getFlags());
16460 }
16461
16462 return SDValue();
16463}
16464
16465/// If the result of a load is shifted/masked/truncated to an effectively
16466/// narrower type, try to transform the load to a narrower type and/or
16467/// use an extending load.
16468SDValue DAGCombiner::reduceLoadWidth(SDNode *N) {
16469 unsigned Opc = N->getOpcode();
16470
16472 SDValue N0 = N->getOperand(0);
16473 EVT VT = N->getValueType(0);
16474 EVT ExtVT = VT;
16475
16476 // This transformation isn't valid for vector loads.
16477 if (VT.isVector())
16478 return SDValue();
16479
16480 // The ShAmt variable is used to indicate that we've consumed a right
16481 // shift. I.e. we want to narrow the width of the load by skipping to load the
16482 // ShAmt least significant bits.
16483 unsigned ShAmt = 0;
16484 // A special case is when the least significant bits from the load are masked
16485 // away, but using an AND rather than a right shift. HasShiftedOffset is used
16486 // to indicate that the narrowed load should be left-shifted ShAmt bits to get
16487 // the result.
16488 unsigned ShiftedOffset = 0;
16489 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
16490 // extended to VT.
16491 if (Opc == ISD::SIGN_EXTEND_INREG) {
16492 ExtType = ISD::SEXTLOAD;
16493 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
16494 } else if (Opc == ISD::SRL || Opc == ISD::SRA) {
16495 // Another special-case: SRL/SRA is basically zero/sign-extending a narrower
16496 // value, or it may be shifting a higher subword, half or byte into the
16497 // lowest bits.
16498
16499 // Only handle shift with constant shift amount, and the shiftee must be a
16500 // load.
16501 auto *LN = dyn_cast<LoadSDNode>(N0);
16502 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16503 if (!N1C || !LN)
16504 return SDValue();
16505 // If the shift amount is larger than the memory type then we're not
16506 // accessing any of the loaded bytes.
16507 ShAmt = N1C->getZExtValue();
16508 uint64_t MemoryWidth = LN->getMemoryVT().getScalarSizeInBits();
16509 if (MemoryWidth <= ShAmt)
16510 return SDValue();
16511 // Attempt to fold away the SRL by using ZEXTLOAD and SRA by using SEXTLOAD.
16512 ExtType = Opc == ISD::SRL ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
16513 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
16514 // If original load is a SEXTLOAD then we can't simply replace it by a
16515 // ZEXTLOAD (we could potentially replace it by a more narrow SEXTLOAD
16516 // followed by a ZEXT, but that is not handled at the moment). Similarly if
16517 // the original load is a ZEXTLOAD and we want to use a SEXTLOAD.
16518 if ((LN->getExtensionType() == ISD::SEXTLOAD ||
16519 LN->getExtensionType() == ISD::ZEXTLOAD) &&
16520 LN->getExtensionType() != ExtType)
16521 return SDValue();
16522 } else if (Opc == ISD::AND) {
16523 // An AND with a constant mask is the same as a truncate + zero-extend.
16524 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
16525 if (!AndC)
16526 return SDValue();
16527
16528 const APInt &Mask = AndC->getAPIntValue();
16529 unsigned ActiveBits = 0;
16530 if (Mask.isMask()) {
16531 ActiveBits = Mask.countr_one();
16532 } else if (Mask.isShiftedMask(ShAmt, ActiveBits)) {
16533 ShiftedOffset = ShAmt;
16534 } else {
16535 return SDValue();
16536 }
16537
16538 ExtType = ISD::ZEXTLOAD;
16539 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
16540 }
16541
16542 // In case Opc==SRL we've already prepared ExtVT/ExtType/ShAmt based on doing
16543 // a right shift. Here we redo some of those checks, to possibly adjust the
16544 // ExtVT even further based on "a masking AND". We could also end up here for
16545 // other reasons (e.g. based on Opc==TRUNCATE) and that is why some checks
16546 // need to be done here as well.
16547 if (Opc == ISD::SRL || N0.getOpcode() == ISD::SRL) {
16548 SDValue SRL = Opc == ISD::SRL ? SDValue(N, 0) : N0;
16549 // Bail out when the SRL has more than one use. This is done for historical
16550 // (undocumented) reasons. Maybe intent was to guard the AND-masking below
16551 // check below? And maybe it could be non-profitable to do the transform in
16552 // case the SRL has multiple uses and we get here with Opc!=ISD::SRL?
16553 // FIXME: Can't we just skip this check for the Opc==ISD::SRL case.
16554 if (!SRL.hasOneUse())
16555 return SDValue();
16556
16557 // Only handle shift with constant shift amount, and the shiftee must be a
16558 // load.
16559 auto *LN = dyn_cast<LoadSDNode>(SRL.getOperand(0));
16560 auto *SRL1C = dyn_cast<ConstantSDNode>(SRL.getOperand(1));
16561 if (!SRL1C || !LN)
16562 return SDValue();
16563
16564 // If the shift amount is larger than the input type then we're not
16565 // accessing any of the loaded bytes. If the load was a zextload/extload
16566 // then the result of the shift+trunc is zero/undef (handled elsewhere).
16567 ShAmt = SRL1C->getZExtValue();
16568 uint64_t MemoryWidth = LN->getMemoryVT().getSizeInBits();
16569 if (ShAmt >= MemoryWidth)
16570 return SDValue();
16571
16572 // Because a SRL must be assumed to *need* to zero-extend the high bits
16573 // (as opposed to anyext the high bits), we can't combine the zextload
16574 // lowering of SRL and an sextload.
16575 if (LN->getExtensionType() == ISD::SEXTLOAD)
16576 return SDValue();
16577
16578 // Avoid reading outside the memory accessed by the original load (could
16579 // happened if we only adjust the load base pointer by ShAmt). Instead we
16580 // try to narrow the load even further. The typical scenario here is:
16581 // (i64 (truncate (i96 (srl (load x), 64)))) ->
16582 // (i64 (truncate (i96 (zextload (load i32 + offset) from i32))))
16583 if (ExtVT.getScalarSizeInBits() > MemoryWidth - ShAmt) {
16584 // Don't replace sextload by zextload.
16585 if (ExtType == ISD::SEXTLOAD)
16586 return SDValue();
16587 // Narrow the load.
16588 ExtType = ISD::ZEXTLOAD;
16589 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
16590 }
16591
16592 // If the SRL is only used by a masking AND, we may be able to adjust
16593 // the ExtVT to make the AND redundant.
16594 SDNode *Mask = *(SRL->user_begin());
16595 if (SRL.hasOneUse() && Mask->getOpcode() == ISD::AND &&
16596 isa<ConstantSDNode>(Mask->getOperand(1))) {
16597 unsigned Offset, ActiveBits;
16598 const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
16599 if (ShiftMask.isMask()) {
16600 EVT MaskedVT =
16601 EVT::getIntegerVT(*DAG.getContext(), ShiftMask.countr_one());
16602 // If the mask is smaller, recompute the type.
16603 if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) &&
16604 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
16605 LN->getAddressSpace(), ExtType, false))
16606 ExtVT = MaskedVT;
16607 } else if (ExtType == ISD::ZEXTLOAD &&
16608 ShiftMask.isShiftedMask(Offset, ActiveBits) &&
16609 (Offset + ShAmt) < VT.getScalarSizeInBits()) {
16610 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
16611 // If the mask is shifted we can use a narrower load and a shl to insert
16612 // the trailing zeros.
16613 if (((Offset + ActiveBits) <= ExtVT.getScalarSizeInBits()) &&
16614 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
16615 LN->getAddressSpace(), ExtType, false)) {
16616 ExtVT = MaskedVT;
16617 ShAmt = Offset + ShAmt;
16618 ShiftedOffset = Offset;
16619 }
16620 }
16621 }
16622
16623 N0 = SRL.getOperand(0);
16624 }
16625
16626 // If the load is shifted left (and the result isn't shifted back right), we
16627 // can fold a truncate through the shift. The typical scenario is that N
16628 // points at a TRUNCATE here so the attempted fold is:
16629 // (truncate (shl (load x), c))) -> (shl (narrow load x), c)
16630 // ShLeftAmt will indicate how much a narrowed load should be shifted left.
16631 unsigned ShLeftAmt = 0;
16632 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
16633 ExtVT == VT && TLI.isNarrowingProfitable(N, N0.getValueType(), VT)) {
16634 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
16635 ShLeftAmt = N01->getZExtValue();
16636 N0 = N0.getOperand(0);
16637 }
16638 }
16639
16640 // Look through a freeze if present between the operation and the load.
16641 // The freeze will be preserved on the narrowed result.
16642 SDValue FreezeNode;
16643 if (N0.getOpcode() == ISD::FREEZE) {
16644 FreezeNode = N0;
16645 N0 = N0.getOperand(0);
16646 }
16647
16648 // If we haven't found a load, we can't narrow it.
16649 if (!isa<LoadSDNode>(N0))
16650 return SDValue();
16651
16652 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16653 // Reducing the width of a volatile load is illegal. For atomics, we may be
16654 // able to reduce the width provided we never widen again. (see D66309)
16655 if (!LN0->isSimple() ||
16656 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
16657 return SDValue();
16658
16659 // Bail early when looking through a multi-use freeze, since other users of
16660 // the freeze can depend on the full load value. But its still safe to change
16661 // the extension type from anyext to zext.
16662 if (FreezeNode && !FreezeNode.hasOneUse() &&
16663 (LN0->getMemoryVT().bitsGT(ExtVT) || ExtType != ISD::ZEXTLOAD ||
16664 (LN0->getExtensionType() != ISD::EXTLOAD &&
16665 LN0->getExtensionType() != ISD::ZEXTLOAD)))
16666 return SDValue();
16667
16668 auto AdjustBigEndianShift = [&](unsigned ShAmt) {
16669 unsigned LVTStoreBits =
16671 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedValue();
16672 return LVTStoreBits - EVTStoreBits - ShAmt;
16673 };
16674
16675 // We need to adjust the pointer to the load by ShAmt bits in order to load
16676 // the correct bytes.
16677 unsigned PtrAdjustmentInBits =
16678 DAG.getDataLayout().isBigEndian() ? AdjustBigEndianShift(ShAmt) : ShAmt;
16679
16680 uint64_t PtrOff = PtrAdjustmentInBits / 8;
16681 SDLoc DL(LN0);
16682 // The original load itself didn't wrap, so an offset within it doesn't.
16683 SDValue NewPtr =
16686 AddToWorklist(NewPtr.getNode());
16687
16688 SDValue Load;
16689 if (ExtType == ISD::NON_EXTLOAD) {
16690 const MDNode *OldRanges = LN0->getRanges();
16691 const MDNode *NewRanges = nullptr;
16692 // If LSBs are loaded and the truncated ConstantRange for the OldRanges
16693 // metadata is not the full-set for the new width then create a NewRanges
16694 // metadata for the truncated load
16695 if (ShAmt == 0 && OldRanges) {
16696 ConstantRange CR = getConstantRangeFromMetadata(*OldRanges);
16697 unsigned BitSize = VT.getScalarSizeInBits();
16698
16699 // It is possible for an 8-bit extending load with 8-bit range
16700 // metadata to be narrowed to an 8-bit load. This guard is necessary to
16701 // ensure that truncation is strictly smaller.
16702 if (CR.getBitWidth() > BitSize) {
16703 ConstantRange TruncatedCR = CR.truncate(BitSize);
16704 if (!TruncatedCR.isFullSet()) {
16705 Metadata *Bounds[2] = {
16707 ConstantInt::get(*DAG.getContext(), TruncatedCR.getLower())),
16709 ConstantInt::get(*DAG.getContext(), TruncatedCR.getUpper()))};
16710 NewRanges = MDNode::get(*DAG.getContext(), Bounds);
16711 }
16712 } else if (CR.getBitWidth() == BitSize)
16713 NewRanges = OldRanges;
16714 }
16715 Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
16716 LN0->getPointerInfo().getWithOffset(PtrOff),
16717 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
16718 LN0->getAAInfo(), NewRanges);
16719 } else
16720 Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
16721 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
16722 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
16723 LN0->getAAInfo());
16724
16725 // Replace the old load's chain with the new load's chain.
16726 WorklistRemover DeadNodes(*this);
16727 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
16728
16729 // Replace old load value for multi-use freeze so all users benefit.
16730 if (FreezeNode && !FreezeNode.hasOneUse())
16731 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), Load.getValue(0));
16732
16733 // If we looked through a freeze, rewrap the narrowed result and add an
16734 // Assert node so downstream analyses can see the range.
16736 if (FreezeNode) {
16737 Result = DAG.getNode(ISD::FREEZE, DL, VT, Result);
16738 if (ExtType == ISD::ZEXTLOAD)
16739 Result =
16740 DAG.getNode(ISD::AssertZext, DL, VT, Result, DAG.getValueType(ExtVT));
16741 else if (ExtType == ISD::SEXTLOAD)
16742 Result =
16743 DAG.getNode(ISD::AssertSext, DL, VT, Result, DAG.getValueType(ExtVT));
16744 }
16745
16746 // Shift the result left, if we've swallowed a left shift.
16747 if (ShLeftAmt != 0) {
16748 // If the shift amount is as large as the result size (but, presumably,
16749 // no larger than the source) then the useful bits of the result are
16750 // zero; we can't simply return the shortened shift, because the result
16751 // of that operation is undefined.
16752 if (ShLeftAmt >= VT.getScalarSizeInBits())
16753 Result = DAG.getConstant(0, DL, VT);
16754 else
16755 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
16756 DAG.getShiftAmountConstant(ShLeftAmt, VT, DL));
16757 }
16758
16759 if (ShiftedOffset != 0) {
16760 // We're using a shifted mask, so the load now has an offset. This means
16761 // that data has been loaded into the lower bytes than it would have been
16762 // before, so we need to shl the loaded data into the correct position in the
16763 // register.
16764 SDValue ShiftC = DAG.getConstant(ShiftedOffset, DL, VT);
16765 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
16766 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
16767 }
16768
16769 // Return the new loaded value.
16770 return Result;
16771}
16772
16773SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
16774 SDValue N0 = N->getOperand(0);
16775 SDValue N1 = N->getOperand(1);
16776 EVT VT = N->getValueType(0);
16777 EVT ExtVT = cast<VTSDNode>(N1)->getVT();
16778 unsigned VTBits = VT.getScalarSizeInBits();
16779 unsigned ExtVTBits = ExtVT.getScalarSizeInBits();
16780 SDLoc DL(N);
16781
16782 // sext_vector_inreg(undef) = 0 because the top bit will all be the same.
16783 if (N0.isUndef())
16784 return DAG.getConstant(0, DL, VT);
16785
16786 // fold (sext_in_reg c1) -> c1
16787 if (SDValue C =
16789 return C;
16790
16791 // If the input is already sign extended, just drop the extension.
16792 if (ExtVTBits >= DAG.ComputeMaxSignificantBits(N0))
16793 return N0;
16794
16795 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
16796 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
16797 ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
16798 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N0.getOperand(0), N1);
16799
16800 // fold (sext_in_reg (sext x)) -> (sext x)
16801 // fold (sext_in_reg (aext x)) -> (sext x)
16802 // if x is small enough or if we know that x has more than 1 sign bit and the
16803 // sign_extend_inreg is extending from one of them.
16804 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
16805 SDValue N00 = N0.getOperand(0);
16806 unsigned N00Bits = N00.getScalarValueSizeInBits();
16807 if ((N00Bits <= ExtVTBits ||
16808 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits) &&
16809 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
16810 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
16811 }
16812
16813 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
16814 // if x is small enough or if we know that x has more than 1 sign bit and the
16815 // sign_extend_inreg is extending from one of them.
16817 SDValue N00 = N0.getOperand(0);
16818 unsigned N00Bits = N00.getScalarValueSizeInBits();
16819 bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
16820 if ((N00Bits == ExtVTBits ||
16821 (!IsZext && (N00Bits < ExtVTBits ||
16822 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits))) &&
16823 (!LegalOperations ||
16825 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, N00);
16826 }
16827
16828 // fold (sext_in_reg (zext x)) -> (sext x)
16829 // iff we are extending the source sign bit.
16830 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
16831 SDValue N00 = N0.getOperand(0);
16832 if (N00.getScalarValueSizeInBits() == ExtVTBits &&
16833 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
16834 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
16835 }
16836
16837 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
16838 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1)))
16839 return DAG.getZeroExtendInReg(N0, DL, ExtVT);
16840
16841 // fold operands of sext_in_reg based on knowledge that the top bits are not
16842 // demanded.
16844 return SDValue(N, 0);
16845
16846 // fold (sext_in_reg (load x)) -> (smaller sextload x)
16847 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
16848 if (SDValue NarrowLoad = reduceLoadWidth(N))
16849 return NarrowLoad;
16850
16851 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
16852 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
16853 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
16854 if (N0.getOpcode() == ISD::SRL) {
16855 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
16856 if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) {
16857 // We can turn this into an SRA iff the input to the SRL is already sign
16858 // extended enough.
16859 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
16860 if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits)
16861 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
16862 N0.getOperand(1));
16863 }
16864 }
16865
16866 // fold (sext_inreg (extload x)) -> (sextload x)
16867 // If sextload is not supported by target, we can only do the combine when
16868 // load has one use. Doing otherwise can block folding the extload with other
16869 // extends that the target does support.
16871 auto *LN0 = cast<LoadSDNode>(N0);
16872 if (ExtVT == LN0->getMemoryVT() &&
16873 ((!LegalOperations && LN0->isSimple() && N0.hasOneUse()) ||
16874 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
16875 ISD::SEXTLOAD, false))) {
16876 SDValue ExtLoad =
16877 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
16878 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
16879 CombineTo(N, ExtLoad);
16880 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
16881 AddToWorklist(ExtLoad.getNode());
16882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16883 }
16884 }
16885
16886 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
16888 auto *LN0 = cast<LoadSDNode>(N0);
16889
16890 if (N0.hasOneUse() && ExtVT == LN0->getMemoryVT() &&
16891 ((!LegalOperations && LN0->isSimple()) &&
16892 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
16893 ISD::SEXTLOAD, false))) {
16894 SDValue ExtLoad =
16895 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
16896 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
16897 CombineTo(N, ExtLoad);
16898 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
16899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16900 }
16901 }
16902
16903 // fold (sext_inreg (masked_load x)) -> (sext_masked_load x)
16904 // ignore it if the masked load is already sign extended
16905 bool Frozen = N0.getOpcode() == ISD::FREEZE && N0.hasOneUse();
16906 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0)) {
16907 if (ExtVT == Ld->getMemoryVT() && Ld->hasNUsesOfValue(1, 0) &&
16909 TLI.isLoadLegal(VT, ExtVT, Ld->getAlign(), Ld->getAddressSpace(),
16910 ISD::SEXTLOAD, false)) {
16911 SDValue ExtMaskedLoad = DAG.getMaskedLoad(
16912 VT, DL, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(),
16913 Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(),
16914 Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad());
16915 CombineTo(N, Frozen ? N0 : ExtMaskedLoad);
16916 CombineTo(Ld, ExtMaskedLoad, ExtMaskedLoad.getValue(1));
16917 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16918 }
16919 }
16920
16921 // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x)
16922 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
16923 if (SDValue(GN0, 0).hasOneUse() && ExtVT == GN0->getMemoryVT() &&
16925 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
16926 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
16927
16928 SDValue ExtLoad = DAG.getMaskedGather(
16929 DAG.getVTList(VT, MVT::Other), ExtVT, DL, Ops, GN0->getMemOperand(),
16930 GN0->getIndexType(), ISD::SEXTLOAD);
16931
16932 CombineTo(N, ExtLoad);
16933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
16934 AddToWorklist(ExtLoad.getNode());
16935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16936 }
16937 }
16938
16939 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
16940 if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) {
16941 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
16942 N0.getOperand(1), false))
16943 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, BSwap, N1);
16944 }
16945
16946 // Fold (iM_signext_inreg
16947 // (extract_subvector (zext|anyext|sext iN_v to _) _)
16948 // from iN)
16949 // -> (extract_subvector (signext iN_v to iM))
16950 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() &&
16952 SDValue InnerExt = N0.getOperand(0);
16953 EVT InnerExtVT = InnerExt->getValueType(0);
16954 SDValue Extendee = InnerExt->getOperand(0);
16955
16956 if (ExtVTBits == Extendee.getValueType().getScalarSizeInBits() &&
16957 (!LegalOperations ||
16958 TLI.isOperationLegal(ISD::SIGN_EXTEND, InnerExtVT))) {
16959 SDValue SignExtExtendee =
16960 DAG.getNode(ISD::SIGN_EXTEND, DL, InnerExtVT, Extendee);
16961 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SignExtExtendee,
16962 N0.getOperand(1));
16963 }
16964 }
16965
16966 return SDValue();
16967}
16968
16970 SDNode *N, const SDLoc &DL, const TargetLowering &TLI, SelectionDAG &DAG,
16971 bool LegalOperations) {
16972 unsigned InregOpcode = N->getOpcode();
16973 unsigned Opcode = DAG.getOpcode_EXTEND(InregOpcode);
16974
16975 SDValue Src = N->getOperand(0);
16976 EVT VT = N->getValueType(0);
16977 EVT SrcVT = VT.changeVectorElementType(
16978 *DAG.getContext(), Src.getValueType().getVectorElementType());
16979
16980 assert(ISD::isExtVecInRegOpcode(InregOpcode) &&
16981 "Expected EXTEND_VECTOR_INREG dag node in input!");
16982
16983 // Profitability check: our operand must be an one-use CONCAT_VECTORS.
16984 // FIXME: one-use check may be overly restrictive
16985 if (!Src.hasOneUse() || Src.getOpcode() != ISD::CONCAT_VECTORS)
16986 return SDValue();
16987
16988 // Profitability check: we must be extending exactly one of it's operands.
16989 // FIXME: this is probably overly restrictive.
16990 Src = Src.getOperand(0);
16991 if (Src.getValueType() != SrcVT)
16992 return SDValue();
16993
16994 if (LegalOperations && !TLI.isOperationLegal(Opcode, VT))
16995 return SDValue();
16996
16997 return DAG.getNode(Opcode, DL, VT, Src);
16998}
16999
17000SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) {
17001 SDValue N0 = N->getOperand(0);
17002 EVT VT = N->getValueType(0);
17003 SDLoc DL(N);
17004
17005 if (N0.isUndef()) {
17006 // aext_vector_inreg(undef) = undef because the top bits are undefined.
17007 // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same.
17008 return N->getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
17009 ? DAG.getUNDEF(VT)
17010 : DAG.getConstant(0, DL, VT);
17011 }
17012
17013 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
17014 return Res;
17015
17017 return SDValue(N, 0);
17018
17020 LegalOperations))
17021 return R;
17022
17023 return SDValue();
17024}
17025
17026SDValue DAGCombiner::visitTRUNCATE_USAT_U(SDNode *N) {
17027 EVT VT = N->getValueType(0);
17028 SDValue N0 = N->getOperand(0);
17029
17030 SDValue FPVal;
17031 if (sd_match(N0, m_FPToUI(m_Value(FPVal))) &&
17033 ISD::FP_TO_UINT_SAT, FPVal.getValueType(), VT))
17034 return DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), VT, FPVal,
17035 DAG.getValueType(VT.getScalarType()));
17036
17037 return SDValue();
17038}
17039
17040/// Detect patterns of truncation with unsigned saturation:
17041///
17042/// (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
17043/// Return the source value x to be truncated or SDValue() if the pattern was
17044/// not matched.
17045///
17047 unsigned NumDstBits = VT.getScalarSizeInBits();
17048 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17049 // Saturation with truncation. We truncate from InVT to VT.
17050 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17051
17052 SDValue Min;
17053 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17054 if (sd_match(In, m_UMin(m_Value(Min), m_SpecificInt(UnsignedMax))))
17055 return Min;
17056
17057 return SDValue();
17058}
17059
17060/// Detect patterns of truncation with signed saturation:
17061/// (truncate (smin (smax (x, signed_min_of_dest_type),
17062/// signed_max_of_dest_type)) to dest_type)
17063/// or:
17064/// (truncate (smax (smin (x, signed_max_of_dest_type),
17065/// signed_min_of_dest_type)) to dest_type).
17066///
17067/// Return the source value to be truncated or SDValue() if the pattern was not
17068/// matched.
17070 unsigned NumDstBits = VT.getScalarSizeInBits();
17071 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17072 // Saturation with truncation. We truncate from InVT to VT.
17073 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17074
17075 SDValue Val;
17076 APInt SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
17077 APInt SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
17078
17079 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_SpecificInt(SignedMin)),
17080 m_SpecificInt(SignedMax))))
17081 return Val;
17082
17083 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(SignedMax)),
17084 m_SpecificInt(SignedMin))))
17085 return Val;
17086
17087 return SDValue();
17088}
17089
17090/// Detect patterns of truncation with unsigned saturation:
17092 const SDLoc &DL) {
17093 unsigned NumDstBits = VT.getScalarSizeInBits();
17094 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17095 // Saturation with truncation. We truncate from InVT to VT.
17096 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17097
17098 SDValue Val;
17099 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17100 // Min == 0, Max is unsigned max of destination type.
17101 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(UnsignedMax)),
17102 m_Zero())))
17103 return Val;
17104
17105 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_Zero()),
17106 m_SpecificInt(UnsignedMax))))
17107 return Val;
17108
17109 if (sd_match(In, m_UMin(m_SMax(m_Value(Val), m_Zero()),
17110 m_SpecificInt(UnsignedMax))))
17111 return Val;
17112
17113 return SDValue();
17114}
17115
17116static SDValue foldToSaturated(SDNode *N, EVT &VT, SDValue &Src, EVT &SrcVT,
17117 SDLoc &DL, const TargetLowering &TLI,
17118 SelectionDAG &DAG) {
17119 auto AllowedTruncateSat = [&](unsigned Opc, EVT SrcVT, EVT VT) -> bool {
17120 return (TLI.isOperationLegalOrCustom(Opc, SrcVT) &&
17121 TLI.isTypeDesirableForOp(Opc, VT));
17122 };
17123
17124 if (Src.getOpcode() == ISD::SMIN || Src.getOpcode() == ISD::SMAX) {
17125 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_S, SrcVT, VT))
17126 if (SDValue SSatVal = detectSSatSPattern(Src, VT))
17127 return DAG.getNode(ISD::TRUNCATE_SSAT_S, DL, VT, SSatVal);
17128 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17129 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17130 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17131 } else if (Src.getOpcode() == ISD::UMIN) {
17132 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17133 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17134 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17135 if (AllowedTruncateSat(ISD::TRUNCATE_USAT_U, SrcVT, VT))
17136 if (SDValue USatVal = detectUSatUPattern(Src, VT))
17137 return DAG.getNode(ISD::TRUNCATE_USAT_U, DL, VT, USatVal);
17138 }
17139
17140 return SDValue();
17141}
17142
17143SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
17144 SDValue N0 = N->getOperand(0);
17145 EVT VT = N->getValueType(0);
17146 EVT SrcVT = N0.getValueType();
17147 bool isLE = DAG.getDataLayout().isLittleEndian();
17148 SDLoc DL(N);
17149
17150 // trunc(undef) = undef
17151 if (N0.isUndef())
17152 return DAG.getUNDEF(VT);
17153
17154 // fold (truncate (truncate x)) -> (truncate x)
17155 if (N0.getOpcode() == ISD::TRUNCATE)
17156 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17157
17158 // fold saturated truncate
17159 if (SDValue SaturatedTR = foldToSaturated(N, VT, N0, SrcVT, DL, TLI, DAG))
17160 return SaturatedTR;
17161
17162 // fold (truncate c1) -> c1
17163 if (SDValue C = DAG.FoldConstantArithmetic(ISD::TRUNCATE, DL, VT, {N0}))
17164 return C;
17165
17166 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
17167 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
17168 N0.getOpcode() == ISD::SIGN_EXTEND ||
17169 N0.getOpcode() == ISD::ANY_EXTEND) {
17170 // if the source is smaller than the dest, we still need an extend.
17171 if (N0.getOperand(0).getValueType().bitsLT(VT)) {
17172 SDNodeFlags Flags;
17173 if (N0.getOpcode() == ISD::ZERO_EXTEND)
17174 Flags.setNonNeg(N0->getFlags().hasNonNeg());
17175 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
17176 }
17177 // if the source is larger than the dest, than we just need the truncate.
17178 if (N0.getOperand(0).getValueType().bitsGT(VT))
17179 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17180 // if the source and dest are the same type, we can drop both the extend
17181 // and the truncate.
17182 return N0.getOperand(0);
17183 }
17184
17185 // Try to narrow a truncate-of-sext_in_reg to the destination type:
17186 // trunc (sign_ext_inreg X, iM) to iN --> sign_ext_inreg (trunc X to iN), iM
17187 if (!LegalTypes && N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
17188 N0.hasOneUse()) {
17189 SDValue X = N0.getOperand(0);
17190 SDValue ExtVal = N0.getOperand(1);
17191 EVT ExtVT = cast<VTSDNode>(ExtVal)->getVT();
17192 if (ExtVT.bitsLT(VT) && TLI.preferSextInRegOfTruncate(VT, SrcVT, ExtVT)) {
17193 SDValue TrX = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
17194 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, TrX, ExtVal);
17195 }
17196 }
17197
17198 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
17199 if (N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::ANY_EXTEND))
17200 return SDValue();
17201
17202 // Fold extract-and-trunc into a narrow extract. For example:
17203 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
17204 // i32 y = TRUNCATE(i64 x)
17205 // -- becomes --
17206 // v16i8 b = BITCAST (v2i64 val)
17207 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
17208 //
17209 // Note: We only run this optimization after type legalization (which often
17210 // creates this pattern) and before operation legalization after which
17211 // we need to be more careful about the vector instructions that we generate.
17212 if (LegalTypes && !LegalOperations && VT.isScalarInteger() && VT != MVT::i1 &&
17213 N0->hasOneUse()) {
17214 EVT TrTy = N->getValueType(0);
17215 SDValue Src = N0;
17216
17217 // Check for cases where we shift down an upper element before truncation.
17218 int EltOffset = 0;
17219 if (Src.getOpcode() == ISD::SRL && Src.getOperand(0)->hasOneUse()) {
17220 if (auto ShAmt = DAG.getValidShiftAmount(Src)) {
17221 if ((*ShAmt % TrTy.getSizeInBits()) == 0) {
17222 Src = Src.getOperand(0);
17223 EltOffset = *ShAmt / TrTy.getSizeInBits();
17224 }
17225 }
17226 }
17227
17228 if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17229 EVT VecTy = Src.getOperand(0).getValueType();
17230 EVT ExTy = Src.getValueType();
17231
17232 auto EltCnt = VecTy.getVectorElementCount();
17233 unsigned SizeRatio = ExTy.getSizeInBits() / TrTy.getSizeInBits();
17234 auto NewEltCnt = EltCnt * SizeRatio;
17235
17236 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt);
17237 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
17238
17239 SDValue EltNo = Src->getOperand(1);
17240 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
17241 int Elt = EltNo->getAsZExtVal();
17242 int Index = isLE ? (Elt * SizeRatio + EltOffset)
17243 : (Elt * SizeRatio + (SizeRatio - 1) - EltOffset);
17244 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
17245 DAG.getBitcast(NVT, Src.getOperand(0)),
17246 DAG.getVectorIdxConstant(Index, DL));
17247 }
17248 }
17249 }
17250
17251 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
17252 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse() &&
17253 TLI.isTruncateFree(SrcVT, VT)) {
17254 if (!LegalOperations ||
17255 (TLI.isOperationLegal(ISD::SELECT, SrcVT) &&
17256 TLI.isNarrowingProfitable(N0.getNode(), SrcVT, VT))) {
17257 SDLoc SL(N0);
17258 SDValue Cond = N0.getOperand(0);
17259 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
17260 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
17261 return DAG.getNode(ISD::SELECT, DL, VT, Cond, TruncOp0, TruncOp1);
17262 }
17263 }
17264
17265 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
17266 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
17267 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
17268 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
17269 SDValue Amt = N0.getOperand(1);
17270 KnownBits Known = DAG.computeKnownBits(Amt);
17271 unsigned Size = VT.getScalarSizeInBits();
17272 if (Known.countMaxActiveBits() <= Log2_32(Size)) {
17273 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
17274 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17275 if (AmtVT != Amt.getValueType()) {
17276 Amt = DAG.getZExtOrTrunc(Amt, DL, AmtVT);
17277 AddToWorklist(Amt.getNode());
17278 }
17279 return DAG.getNode(ISD::SHL, DL, VT, Trunc, Amt);
17280 }
17281 }
17282
17283 if (SDValue V = foldSubToUSubSat(VT, N0.getNode(), DL))
17284 return V;
17285
17286 if (SDValue ABD = foldABSToABD(N, DL))
17287 return ABD;
17288
17289 // Attempt to pre-truncate BUILD_VECTOR sources.
17290 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
17291 N0.hasOneUse() &&
17292 // Avoid creating illegal types if running after type legalizer.
17293 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
17294 if (TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()))
17295 return DAG.UnrollVectorOp(N);
17296
17297 // trunc(build_vector(ext(x), ext(x)) -> build_vector(x,x)
17298 if (SDValue SplatVal = DAG.getSplatValue(N0)) {
17299 if (ISD::isExtOpcode(SplatVal.getOpcode()) &&
17300 SrcVT.getScalarType() == SplatVal.getValueType())
17301 return DAG.UnrollVectorOp(N);
17302 }
17303 }
17304
17305 // trunc (splat_vector x) -> splat_vector (trunc x)
17306 if (N0.getOpcode() == ISD::SPLAT_VECTOR &&
17307 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType())) &&
17308 (!LegalOperations || TLI.isOperationLegal(ISD::SPLAT_VECTOR, VT))) {
17309 EVT SVT = VT.getScalarType();
17310 return DAG.getSplatVector(
17311 VT, DL, DAG.getNode(ISD::TRUNCATE, DL, SVT, N0->getOperand(0)));
17312 }
17313
17314 // Fold a series of buildvector, bitcast, and truncate if possible.
17315 // For example fold
17316 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
17317 // (2xi32 (buildvector x, y)).
17318 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
17319 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
17321 N0.getOperand(0).hasOneUse()) {
17322 SDValue BuildVect = N0.getOperand(0);
17323 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
17324 EVT TruncVecEltTy = VT.getVectorElementType();
17325
17326 // Check that the element types match.
17327 if (BuildVectEltTy == TruncVecEltTy) {
17328 // Now we only need to compute the offset of the truncated elements.
17329 unsigned BuildVecNumElts = BuildVect.getNumOperands();
17330 unsigned TruncVecNumElts = VT.getVectorNumElements();
17331 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
17332 unsigned FirstElt = isLE ? 0 : (TruncEltOffset - 1);
17333
17334 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
17335 "Invalid number of elements");
17336
17338 for (unsigned i = FirstElt, e = BuildVecNumElts; i < e;
17339 i += TruncEltOffset)
17340 Opnds.push_back(BuildVect.getOperand(i));
17341
17342 return DAG.getBuildVector(VT, DL, Opnds);
17343 }
17344 }
17345
17346 // fold (truncate (load x)) -> (smaller load x)
17347 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
17348 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
17349 if (SDValue Reduced = reduceLoadWidth(N))
17350 return Reduced;
17351
17352 // Handle the case where the truncated result is at least as wide as the
17353 // loaded type.
17354 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
17355 auto *LN0 = cast<LoadSDNode>(N0);
17356 if (LN0->isSimple() && LN0->getMemoryVT().bitsLE(VT)) {
17357 SDValue NewLoad = DAG.getExtLoad(
17358 LN0->getExtensionType(), SDLoc(LN0), VT, LN0->getChain(),
17359 LN0->getBasePtr(), LN0->getMemoryVT(), LN0->getMemOperand());
17360 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
17361 return NewLoad;
17362 }
17363 }
17364 }
17365
17366 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
17367 // where ... are all 'undef'.
17368 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
17370 SDValue V;
17371 unsigned Idx = 0;
17372 unsigned NumDefs = 0;
17373
17374 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
17375 SDValue X = N0.getOperand(i);
17376 if (!X.isUndef()) {
17377 V = X;
17378 Idx = i;
17379 NumDefs++;
17380 }
17381 // Stop if more than one members are non-undef.
17382 if (NumDefs > 1)
17383 break;
17384
17387 X.getValueType().getVectorElementCount()));
17388 }
17389
17390 if (NumDefs == 0)
17391 return DAG.getUNDEF(VT);
17392
17393 if (NumDefs == 1) {
17394 assert(V.getNode() && "The single defined operand is empty!");
17396 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
17397 if (i != Idx) {
17398 Opnds.push_back(DAG.getUNDEF(VTs[i]));
17399 continue;
17400 }
17401 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
17402 AddToWorklist(NV.getNode());
17403 Opnds.push_back(NV);
17404 }
17405 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
17406 }
17407 }
17408
17409 // Fold truncate of a bitcast of a vector to an extract of the low vector
17410 // element.
17411 //
17412 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
17413 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
17414 SDValue VecSrc = N0.getOperand(0);
17415 EVT VecSrcVT = VecSrc.getValueType();
17416 if (VecSrcVT.isVectorOf(VT) &&
17417 (!LegalOperations ||
17418 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
17419 unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
17420 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VecSrc,
17421 DAG.getVectorIdxConstant(Idx, DL));
17422 }
17423 }
17424
17425 // Simplify the operands using demanded-bits information.
17427 return SDValue(N, 0);
17428
17429 // fold (truncate (extract_subvector(ext x))) ->
17430 // (extract_subvector x)
17431 // TODO: This can be generalized to cover cases where the truncate and extract
17432 // do not fully cancel each other out.
17433 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
17434 SDValue N00 = N0.getOperand(0);
17435 if (N00.getOpcode() == ISD::SIGN_EXTEND ||
17436 N00.getOpcode() == ISD::ZERO_EXTEND ||
17437 N00.getOpcode() == ISD::ANY_EXTEND) {
17438 if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
17440 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
17441 N00.getOperand(0), N0.getOperand(1));
17442 }
17443 }
17444
17445 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
17446 return NewVSel;
17447
17448 // Narrow a suitable binary operation with a non-opaque constant operand by
17449 // moving it ahead of the truncate. This is limited to pre-legalization
17450 // because targets may prefer a wider type during later combines and invert
17451 // this transform.
17452 switch (N0.getOpcode()) {
17453 case ISD::ADD:
17454 case ISD::SUB:
17455 case ISD::MUL:
17456 case ISD::AND:
17457 case ISD::OR:
17458 case ISD::XOR:
17459 if (!LegalOperations && N0.hasOneUse() &&
17460 (N0.getOperand(0) == N0.getOperand(1) ||
17462 isConstantOrConstantVector(N0.getOperand(1), true))) {
17463 // TODO: We already restricted this to pre-legalization, but for vectors
17464 // we are extra cautious to not create an unsupported operation.
17465 // Target-specific changes are likely needed to avoid regressions here.
17466 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
17467 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17468 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
17469 SDNodeFlags Flags;
17470 // Propagate nuw for sub.
17471 if (N0->getOpcode() == ISD::SUB && N0->getFlags().hasNoUnsignedWrap() &&
17473 N0->getOperand(0),
17475 VT.getScalarSizeInBits())))
17476 Flags.setNoUnsignedWrap(true);
17477 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR, Flags);
17478 }
17479 }
17480 break;
17481 case ISD::ADDE:
17482 case ISD::UADDO_CARRY:
17483 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
17484 // (trunc uaddo_carry(X, Y, Carry)) ->
17485 // (uaddo_carry trunc(X), trunc(Y), Carry)
17486 // When the adde's carry is not used.
17487 // We only do for uaddo_carry before legalize operation
17488 if (((!LegalOperations && N0.getOpcode() == ISD::UADDO_CARRY) ||
17489 TLI.isOperationLegal(N0.getOpcode(), VT)) &&
17490 N0.hasOneUse() && !N0->hasAnyUseOfValue(1)) {
17491 SDValue X = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17492 SDValue Y = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
17493 SDVTList VTs = DAG.getVTList(VT, N0->getValueType(1));
17494 return DAG.getNode(N0.getOpcode(), DL, VTs, X, Y, N0.getOperand(2));
17495 }
17496 break;
17497 case ISD::USUBSAT:
17498 // Truncate the USUBSAT only if LHS is a known zero-extension, its not
17499 // enough to know that the upper bits are zero we must ensure that we don't
17500 // introduce an extra truncate.
17501 if (!LegalOperations && N0.hasOneUse() &&
17504 VT.getScalarSizeInBits() &&
17505 hasOperation(N0.getOpcode(), VT)) {
17506 return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1),
17507 DAG, DL);
17508 }
17509 break;
17510 case ISD::AVGCEILS:
17511 case ISD::AVGCEILU:
17512 // trunc (avgceilu (sext (x), sext (y))) -> avgceils(x, y)
17513 // trunc (avgceils (zext (x), zext (y))) -> avgceilu(x, y)
17514 if (N0.hasOneUse()) {
17515 SDValue Op0 = N0.getOperand(0);
17516 SDValue Op1 = N0.getOperand(1);
17517 if (N0.getOpcode() == ISD::AVGCEILU) {
17519 Op0.getOpcode() == ISD::SIGN_EXTEND &&
17520 Op1.getOpcode() == ISD::SIGN_EXTEND &&
17521 Op0.getOperand(0).getValueType() == VT &&
17522 Op1.getOperand(0).getValueType() == VT)
17523 return DAG.getNode(ISD::AVGCEILS, DL, VT, Op0.getOperand(0),
17524 Op1.getOperand(0));
17525 } else {
17527 Op0.getOpcode() == ISD::ZERO_EXTEND &&
17528 Op1.getOpcode() == ISD::ZERO_EXTEND &&
17529 Op0.getOperand(0).getValueType() == VT &&
17530 Op1.getOperand(0).getValueType() == VT)
17531 return DAG.getNode(ISD::AVGCEILU, DL, VT, Op0.getOperand(0),
17532 Op1.getOperand(0));
17533 }
17534 }
17535 [[fallthrough]];
17536 case ISD::AVGFLOORS:
17537 case ISD::AVGFLOORU:
17538 case ISD::ABDS:
17539 case ISD::ABDU:
17540 // (trunc (avg a, b)) -> (avg (trunc a), (trunc b))
17541 // (trunc (abdu/abds a, b)) -> (abdu/abds (trunc a), (trunc b))
17542 if (!LegalOperations && N0.hasOneUse() &&
17543 TLI.isOperationLegal(N0.getOpcode(), VT)) {
17544 EVT TruncVT = VT;
17545 unsigned SrcBits = SrcVT.getScalarSizeInBits();
17546 unsigned TruncBits = TruncVT.getScalarSizeInBits();
17547
17548 SDValue A = N0.getOperand(0);
17549 SDValue B = N0.getOperand(1);
17550 bool CanFold = false;
17551
17552 if (N0.getOpcode() == ISD::AVGFLOORU || N0.getOpcode() == ISD::AVGCEILU ||
17553 N0.getOpcode() == ISD::ABDU) {
17554 APInt UpperBits = APInt::getBitsSetFrom(SrcBits, TruncBits);
17555 CanFold = DAG.MaskedValueIsZero(B, UpperBits) &&
17556 DAG.MaskedValueIsZero(A, UpperBits);
17557 } else {
17558 unsigned NeededBits = SrcBits - TruncBits;
17559 CanFold = DAG.ComputeNumSignBits(B) > NeededBits &&
17560 DAG.ComputeNumSignBits(A) > NeededBits;
17561 }
17562
17563 if (CanFold) {
17564 SDValue NewA = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, A);
17565 SDValue NewB = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, B);
17566 return DAG.getNode(N0.getOpcode(), DL, TruncVT, NewA, NewB);
17567 }
17568 }
17569 break;
17570 }
17571
17572 return SDValue();
17573}
17574
17575static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
17576 SDValue Elt = N->getOperand(i);
17577 if (Elt.getOpcode() != ISD::MERGE_VALUES)
17578 return Elt.getNode();
17579 return Elt.getOperand(Elt.getResNo()).getNode();
17580}
17581
17582/// build_pair (load, load) -> load
17583/// if load locations are consecutive.
17584SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
17585 assert(N->getOpcode() == ISD::BUILD_PAIR);
17586
17587 auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
17588 auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
17589
17590 // A BUILD_PAIR is always having the least significant part in elt 0 and the
17591 // most significant part in elt 1. So when combining into one large load, we
17592 // need to consider the endianness.
17593 if (DAG.getDataLayout().isBigEndian())
17594 std::swap(LD1, LD2);
17595
17596 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) ||
17597 !LD1->hasOneUse() || !LD2->hasOneUse() ||
17598 LD1->getAddressSpace() != LD2->getAddressSpace())
17599 return SDValue();
17600
17601 unsigned LD1Fast = 0;
17602 EVT LD1VT = LD1->getValueType(0);
17603 unsigned LD1Bytes = LD1VT.getStoreSize();
17604 if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
17605 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) &&
17606 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
17607 *LD1->getMemOperand(), &LD1Fast) && LD1Fast)
17608 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
17609 LD1->getPointerInfo(), LD1->getAlign());
17610
17611 return SDValue();
17612}
17613
17614static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
17615 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
17616 // and Lo parts; on big-endian machines it doesn't.
17617 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
17618}
17619
17620SDValue DAGCombiner::foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
17621 const TargetLowering &TLI) {
17622 // If this is not a bitcast to an FP type or if the target doesn't have
17623 // IEEE754-compliant FP logic, we're done.
17624 EVT VT = N->getValueType(0);
17625 SDValue N0 = N->getOperand(0);
17626 EVT SourceVT = N0.getValueType();
17627
17628 if (!VT.isFloatingPoint())
17629 return SDValue();
17630
17631 // TODO: Handle cases where the integer constant is a different scalar
17632 // bitwidth to the FP.
17633 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
17634 return SDValue();
17635
17636 unsigned FPOpcode;
17637 APInt SignMask;
17638 switch (N0.getOpcode()) {
17639 case ISD::AND:
17640 FPOpcode = ISD::FABS;
17641 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
17642 break;
17643 case ISD::XOR:
17644 FPOpcode = ISD::FNEG;
17645 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
17646 break;
17647 case ISD::OR:
17648 FPOpcode = ISD::FABS;
17649 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
17650 break;
17651 default:
17652 return SDValue();
17653 }
17654
17655 if (LegalOperations && !TLI.isOperationLegal(FPOpcode, VT))
17656 return SDValue();
17657
17658 // This needs to be the inverse of logic in foldSignChangeInBitcast.
17659 // FIXME: I don't think looking for bitcast intrinsically makes sense, but
17660 // removing this would require more changes.
17661 auto IsBitCastOrFree = [&TLI, FPOpcode](SDValue Op, EVT VT) {
17662 if (sd_match(Op, m_BitCast(m_SpecificVT(VT))))
17663 return true;
17664
17665 return FPOpcode == ISD::FABS ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT);
17666 };
17667
17668 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
17669 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
17670 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
17671 // fneg (fabs X)
17672 SDValue LogicOp0 = N0.getOperand(0);
17673 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
17674 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
17675 IsBitCastOrFree(LogicOp0, VT)) {
17676 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, LogicOp0);
17677 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, CastOp0);
17678 NumFPLogicOpsConv++;
17679 if (N0.getOpcode() == ISD::OR)
17680 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
17681 return FPOp;
17682 }
17683
17684 return SDValue();
17685}
17686
17687SDValue DAGCombiner::visitBITCAST(SDNode *N) {
17688 SDValue N0 = N->getOperand(0);
17689 EVT VT = N->getValueType(0);
17690
17691 if (N0.isUndef())
17692 return DAG.getUNDEF(VT);
17693
17694 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
17695 // Only do this before legalize types, unless both types are integer and the
17696 // scalar type is legal. Only do this before legalize ops, since the target
17697 // maybe depending on the bitcast.
17698 // First check to see if this is all constant.
17699 // TODO: Support FP bitcasts after legalize types.
17700 if (VT.isVector() &&
17701 (!LegalTypes ||
17702 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
17703 TLI.isTypeLegal(VT.getVectorElementType()))) &&
17704 N0.getOpcode() == ISD::BUILD_VECTOR && N0->hasOneUse() &&
17705 cast<BuildVectorSDNode>(N0)->isConstant())
17706 return DAG.FoldConstantBuildVector(cast<BuildVectorSDNode>(N0), SDLoc(N),
17708
17709 // If the input is a constant, let getNode fold it.
17710 if (isIntOrFPConstant(N0)) {
17711 // If we can't allow illegal operations, we need to check that this is just
17712 // a fp -> int or int -> conversion and that the resulting operation will
17713 // be legal.
17714 if (!LegalOperations ||
17715 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
17717 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
17718 TLI.isOperationLegal(ISD::Constant, VT))) {
17719 SDValue C = DAG.getBitcast(VT, N0);
17720 if (C.getNode() != N)
17721 return C;
17722 }
17723 }
17724
17725 // (conv (conv x, t1), t2) -> (conv x, t2)
17726 if (N0.getOpcode() == ISD::BITCAST)
17727 return DAG.getBitcast(VT, N0.getOperand(0));
17728
17729 // fold (conv (logicop (conv x), (c))) -> (logicop x, (conv c))
17730 // iff the current bitwise logicop type isn't legal
17731 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && VT.isInteger() &&
17732 !TLI.isTypeLegal(N0.getOperand(0).getValueType())) {
17733 auto IsFreeBitcast = [VT](SDValue V) {
17734 return (V.getOpcode() == ISD::BITCAST &&
17735 V.getOperand(0).getValueType() == VT) ||
17737 V->hasOneUse());
17738 };
17739 if (IsFreeBitcast(N0.getOperand(0)) && IsFreeBitcast(N0.getOperand(1)))
17740 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
17741 DAG.getBitcast(VT, N0.getOperand(0)),
17742 DAG.getBitcast(VT, N0.getOperand(1)));
17743 }
17744
17745 // fold (conv (load x)) -> (load (conv*)x)
17746 // fold (conv (freeze (load x))) -> (freeze (load (conv*)x))
17747 // If the resultant load doesn't need a higher alignment than the original!
17748 auto CastLoad = [this, &VT](SDValue N0, const SDLoc &DL) {
17749 // Peek through scalar_to_vector if the scalar is same size as VT - often a
17750 // leftover from legalization.
17751 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && N0.hasOneUse() &&
17753 N0 = N0.getOperand(0);
17754 if (N0.getOpcode() == ISD::AssertNoFPClass)
17755 N0 = N0.getOperand(0);
17756 if (!ISD::isNormalLoad(N0.getNode()) || !N0.hasOneUse())
17757 return SDValue();
17758
17759 // Do not remove the cast if the types differ in endian layout.
17762 return SDValue();
17763
17764 // If the load is volatile, we only want to change the load type if the
17765 // resulting load is legal. Otherwise we might increase the number of
17766 // memory accesses. We don't care if the original type was legal or not
17767 // as we assume software couldn't rely on the number of accesses of an
17768 // illegal type.
17769 auto *LN0 = cast<LoadSDNode>(N0);
17770 if ((LegalOperations || !LN0->isSimple()) &&
17771 !TLI.isOperationLegal(ISD::LOAD, VT))
17772 return SDValue();
17773
17774 if (!TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
17775 *LN0->getMemOperand()))
17776 return SDValue();
17777
17778 // If the range metadata type does not match the new memory
17779 // operation type, remove the range metadata.
17780 if (const MDNode *MD = LN0->getRanges()) {
17781 ConstantInt *Lower = mdconst::extract<ConstantInt>(MD->getOperand(0));
17782 if (Lower->getBitWidth() != VT.getScalarSizeInBits() || !VT.isInteger()) {
17783 LN0->getMemOperand()->clearRanges();
17784 }
17785 }
17786 SDValue Load = DAG.getLoad(VT, DL, LN0->getChain(), LN0->getBasePtr(),
17787 LN0->getMemOperand());
17788 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
17789 return Load;
17790 };
17791
17792 if (SDValue NewLd = CastLoad(N0, SDLoc(N)))
17793 return NewLd;
17794
17795 if (N0.getOpcode() == ISD::FREEZE && N0.hasOneUse())
17796 if (SDValue NewLd = CastLoad(N0.getOperand(0), SDLoc(N)))
17797 return DAG.getFreeze(NewLd);
17798
17799 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
17800 return V;
17801
17802 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
17803 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
17804 //
17805 // For ppc_fp128:
17806 // fold (bitcast (fneg x)) ->
17807 // flipbit = signbit
17808 // (xor (bitcast x) (build_pair flipbit, flipbit))
17809 //
17810 // fold (bitcast (fabs x)) ->
17811 // flipbit = (and (extract_element (bitcast x), 0), signbit)
17812 // (xor (bitcast x) (build_pair flipbit, flipbit))
17813 // This often reduces constant pool loads.
17814 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
17815 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
17816 N0->hasOneUse() && VT.isInteger() && !VT.isVector() &&
17817 !N0.getValueType().isVector()) {
17818 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
17819 AddToWorklist(NewConv.getNode());
17820
17821 SDLoc DL(N);
17822 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
17823 assert(VT.getSizeInBits() == 128);
17824 SDValue SignBit = DAG.getConstant(
17825 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
17826 SDValue FlipBit;
17827 if (N0.getOpcode() == ISD::FNEG) {
17828 FlipBit = SignBit;
17829 AddToWorklist(FlipBit.getNode());
17830 } else {
17831 assert(N0.getOpcode() == ISD::FABS);
17832 SDValue Hi =
17833 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
17835 SDLoc(NewConv)));
17836 AddToWorklist(Hi.getNode());
17837 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
17838 AddToWorklist(FlipBit.getNode());
17839 }
17840 SDValue FlipBits =
17841 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
17842 AddToWorklist(FlipBits.getNode());
17843 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
17844 }
17845 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
17846 if (N0.getOpcode() == ISD::FNEG)
17847 return DAG.getNode(ISD::XOR, DL, VT,
17848 NewConv, DAG.getConstant(SignBit, DL, VT));
17849 assert(N0.getOpcode() == ISD::FABS);
17850 return DAG.getNode(ISD::AND, DL, VT,
17851 NewConv, DAG.getConstant(~SignBit, DL, VT));
17852 }
17853
17854 // fold (bitconvert (fcopysign cst, x)) ->
17855 // (or (and (bitconvert x), sign), (and cst, (not sign)))
17856 // Note that we don't handle (copysign x, cst) because this can always be
17857 // folded to an fneg or fabs.
17858 //
17859 // For ppc_fp128:
17860 // fold (bitcast (fcopysign cst, x)) ->
17861 // flipbit = (and (extract_element
17862 // (xor (bitcast cst), (bitcast x)), 0),
17863 // signbit)
17864 // (xor (bitcast cst) (build_pair flipbit, flipbit))
17865 if (N0.getOpcode() == ISD::FCOPYSIGN && N0->hasOneUse() &&
17867 !VT.isVector()) {
17868 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
17869 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
17870 if (isTypeLegal(IntXVT)) {
17871 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
17872 AddToWorklist(X.getNode());
17873
17874 // If X has a different width than the result/lhs, sext it or truncate it.
17875 unsigned VTWidth = VT.getSizeInBits();
17876 if (OrigXWidth < VTWidth) {
17877 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
17878 AddToWorklist(X.getNode());
17879 } else if (OrigXWidth > VTWidth) {
17880 // To get the sign bit in the right place, we have to shift it right
17881 // before truncating.
17882 SDLoc DL(X);
17883 X = DAG.getNode(ISD::SRL, DL,
17884 X.getValueType(), X,
17885 DAG.getConstant(OrigXWidth-VTWidth, DL,
17886 X.getValueType()));
17887 AddToWorklist(X.getNode());
17888 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
17889 AddToWorklist(X.getNode());
17890 }
17891
17892 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
17893 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
17894 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
17895 AddToWorklist(Cst.getNode());
17896 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
17897 AddToWorklist(X.getNode());
17898 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
17899 AddToWorklist(XorResult.getNode());
17900 SDValue XorResult64 = DAG.getNode(
17901 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
17903 SDLoc(XorResult)));
17904 AddToWorklist(XorResult64.getNode());
17905 SDValue FlipBit =
17906 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
17907 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
17908 AddToWorklist(FlipBit.getNode());
17909 SDValue FlipBits =
17910 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
17911 AddToWorklist(FlipBits.getNode());
17912 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
17913 }
17914 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
17915 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
17916 X, DAG.getConstant(SignBit, SDLoc(X), VT));
17917 AddToWorklist(X.getNode());
17918
17919 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
17920 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
17921 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
17922 AddToWorklist(Cst.getNode());
17923
17924 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
17925 }
17926 }
17927
17928 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
17929 if (N0.getOpcode() == ISD::BUILD_PAIR)
17930 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
17931 return CombineLD;
17932
17933 // int_vt (bitcast (vec_vt (scalar_to_vector elt_vt:x)))
17934 // => int_vt (any_extend elt_vt:x)
17935 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isScalarInteger()) {
17936 SDValue SrcScalar = N0.getOperand(0);
17937 if (SrcScalar.getValueType().isScalarInteger())
17938 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SrcScalar);
17939 }
17940
17941 // Remove double bitcasts from shuffles - this is often a legacy of
17942 // XformToShuffleWithZero being used to combine bitmaskings (of
17943 // float vectors bitcast to integer vectors) into shuffles.
17944 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
17945 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
17946 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
17949 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
17950
17951 // If operands are a bitcast, peek through if it casts the original VT.
17952 // If operands are a constant, just bitcast back to original VT.
17953 auto PeekThroughBitcast = [&](SDValue Op) {
17954 if (Op.getOpcode() == ISD::BITCAST &&
17955 Op.getOperand(0).getValueType() == VT)
17956 return SDValue(Op.getOperand(0));
17957 if (Op.isUndef() || isAnyConstantBuildVector(Op))
17958 return DAG.getBitcast(VT, Op);
17959 return SDValue();
17960 };
17961
17962 // FIXME: If either input vector is bitcast, try to convert the shuffle to
17963 // the result type of this bitcast. This would eliminate at least one
17964 // bitcast. See the transform in InstCombine.
17965 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
17966 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
17967 if (!(SV0 && SV1))
17968 return SDValue();
17969
17970 int MaskScale =
17972 SmallVector<int, 8> NewMask;
17973 for (int M : SVN->getMask())
17974 for (int i = 0; i != MaskScale; ++i)
17975 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
17976
17977 SDValue LegalShuffle =
17978 TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
17979 if (LegalShuffle)
17980 return LegalShuffle;
17981 }
17982
17983 return SDValue();
17984}
17985
17986SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
17987 EVT VT = N->getValueType(0);
17988 return CombineConsecutiveLoads(N, VT);
17989}
17990
17991SDValue DAGCombiner::visitFREEZE(SDNode *N) {
17992 SDValue N0 = N->getOperand(0);
17993
17995 return N0;
17996
17997 // If we have frozen and unfrozen users of N0, update so everything uses N.
17998 if (!N0.isUndef() && !N0.hasOneUse()) {
17999 SDValue FrozenN0(N, 0);
18000 // Unfreeze all (possibly nested) uses of N to avoid double deleting N from
18001 // the CSE map.
18002 while (!N->use_empty())
18003 DAG.ReplaceAllUsesOfValueWith(FrozenN0, N0);
18004 DAG.ReplaceAllUsesOfValueWith(N0, FrozenN0);
18005 // ReplaceAllUsesOfValueWith will have also updated the use in N, thus
18006 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18007 assert(N->getOperand(0) == FrozenN0 && "Expected cycle in DAG");
18008 DAG.UpdateNodeOperands(N, N0);
18009 // Revisit the node.
18010 AddToWorklist(N);
18011 return FrozenN0;
18012 }
18013
18014 // We currently avoid folding freeze over SRA/SRL, due to the problems seen
18015 // with (freeze (assert ext)) blocking simplifications of SRA/SRL. See for
18016 // example https://reviews.llvm.org/D136529#4120959.
18017 if (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)
18018 return SDValue();
18019
18020 // Fold freeze(op(x, ...)) -> op(freeze(x), ...).
18021 // Try to push freeze through instructions that propagate but don't produce
18022 // poison as far as possible. If an operand of freeze follows three
18023 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
18024 // guaranteed-non-poison operands (or is a BUILD_VECTOR or similar) then push
18025 // the freeze through to the operands that are not guaranteed non-poison.
18026 // NOTE: we will strip poison-generating flags, so ignore them here.
18028 /*ConsiderFlags*/ false) ||
18029 N0->getNumValues() != 1 || !N0->hasOneUse())
18030 return SDValue();
18031
18032 // TOOD: we should always allow multiple operands, however this increases the
18033 // likelihood of infinite loops due to the ReplaceAllUsesOfValueWith call
18034 // below causing later nodes that share frozen operands to fold again and no
18035 // longer being able to confirm other operands are not poison due to recursion
18036 // depth limits on isGuaranteedNotToBeUndefOrPoison.
18037 bool AllowMultipleMaybePoisonOperands =
18038 N0.getOpcode() == ISD::SELECT_CC || N0.getOpcode() == ISD::SETCC ||
18039 N0.getOpcode() == ISD::BUILD_VECTOR ||
18041 N0.getOpcode() == ISD::BUILD_PAIR ||
18044
18045 // Avoid turning a BUILD_VECTOR that can be recognized as "all zeros", "all
18046 // ones" or "constant" into something that depends on FrozenUndef. We can
18047 // instead pick undef values to keep those properties, while at the same time
18048 // folding away the freeze.
18049 // If we implement a more general solution for folding away freeze(undef) in
18050 // the future, then this special handling can be removed.
18051 if (N0.getOpcode() == ISD::BUILD_VECTOR) {
18052 SDLoc DL(N0);
18053 EVT VT = N0.getValueType();
18055 return DAG.getAllOnesConstant(DL, VT);
18058 for (const SDValue &Op : N0->op_values())
18059 NewVecC.push_back(
18060 Op.isUndef() ? DAG.getConstant(0, DL, Op.getValueType()) : Op);
18061 return DAG.getBuildVector(VT, DL, NewVecC);
18062 }
18063 }
18064
18065 SmallSet<SDValue, 8> MaybePoisonOperands;
18066 SmallVector<unsigned, 8> MaybePoisonOperandNumbers;
18067 for (auto [OpNo, Op] : enumerate(N0->ops())) {
18070 continue;
18071 bool HadMaybePoisonOperands = !MaybePoisonOperands.empty();
18072 bool IsNewMaybePoisonOperand = MaybePoisonOperands.insert(Op).second;
18073 if (IsNewMaybePoisonOperand)
18074 MaybePoisonOperandNumbers.push_back(OpNo);
18075 if (!HadMaybePoisonOperands)
18076 continue;
18077 if (IsNewMaybePoisonOperand && !AllowMultipleMaybePoisonOperands) {
18078 // Multiple maybe-poison ops when not allowed - bail out.
18079 return SDValue();
18080 }
18081 }
18082 // NOTE: the whole op may be not guaranteed to not be undef or poison because
18083 // it could create undef or poison due to it's poison-generating flags.
18084 // So not finding any maybe-poison operands is fine.
18085
18086 for (unsigned OpNo : MaybePoisonOperandNumbers) {
18087 // N0 can mutate during iteration, so make sure to refetch the maybe poison
18088 // operands via the operand numbers. The typical scenario is that we have
18089 // something like this
18090 // t262: i32 = freeze t181
18091 // t150: i32 = ctlz_zero_poison t262
18092 // t184: i32 = ctlz_zero_poison t181
18093 // t268: i32 = select_cc t181, Constant:i32<0>, t184, t186, setne:ch
18094 // When freezing the t181 operand we get t262 back, and then the
18095 // ReplaceAllUsesOfValueWith call will not only replace t181 by t262, but
18096 // also recursively replace t184 by t150.
18097 SDValue MaybePoisonOperand = N->getOperand(0).getOperand(OpNo);
18098 // Don't replace every single UNDEF everywhere with frozen UNDEF, though.
18099 if (MaybePoisonOperand.isUndef())
18100 continue;
18101 // First, freeze each offending operand.
18102 SDValue FrozenMaybePoisonOperand = DAG.getFreeze(MaybePoisonOperand);
18103 // Then, change all other uses of unfrozen operand to use frozen operand.
18104 DAG.ReplaceAllUsesOfValueWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
18105 if (FrozenMaybePoisonOperand.getOpcode() == ISD::FREEZE &&
18106 FrozenMaybePoisonOperand.getOperand(0) == FrozenMaybePoisonOperand) {
18107 // But, that also updated the use in the freeze we just created, thus
18108 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18109 DAG.UpdateNodeOperands(FrozenMaybePoisonOperand.getNode(),
18110 MaybePoisonOperand);
18111 }
18112
18113 // This node has been merged with another.
18114 if (N->getOpcode() == ISD::DELETED_NODE)
18115 return SDValue(N, 0);
18116 }
18117
18118 assert(N->getOpcode() != ISD::DELETED_NODE && "Node was deleted!");
18119
18120 // The whole node may have been updated, so the value we were holding
18121 // may no longer be valid. Re-fetch the operand we're `freeze`ing.
18122 N0 = N->getOperand(0);
18123
18124 // Finally, recreate the node, it's operands were updated to use
18125 // frozen operands, so we just need to use it's "original" operands.
18127 // TODO: ISD::UNDEF and ISD::POISON should get separate handling, but best
18128 // leave for a future patch.
18129 for (SDValue &Op : Ops) {
18130 if (Op.isUndef())
18131 Op = DAG.getFreeze(Op);
18132 }
18133
18134 SDLoc DL(N0);
18135
18136 // Special case handling for ShuffleVectorSDNode nodes.
18137 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N0))
18138 return DAG.getVectorShuffle(N0.getValueType(), DL, Ops[0], Ops[1],
18139 SVN->getMask());
18140
18141 // NOTE: this strips poison generating flags.
18142 // Folding freeze(op(x, ...)) -> op(freeze(x), ...) does not require nnan,
18143 // ninf, nsz, or fast.
18144 // However, contract, reassoc, afn, and arcp should be preserved,
18145 // as these fast-math flags do not introduce poison values.
18146 SDNodeFlags SrcFlags = N0->getFlags();
18147 SDNodeFlags SafeFlags;
18148 SafeFlags.setAllowContract(SrcFlags.hasAllowContract());
18149 SafeFlags.setAllowReassociation(SrcFlags.hasAllowReassociation());
18150 SafeFlags.setApproximateFuncs(SrcFlags.hasApproximateFuncs());
18151 SafeFlags.setAllowReciprocal(SrcFlags.hasAllowReciprocal());
18152 return DAG.getNode(N0.getOpcode(), DL, N0->getVTList(), Ops, SafeFlags);
18153}
18154
18155// Returns true if floating point contraction is allowed on the FMUL-SDValue
18156// `N`
18158 assert(N.getOpcode() == ISD::FMUL);
18159
18160 return Options.AllowFPOpFusion == FPOpFusion::Fast ||
18161 N->getFlags().hasAllowContract();
18162}
18163
18164/// Try to perform FMA combining on a given FADD node.
18165SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
18166 SDValue N0 = N->getOperand(0);
18167 SDValue N1 = N->getOperand(1);
18168 EVT VT = N->getValueType(0);
18169 SDLoc SL(N);
18170 const TargetOptions &Options = DAG.getTarget().Options;
18171
18172 // Floating-point multiply-add with intermediate rounding.
18173 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18174
18175 // Floating-point multiply-add without intermediate rounding.
18176 bool HasFMA =
18177 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18179
18180 // No valid opcode, do not combine.
18181 if (!HasFMAD && !HasFMA)
18182 return SDValue();
18183
18184 bool AllowFusionGlobally =
18185 Options.AllowFPOpFusion == FPOpFusion::Fast || HasFMAD;
18186 // If the addition is not contractable, do not combine.
18187 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18188 return SDValue();
18189
18190 // Folding fadd (fmul x, y), (fmul x, y) -> fma x, y, (fmul x, y) is never
18191 // beneficial. It does not reduce latency. It increases register pressure. It
18192 // replaces an fadd with an fma which is a more complex instruction, so is
18193 // likely to have a larger encoding, use more functional units, etc.
18194 if (N0 == N1)
18195 return SDValue();
18196
18197 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18198 return SDValue();
18199
18200 // Always prefer FMAD to FMA for precision.
18201 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18203
18204 auto isFusedOp = [&](SDValue N) {
18205 unsigned Opcode = N.getOpcode();
18206 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
18207 };
18208
18209 // Is the node an FMUL and contractable either due to global flags or
18210 // SDNodeFlags.
18211 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18212 if (N.getOpcode() != ISD::FMUL)
18213 return false;
18214 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18215 };
18216 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
18217 // prefer to fold the multiply with fewer uses.
18219 if (N0->use_size() > N1->use_size())
18220 std::swap(N0, N1);
18221 }
18222
18223 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
18224 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
18225 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
18226 N0.getOperand(1), N1);
18227 }
18228
18229 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
18230 // Note: Commutes FADD operands.
18231 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
18232 return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0),
18233 N1.getOperand(1), N0);
18234 }
18235
18236 // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E)
18237 // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E)
18238 // This also works with nested fma instructions:
18239 // fadd (fma A, B, (fma (C, D, (fmul (E, F))))), G -->
18240 // fma A, B, (fma C, D, fma (E, F, G))
18241 // fadd (G, (fma A, B, (fma (C, D, (fmul (E, F)))))) -->
18242 // fma A, B, (fma C, D, fma (E, F, G)).
18243 // This requires reassociation because it changes the order of operations.
18244 bool CanReassociate = N->getFlags().hasAllowReassociation();
18245 if (CanReassociate) {
18246 SDValue FMA, E;
18247 if (isFusedOp(N0) && N0.hasOneUse()) {
18248 FMA = N0;
18249 E = N1;
18250 } else if (isFusedOp(N1) && N1.hasOneUse()) {
18251 FMA = N1;
18252 E = N0;
18253 }
18254
18255 SDValue TmpFMA = FMA;
18256 while (E && isFusedOp(TmpFMA) && TmpFMA.hasOneUse()) {
18257 SDValue FMul = TmpFMA->getOperand(2);
18258 if (FMul.getOpcode() == ISD::FMUL && FMul.hasOneUse()) {
18259 SDValue C = FMul.getOperand(0);
18260 SDValue D = FMul.getOperand(1);
18261 SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E);
18263 // Replacing the inner FMul could cause the outer FMA to be simplified
18264 // away.
18265 return FMA.getOpcode() == ISD::DELETED_NODE ? SDValue(N, 0) : FMA;
18266 }
18267
18268 TmpFMA = TmpFMA->getOperand(2);
18269 }
18270 }
18271
18272 // Look through FP_EXTEND nodes to do more combining.
18273
18274 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
18275 if (N0.getOpcode() == ISD::FP_EXTEND) {
18276 SDValue N00 = N0.getOperand(0);
18277 if (isContractableFMUL(N00) &&
18278 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18279 N00.getValueType())) {
18280 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18281 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18282 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18283 N1);
18284 }
18285 }
18286
18287 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
18288 // Note: Commutes FADD operands.
18289 if (N1.getOpcode() == ISD::FP_EXTEND) {
18290 SDValue N10 = N1.getOperand(0);
18291 if (isContractableFMUL(N10) &&
18292 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18293 N10.getValueType())) {
18294 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18295 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)),
18296 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)),
18297 N0);
18298 }
18299 }
18300
18301 // More folding opportunities when target permits.
18302 if (Aggressive) {
18303 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
18304 // -> (fma x, y, (fma (fpext u), (fpext v), z))
18305 auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18306 SDValue Z) {
18307 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
18308 DAG.getNode(PreferredFusedOpcode, SL, VT,
18309 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18310 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
18311 Z));
18312 };
18313 if (isFusedOp(N0)) {
18314 SDValue N02 = N0.getOperand(2);
18315 if (N02.getOpcode() == ISD::FP_EXTEND) {
18316 SDValue N020 = N02.getOperand(0);
18317 if (isContractableFMUL(N020) &&
18318 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18319 N020.getValueType())) {
18320 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
18321 N020.getOperand(0), N020.getOperand(1),
18322 N1);
18323 }
18324 }
18325 }
18326
18327 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
18328 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
18329 // FIXME: This turns two single-precision and one double-precision
18330 // operation into two double-precision operations, which might not be
18331 // interesting for all targets, especially GPUs.
18332 auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18333 SDValue Z) {
18334 return DAG.getNode(
18335 PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
18336 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
18337 DAG.getNode(PreferredFusedOpcode, SL, VT,
18338 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18339 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z));
18340 };
18341 if (N0.getOpcode() == ISD::FP_EXTEND) {
18342 SDValue N00 = N0.getOperand(0);
18343 if (isFusedOp(N00)) {
18344 SDValue N002 = N00.getOperand(2);
18345 if (isContractableFMUL(N002) &&
18346 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18347 N00.getValueType())) {
18348 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
18349 N002.getOperand(0), N002.getOperand(1),
18350 N1);
18351 }
18352 }
18353 }
18354
18355 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
18356 // -> (fma y, z, (fma (fpext u), (fpext v), x))
18357 if (isFusedOp(N1)) {
18358 SDValue N12 = N1.getOperand(2);
18359 if (N12.getOpcode() == ISD::FP_EXTEND) {
18360 SDValue N120 = N12.getOperand(0);
18361 if (isContractableFMUL(N120) &&
18362 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18363 N120.getValueType())) {
18364 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
18365 N120.getOperand(0), N120.getOperand(1),
18366 N0);
18367 }
18368 }
18369 }
18370
18371 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
18372 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
18373 // FIXME: This turns two single-precision and one double-precision
18374 // operation into two double-precision operations, which might not be
18375 // interesting for all targets, especially GPUs.
18376 if (N1.getOpcode() == ISD::FP_EXTEND) {
18377 SDValue N10 = N1.getOperand(0);
18378 if (isFusedOp(N10)) {
18379 SDValue N102 = N10.getOperand(2);
18380 if (isContractableFMUL(N102) &&
18381 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18382 N10.getValueType())) {
18383 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
18384 N102.getOperand(0), N102.getOperand(1),
18385 N0);
18386 }
18387 }
18388 }
18389 }
18390
18391 return SDValue();
18392}
18393
18394/// Try to perform FMA combining on a given FSUB node.
18395SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
18396 SDValue N0 = N->getOperand(0);
18397 SDValue N1 = N->getOperand(1);
18398 EVT VT = N->getValueType(0);
18399 SDLoc SL(N);
18400
18401 const TargetOptions &Options = DAG.getTarget().Options;
18402 // Floating-point multiply-add with intermediate rounding.
18403 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18404
18405 // Floating-point multiply-add without intermediate rounding.
18406 bool HasFMA =
18407 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18409
18410 // No valid opcode, do not combine.
18411 if (!HasFMAD && !HasFMA)
18412 return SDValue();
18413
18414 const SDNodeFlags Flags = N->getFlags();
18415 bool AllowFusionGlobally =
18416 (Options.AllowFPOpFusion == FPOpFusion::Fast || HasFMAD);
18417
18418 // If the subtraction is not contractable, do not combine.
18419 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18420 return SDValue();
18421
18422 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18423 return SDValue();
18424
18425 // Always prefer FMAD to FMA for precision.
18426 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18428 bool NoSignedZero = Flags.hasNoSignedZeros();
18429
18430 // Is the node an FMUL and contractable either due to global flags or
18431 // SDNodeFlags.
18432 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18433 if (N.getOpcode() != ISD::FMUL)
18434 return false;
18435 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18436 };
18437
18438 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18439 auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
18440 if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
18441 return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
18442 XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z));
18443 }
18444 return SDValue();
18445 };
18446
18447 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18448 // Note: Commutes FSUB operands.
18449 auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
18450 if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
18451 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18452 DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
18453 YZ.getOperand(1), X);
18454 }
18455 return SDValue();
18456 };
18457
18458 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
18459 // prefer to fold the multiply with fewer uses.
18460 if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
18461 (N0->use_size() > N1->use_size())) {
18462 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
18463 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18464 return V;
18465 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
18466 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18467 return V;
18468 } else {
18469 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18470 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18471 return V;
18472 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18473 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18474 return V;
18475 }
18476
18477 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
18478 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
18479 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
18480 SDValue N00 = N0.getOperand(0).getOperand(0);
18481 SDValue N01 = N0.getOperand(0).getOperand(1);
18482 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18483 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
18484 DAG.getNode(ISD::FNEG, SL, VT, N1));
18485 }
18486
18487 // Look through FP_EXTEND nodes to do more combining.
18488
18489 // fold (fsub (fpext (fmul x, y)), z)
18490 // -> (fma (fpext x), (fpext y), (fneg z))
18491 if (N0.getOpcode() == ISD::FP_EXTEND) {
18492 SDValue N00 = N0.getOperand(0);
18493 if (isContractableFMUL(N00) &&
18494 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18495 N00.getValueType())) {
18496 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18497 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18498 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18499 DAG.getNode(ISD::FNEG, SL, VT, N1));
18500 }
18501 }
18502
18503 // fold (fsub x, (fpext (fmul y, z)))
18504 // -> (fma (fneg (fpext y)), (fpext z), x)
18505 // Note: Commutes FSUB operands.
18506 if (N1.getOpcode() == ISD::FP_EXTEND) {
18507 SDValue N10 = N1.getOperand(0);
18508 if (isContractableFMUL(N10) &&
18509 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18510 N10.getValueType())) {
18511 return DAG.getNode(
18512 PreferredFusedOpcode, SL, VT,
18513 DAG.getNode(ISD::FNEG, SL, VT,
18514 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))),
18515 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0);
18516 }
18517 }
18518
18519 // fold (fsub (fpext (fneg (fmul, x, y))), z)
18520 // -> (fneg (fma (fpext x), (fpext y), z))
18521 // Note: This could be removed with appropriate canonicalization of the
18522 // input expression into (fneg (fadd (fpext (fmul, x, y)), z)). However, the
18523 // command line flag -fp-contract=fast and fast-math flag contract prevent
18524 // from implementing the canonicalization in visitFSUB.
18525 if (N0.getOpcode() == ISD::FP_EXTEND) {
18526 SDValue N00 = N0.getOperand(0);
18527 if (N00.getOpcode() == ISD::FNEG) {
18528 SDValue N000 = N00.getOperand(0);
18529 if (isContractableFMUL(N000) &&
18530 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18531 N00.getValueType())) {
18532 return DAG.getNode(
18533 ISD::FNEG, SL, VT,
18534 DAG.getNode(PreferredFusedOpcode, SL, VT,
18535 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
18536 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
18537 N1));
18538 }
18539 }
18540 }
18541
18542 // fold (fsub (fneg (fpext (fmul, x, y))), z)
18543 // -> (fneg (fma (fpext x)), (fpext y), z)
18544 // Note: This could be removed with appropriate canonicalization of the
18545 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
18546 // command line flag -fp-contract=fast and fast-math flag contract prevent
18547 // from implementing the canonicalization in visitFSUB.
18548 if (N0.getOpcode() == ISD::FNEG) {
18549 SDValue N00 = N0.getOperand(0);
18550 if (N00.getOpcode() == ISD::FP_EXTEND) {
18551 SDValue N000 = N00.getOperand(0);
18552 if (isContractableFMUL(N000) &&
18553 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18554 N000.getValueType())) {
18555 return DAG.getNode(
18556 ISD::FNEG, SL, VT,
18557 DAG.getNode(PreferredFusedOpcode, SL, VT,
18558 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
18559 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
18560 N1));
18561 }
18562 }
18563 }
18564
18565 auto isContractableAndReassociableFMUL = [&isContractableFMUL](SDValue N) {
18566 return isContractableFMUL(N) && N->getFlags().hasAllowReassociation();
18567 };
18568
18569 auto isFusedOp = [&](SDValue N) {
18570 unsigned Opcode = N.getOpcode();
18571 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
18572 };
18573
18574 // More folding opportunities when target permits.
18575 if (Aggressive && N->getFlags().hasAllowReassociation()) {
18576 bool CanFuse = N->getFlags().hasAllowContract();
18577 // fold (fsub (fma x, y, (fmul u, v)), z)
18578 // -> (fma x, y (fma u, v, (fneg z)))
18579 if (CanFuse && isFusedOp(N0) &&
18580 isContractableAndReassociableFMUL(N0.getOperand(2)) &&
18581 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
18582 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
18583 N0.getOperand(1),
18584 DAG.getNode(PreferredFusedOpcode, SL, VT,
18585 N0.getOperand(2).getOperand(0),
18586 N0.getOperand(2).getOperand(1),
18587 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18588 }
18589
18590 // fold (fsub x, (fma y, z, (fmul u, v)))
18591 // -> (fma (fneg y), z, (fma (fneg u), v, x))
18592 if (CanFuse && isFusedOp(N1) &&
18593 isContractableAndReassociableFMUL(N1.getOperand(2)) &&
18594 N1->hasOneUse() && NoSignedZero) {
18595 SDValue N20 = N1.getOperand(2).getOperand(0);
18596 SDValue N21 = N1.getOperand(2).getOperand(1);
18597 return DAG.getNode(
18598 PreferredFusedOpcode, SL, VT,
18599 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
18600 DAG.getNode(PreferredFusedOpcode, SL, VT,
18601 DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0));
18602 }
18603
18604 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
18605 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
18606 if (isFusedOp(N0) && N0->hasOneUse()) {
18607 SDValue N02 = N0.getOperand(2);
18608 if (N02.getOpcode() == ISD::FP_EXTEND) {
18609 SDValue N020 = N02.getOperand(0);
18610 if (isContractableAndReassociableFMUL(N020) &&
18611 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18612 N020.getValueType())) {
18613 return DAG.getNode(
18614 PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1),
18615 DAG.getNode(
18616 PreferredFusedOpcode, SL, VT,
18617 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)),
18618 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)),
18619 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18620 }
18621 }
18622 }
18623
18624 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
18625 // -> (fma (fpext x), (fpext y),
18626 // (fma (fpext u), (fpext v), (fneg z)))
18627 // FIXME: This turns two single-precision and one double-precision
18628 // operation into two double-precision operations, which might not be
18629 // interesting for all targets, especially GPUs.
18630 if (N0.getOpcode() == ISD::FP_EXTEND) {
18631 SDValue N00 = N0.getOperand(0);
18632 if (isFusedOp(N00)) {
18633 SDValue N002 = N00.getOperand(2);
18634 if (isContractableAndReassociableFMUL(N002) &&
18635 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18636 N00.getValueType())) {
18637 return DAG.getNode(
18638 PreferredFusedOpcode, SL, VT,
18639 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18640 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18641 DAG.getNode(
18642 PreferredFusedOpcode, SL, VT,
18643 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)),
18644 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)),
18645 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18646 }
18647 }
18648 }
18649
18650 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
18651 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
18652 if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
18653 N1->hasOneUse()) {
18654 SDValue N120 = N1.getOperand(2).getOperand(0);
18655 if (isContractableAndReassociableFMUL(N120) &&
18656 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18657 N120.getValueType())) {
18658 SDValue N1200 = N120.getOperand(0);
18659 SDValue N1201 = N120.getOperand(1);
18660 return DAG.getNode(
18661 PreferredFusedOpcode, SL, VT,
18662 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
18663 DAG.getNode(PreferredFusedOpcode, SL, VT,
18664 DAG.getNode(ISD::FNEG, SL, VT,
18665 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)),
18666 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0));
18667 }
18668 }
18669
18670 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
18671 // -> (fma (fneg (fpext y)), (fpext z),
18672 // (fma (fneg (fpext u)), (fpext v), x))
18673 // FIXME: This turns two single-precision and one double-precision
18674 // operation into two double-precision operations, which might not be
18675 // interesting for all targets, especially GPUs.
18676 if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) {
18677 SDValue CvtSrc = N1.getOperand(0);
18678 SDValue N100 = CvtSrc.getOperand(0);
18679 SDValue N101 = CvtSrc.getOperand(1);
18680 SDValue N102 = CvtSrc.getOperand(2);
18681 if (isContractableAndReassociableFMUL(N102) &&
18682 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18683 CvtSrc.getValueType())) {
18684 SDValue N1020 = N102.getOperand(0);
18685 SDValue N1021 = N102.getOperand(1);
18686 return DAG.getNode(
18687 PreferredFusedOpcode, SL, VT,
18688 DAG.getNode(ISD::FNEG, SL, VT,
18689 DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)),
18690 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
18691 DAG.getNode(PreferredFusedOpcode, SL, VT,
18692 DAG.getNode(ISD::FNEG, SL, VT,
18693 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)),
18694 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0));
18695 }
18696 }
18697 }
18698
18699 return SDValue();
18700}
18701
18702/// Try to perform FMA combining on a given FMUL node based on the distributive
18703/// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
18704/// subtraction instead of addition).
18705SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
18706 SDValue N0 = N->getOperand(0);
18707 SDValue N1 = N->getOperand(1);
18708 EVT VT = N->getValueType(0);
18709 SDLoc SL(N);
18710
18711 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
18712
18713 const TargetOptions &Options = DAG.getTarget().Options;
18714
18715 // The transforms below are incorrect when x == 0 and y == inf, because the
18716 // intermediate multiplication produces a nan.
18717 SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1;
18718 if (!FAdd->getFlags().hasNoInfs())
18719 return SDValue();
18720
18721 // Floating-point multiply-add without intermediate rounding.
18722 bool HasFMA =
18724 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18726
18727 // Floating-point multiply-add with intermediate rounding. This can result
18728 // in a less precise result due to the changed rounding order.
18729 bool HasFMAD = LegalOperations && TLI.isFMADLegal(DAG, N);
18730
18731 // No valid opcode, do not combine.
18732 if (!HasFMAD && !HasFMA)
18733 return SDValue();
18734
18735 // Always prefer FMAD to FMA for precision.
18736 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18738
18739 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
18740 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
18741 auto FuseFADD = [&](SDValue X, SDValue Y) {
18742 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
18743 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
18744 if (C->isExactlyValue(+1.0))
18745 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
18746 Y);
18747 if (C->isExactlyValue(-1.0))
18748 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
18749 DAG.getNode(ISD::FNEG, SL, VT, Y));
18750 }
18751 }
18752 return SDValue();
18753 };
18754
18755 if (SDValue FMA = FuseFADD(N0, N1))
18756 return FMA;
18757 if (SDValue FMA = FuseFADD(N1, N0))
18758 return FMA;
18759
18760 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
18761 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
18762 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
18763 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
18764 auto FuseFSUB = [&](SDValue X, SDValue Y) {
18765 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
18766 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
18767 if (C0->isExactlyValue(+1.0))
18768 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18769 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
18770 Y);
18771 if (C0->isExactlyValue(-1.0))
18772 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18773 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
18774 DAG.getNode(ISD::FNEG, SL, VT, Y));
18775 }
18776 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
18777 if (C1->isExactlyValue(+1.0))
18778 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
18779 DAG.getNode(ISD::FNEG, SL, VT, Y));
18780 if (C1->isExactlyValue(-1.0))
18781 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
18782 Y);
18783 }
18784 }
18785 return SDValue();
18786 };
18787
18788 if (SDValue FMA = FuseFSUB(N0, N1))
18789 return FMA;
18790 if (SDValue FMA = FuseFSUB(N1, N0))
18791 return FMA;
18792
18793 return SDValue();
18794}
18795
18796SDValue DAGCombiner::visitFADD(SDNode *N) {
18797 SDValue N0 = N->getOperand(0);
18798 SDValue N1 = N->getOperand(1);
18799 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0);
18800 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1);
18801 EVT VT = N->getValueType(0);
18802 SDLoc DL(N);
18803 SDNodeFlags Flags = N->getFlags();
18804 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
18805
18806 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
18807 return R;
18808
18809 // fold (fadd c1, c2) -> c1 + c2
18810 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FADD, DL, VT, {N0, N1}))
18811 return C;
18812
18813 // canonicalize constant to RHS
18814 if (N0CFP && !N1CFP)
18815 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
18816
18817 // fold vector ops
18818 if (VT.isVector())
18819 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
18820 return FoldedVOp;
18821
18822 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
18823 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
18824 if (N1C && N1C->isZero())
18825 if (N1C->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0)))
18826 return N0;
18827
18828 if (SDValue NewSel = foldBinOpIntoSelect(N))
18829 return NewSel;
18830
18831 // fold (fadd A, (fneg B)) -> (fsub A, B)
18832 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
18833 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
18834 N1, DAG, LegalOperations, ForCodeSize))
18835 return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1);
18836
18837 // fold (fadd (fneg A), B) -> (fsub B, A)
18838 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
18839 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
18840 N0, DAG, LegalOperations, ForCodeSize))
18841 return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0);
18842
18843 auto isFMulNegTwo = [](SDValue FMul) {
18844 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
18845 return false;
18846 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
18847 return C && C->isExactlyValue(-2.0);
18848 };
18849
18850 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
18851 if (isFMulNegTwo(N0)) {
18852 SDValue B = N0.getOperand(0);
18853 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
18854 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add);
18855 }
18856 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
18857 if (isFMulNegTwo(N1)) {
18858 SDValue B = N1.getOperand(0);
18859 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
18860 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add);
18861 }
18862
18863 // No FP constant should be created after legalization as Instruction
18864 // Selection pass has a hard time dealing with FP constants.
18865 bool AllowNewConst = (Level < AfterLegalizeDAG);
18866
18867 // If nnan is enabled, fold lots of things.
18868 if (Flags.hasNoNaNs() && AllowNewConst) {
18869 // If allowed, fold (fadd (fneg x), x) -> 0.0
18870 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
18871 return DAG.getConstantFP(0.0, DL, VT);
18872
18873 // If allowed, fold (fadd x, (fneg x)) -> 0.0
18874 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
18875 return DAG.getConstantFP(0.0, DL, VT);
18876 }
18877
18878 // If reassoc and nsz, fold lots of things.
18879 // TODO: break out portions of the transformations below for which Unsafe is
18880 // considered and which do not require both nsz and reassoc
18881 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
18882 AllowNewConst) {
18883 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
18884 if (N1CFP && N0.getOpcode() == ISD::FADD &&
18886 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1);
18887 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC);
18888 }
18889
18890 // We can fold chains of FADD's of the same value into multiplications.
18891 // This transform is not safe in general because we are reducing the number
18892 // of rounding steps.
18893 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
18894 if (N0.getOpcode() == ISD::FMUL) {
18895 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
18896 bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
18897
18898 // (fadd (fmul x, c), x) -> (fmul x, c+1)
18899 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
18900 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
18901 DAG.getConstantFP(1.0, DL, VT));
18902 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
18903 }
18904
18905 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
18906 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
18907 N1.getOperand(0) == N1.getOperand(1) &&
18908 N0.getOperand(0) == N1.getOperand(0)) {
18909 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
18910 DAG.getConstantFP(2.0, DL, VT));
18911 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
18912 }
18913 }
18914
18915 if (N1.getOpcode() == ISD::FMUL) {
18916 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
18917 bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
18918
18919 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
18920 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
18921 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
18922 DAG.getConstantFP(1.0, DL, VT));
18923 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
18924 }
18925
18926 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
18927 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
18928 N0.getOperand(0) == N0.getOperand(1) &&
18929 N1.getOperand(0) == N0.getOperand(0)) {
18930 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
18931 DAG.getConstantFP(2.0, DL, VT));
18932 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
18933 }
18934 }
18935
18936 if (N0.getOpcode() == ISD::FADD) {
18937 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
18938 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
18939 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
18940 (N0.getOperand(0) == N1)) {
18941 return DAG.getNode(ISD::FMUL, DL, VT, N1,
18942 DAG.getConstantFP(3.0, DL, VT));
18943 }
18944 }
18945
18946 if (N1.getOpcode() == ISD::FADD) {
18947 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
18948 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
18949 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
18950 N1.getOperand(0) == N0) {
18951 return DAG.getNode(ISD::FMUL, DL, VT, N0,
18952 DAG.getConstantFP(3.0, DL, VT));
18953 }
18954 }
18955
18956 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
18957 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
18958 N0.getOperand(0) == N0.getOperand(1) &&
18959 N1.getOperand(0) == N1.getOperand(1) &&
18960 N0.getOperand(0) == N1.getOperand(0)) {
18961 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
18962 DAG.getConstantFP(4.0, DL, VT));
18963 }
18964 }
18965 } // reassoc && nsz && AllowNewConst
18966
18967 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros()) {
18968 // Fold fadd(vecreduce(x), vecreduce(y)) -> vecreduce(fadd(x, y))
18969 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FADD, ISD::FADD, DL,
18970 VT, N0, N1, Flags))
18971 return SD;
18972 }
18973
18974 // FADD -> FMA combines:
18975 if (SDValue Fused = visitFADDForFMACombine(N)) {
18976 if (Fused.getOpcode() != ISD::DELETED_NODE)
18977 AddToWorklist(Fused.getNode());
18978 return Fused;
18979 }
18980 return SDValue();
18981}
18982
18983SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) {
18984 SDValue Chain = N->getOperand(0);
18985 SDValue N0 = N->getOperand(1);
18986 SDValue N1 = N->getOperand(2);
18987 EVT VT = N->getValueType(0);
18988 EVT ChainVT = N->getValueType(1);
18989 SDLoc DL(N);
18990 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
18991
18992 // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B)
18993 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
18994 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
18995 N1, DAG, LegalOperations, ForCodeSize)) {
18996 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
18997 {Chain, N0, NegN1});
18998 }
18999
19000 // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A)
19001 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
19002 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
19003 N0, DAG, LegalOperations, ForCodeSize)) {
19004 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
19005 {Chain, N1, NegN0});
19006 }
19007 return SDValue();
19008}
19009
19010SDValue DAGCombiner::visitFSUB(SDNode *N) {
19011 SDValue N0 = N->getOperand(0);
19012 SDValue N1 = N->getOperand(1);
19013 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
19014 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19015 EVT VT = N->getValueType(0);
19016 SDLoc DL(N);
19017 const SDNodeFlags Flags = N->getFlags();
19018 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19019
19020 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19021 return R;
19022
19023 // fold (fsub c1, c2) -> c1-c2
19024 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FSUB, DL, VT, {N0, N1}))
19025 return C;
19026
19027 // fold vector ops
19028 if (VT.isVector())
19029 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19030 return FoldedVOp;
19031
19032 if (SDValue NewSel = foldBinOpIntoSelect(N))
19033 return NewSel;
19034
19035 // (fsub A, 0) -> A
19036 if (N1CFP && N1CFP->isZero()) {
19037 if (!N1CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19038 return N0;
19039 }
19040 }
19041
19042 if (N0 == N1) {
19043 // (fsub x, x) -> 0.0
19044 if (Flags.hasNoNaNs())
19045 return DAG.getConstantFP(0.0f, DL, VT);
19046 }
19047
19048 // (fsub -0.0, N1) -> -N1
19049 if (N0CFP && N0CFP->isZero()) {
19050 if (N0CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19051 // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are
19052 // flushed to zero, unless all users treat denorms as zero (DAZ).
19053 // FIXME: This transform will change the sign of a NaN and the behavior
19054 // of a signaling NaN. It is only valid when a NoNaN flag is present.
19055 DenormalMode DenormMode = DAG.getDenormalMode(VT);
19056 if (DenormMode == DenormalMode::getIEEE()) {
19057 if (SDValue NegN1 =
19058 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19059 return NegN1;
19060 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
19061 return DAG.getNode(ISD::FNEG, DL, VT, N1);
19062 }
19063 }
19064 }
19065
19066 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
19067 N1.getOpcode() == ISD::FADD) {
19068 // X - (X + Y) -> -Y
19069 if (N0 == N1->getOperand(0))
19070 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1));
19071 // X - (Y + X) -> -Y
19072 if (N0 == N1->getOperand(1))
19073 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0));
19074 }
19075
19076 // fold (fsub A, (fneg B)) -> (fadd A, B)
19077 if (SDValue NegN1 =
19078 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19079 return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1);
19080
19081 // FSUB -> FMA combines:
19082 if (SDValue Fused = visitFSUBForFMACombine(N)) {
19083 AddToWorklist(Fused.getNode());
19084 return Fused;
19085 }
19086
19087 return SDValue();
19088}
19089
19090// Transform IEEE Floats:
19091// (fmul C, (uitofp Pow2))
19092// -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
19093// (fdiv C, (uitofp Pow2))
19094// -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
19095//
19096// The rationale is fmul/fdiv by a power of 2 is just change the exponent, so
19097// there is no need for more than an add/sub.
19098//
19099// This is valid under the following circumstances:
19100// 1) We are dealing with IEEE floats
19101// 2) C is normal
19102// 3) The fmul/fdiv add/sub will not go outside of min/max exponent bounds.
19103// TODO: Much of this could also be used for generating `ldexp` on targets the
19104// prefer it.
19105SDValue DAGCombiner::combineFMulOrFDivWithIntPow2(SDNode *N) {
19106 EVT VT = N->getValueType(0);
19108 return SDValue();
19109
19110 SDValue ConstOp, Pow2Op;
19111
19112 std::optional<int> Mantissa;
19113 auto GetConstAndPow2Ops = [&](unsigned ConstOpIdx) {
19114 if (ConstOpIdx == 1 && N->getOpcode() == ISD::FDIV)
19115 return false;
19116
19117 ConstOp = peekThroughBitcasts(N->getOperand(ConstOpIdx));
19118 Pow2Op = N->getOperand(1 - ConstOpIdx);
19119 unsigned Pow2Opc = Pow2Op.getOpcode();
19120 if (Pow2Opc != ISD::UINT_TO_FP && Pow2Opc != ISD::SINT_TO_FP)
19121 return false;
19122
19123 Pow2Op = Pow2Op.getOperand(0);
19124
19125 KnownBits Pow2OpKnownBits = DAG.computeKnownBits(Pow2Op);
19126 if (Pow2Opc == ISD::SINT_TO_FP && !Pow2OpKnownBits.isNonNegative())
19127 return false;
19128
19129 int MaxExpChange = Pow2OpKnownBits.countMaxActiveBits();
19130
19131 auto IsFPConstValid = [N, MaxExpChange, &Mantissa](ConstantFPSDNode *CFP) {
19132 if (CFP == nullptr)
19133 return false;
19134
19135 const APFloat &APF = CFP->getValueAPF();
19136
19137 // Make sure we have normal constant.
19138 if (!APF.isNormal())
19139 return false;
19140
19141 // Make sure the floats exponent is within the bounds that this transform
19142 // produces bitwise equals value.
19143 int CurExp = ilogb(APF);
19144 // FMul by pow2 will only increase exponent.
19145 int MinExp =
19146 N->getOpcode() == ISD::FMUL ? CurExp : (CurExp - MaxExpChange);
19147 // FDiv by pow2 will only decrease exponent.
19148 int MaxExp =
19149 N->getOpcode() == ISD::FDIV ? CurExp : (CurExp + MaxExpChange);
19150 if (MinExp <= APFloat::semanticsMinExponent(APF.getSemantics()) ||
19152 return false;
19153
19154 // Finally make sure we actually know the mantissa for the float type.
19155 int ThisMantissa = APFloat::semanticsPrecision(APF.getSemantics()) - 1;
19156 if (!Mantissa)
19157 Mantissa = ThisMantissa;
19158
19159 return *Mantissa == ThisMantissa && ThisMantissa > 0;
19160 };
19161
19162 // TODO: We may be able to include undefs.
19163 return ISD::matchUnaryFpPredicate(ConstOp, IsFPConstValid);
19164 };
19165
19166 if (!GetConstAndPow2Ops(0) && !GetConstAndPow2Ops(1))
19167 return SDValue();
19168
19169 if (!TLI.optimizeFMulOrFDivAsShiftAddBitcast(N, ConstOp, Pow2Op))
19170 return SDValue();
19171
19172 // Get log2 after all other checks have taken place. This is because
19173 // BuildLogBase2 may create a new node.
19174 SDLoc DL(N);
19175 // Get Log2 type with same bitwidth as the float type (VT).
19176 EVT NewIntVT = VT.changeElementType(
19177 *DAG.getContext(),
19179
19180 SDValue Log2 = BuildLogBase2(Pow2Op, DL, DAG.isKnownNeverZero(Pow2Op),
19181 /*InexpensiveOnly*/ true, NewIntVT);
19182 if (!Log2)
19183 return SDValue();
19184
19185 // Perform actual transform.
19186 SDValue MantissaShiftCnt =
19187 DAG.getShiftAmountConstant(*Mantissa, NewIntVT, DL);
19188 // TODO: Sometimes Log2 is of form `(X + C)`. `(X + C) << C1` should fold to
19189 // `(X << C1) + (C << C1)`, but that isn't always the case because of the
19190 // cast. We could implement that by handle here to handle the casts.
19191 SDValue Shift = DAG.getNode(ISD::SHL, DL, NewIntVT, Log2, MantissaShiftCnt);
19192 SDValue ResAsInt =
19193 DAG.getNode(N->getOpcode() == ISD::FMUL ? ISD::ADD : ISD::SUB, DL,
19194 NewIntVT, DAG.getBitcast(NewIntVT, ConstOp), Shift);
19195 SDValue ResAsFP = DAG.getBitcast(VT, ResAsInt);
19196 return ResAsFP;
19197}
19198
19199SDValue DAGCombiner::visitFMUL(SDNode *N) {
19200 SDValue N0 = N->getOperand(0);
19201 SDValue N1 = N->getOperand(1);
19202 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19203 EVT VT = N->getValueType(0);
19204 SDLoc DL(N);
19205 const SDNodeFlags Flags = N->getFlags();
19206 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19207
19208 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19209 return R;
19210
19211 // fold (fmul c1, c2) -> c1*c2
19212 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMUL, DL, VT, {N0, N1}))
19213 return C;
19214
19215 // canonicalize constant to RHS
19218 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
19219
19220 // fold vector ops
19221 if (VT.isVector())
19222 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19223 return FoldedVOp;
19224
19225 if (SDValue NewSel = foldBinOpIntoSelect(N))
19226 return NewSel;
19227
19228 if (Flags.hasAllowReassociation()) {
19229 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
19231 N0.getOpcode() == ISD::FMUL) {
19232 SDValue N00 = N0.getOperand(0);
19233 SDValue N01 = N0.getOperand(1);
19234 // Avoid an infinite loop by making sure that N00 is not a constant
19235 // (the inner multiply has not been constant folded yet).
19238 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
19239 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
19240 }
19241 }
19242
19243 // Match a special-case: we convert X * 2.0 into fadd.
19244 // fmul (fadd X, X), C -> fmul X, 2.0 * C
19245 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
19246 N0.getOperand(0) == N0.getOperand(1)) {
19247 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
19248 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
19249 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
19250 }
19251
19252 // Fold fmul(vecreduce(x), vecreduce(y)) -> vecreduce(fmul(x, y))
19253 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FMUL, ISD::FMUL, DL,
19254 VT, N0, N1, Flags))
19255 return SD;
19256 }
19257
19258 // fold (fmul X, 2.0) -> (fadd X, X)
19259 if (N1CFP && N1CFP->isExactlyValue(+2.0))
19260 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
19261
19262 // fold (fmul X, -1.0) -> (fsub -0.0, X)
19263 if (N1CFP && N1CFP->isExactlyValue(-1.0)) {
19264 if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) {
19265 return DAG.getNode(ISD::FSUB, DL, VT,
19266 DAG.getConstantFP(-0.0, DL, VT), N0, Flags);
19267 }
19268 }
19269
19270 // -N0 * -N1 --> N0 * N1
19275 SDValue NegN0 =
19276 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19277 if (NegN0) {
19278 HandleSDNode NegN0Handle(NegN0);
19279 SDValue NegN1 =
19280 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19281 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19283 return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1);
19284 }
19285
19286 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
19287 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
19288 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
19289 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
19290 TLI.isOperationLegal(ISD::FABS, VT)) {
19291 SDValue Select = N0, X = N1;
19292 if (Select.getOpcode() != ISD::SELECT)
19293 std::swap(Select, X);
19294
19295 SDValue Cond = Select.getOperand(0);
19296 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
19297 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
19298
19299 if (TrueOpnd && FalseOpnd && Cond.getOpcode() == ISD::SETCC &&
19300 Cond.getOperand(0) == X && isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
19301 cast<ConstantFPSDNode>(Cond.getOperand(1))->isPosZero()) {
19302 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19303 switch (CC) {
19304 default: break;
19305 case ISD::SETOLT:
19306 case ISD::SETULT:
19307 case ISD::SETOLE:
19308 case ISD::SETULE:
19309 case ISD::SETLT:
19310 case ISD::SETLE:
19311 std::swap(TrueOpnd, FalseOpnd);
19312 [[fallthrough]];
19313 case ISD::SETOGT:
19314 case ISD::SETUGT:
19315 case ISD::SETOGE:
19316 case ISD::SETUGE:
19317 case ISD::SETGT:
19318 case ISD::SETGE:
19319 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
19320 TLI.isOperationLegal(ISD::FNEG, VT))
19321 return DAG.getNode(ISD::FNEG, DL, VT,
19322 DAG.getNode(ISD::FABS, DL, VT, X));
19323 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
19324 return DAG.getNode(ISD::FABS, DL, VT, X);
19325
19326 break;
19327 }
19328 }
19329 }
19330
19331 // FMUL -> FMA combines:
19332 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
19333 AddToWorklist(Fused.getNode());
19334 return Fused;
19335 }
19336
19337 // Don't do `combineFMulOrFDivWithIntPow2` until after FMUL -> FMA has been
19338 // able to run.
19339 if (SDValue R = combineFMulOrFDivWithIntPow2(N))
19340 return R;
19341
19342 return SDValue();
19343}
19344
19345SDValue DAGCombiner::visitFMA(SDNode *N) {
19346 SDValue N0 = N->getOperand(0);
19347 SDValue N1 = N->getOperand(1);
19348 SDValue N2 = N->getOperand(2);
19349 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
19350 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
19351 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
19352 EVT VT = N->getValueType(0);
19353 SDLoc DL(N);
19354 // FMA nodes have flags that propagate to the created nodes.
19355 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19356
19357 // Constant fold FMA.
19358 if (SDValue C =
19359 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
19360 return C;
19361
19362 // (-N0 * -N1) + N2 --> (N0 * N1) + N2
19367 SDValue NegN0 =
19368 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19369 if (NegN0) {
19370 HandleSDNode NegN0Handle(NegN0);
19371 SDValue NegN1 =
19372 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19373 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19375 return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2);
19376 }
19377
19378 if (N->getFlags().hasNoNaNs() && N->getFlags().hasNoInfs()) {
19379 if (N->getFlags().hasNoSignedZeros() || (N2CFP && !N2CFP->isNegZero())) {
19380 if (N0CFP && N0CFP->isZero())
19381 return N2;
19382 if (N1CFP && N1CFP->isZero())
19383 return N2;
19384 }
19385 }
19386
19387 if (N0CFP && N0CFP->isExactlyValue(1.0))
19388 return DAG.getNode(ISD::FADD, DL, VT, N1, N2);
19389 if (N1CFP && N1CFP->isExactlyValue(1.0))
19390 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19391
19392 // Canonicalize (fma c, x, y) -> (fma x, c, y)
19395 return DAG.getNode(ISD::FMA, DL, VT, N1, N0, N2);
19396
19397 bool CanReassociate = N->getFlags().hasAllowReassociation();
19398 if (CanReassociate) {
19399 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
19400 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
19403 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19404 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1)));
19405 }
19406
19407 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
19408 if (N0.getOpcode() == ISD::FMUL &&
19411 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19412 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)),
19413 N2);
19414 }
19415 }
19416
19417 // (fma x, -1, y) -> (fadd (fneg x), y)
19418 if (N1CFP) {
19419 if (N1CFP->isExactlyValue(1.0))
19420 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19421
19422 if (N1CFP->isExactlyValue(-1.0) &&
19423 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
19424 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
19425 AddToWorklist(RHSNeg.getNode());
19426 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
19427 }
19428
19429 // fma (fneg x), K, y -> fma x -K, y
19430 if (N0.getOpcode() == ISD::FNEG &&
19432 (N1.hasOneUse() &&
19433 !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, ForCodeSize)))) {
19434 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19435 DAG.getNode(ISD::FNEG, DL, VT, N1), N2);
19436 }
19437 }
19438
19439 if (CanReassociate) {
19440 // (fma x, c, x) -> (fmul x, (c+1))
19441 if (N1CFP && N0 == N2) {
19442 return DAG.getNode(
19443 ISD::FMUL, DL, VT, N0,
19444 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT)));
19445 }
19446
19447 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
19448 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
19449 return DAG.getNode(
19450 ISD::FMUL, DL, VT, N0,
19451 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT)));
19452 }
19453 }
19454
19455 // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z))
19456 // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z))
19457 if (!TLI.isFNegFree(VT))
19459 SDValue(N, 0), DAG, LegalOperations, ForCodeSize))
19460 return DAG.getNode(ISD::FNEG, DL, VT, Neg);
19461 return SDValue();
19462}
19463
19464SDValue DAGCombiner::visitFMAD(SDNode *N) {
19465 SDValue N0 = N->getOperand(0);
19466 SDValue N1 = N->getOperand(1);
19467 SDValue N2 = N->getOperand(2);
19468 EVT VT = N->getValueType(0);
19469 SDLoc DL(N);
19470
19471 // Constant fold FMAD.
19472 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMAD, DL, VT, {N0, N1, N2}))
19473 return C;
19474
19475 return SDValue();
19476}
19477
19478SDValue DAGCombiner::visitFMULADD(SDNode *N) {
19479 SDValue N0 = N->getOperand(0);
19480 SDValue N1 = N->getOperand(1);
19481 SDValue N2 = N->getOperand(2);
19482 EVT VT = N->getValueType(0);
19483 SDLoc DL(N);
19484
19485 // Constant fold FMULADD.
19486 if (SDValue C =
19487 DAG.FoldConstantArithmetic(ISD::FMULADD, DL, VT, {N0, N1, N2}))
19488 return C;
19489
19490 return SDValue();
19491}
19492
19493// Combine multiple FDIVs with the same divisor into multiple FMULs by the
19494// reciprocal.
19495// E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
19496// Notice that this is not always beneficial. One reason is different targets
19497// may have different costs for FDIV and FMUL, so sometimes the cost of two
19498// FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
19499// is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
19500SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
19501 // TODO: Limit this transform based on optsize/minsize - it always creates at
19502 // least 1 extra instruction. But the perf win may be substantial enough
19503 // that only minsize should restrict this.
19504 const SDNodeFlags Flags = N->getFlags();
19505 if (LegalDAG || !Flags.hasAllowReciprocal())
19506 return SDValue();
19507
19508 // Skip if current node is a reciprocal/fneg-reciprocal.
19509 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
19510 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
19511 if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0)))
19512 return SDValue();
19513
19514 // Exit early if the target does not want this transform or if there can't
19515 // possibly be enough uses of the divisor to make the transform worthwhile.
19516 unsigned MinUses = TLI.combineRepeatedFPDivisors();
19517
19518 // For splat vectors, scale the number of uses by the splat factor. If we can
19519 // convert the division into a scalar op, that will likely be much faster.
19520 unsigned NumElts = 1;
19521 EVT VT = N->getValueType(0);
19522 if (VT.isVector() && DAG.isSplatValue(N1))
19523 NumElts = VT.getVectorMinNumElements();
19524
19525 if (!MinUses || (N1->use_size() * NumElts) < MinUses)
19526 return SDValue();
19527
19528 // Find all FDIV users of the same divisor.
19529 // Use a set because duplicates may be present in the user list.
19530 SetVector<SDNode *> Users;
19531 for (auto *U : N1->users()) {
19532 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
19533 // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet.
19534 if (U->getOperand(1).getOpcode() == ISD::FSQRT &&
19535 U->getOperand(0) == U->getOperand(1).getOperand(0) &&
19536 U->getFlags().hasAllowReassociation() &&
19537 U->getFlags().hasNoSignedZeros())
19538 continue;
19539
19540 // This division is eligible for optimization only if global unsafe math
19541 // is enabled or if this division allows reciprocal formation.
19542 if (U->getFlags().hasAllowReciprocal())
19543 Users.insert(U);
19544 }
19545 }
19546
19547 // Now that we have the actual number of divisor uses, make sure it meets
19548 // the minimum threshold specified by the target.
19549 if ((Users.size() * NumElts) < MinUses)
19550 return SDValue();
19551
19552 SDLoc DL(N);
19553 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
19554 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
19555
19556 // Dividend / Divisor -> Dividend * Reciprocal
19557 for (auto *U : Users) {
19558 SDValue Dividend = U->getOperand(0);
19559 if (Dividend != FPOne) {
19560 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
19561 Reciprocal, Flags);
19562 CombineTo(U, NewNode);
19563 } else if (U != Reciprocal.getNode()) {
19564 // In the absence of fast-math-flags, this user node is always the
19565 // same node as Reciprocal, but with FMF they may be different nodes.
19566 CombineTo(U, Reciprocal);
19567 }
19568 }
19569 return SDValue(N, 0); // N was replaced.
19570}
19571
19572SDValue DAGCombiner::visitFDIV(SDNode *N) {
19573 SDValue N0 = N->getOperand(0);
19574 SDValue N1 = N->getOperand(1);
19575 EVT VT = N->getValueType(0);
19576 SDLoc DL(N);
19577 SDNodeFlags Flags = N->getFlags();
19578 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19579
19580 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19581 return R;
19582
19583 // fold (fdiv c1, c2) -> c1/c2
19584 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FDIV, DL, VT, {N0, N1}))
19585 return C;
19586
19587 // fold vector ops
19588 if (VT.isVector())
19589 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19590 return FoldedVOp;
19591
19592 if (SDValue NewSel = foldBinOpIntoSelect(N))
19593 return NewSel;
19594
19596 return V;
19597
19598 // fold (fdiv X, c2) -> (fmul X, 1/c2) if there is no loss in precision, or
19599 // the loss is acceptable with AllowReciprocal.
19600 if (auto *N1CFP = isConstOrConstSplatFP(N1, true)) {
19601 // Compute the reciprocal 1.0 / c2.
19602 const APFloat &N1APF = N1CFP->getValueAPF();
19603 APFloat Recip = APFloat::getOne(N1APF.getSemantics());
19605 // Only do the transform if the reciprocal is a legal fp immediate that
19606 // isn't too nasty (eg NaN, denormal, ...).
19607 if (((st == APFloat::opOK && !Recip.isDenormal()) ||
19608 (st == APFloat::opInexact && Flags.hasAllowReciprocal())) &&
19609 (!LegalOperations ||
19610 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
19611 // backend)... we should handle this gracefully after Legalize.
19612 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
19614 TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
19615 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19616 DAG.getConstantFP(Recip, DL, VT));
19617 }
19618
19619 if (Flags.hasAllowReciprocal()) {
19620 // If this FDIV is part of a reciprocal square root, it may be folded
19621 // into a target-specific square root estimate instruction.
19622 bool N1AllowReciprocal = N1->getFlags().hasAllowReciprocal();
19623 if (N1.getOpcode() == ISD::FSQRT) {
19624 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), N1->getFlags()))
19625 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19626 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
19627 N1.getOperand(0).getOpcode() == ISD::FSQRT &&
19628 N1AllowReciprocal) {
19629 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
19630 N1.getOperand(0)->getFlags())) {
19631 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
19632 AddToWorklist(RV.getNode());
19633 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19634 }
19635 } else if (N1.getOpcode() == ISD::FP_ROUND &&
19636 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
19637 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
19638 N1.getOperand(0)->getFlags())) {
19639 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
19640 AddToWorklist(RV.getNode());
19641 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19642 }
19643 } else if (N1.getOpcode() == ISD::FMUL) {
19644 // Look through an FMUL. Even though this won't remove the FDIV directly,
19645 // it's still worthwhile to get rid of the FSQRT if possible.
19646 SDValue Sqrt, Y;
19647 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
19648 Sqrt = N1.getOperand(0);
19649 Y = N1.getOperand(1);
19650 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
19651 Sqrt = N1.getOperand(1);
19652 Y = N1.getOperand(0);
19653 }
19654 if (Sqrt.getNode()) {
19655 // If the other multiply operand is known positive, pull it into the
19656 // sqrt. That will eliminate the division if we convert to an estimate.
19657 if (Flags.hasAllowReassociation() && N1.hasOneUse() &&
19658 N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) {
19659 SDValue A;
19660 if (Y.getOpcode() == ISD::FABS && Y.hasOneUse())
19661 A = Y.getOperand(0);
19662 else if (Y == Sqrt.getOperand(0))
19663 A = Y;
19664 if (A) {
19665 // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z)
19666 // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A)
19667 SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A);
19668 SDValue AAZ =
19669 DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0));
19670 if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Sqrt->getFlags()))
19671 return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt);
19672
19673 // Estimate creation failed. Clean up speculatively created nodes.
19674 recursivelyDeleteUnusedNodes(AAZ.getNode());
19675 }
19676 }
19677
19678 // We found a FSQRT, so try to make this fold:
19679 // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y)
19680 if (SDValue Rsqrt =
19681 buildRsqrtEstimate(Sqrt.getOperand(0), Sqrt->getFlags())) {
19682 SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y);
19683 AddToWorklist(Div.getNode());
19684 return DAG.getNode(ISD::FMUL, DL, VT, N0, Div);
19685 }
19686 }
19687 }
19688
19689 // Fold into a reciprocal estimate and multiply instead of a real divide.
19690 if (Flags.hasNoInfs())
19691 if (SDValue RV = BuildDivEstimate(N0, N1, Flags))
19692 return RV;
19693 }
19694
19695 // Fold X/Sqrt(X) -> Sqrt(X)
19696 if (DAG.canIgnoreSignBitOfZero(SDValue(N, 0)) &&
19697 Flags.hasAllowReassociation())
19698 if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0))
19699 return N1;
19700
19701 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
19706 SDValue NegN0 =
19707 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19708 if (NegN0) {
19709 HandleSDNode NegN0Handle(NegN0);
19710 SDValue NegN1 =
19711 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19712 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19714 return DAG.getNode(ISD::FDIV, DL, VT, NegN0, NegN1);
19715 }
19716
19717 if (SDValue R = combineFMulOrFDivWithIntPow2(N))
19718 return R;
19719
19720 return SDValue();
19721}
19722
19723SDValue DAGCombiner::visitFREM(SDNode *N) {
19724 SDValue N0 = N->getOperand(0);
19725 SDValue N1 = N->getOperand(1);
19726 EVT VT = N->getValueType(0);
19727 SDNodeFlags Flags = N->getFlags();
19728 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19729 SDLoc DL(N);
19730
19731 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19732 return R;
19733
19734 // fold (frem c1, c2) -> fmod(c1,c2)
19735 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FREM, DL, VT, {N0, N1}))
19736 return C;
19737
19738 if (SDValue NewSel = foldBinOpIntoSelect(N))
19739 return NewSel;
19740
19741 // Lower frem N0, N1 => x - trunc(N0 / N1) * N1, providing N1 is an integer
19742 // power of 2.
19743 if (!TLI.isOperationLegal(ISD::FREM, VT) &&
19747 DAG.isKnownToBeAPowerOfTwoFP(N1)) {
19748 bool NeedsCopySign = !DAG.canIgnoreSignBitOfZero(SDValue(N, 0)) &&
19750 SDValue Div = DAG.getNode(ISD::FDIV, DL, VT, N0, N1);
19751 SDValue Rnd = DAG.getNode(ISD::FTRUNC, DL, VT, Div);
19752 SDValue MLA;
19754 MLA = DAG.getNode(ISD::FMA, DL, VT, DAG.getNode(ISD::FNEG, DL, VT, Rnd),
19755 N1, N0);
19756 } else {
19757 SDValue Mul = DAG.getNode(ISD::FMUL, DL, VT, Rnd, N1);
19758 MLA = DAG.getNode(ISD::FSUB, DL, VT, N0, Mul);
19759 }
19760 return NeedsCopySign ? DAG.getNode(ISD::FCOPYSIGN, DL, VT, MLA, N0) : MLA;
19761 }
19762
19763 return SDValue();
19764}
19765
19766SDValue DAGCombiner::visitFSQRT(SDNode *N) {
19767 SDNodeFlags Flags = N->getFlags();
19768
19769 // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as:
19770 // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN
19771 if (!Flags.hasApproximateFuncs() || !Flags.hasNoInfs())
19772 return SDValue();
19773
19774 SDValue N0 = N->getOperand(0);
19775 if (TLI.isFsqrtCheap(N0, DAG))
19776 return SDValue();
19777
19778 // FSQRT nodes have flags that propagate to the created nodes.
19779 SelectionDAG::FlagInserter FlagInserter(DAG, Flags);
19780 // TODO: If this is N0/sqrt(N0), and we reach this node before trying to
19781 // transform the fdiv, we may produce a sub-optimal estimate sequence
19782 // because the reciprocal calculation may not have to filter out a
19783 // 0.0 input.
19784 return buildSqrtEstimate(N0, Flags);
19785}
19786
19787/// copysign(x, fp_extend(y)) -> copysign(x, y)
19788/// copysign(x, fp_round(y)) -> copysign(x, y)
19789/// Operands to the functions are the type of X and Y respectively.
19790static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(EVT XTy, EVT YTy) {
19791 // Always fold no-op FP casts.
19792 if (XTy == YTy)
19793 return true;
19794
19795 // Do not optimize out type conversion of f128 type yet.
19796 // For some targets like x86_64, configuration is changed to keep one f128
19797 // value in one SSE register, but instruction selection cannot handle
19798 // FCOPYSIGN on SSE registers yet.
19799 if (YTy == MVT::f128)
19800 return false;
19801
19802 // Avoid mismatched vector operand types, for better instruction selection.
19803 return !YTy.isVector();
19804}
19805
19807 SDValue N1 = N->getOperand(1);
19808 if (N1.getOpcode() != ISD::FP_EXTEND &&
19809 N1.getOpcode() != ISD::FP_ROUND)
19810 return false;
19811 EVT N1VT = N1->getValueType(0);
19812 EVT N1Op0VT = N1->getOperand(0).getValueType();
19813 return CanCombineFCOPYSIGN_EXTEND_ROUND(N1VT, N1Op0VT);
19814}
19815
19816SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
19817 SDValue N0 = N->getOperand(0);
19818 SDValue N1 = N->getOperand(1);
19819 EVT VT = N->getValueType(0);
19820 SDLoc DL(N);
19821
19822 // fold (fcopysign c1, c2) -> fcopysign(c1,c2)
19823 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FCOPYSIGN, DL, VT, {N0, N1}))
19824 return C;
19825
19826 // copysign(x, fp_extend(y)) -> copysign(x, y)
19827 // copysign(x, fp_round(y)) -> copysign(x, y)
19829 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N0, N1.getOperand(0));
19830
19832 return SDValue(N, 0);
19833
19834 if (VT != N1.getValueType())
19835 return SDValue();
19836
19837 // If this is equivalent to a disjoint or, replace it with one. This can
19838 // happen if the sign operand is a sign mask (i.e., x << sign_bit_position).
19839 if (DAG.SignBitIsZeroFP(N0) &&
19841 // TODO: Just directly match the shift pattern. computeKnownBits is heavy
19842 // for a such a narrowly targeted case.
19843 EVT IntVT = VT.changeTypeToInteger();
19844 // TODO: It appears to be profitable in some situations to unconditionally
19845 // emit a fabs(n0) to perform this combine.
19846 SDValue CastSrc0 = DAG.getNode(ISD::BITCAST, DL, IntVT, N0);
19847 SDValue CastSrc1 = DAG.getNode(ISD::BITCAST, DL, IntVT, N1);
19848
19849 SDValue SignOr = DAG.getNode(ISD::OR, DL, IntVT, CastSrc0, CastSrc1,
19851 return DAG.getNode(ISD::BITCAST, DL, VT, SignOr);
19852 }
19853
19854 return SDValue();
19855}
19856
19857SDValue DAGCombiner::visitFPOW(SDNode *N) {
19858 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1));
19859 if (!ExponentC)
19860 return SDValue();
19861 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19862
19863 // Try to convert x ** (1/3) into cube root.
19864 // TODO: Handle the various flavors of long double.
19865 // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
19866 // Some range near 1/3 should be fine.
19867 EVT VT = N->getValueType(0);
19868 EVT ScalarVT = VT.getScalarType();
19869 if ((ScalarVT == MVT::f32 &&
19870 ExponentC->getValueAPF().isExactlyValue(1.0f / 3.0f)) ||
19871 (ScalarVT == MVT::f64 &&
19872 ExponentC->getValueAPF().isExactlyValue(1.0 / 3.0))) {
19873 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
19874 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
19875 // pow(-val, 1/3) = nan; cbrt(-val) = -num.
19876 // For regular numbers, rounding may cause the results to differ.
19877 // Therefore, we require { nsz ninf nnan afn } for this transform.
19878 // TODO: We could select out the special cases if we don't have nsz/ninf.
19879 SDNodeFlags Flags = N->getFlags();
19880 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() ||
19881 !Flags.hasApproximateFuncs())
19882 return SDValue();
19883
19884 // Do not create a cbrt() libcall if the target does not have it, and do not
19885 // turn a pow that has lowering support into a cbrt() libcall.
19886 RTLIB::Libcall LC = RTLIB::getCBRT(VT);
19887 bool HasLibCall =
19888 DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported;
19889 if (!HasLibCall ||
19892 return SDValue();
19893
19894 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0));
19895 }
19896
19897 // Try to convert x ** (1/4) and x ** (3/4) into square roots.
19898 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
19899 // TODO: This could be extended (using a target hook) to handle smaller
19900 // power-of-2 fractional exponents.
19901 bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25);
19902 bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75);
19903 if (ExponentIs025 || ExponentIs075) {
19904 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
19905 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
19906 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
19907 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
19908 // For regular numbers, rounding may cause the results to differ.
19909 // Therefore, we require { nsz ninf afn } for this transform.
19910 // TODO: We could select out the special cases if we don't have nsz/ninf.
19911 SDNodeFlags Flags = N->getFlags();
19912
19913 // We only need no signed zeros for the 0.25 case.
19914 if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() ||
19915 !Flags.hasApproximateFuncs())
19916 return SDValue();
19917
19918 // Don't double the number of libcalls. We are trying to inline fast code.
19920 return SDValue();
19921
19922 // Assume that libcalls are the smallest code.
19923 // TODO: This restriction should probably be lifted for vectors.
19924 if (ForCodeSize)
19925 return SDValue();
19926
19927 // pow(X, 0.25) --> sqrt(sqrt(X))
19928 SDLoc DL(N);
19929 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0));
19930 SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt);
19931 if (ExponentIs025)
19932 return SqrtSqrt;
19933 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
19934 return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt);
19935 }
19936
19937 return SDValue();
19938}
19939
19941 const TargetLowering &TLI) {
19942 // We can fold the fpto[us]i -> [us]itofp pattern into a single ftrunc.
19943 // Additionally, if there are clamps ([us]min or [us]max) around
19944 // the fpto[us]i, we can fold those into fminnum/fmaxnum around the ftrunc.
19945 // If NoSignedZerosFPMath is enabled, this is a direct replacement.
19946 // Otherwise, for strict math, we must handle edge cases:
19947 // 1. For unsigned conversions, use FABS to handle negative cases. Take -0.0
19948 // as example, it first becomes integer 0, and is converted back to +0.0.
19949 // FTRUNC on its own could produce -0.0.
19950
19951 // FIXME: We should be able to use node-level FMF here.
19952 EVT VT = N->getValueType(0);
19954 return SDValue();
19955
19956 bool IsUnsigned = N->getOpcode() == ISD::UINT_TO_FP;
19957 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP;
19958 assert