LLVM 24.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 "SDNodeDbgValue.h"
83
84using namespace llvm;
85using namespace llvm::SDPatternMatch;
86
87#define DEBUG_TYPE "dagcombine"
88
89STATISTIC(NodesCombined , "Number of dag nodes combined");
90STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
91STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
92STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
93STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
94STATISTIC(SlicedLoads, "Number of load sliced");
95STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
96
97DEBUG_COUNTER(DAGCombineCounter, "dagcombine",
98 "Controls whether a DAG combine is performed for a node");
99
100static cl::opt<bool>
101CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
102 cl::desc("Enable DAG combiner's use of IR alias analysis"));
103
104static cl::opt<bool>
105UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
106 cl::desc("Enable DAG combiner's use of TBAA"));
107
108#ifndef NDEBUG
110CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
111 cl::desc("Only use DAG-combiner alias analysis in this"
112 " function"));
113#endif
114
115/// Hidden option to stress test load slicing, i.e., when this option
116/// is enabled, load slicing bypasses most of its profitability guards.
117static cl::opt<bool>
118StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
119 cl::desc("Bypass the profitability model of load slicing"),
120 cl::init(false));
121
122static cl::opt<bool>
123 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
124 cl::desc("DAG combiner may split indexing from loads"));
125
126static cl::opt<bool>
127 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
128 cl::desc("DAG combiner enable merging multiple stores "
129 "into a wider store"));
130
132 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
133 cl::desc("Limit the number of operands to inline for Token Factors"));
134
136 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
137 cl::desc("Limit the number of times for the same StoreNode and RootNode "
138 "to bail out in store merging dependence check"));
139
141 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
142 cl::desc("DAG combiner enable reducing the width of load/op/store "
143 "sequence"));
145 "combiner-reduce-load-op-store-width-force-narrowing-profitable",
146 cl::Hidden, cl::init(false),
147 cl::desc("DAG combiner force override the narrowing profitable check when "
148 "reducing the width of load/op/store sequences"));
149
151 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
152 cl::desc("DAG combiner enable load/<replace bytes>/store with "
153 "a narrower store"));
154
156 "combiner-topological-sorting", cl::Hidden, cl::init(false),
157 cl::desc("DAG combiner nodes consistently processed in topological order"));
158
159static cl::opt<bool> DisableCombines("combiner-disabled", cl::Hidden,
160 cl::init(false),
161 cl::desc("Disable the DAG combiner"));
162
163namespace {
164
165 class DAGCombiner {
166 SelectionDAG &DAG;
167 const TargetLowering &TLI;
168 const SelectionDAGTargetInfo *STI;
170 CodeGenOptLevel OptLevel;
171 bool LegalDAG = false;
172 bool LegalOperations = false;
173 bool LegalTypes = false;
174 bool ForCodeSize;
175 bool DisableGenericCombines;
176
177 /// Worklist of all of the nodes that need to be simplified.
178 ///
179 /// This must behave as a stack -- new nodes to process are pushed onto the
180 /// back and when processing we pop off of the back.
181 ///
182 /// The worklist will not contain duplicates but may contain null entries
183 /// due to nodes being deleted from the underlying DAG. For fast lookup and
184 /// deduplication, the index of the node in this vector is stored in the
185 /// node in SDNode::CombinerWorklistIndex.
187
188 /// This records all nodes attempted to be added to the worklist since we
189 /// considered a new worklist entry. As we keep do not add duplicate nodes
190 /// in the worklist, this is different from the tail of the worklist.
192
193 /// Map from candidate StoreNode to the pair of RootNode and count.
194 /// The count is used to track how many times we have seen the StoreNode
195 /// with the same RootNode bail out in dependence check. If we have seen
196 /// the bail out for the same pair many times over a limit, we won't
197 /// consider the StoreNode with the same RootNode as store merging
198 /// candidate again.
200
201 // BatchAA - Used for DAG load/store alias analysis.
202 BatchAAResults *BatchAA;
203
204 /// This caches all chains that have already been processed in
205 /// DAGCombiner::getStoreMergeCandidates() and found to have no mergeable
206 /// stores candidates.
207 SmallPtrSet<SDNode *, 4> ChainsWithoutMergeableStores;
208
209 /// When an instruction is simplified, add all users of the instruction to
210 /// the work lists because they might get more simplified now.
211 void AddUsersToWorklist(SDNode *N) {
212 for (SDNode *Node : N->users())
213 AddToWorklist(Node);
214 }
215
216 /// Convenient shorthand to add a node and all of its user to the worklist.
217 void AddToWorklistWithUsers(SDNode *N) {
218 AddUsersToWorklist(N);
219 AddToWorklist(N);
220 }
221
222 // Prune potentially dangling nodes. This is called after
223 // any visit to a node, but should also be called during a visit after any
224 // failed combine which may have created a DAG node.
225 void clearAddedDanglingWorklistEntries() {
226 // Check any nodes added to the worklist to see if they are prunable.
227 while (!PruningList.empty()) {
228 auto *N = PruningList.pop_back_val();
229 if (N->use_empty())
230 recursivelyDeleteUnusedNodes(N);
231 }
232 }
233
234 SDNode *getNextWorklistEntry() {
235 // Before we do any work, remove nodes that are not in use.
236 clearAddedDanglingWorklistEntries();
237 SDNode *N = nullptr;
238 // The Worklist holds the SDNodes in order, but it may contain null
239 // entries.
240 while (!N && !Worklist.empty()) {
241 N = Worklist.pop_back_val();
242 }
243
244 if (N) {
245 assert(N->getCombinerWorklistIndex() >= 0 &&
246 "Found a worklist entry without a corresponding map entry!");
247 // Set to -2 to indicate that we combined the node.
248 N->setCombinerWorklistIndex(-2);
249 }
250 return N;
251 }
252
253 /// Call the node-specific routine that folds each particular type of node.
254 SDValue visit(SDNode *N);
255
256 public:
257 DAGCombiner(SelectionDAG &D, BatchAAResults *BatchAA, CodeGenOptLevel OL)
258 : DAG(D), TLI(D.getTargetLoweringInfo()),
259 STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL),
260 BatchAA(BatchAA) {
261 ForCodeSize = DAG.shouldOptForSize();
262 DisableGenericCombines =
263 DisableCombines || (STI && STI->disableGenericCombines(OptLevel));
264 }
265
266 void ConsiderForPruning(SDNode *N) {
267 // Mark this for potential pruning.
268 PruningList.insert(N);
269 }
270
271 /// Add to the worklist making sure its instance is at the back (next to be
272 /// processed.)
273 void AddToWorklist(SDNode *N, bool IsCandidateForPruning = true,
274 bool SkipIfCombinedBefore = false) {
275 assert(N->getOpcode() != ISD::DELETED_NODE &&
276 "Deleted Node added to Worklist");
277
278 // Skip handle nodes as they can't usefully be combined and confuse the
279 // zero-use deletion strategy.
280 if (N->getOpcode() == ISD::HANDLENODE)
281 return;
282
283 if (SkipIfCombinedBefore && N->getCombinerWorklistIndex() == -2)
284 return;
285
286 if (IsCandidateForPruning)
287 ConsiderForPruning(N);
288
289 if (N->getCombinerWorklistIndex() < 0) {
290 N->setCombinerWorklistIndex(Worklist.size());
291 Worklist.push_back(N);
292 }
293 }
294
295 /// Remove all instances of N from the worklist.
296 void removeFromWorklist(SDNode *N) {
297 PruningList.remove(N);
298 StoreRootCountMap.erase(N);
299
300 int WorklistIndex = N->getCombinerWorklistIndex();
301 // If not in the worklist, the index might be -1 or -2 (was combined
302 // before). As the node gets deleted anyway, there's no need to update
303 // the index.
304 if (WorklistIndex < 0)
305 return; // Not in the worklist.
306
307 // Null out the entry rather than erasing it to avoid a linear operation.
308 Worklist[WorklistIndex] = nullptr;
309 N->setCombinerWorklistIndex(-1);
310 }
311
312 void deleteAndRecombine(SDNode *N);
313 bool recursivelyDeleteUnusedNodes(SDNode *N);
314
315 /// Replaces all uses of the results of one DAG node with new values.
316 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
317 bool AddTo = true);
318
319 /// Replaces all uses of the results of one DAG node with new values.
320 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
321 return CombineTo(N, &Res, 1, AddTo);
322 }
323
324 /// Replaces all uses of the results of one DAG node with new values.
325 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
326 bool AddTo = true) {
327 SDValue To[] = { Res0, Res1 };
328 return CombineTo(N, To, 2, AddTo);
329 }
330
331 SDValue CombineTo(SDNode *N, SmallVectorImpl<SDValue> *To,
332 bool AddTo = true) {
333 return CombineTo(N, To->data(), To->size(), AddTo);
334 }
335
336 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
337
338 private:
339 /// Check the specified integer node value to see if it can be simplified or
340 /// if things it uses can be simplified by bit propagation.
341 /// If so, return true.
342 bool SimplifyDemandedBits(SDValue Op) {
343 unsigned BitWidth = Op.getScalarValueSizeInBits();
344 APInt DemandedBits = APInt::getAllOnes(BitWidth);
345 return SimplifyDemandedBits(Op, DemandedBits);
346 }
347
348 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
349 EVT VT = Op.getValueType();
350 APInt DemandedElts = VT.isFixedLengthVector()
352 : APInt(1, 1);
353 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, false);
354 }
355
356 /// Check the specified vector node value to see if it can be simplified or
357 /// if things it uses can be simplified as it only uses some of the
358 /// elements. If so, return true.
359 bool SimplifyDemandedVectorElts(SDValue Op) {
360 // TODO: For now just pretend it cannot be simplified.
361 if (Op.getValueType().isScalableVector())
362 return false;
363
364 unsigned NumElts = Op.getValueType().getVectorNumElements();
365 APInt DemandedElts = APInt::getAllOnes(NumElts);
366 return SimplifyDemandedVectorElts(Op, DemandedElts);
367 }
368
369 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
370 const APInt &DemandedElts,
371 bool AssumeSingleUse = false);
372 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
373 bool AssumeSingleUse = false);
374
375 bool CombineToPreIndexedLoadStore(SDNode *N);
376 bool CombineToPostIndexedLoadStore(SDNode *N);
377 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
378 bool SliceUpLoad(SDNode *N);
379
380 // Looks up the chain to find a unique (unaliased) store feeding the passed
381 // load. If no such store is found, returns a nullptr.
382 // Note: This will look past a CALLSEQ_START if the load is chained to it so
383 // so that it can find stack stores for byval params.
384 StoreSDNode *getUniqueStoreFeeding(LoadSDNode *LD, int64_t &Offset);
385 // Scalars have size 0 to distinguish from singleton vectors.
386 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
387 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
388 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
389
390 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
391 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
392 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
393 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
394 SDValue PromoteIntBinOp(SDValue Op);
395 SDValue PromoteIntShiftOp(SDValue Op);
396 SDValue PromoteExtend(SDValue Op);
397 bool PromoteLoad(SDValue Op);
398
399 SDValue foldShiftToAvg(SDNode *N, const SDLoc &DL);
400 // Fold `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`
401 SDValue foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT);
402
403 SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
404 SDValue RHS, SDValue True, SDValue False,
405 ISD::CondCode CC);
406
407 /// Call the node-specific routine that knows how to fold each
408 /// particular type of node. If that doesn't do anything, try the
409 /// target-specific DAG combines.
410 SDValue combine(SDNode *N);
411
412 // Visitation implementation - Implement dag node combining for different
413 // node types. The semantics are as follows:
414 // Return Value:
415 // SDValue.getNode() == 0 - No change was made
416 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
417 // otherwise - N should be replaced by the returned Operand.
418 //
419 SDValue visitTokenFactor(SDNode *N);
420 SDValue visitMERGE_VALUES(SDNode *N);
421 SDValue visitADD(SDNode *N);
422 SDValue visitADDLike(SDNode *N);
423 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, const SDLoc &DL);
424 SDValue visitPTRADD(SDNode *N);
425 SDValue visitSUB(SDNode *N);
426 SDValue visitADDSAT(SDNode *N);
427 SDValue visitSUBSAT(SDNode *N);
428 SDValue visitADDC(SDNode *N);
429 SDValue visitADDO(SDNode *N);
430 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
431 SDValue visitSUBC(SDNode *N);
432 SDValue visitSUBO(SDNode *N);
433 SDValue visitADDE(SDNode *N);
434 SDValue visitUADDO_CARRY(SDNode *N);
435 SDValue visitSADDO_CARRY(SDNode *N);
436 SDValue visitUADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
437 SDNode *N);
438 SDValue visitSADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
439 SDNode *N);
440 SDValue visitSUBE(SDNode *N);
441 SDValue visitUSUBO_CARRY(SDNode *N);
442 SDValue visitSSUBO_CARRY(SDNode *N);
443 SDValue visitMUL(SDNode *N);
444 SDValue visitMULFIX(SDNode *N);
445 SDValue useDivRem(SDNode *N);
446 SDValue visitSDIV(SDNode *N);
447 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
448 SDValue visitUDIV(SDNode *N);
449 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
450 SDValue visitREM(SDNode *N);
451 SDValue visitMULHU(SDNode *N);
452 SDValue visitMULHS(SDNode *N);
453 SDValue visitAVG(SDNode *N);
454 SDValue visitABD(SDNode *N);
455 SDValue visitSMUL_LOHI(SDNode *N);
456 SDValue visitUMUL_LOHI(SDNode *N);
457 SDValue visitMULO(SDNode *N);
458 SDValue visitIMINMAX(SDNode *N);
459 SDValue visitAND(SDNode *N);
460 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
461 SDValue visitOR(SDNode *N);
462 SDValue visitORLike(SDValue N0, SDValue N1, const SDLoc &DL);
463 SDValue visitXOR(SDNode *N);
464 SDValue SimplifyVCastOp(SDNode *N, const SDLoc &DL);
465 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
466 SDValue visitSHL(SDNode *N);
467 SDValue visitSRA(SDNode *N);
468 SDValue visitSRL(SDNode *N);
469 SDValue visitFunnelShift(SDNode *N);
470 SDValue visitSHLSAT(SDNode *N);
471 SDValue visitRotate(SDNode *N);
472 SDValue visitABS(SDNode *N);
473 SDValue visitABS_MIN_POISON(SDNode *N);
474 SDValue visitCLMUL(SDNode *N);
475 SDValue visitPEXT(SDNode *N);
476 SDValue visitPDEP(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 visitSELECT_CC(SDNode *N);
487 SDValue visitSETCC(SDNode *N);
488 SDValue visitSETCCCARRY(SDNode *N);
489 SDValue visitSIGN_EXTEND(SDNode *N);
490 SDValue visitZERO_EXTEND(SDNode *N);
491 SDValue visitANY_EXTEND(SDNode *N);
492 SDValue visitAssertExt(SDNode *N);
493 SDValue visitAssertAlign(SDNode *N);
494 SDValue visitIS_FPCLASS(SDNode *N);
495 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
496 SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
497 SDValue visitTRUNCATE(SDNode *N);
498 SDValue visitTRUNCATE_USAT_U(SDNode *N);
499 SDValue visitBITCAST(SDNode *N);
500 SDValue visitFREEZE(SDNode *N);
501 SDValue visitBUILD_PAIR(SDNode *N);
502 SDValue visitFADD(SDNode *N);
503 SDValue visitSTRICT_FADD(SDNode *N);
504 SDValue visitFSUB(SDNode *N);
505 SDValue visitFMUL(SDNode *N);
506 SDValue visitFMA(SDNode *N);
507 SDValue visitFMAD(SDNode *N);
508 SDValue visitFMULADD(SDNode *N);
509 SDValue visitFDIV(SDNode *N);
510 SDValue visitFREM(SDNode *N);
511 SDValue visitFSQRT(SDNode *N);
512 SDValue visitFCOPYSIGN(SDNode *N);
513 SDValue visitFPOW(SDNode *N);
514 SDValue visitFCANONICALIZE(SDNode *N);
515 SDValue visitSINT_TO_FP(SDNode *N);
516 SDValue visitUINT_TO_FP(SDNode *N);
517 SDValue visitFP_TO_SINT(SDNode *N);
518 SDValue visitFP_TO_UINT(SDNode *N);
519 SDValue visitXROUND(SDNode *N);
520 SDValue visitFP_ROUND(SDNode *N);
521 SDValue visitFP_EXTEND(SDNode *N);
522 SDValue visitFNEG(SDNode *N);
523 SDValue visitFABS(SDNode *N);
524 SDValue visitFCEIL(SDNode *N);
525 SDValue visitFTRUNC(SDNode *N);
526 SDValue visitFFREXP(SDNode *N);
527 SDValue visitFFLOOR(SDNode *N);
528 SDValue visitFMinMax(SDNode *N);
529 SDValue visitBRCOND(SDNode *N);
530 SDValue visitBR_CC(SDNode *N);
531 SDValue visitLOAD(SDNode *N);
532
533 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
534 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
535 SDValue replaceStoreOfInsertLoad(StoreSDNode *ST);
536
537 bool refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(SDNode *N);
538 SDValue combineStoreConcatTruncVector(StoreSDNode *N);
539 SDValue visitSTORE(SDNode *N);
540 SDValue visitATOMIC_STORE(SDNode *N);
541 SDValue visitLIFETIME_END(SDNode *N);
542 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
543 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
544 SDValue visitBUILD_VECTOR(SDNode *N);
545 SDValue visitCONCAT_VECTORS(SDNode *N);
546 SDValue visitVECTOR_INTERLEAVE(SDNode *N);
547 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
548 SDValue visitVECTOR_SHUFFLE(SDNode *N);
549 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
550 SDValue visitINSERT_SUBVECTOR(SDNode *N);
551 SDValue visitVECTOR_COMPRESS(SDNode *N);
552 SDValue visitMLOAD(SDNode *N);
553 SDValue visitMSTORE(SDNode *N);
554 SDValue visitMGATHER(SDNode *N);
555 SDValue visitMSCATTER(SDNode *N);
556 SDValue visitMHISTOGRAM(SDNode *N);
557 SDValue visitPARTIAL_REDUCE_MLA(SDNode *N);
558 SDValue visitLOOP_DEPENDENCE_MASK(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,
1375 Opc, m_Value(RedA, m_OneUse(m_UnaryOp(RedOpc, m_Value(A)))),
1376 m_Value(B, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1377 sd_match(N1,
1379 Opc, m_Value(RedB, m_OneUse(m_UnaryOp(RedOpc, m_Value(C)))),
1380 m_Value(D, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1381 A.getValueType() == C.getValueType() &&
1382 hasOperation(Opc, A.getValueType()) &&
1383 TLI.shouldReassociateReduction(RedOpc, VT)) {
1384 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1385 (!N0->getFlags().hasAllowReassociation() ||
1387 !RedA->getFlags().hasAllowReassociation() ||
1388 !RedB->getFlags().hasAllowReassociation()))
1389 return SDValue();
1390 SelectionDAG::FlagInserter FlagsInserter(
1391 DAG, Flags & N0->getFlags() & N1->getFlags() & RedA->getFlags() &
1392 RedB->getFlags());
1393 SDValue Op = DAG.getNode(Opc, DL, A.getValueType(), A, C);
1394 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1395 SDValue Op2 = DAG.getNode(Opc, DL, VT, B, D);
1396 return DAG.getNode(Opc, DL, VT, Red, Op2);
1397 }
1398
1399 // Reassociate a reduction chain so two reductions become adjacent and the
1400 // folds above can merge them:
1401 // op(vecreduce(X), op(vecreduce(Y), Z))
1402 // -> op(vecreduce(op(X, Y)), Z)
1403 // Applied to fixpoint by the combiner worklist, this collapses an
1404 // arbitrarily long chain of reductions (such as the left-leaning chain SLP
1405 // emits) into a single reduction.
1406 auto FoldReductionChain = [&](SDValue Red0, SDValue Chain) -> SDValue {
1407 SDValue X, Y, Z, RedY;
1408 if (!sd_match(Red0, m_OneUse(m_UnaryOp(RedOpc, m_Value(X)))) ||
1409 !sd_match(
1410 Chain,
1412 Opc, m_Value(RedY, m_OneUse(m_UnaryOp(RedOpc, m_Value(Y)))),
1413 m_Value(Z, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) ||
1414 X.getValueType() != Y.getValueType() ||
1415 !hasOperation(Opc, X.getValueType()) ||
1416 !TLI.shouldReassociateReduction(RedOpc, VT))
1417 return SDValue();
1418 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1419 (!Chain->getFlags().hasAllowReassociation() ||
1420 !Red0->getFlags().hasAllowReassociation() ||
1421 !RedY->getFlags().hasAllowReassociation()))
1422 return SDValue();
1423 SelectionDAG::FlagInserter FlagsInserter(
1424 DAG, Flags & Chain->getFlags() & Red0->getFlags() & RedY->getFlags());
1425 SDValue Op = DAG.getNode(Opc, DL, X.getValueType(), X, Y);
1426 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1427 return DAG.getNode(Opc, DL, VT, Red, Z);
1428 };
1429 if (SDValue V = FoldReductionChain(N0, N1))
1430 return V;
1431 if (SDValue V = FoldReductionChain(N1, N0))
1432 return V;
1433
1434 return SDValue();
1435}
1436
1437SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1438 bool AddTo) {
1439 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1440 ++NodesCombined;
1441 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1442 To[0].dump(&DAG);
1443 dbgs() << " and " << NumTo - 1 << " other values\n");
1444 for (unsigned i = 0, e = NumTo; i != e; ++i)
1445 assert((!To[i].getNode() ||
1446 N->getValueType(i) == To[i].getValueType()) &&
1447 "Cannot combine value to value of different type!");
1448
1449 WorklistRemover DeadNodes(*this);
1450 DAG.ReplaceAllUsesWith(N, To);
1451 if (AddTo) {
1452 // Push the new nodes and any users onto the worklist
1453 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1454 if (To[i].getNode())
1455 AddToWorklistWithUsers(To[i].getNode());
1456 }
1457 }
1458
1459 // Finally, if the node is now dead, remove it from the graph. The node
1460 // may not be dead if the replacement process recursively simplified to
1461 // something else needing this node.
1462 if (N->use_empty())
1463 deleteAndRecombine(N);
1464 return SDValue(N, 0);
1465}
1466
1467void DAGCombiner::
1468CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1469 // Replace the old value with the new one.
1470 ++NodesCombined;
1471 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.dump(&DAG);
1472 dbgs() << "\nWith: "; TLO.New.dump(&DAG); dbgs() << '\n');
1473
1474 // Replace all uses.
1475 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1476
1477 // Push the new node and any (possibly new) users onto the worklist.
1478 AddToWorklistWithUsers(TLO.New.getNode());
1479
1480 // Finally, if the node is now dead, remove it from the graph.
1481 recursivelyDeleteUnusedNodes(TLO.Old.getNode());
1482}
1483
1484/// Check the specified integer node value to see if it can be simplified or if
1485/// things it uses can be simplified by bit propagation. If so, return true.
1486bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1487 const APInt &DemandedElts,
1488 bool AssumeSingleUse) {
1489 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1490 KnownBits Known;
1491 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1492 AssumeSingleUse))
1493 return false;
1494
1495 // Revisit the node.
1496 AddToWorklist(Op.getNode());
1497
1498 CommitTargetLoweringOpt(TLO);
1499 return true;
1500}
1501
1502/// Check the specified vector node value to see if it can be simplified or
1503/// if things it uses can be simplified as it only uses some of the elements.
1504/// If so, return true.
1505bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1506 const APInt &DemandedElts,
1507 bool AssumeSingleUse) {
1508 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1509 APInt KnownUndef, KnownZero;
1510 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1511 TLO, 0, AssumeSingleUse))
1512 return false;
1513
1514 // Revisit the node.
1515 AddToWorklist(Op.getNode());
1516
1517 CommitTargetLoweringOpt(TLO);
1518 return true;
1519}
1520
1521void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1522 SDLoc DL(Load);
1523 EVT VT = Load->getValueType(0);
1524 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1525
1526 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1527 Trunc.dump(&DAG); dbgs() << '\n');
1528
1529 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1530 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1531
1532 AddToWorklist(Trunc.getNode());
1533 recursivelyDeleteUnusedNodes(Load);
1534}
1535
1536SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1537 Replace = false;
1538 SDLoc DL(Op);
1539 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1540 LoadSDNode *LD = cast<LoadSDNode>(Op);
1541 EVT MemVT = LD->getMemoryVT();
1543 : LD->getExtensionType();
1544 Replace = true;
1545 return DAG.getExtLoad(ExtType, DL, PVT,
1546 LD->getChain(), LD->getBasePtr(),
1547 MemVT, LD->getMemOperand());
1548 }
1549
1550 unsigned Opc = Op.getOpcode();
1551 switch (Opc) {
1552 default: break;
1553 case ISD::AssertSext:
1554 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1555 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1556 break;
1557 case ISD::AssertZext:
1558 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1559 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1560 break;
1561 case ISD::Constant: {
1562 unsigned ExtOpc =
1563 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1564 return DAG.getNode(ExtOpc, DL, PVT, Op);
1565 }
1566 }
1567
1568 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1569 return SDValue();
1570 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1571}
1572
1573SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1575 return SDValue();
1576 EVT OldVT = Op.getValueType();
1577 SDLoc DL(Op);
1578 bool Replace = false;
1579 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1580 if (!NewOp.getNode())
1581 return SDValue();
1582 AddToWorklist(NewOp.getNode());
1583
1584 if (Replace)
1585 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1586 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1587 DAG.getValueType(OldVT));
1588}
1589
1590SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1591 EVT OldVT = Op.getValueType();
1592 SDLoc DL(Op);
1593 bool Replace = false;
1594 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1595 if (!NewOp.getNode())
1596 return SDValue();
1597 AddToWorklist(NewOp.getNode());
1598
1599 if (Replace)
1600 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1601 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1602}
1603
1604/// Promote the specified integer binary operation if the target indicates it is
1605/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1606/// i32 since i16 instructions are longer.
1607SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1608 if (!LegalOperations)
1609 return SDValue();
1610
1611 EVT VT = Op.getValueType();
1612 if (VT.isVector() || !VT.isInteger())
1613 return SDValue();
1614
1615 // If operation type is 'undesirable', e.g. i16 on x86, consider
1616 // promoting it.
1617 unsigned Opc = Op.getOpcode();
1618 if (TLI.isTypeDesirableForOp(Opc, VT))
1619 return SDValue();
1620
1621 EVT PVT = VT;
1622 // Consult target whether it is a good idea to promote this operation and
1623 // what's the right type to promote it to.
1624 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1625 assert(PVT != VT && "Don't know what type to promote to!");
1626
1627 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1628
1629 bool Replace0 = false;
1630 SDValue N0 = Op.getOperand(0);
1631 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1632
1633 bool Replace1 = false;
1634 SDValue N1 = Op.getOperand(1);
1635 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1636 SDLoc DL(Op);
1637
1638 SDValue RV =
1639 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1640
1641 // We are always replacing N0/N1's use in N and only need additional
1642 // replacements if there are additional uses.
1643 // Note: We are checking uses of the *nodes* (SDNode) rather than values
1644 // (SDValue) here because the node may reference multiple values
1645 // (for example, the chain value of a load node).
1646 Replace0 &= !N0->hasOneUse();
1647 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1648
1649 // Combine Op here so it is preserved past replacements.
1650 CombineTo(Op.getNode(), RV);
1651
1652 // If operands have a use ordering, make sure we deal with
1653 // predecessor first.
1654 if (Replace0 && Replace1 && N0->isPredecessorOf(N1.getNode())) {
1655 std::swap(N0, N1);
1656 std::swap(NN0, NN1);
1657 }
1658
1659 if (Replace0) {
1660 AddToWorklist(NN0.getNode());
1661 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1662 }
1663 if (Replace1) {
1664 AddToWorklist(NN1.getNode());
1665 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1666 }
1667 return Op;
1668 }
1669 return SDValue();
1670}
1671
1672/// Promote the specified integer shift operation if the target indicates it is
1673/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1674/// i32 since i16 instructions are longer.
1675SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1676 if (!LegalOperations)
1677 return SDValue();
1678
1679 EVT VT = Op.getValueType();
1680 if (VT.isVector() || !VT.isInteger())
1681 return SDValue();
1682
1683 // If operation type is 'undesirable', e.g. i16 on x86, consider
1684 // promoting it.
1685 unsigned Opc = Op.getOpcode();
1686 if (TLI.isTypeDesirableForOp(Opc, VT))
1687 return SDValue();
1688
1689 EVT PVT = VT;
1690 // Consult target whether it is a good idea to promote this operation and
1691 // what's the right type to promote it to.
1692 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1693 assert(PVT != VT && "Don't know what type to promote to!");
1694
1695 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1696
1697 SDNodeFlags TruncFlags;
1698 bool Replace = false;
1699 SDValue N0 = Op.getOperand(0);
1700 if (Opc == ISD::SRA) {
1701 N0 = SExtPromoteOperand(N0, PVT);
1702 } else if (Opc == ISD::SRL) {
1703 N0 = ZExtPromoteOperand(N0, PVT);
1704 } else {
1705 if (Op->getFlags().hasNoUnsignedWrap()) {
1706 N0 = ZExtPromoteOperand(N0, PVT);
1707 TruncFlags = SDNodeFlags::NoUnsignedWrap;
1708 } else if (Op->getFlags().hasNoSignedWrap()) {
1709 N0 = SExtPromoteOperand(N0, PVT);
1710 TruncFlags = SDNodeFlags::NoSignedWrap;
1711 } else {
1712 N0 = PromoteOperand(N0, PVT, Replace);
1713 }
1714 }
1715
1716 if (!N0.getNode())
1717 return SDValue();
1718
1719 SDLoc DL(Op);
1720 SDValue N1 = Op.getOperand(1);
1721 SDValue RV = DAG.getNode(ISD::TRUNCATE, DL, VT,
1722 DAG.getNode(Opc, DL, PVT, N0, N1), TruncFlags);
1723
1724 if (Replace)
1725 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1726
1727 // Deal with Op being deleted.
1728 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1729 return RV;
1730 }
1731 return SDValue();
1732}
1733
1734SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1735 if (!LegalOperations)
1736 return SDValue();
1737
1738 EVT VT = Op.getValueType();
1739 if (VT.isVector() || !VT.isInteger())
1740 return SDValue();
1741
1742 // If operation type is 'undesirable', e.g. i16 on x86, consider
1743 // promoting it.
1744 unsigned Opc = Op.getOpcode();
1745 if (TLI.isTypeDesirableForOp(Opc, VT))
1746 return SDValue();
1747
1748 EVT PVT = VT;
1749 // Consult target whether it is a good idea to promote this operation and
1750 // what's the right type to promote it to.
1751 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1752 assert(PVT != VT && "Don't know what type to promote to!");
1753 // fold (aext (aext x)) -> (aext x)
1754 // fold (aext (zext x)) -> (zext x)
1755 // fold (aext (sext x)) -> (sext x)
1756 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1757 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1758 }
1759 return SDValue();
1760}
1761
1762bool DAGCombiner::PromoteLoad(SDValue Op) {
1763 if (!LegalOperations)
1764 return false;
1765
1766 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1767 return false;
1768
1769 EVT VT = Op.getValueType();
1770 if (VT.isVector() || !VT.isInteger())
1771 return false;
1772
1773 // If operation type is 'undesirable', e.g. i16 on x86, consider
1774 // promoting it.
1775 unsigned Opc = Op.getOpcode();
1776 if (TLI.isTypeDesirableForOp(Opc, VT))
1777 return false;
1778
1779 EVT PVT = VT;
1780 // Consult target whether it is a good idea to promote this operation and
1781 // what's the right type to promote it to.
1782 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1783 assert(PVT != VT && "Don't know what type to promote to!");
1784
1785 SDLoc DL(Op);
1786 SDNode *N = Op.getNode();
1787 LoadSDNode *LD = cast<LoadSDNode>(N);
1788 EVT MemVT = LD->getMemoryVT();
1790 : LD->getExtensionType();
1791 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1792 LD->getChain(), LD->getBasePtr(),
1793 MemVT, LD->getMemOperand());
1794 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1795
1796 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1797 Result.dump(&DAG); dbgs() << '\n');
1798
1799 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1800 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1801
1802 AddToWorklist(Result.getNode());
1803 recursivelyDeleteUnusedNodes(N);
1804 return true;
1805 }
1806
1807 return false;
1808}
1809
1810/// Recursively delete a node which has no uses and any operands for
1811/// which it is the only use.
1812///
1813/// Note that this both deletes the nodes and removes them from the worklist.
1814/// It also adds any nodes who have had a user deleted to the worklist as they
1815/// may now have only one use and subject to other combines.
1816bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1817 if (!N->use_empty())
1818 return false;
1819
1820 SmallSetVector<SDNode *, 16> Nodes;
1821 Nodes.insert(N);
1822 do {
1823 N = Nodes.pop_back_val();
1824 if (!N)
1825 continue;
1826
1827 if (N->use_empty()) {
1828 for (const SDValue &ChildN : N->op_values())
1829 Nodes.insert(ChildN.getNode());
1830
1831 removeFromWorklist(N);
1832 DAG.DeleteNode(N);
1833 } else {
1834 AddToWorklist(N);
1835 }
1836 } while (!Nodes.empty());
1837 return true;
1838}
1839
1840//===----------------------------------------------------------------------===//
1841// Main DAG Combiner implementation
1842//===----------------------------------------------------------------------===//
1843
1844void DAGCombiner::Run(CombineLevel AtLevel) {
1845 // set the instance variables, so that the various visit routines may use it.
1846 Level = AtLevel;
1847 LegalDAG = Level >= AfterLegalizeDAG;
1848 LegalOperations = Level >= AfterLegalizeVectorOps;
1849 LegalTypes = Level >= AfterLegalizeTypes;
1850
1851 bool UseTopologicalSorting = EnableTopologicalSorting.getNumOccurrences() > 0
1853 : TLI.useTopologicalSorting();
1854
1855 WorklistInserter AddNodes(*this);
1856
1857 if (UseTopologicalSorting)
1859
1860 // Add all the dag nodes to the worklist.
1861 //
1862 // Note: All nodes are not added to PruningList here, this is because the only
1863 // nodes which can be deleted are those which have no uses and all other nodes
1864 // which would otherwise be added to the worklist by the first call to
1865 // getNextWorklistEntry are already present in it.
1866 if (UseTopologicalSorting) {
1867 for (SDNode &Node : reverse(DAG.allnodes()))
1868 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1869 } else {
1870 for (SDNode &Node : DAG.allnodes())
1871 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1872 }
1873
1874 // Create a dummy node (which is not added to allnodes), that adds a reference
1875 // to the root node, preventing it from being deleted, and tracking any
1876 // changes of the root.
1877 HandleSDNode Dummy(DAG.getRoot());
1878
1879 // While we have a valid worklist entry node, try to combine it.
1880 while (SDNode *N = getNextWorklistEntry()) {
1881 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1882 // N is deleted from the DAG, since they too may now be dead or may have a
1883 // reduced number of uses, allowing other xforms.
1884 if (recursivelyDeleteUnusedNodes(N))
1885 continue;
1886
1887 WorklistRemover DeadNodes(*this);
1888
1889 // If this combine is running after legalizing the DAG, re-legalize any
1890 // nodes pulled off the worklist.
1891 if (LegalDAG) {
1892 SmallSetVector<SDNode *, 16> UpdatedNodes;
1893 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1894
1895 for (SDNode *LN : UpdatedNodes)
1896 AddToWorklistWithUsers(LN);
1897
1898 if (!NIsValid)
1899 continue;
1900 }
1901
1902 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1903
1904 // Add any operands of the new node which have not yet been combined to the
1905 // worklist as well. getNextWorklistEntry flags nodes that have been
1906 // combined before. Because the worklist uniques things already, this won't
1907 // repeatedly process the same operand.
1908 for (const SDValue &ChildN : N->op_values())
1909 AddToWorklist(ChildN.getNode(), /*IsCandidateForPruning=*/true,
1910 /*SkipIfCombinedBefore=*/true);
1911
1912 SDValue RV = combine(N);
1913
1914 if (!RV.getNode())
1915 continue;
1916
1917 ++NodesCombined;
1918
1919 // Invalidate cached info.
1920 ChainsWithoutMergeableStores.clear();
1921
1922 // If we get back the same node we passed in, rather than a new node or
1923 // zero, we know that the node must have defined multiple values and
1924 // CombineTo was used. Since CombineTo takes care of the worklist
1925 // mechanics for us, we have no work to do in this case.
1926 if (RV.getNode() == N)
1927 continue;
1928
1929 assert(N->getOpcode() != ISD::DELETED_NODE &&
1930 RV.getOpcode() != ISD::DELETED_NODE &&
1931 "Node was deleted but visit returned new node!");
1932
1933 LLVM_DEBUG(dbgs() << " ... into: "; RV.dump(&DAG));
1934
1935 if (N->getNumValues() == RV->getNumValues())
1936 DAG.ReplaceAllUsesWith(N, RV.getNode());
1937 else {
1938 assert(N->getValueType(0) == RV.getValueType() &&
1939 N->getNumValues() == 1 && "Type mismatch");
1940 DAG.ReplaceAllUsesWith(N, &RV);
1941 }
1942
1943 // Push the new node and any users onto the worklist. Omit this if the
1944 // new node is the EntryToken (e.g. if a store managed to get optimized
1945 // out), because re-visiting the EntryToken and its users will not uncover
1946 // any additional opportunities, but there may be a large number of such
1947 // users, potentially causing compile time explosion.
1948 if (RV.getOpcode() != ISD::EntryToken)
1949 AddToWorklistWithUsers(RV.getNode());
1950
1951 // Finally, if the node is now dead, remove it from the graph. The node
1952 // may not be dead if the replacement process recursively simplified to
1953 // something else needing this node. This will also take care of adding any
1954 // operands which have lost a user to the worklist.
1955 recursivelyDeleteUnusedNodes(N);
1956 }
1957
1958 // If the root changed (e.g. it was a dead load, update the root).
1959 DAG.setRoot(Dummy.getValue());
1960 DAG.RemoveDeadNodes();
1961}
1962
1963SDValue DAGCombiner::visit(SDNode *N) {
1964 // clang-format off
1965 switch (N->getOpcode()) {
1966 default: break;
1967 case ISD::TokenFactor: return visitTokenFactor(N);
1968 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1969 case ISD::ADD: return visitADD(N);
1970 case ISD::PTRADD: return visitPTRADD(N);
1971 case ISD::SUB: return visitSUB(N);
1972 case ISD::SADDSAT:
1973 case ISD::UADDSAT: return visitADDSAT(N);
1974 case ISD::SSUBSAT:
1975 case ISD::USUBSAT: return visitSUBSAT(N);
1976 case ISD::ADDC: return visitADDC(N);
1977 case ISD::SADDO:
1978 case ISD::UADDO: return visitADDO(N);
1979 case ISD::SUBC: return visitSUBC(N);
1980 case ISD::SSUBO:
1981 case ISD::USUBO: return visitSUBO(N);
1982 case ISD::ADDE: return visitADDE(N);
1983 case ISD::UADDO_CARRY: return visitUADDO_CARRY(N);
1984 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
1985 case ISD::SUBE: return visitSUBE(N);
1986 case ISD::USUBO_CARRY: return visitUSUBO_CARRY(N);
1987 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
1988 case ISD::SMULFIX:
1989 case ISD::SMULFIXSAT:
1990 case ISD::UMULFIX:
1991 case ISD::UMULFIXSAT: return visitMULFIX(N);
1992 case ISD::MUL: return visitMUL(N);
1993 case ISD::SDIV: return visitSDIV(N);
1994 case ISD::UDIV: return visitUDIV(N);
1995 case ISD::SREM:
1996 case ISD::UREM: return visitREM(N);
1997 case ISD::MULHU: return visitMULHU(N);
1998 case ISD::MULHS: return visitMULHS(N);
1999 case ISD::AVGFLOORS:
2000 case ISD::AVGFLOORU:
2001 case ISD::AVGCEILS:
2002 case ISD::AVGCEILU: return visitAVG(N);
2003 case ISD::ABDS:
2004 case ISD::ABDU: return visitABD(N);
2005 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
2006 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
2007 case ISD::SMULO:
2008 case ISD::UMULO: return visitMULO(N);
2009 case ISD::SMIN:
2010 case ISD::SMAX:
2011 case ISD::UMIN:
2012 case ISD::UMAX: return visitIMINMAX(N);
2013 case ISD::AND: return visitAND(N);
2014 case ISD::OR: return visitOR(N);
2015 case ISD::XOR: return visitXOR(N);
2016 case ISD::SHL: return visitSHL(N);
2017 case ISD::SRA: return visitSRA(N);
2018 case ISD::SRL: return visitSRL(N);
2019 case ISD::ROTR:
2020 case ISD::ROTL: return visitRotate(N);
2021 case ISD::FSHL:
2022 case ISD::FSHR: return visitFunnelShift(N);
2023 case ISD::SSHLSAT:
2024 case ISD::USHLSAT: return visitSHLSAT(N);
2025 case ISD::ABS: return visitABS(N);
2026 case ISD::ABS_MIN_POISON: return visitABS_MIN_POISON(N);
2027 case ISD::CLMUL:
2028 case ISD::CLMULR:
2029 case ISD::CLMULH: return visitCLMUL(N);
2030 case ISD::PEXT: return visitPEXT(N);
2031 case ISD::PDEP: return visitPDEP(N);
2032 case ISD::BSWAP: return visitBSWAP(N);
2033 case ISD::BITREVERSE: return visitBITREVERSE(N);
2034 case ISD::CTLZ: return visitCTLZ(N);
2035 case ISD::CTLZ_ZERO_POISON: return visitCTLZ_ZERO_POISON(N);
2036 case ISD::CTTZ: return visitCTTZ(N);
2037 case ISD::CTTZ_ZERO_POISON: return visitCTTZ_ZERO_POISON(N);
2038 case ISD::CTPOP: return visitCTPOP(N);
2039 case ISD::SELECT: return visitSELECT(N);
2040 case ISD::VSELECT: return visitVSELECT(N);
2041 case ISD::SELECT_CC: return visitSELECT_CC(N);
2042 case ISD::SETCC: return visitSETCC(N);
2043 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
2044 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
2045 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
2046 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
2047 case ISD::AssertSext:
2048 case ISD::AssertZext: return visitAssertExt(N);
2049 case ISD::AssertAlign: return visitAssertAlign(N);
2050 case ISD::IS_FPCLASS: return visitIS_FPCLASS(N);
2051 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
2054 case ISD::ANY_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
2055 case ISD::TRUNCATE: return visitTRUNCATE(N);
2056 case ISD::TRUNCATE_USAT_U: return visitTRUNCATE_USAT_U(N);
2057 case ISD::BITCAST: return visitBITCAST(N);
2058 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
2059 case ISD::FADD: return visitFADD(N);
2060 case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
2061 case ISD::FSUB: return visitFSUB(N);
2062 case ISD::FMUL: return visitFMUL(N);
2063 case ISD::FMA: return visitFMA(N);
2064 case ISD::FMAD: return visitFMAD(N);
2065 case ISD::FMULADD: return visitFMULADD(N);
2066 case ISD::FDIV: return visitFDIV(N);
2067 case ISD::FREM: return visitFREM(N);
2068 case ISD::FSQRT: return visitFSQRT(N);
2069 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
2070 case ISD::FPOW: return visitFPOW(N);
2071 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
2072 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
2073 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
2074 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
2075 case ISD::LROUND:
2076 case ISD::LLROUND:
2077 case ISD::LRINT:
2078 case ISD::LLRINT: return visitXROUND(N);
2079 case ISD::FP_ROUND: return visitFP_ROUND(N);
2080 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
2081 case ISD::FNEG: return visitFNEG(N);
2082 case ISD::FABS: return visitFABS(N);
2083 case ISD::FFLOOR: return visitFFLOOR(N);
2084 case ISD::FMINNUM:
2085 case ISD::FMAXNUM:
2086 case ISD::FMINIMUM:
2087 case ISD::FMAXIMUM:
2088 case ISD::FMINIMUMNUM:
2089 case ISD::FMAXIMUMNUM: return visitFMinMax(N);
2090 case ISD::FCEIL: return visitFCEIL(N);
2091 case ISD::FTRUNC: return visitFTRUNC(N);
2092 case ISD::FFREXP: return visitFFREXP(N);
2093 case ISD::BRCOND: return visitBRCOND(N);
2094 case ISD::BR_CC: return visitBR_CC(N);
2095 case ISD::LOAD: return visitLOAD(N);
2096 case ISD::STORE: return visitSTORE(N);
2097 case ISD::ATOMIC_STORE: return visitATOMIC_STORE(N);
2098 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
2099 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
2100 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
2101 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
2102 case ISD::VECTOR_INTERLEAVE: return visitVECTOR_INTERLEAVE(N);
2103 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
2104 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
2105 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
2106 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
2107 case ISD::MGATHER: return visitMGATHER(N);
2108 case ISD::MLOAD: return visitMLOAD(N);
2109 case ISD::MSCATTER: return visitMSCATTER(N);
2110 case ISD::MSTORE: return visitMSTORE(N);
2111 case ISD::EXPERIMENTAL_VECTOR_HISTOGRAM: return visitMHISTOGRAM(N);
2116 return visitPARTIAL_REDUCE_MLA(N);
2119 return visitLOOP_DEPENDENCE_MASK(N);
2120 case ISD::VECTOR_COMPRESS: return visitVECTOR_COMPRESS(N);
2121 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
2122 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
2123 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
2124 case ISD::FP_TO_BF16: return visitFP_TO_BF16(N);
2125 case ISD::BF16_TO_FP: return visitBF16_TO_FP(N);
2126 case ISD::FREEZE: return visitFREEZE(N);
2127 case ISD::GET_FPENV_MEM: return visitGET_FPENV_MEM(N);
2128 case ISD::SET_FPENV_MEM: return visitSET_FPENV_MEM(N);
2129 case ISD::FCANONICALIZE: return visitFCANONICALIZE(N);
2132 case ISD::VECREDUCE_ADD:
2133 case ISD::VECREDUCE_MUL:
2134 case ISD::VECREDUCE_AND:
2135 case ISD::VECREDUCE_OR:
2136 case ISD::VECREDUCE_XOR:
2146 case ISD::VECREDUCE_FMINIMUMNUM: return visitVECREDUCE(N);
2147#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
2148#include "llvm/IR/VPIntrinsics.def"
2149 return visitVPOp(N);
2150 }
2151 // clang-format on
2152 return SDValue();
2153}
2154
2155SDValue DAGCombiner::combine(SDNode *N) {
2156 if (!DebugCounter::shouldExecute(DAGCombineCounter))
2157 return SDValue();
2158
2159 SDValue RV;
2160 if (!DisableGenericCombines)
2161 RV = visit(N);
2162
2163 // If nothing happened, try a target-specific DAG combine.
2164 if (!RV.getNode()) {
2165 assert(N->getOpcode() != ISD::DELETED_NODE &&
2166 "Node was deleted but visit returned NULL!");
2167
2168 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
2169 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
2170
2171 // Expose the DAG combiner to the target combiner impls.
2172 TargetLowering::DAGCombinerInfo
2173 DagCombineInfo(DAG, Level, false, this);
2174
2175 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
2176 }
2177 }
2178
2179 // If nothing happened still, try promoting the operation.
2180 if (!RV.getNode()) {
2181 switch (N->getOpcode()) {
2182 default: break;
2183 case ISD::ADD:
2184 case ISD::SUB:
2185 case ISD::MUL:
2186 case ISD::AND:
2187 case ISD::OR:
2188 case ISD::XOR:
2189 RV = PromoteIntBinOp(SDValue(N, 0));
2190 break;
2191 case ISD::SHL:
2192 case ISD::SRA:
2193 case ISD::SRL:
2194 RV = PromoteIntShiftOp(SDValue(N, 0));
2195 break;
2196 case ISD::SIGN_EXTEND:
2197 case ISD::ZERO_EXTEND:
2198 case ISD::ANY_EXTEND:
2199 RV = PromoteExtend(SDValue(N, 0));
2200 break;
2201 case ISD::LOAD:
2202 if (PromoteLoad(SDValue(N, 0)))
2203 RV = SDValue(N, 0);
2204 break;
2205 }
2206 }
2207
2208 // If N is a commutative binary node, try to eliminate it if the commuted
2209 // version is already present in the DAG.
2210 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode())) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
2213
2214 // Constant operands are canonicalized to RHS.
2215 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
2216 SDValue Ops[] = {N1, N0};
2217 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
2218 N->getFlags());
2219 if (CSENode)
2220 return SDValue(CSENode, 0);
2221 }
2222 }
2223
2224 return RV;
2225}
2226
2227/// Given a node, return its input chain if it has one, otherwise return a null
2228/// sd operand.
2230 if (unsigned NumOps = N->getNumOperands()) {
2231 if (N->getOperand(0).getValueType() == MVT::Other)
2232 return N->getOperand(0);
2233 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
2234 return N->getOperand(NumOps-1);
2235 for (unsigned i = 1; i < NumOps-1; ++i)
2236 if (N->getOperand(i).getValueType() == MVT::Other)
2237 return N->getOperand(i);
2238 }
2239 return SDValue();
2240}
2241
2242SDValue DAGCombiner::visitFCANONICALIZE(SDNode *N) {
2243 SDValue Operand = N->getOperand(0);
2244 EVT VT = Operand.getValueType();
2245 SDLoc dl(N);
2246
2247 // Canonicalize undef to quiet NaN.
2248 if (Operand.isUndef()) {
2249 APFloat CanonicalQNaN = APFloat::getQNaN(VT.getFltSemantics());
2250 return DAG.getConstantFP(CanonicalQNaN, dl, VT);
2251 }
2252 return SDValue();
2253}
2254
2255SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
2256 // If N has two operands, where one has an input chain equal to the other,
2257 // the 'other' chain is redundant.
2258 if (N->getNumOperands() == 2) {
2259 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
2260 return N->getOperand(0);
2261 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
2262 return N->getOperand(1);
2263 }
2264
2265 // Don't simplify token factors if optnone.
2266 if (OptLevel == CodeGenOptLevel::None)
2267 return SDValue();
2268
2269 // Don't simplify the token factor if the node itself has too many operands.
2270 if (N->getNumOperands() > TokenFactorInlineLimit)
2271 return SDValue();
2272
2273 // If the sole user is a token factor, we should make sure we have a
2274 // chance to merge them together. This prevents TF chains from inhibiting
2275 // optimizations.
2276 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TokenFactor)
2277 AddToWorklist(*(N->user_begin()));
2278
2279 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
2280 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
2281 SmallPtrSet<SDNode*, 16> SeenOps;
2282 bool Changed = false; // If we should replace this token factor.
2283
2284 // Start out with this token factor.
2285 TFs.push_back(N);
2286
2287 // Iterate through token factors. The TFs grows when new token factors are
2288 // encountered.
2289 for (unsigned i = 0; i < TFs.size(); ++i) {
2290 // Limit number of nodes to inline, to avoid quadratic compile times.
2291 // We have to add the outstanding Token Factors to Ops, otherwise we might
2292 // drop Ops from the resulting Token Factors.
2293 if (Ops.size() > TokenFactorInlineLimit) {
2294 for (unsigned j = i; j < TFs.size(); j++)
2295 Ops.emplace_back(TFs[j], 0);
2296 // Drop unprocessed Token Factors from TFs, so we do not add them to the
2297 // combiner worklist later.
2298 TFs.resize(i);
2299 break;
2300 }
2301
2302 SDNode *TF = TFs[i];
2303 // Check each of the operands.
2304 for (const SDValue &Op : TF->op_values()) {
2305 switch (Op.getOpcode()) {
2306 case ISD::EntryToken:
2307 // Entry tokens don't need to be added to the list. They are
2308 // redundant.
2309 Changed = true;
2310 break;
2311
2312 case ISD::TokenFactor:
2313 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
2314 // Queue up for processing.
2315 TFs.push_back(Op.getNode());
2316 Changed = true;
2317 break;
2318 }
2319 [[fallthrough]];
2320
2321 default:
2322 // Only add if it isn't already in the list.
2323 if (SeenOps.insert(Op.getNode()).second)
2324 Ops.push_back(Op);
2325 else
2326 Changed = true;
2327 break;
2328 }
2329 }
2330 }
2331
2332 // Re-visit inlined Token Factors, to clean them up in case they have been
2333 // removed. Skip the first Token Factor, as this is the current node.
2334 for (unsigned i = 1, e = TFs.size(); i < e; i++)
2335 AddToWorklist(TFs[i]);
2336
2337 // Remove Nodes that are chained to another node in the list. Do so
2338 // by walking up chains breath-first stopping when we've seen
2339 // another operand. In general we must climb to the EntryNode, but we can exit
2340 // early if we find all remaining work is associated with just one operand as
2341 // no further pruning is possible.
2342
2343 // List of nodes to search through and original Ops from which they originate.
2345 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
2346 SmallPtrSet<SDNode *, 16> SeenChains;
2347 bool DidPruneOps = false;
2348
2349 unsigned NumLeftToConsider = 0;
2350 for (const SDValue &Op : Ops) {
2351 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
2352 OpWorkCount.push_back(1);
2353 }
2354
2355 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
2356 // If this is an Op, we can remove the op from the list. Remark any
2357 // search associated with it as from the current OpNumber.
2358 if (SeenOps.contains(Op)) {
2359 Changed = true;
2360 DidPruneOps = true;
2361 unsigned OrigOpNumber = 0;
2362 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
2363 OrigOpNumber++;
2364 assert((OrigOpNumber != Ops.size()) &&
2365 "expected to find TokenFactor Operand");
2366 // Re-mark worklist from OrigOpNumber to OpNumber
2367 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
2368 if (Worklist[i].second == OrigOpNumber) {
2369 Worklist[i].second = OpNumber;
2370 }
2371 }
2372 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
2373 OpWorkCount[OrigOpNumber] = 0;
2374 NumLeftToConsider--;
2375 }
2376 // Add if it's a new chain
2377 if (SeenChains.insert(Op).second) {
2378 OpWorkCount[OpNumber]++;
2379 Worklist.push_back(std::make_pair(Op, OpNumber));
2380 }
2381 };
2382
2383 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
2384 // We need at least be consider at least 2 Ops to prune.
2385 if (NumLeftToConsider <= 1)
2386 break;
2387 auto CurNode = Worklist[i].first;
2388 auto CurOpNumber = Worklist[i].second;
2389 assert((OpWorkCount[CurOpNumber] > 0) &&
2390 "Node should not appear in worklist");
2391 switch (CurNode->getOpcode()) {
2392 case ISD::EntryToken:
2393 // Hitting EntryToken is the only way for the search to terminate without
2394 // hitting
2395 // another operand's search. Prevent us from marking this operand
2396 // considered.
2397 NumLeftToConsider++;
2398 break;
2399 case ISD::TokenFactor:
2400 for (const SDValue &Op : CurNode->op_values())
2401 AddToWorklist(i, Op.getNode(), CurOpNumber);
2402 break;
2404 case ISD::LIFETIME_END:
2405 case ISD::CopyFromReg:
2406 case ISD::CopyToReg:
2407 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
2408 break;
2409 default:
2410 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
2411 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
2412 break;
2413 }
2414 OpWorkCount[CurOpNumber]--;
2415 if (OpWorkCount[CurOpNumber] == 0)
2416 NumLeftToConsider--;
2417 }
2418
2419 // If we've changed things around then replace token factor.
2420 if (Changed) {
2422 if (Ops.empty()) {
2423 // The entry token is the only possible outcome.
2424 Result = DAG.getEntryNode();
2425 } else {
2426 if (DidPruneOps) {
2427 SmallVector<SDValue, 8> PrunedOps;
2428 //
2429 for (const SDValue &Op : Ops) {
2430 if (SeenChains.count(Op.getNode()) == 0)
2431 PrunedOps.push_back(Op);
2432 }
2433 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2434 } else {
2435 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2436 }
2437 }
2438 return Result;
2439 }
2440 return SDValue();
2441}
2442
2443/// MERGE_VALUES can always be eliminated.
2444SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2445 WorklistRemover DeadNodes(*this);
2446 // Replacing results may cause a different MERGE_VALUES to suddenly
2447 // be CSE'd with N, and carry its uses with it. Iterate until no
2448 // uses remain, to ensure that the node can be safely deleted.
2449 // First add the users of this node to the work list so that they
2450 // can be tried again once they have new operands.
2451 AddUsersToWorklist(N);
2452 do {
2453 // Do as a single replacement to avoid rewalking use lists.
2455 DAG.ReplaceAllUsesWith(N, Ops.data());
2456 } while (!N->use_empty());
2457 deleteAndRecombine(N);
2458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2459}
2460
2461/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2462/// ConstantSDNode pointer else nullptr.
2465 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2466}
2467
2468// isTruncateOf - If N is a truncate of some other value, return true, record
2469// the value being truncated in Op and which of Op's bits are zero/one in Known.
2470// This function computes KnownBits to avoid a duplicated call to
2471// computeKnownBits in the caller.
2473 KnownBits &Known) {
2474 if (N->getOpcode() == ISD::TRUNCATE) {
2475 Op = N->getOperand(0);
2476 Known = DAG.computeKnownBits(Op);
2477 if (N->getFlags().hasNoUnsignedWrap())
2478 Known.Zero.setBitsFrom(N.getScalarValueSizeInBits());
2479 return true;
2480 }
2481
2482 if (N.getValueType().getScalarType() != MVT::i1 ||
2483 !sd_match(
2485 return false;
2486
2487 Known = DAG.computeKnownBits(Op);
2488 return (Known.Zero | 1).isAllOnes();
2489}
2490
2491/// Return true if 'Use' is a load or a store that uses N as its base pointer
2492/// and that N may be folded in the load / store addressing mode.
2494 const TargetLowering &TLI) {
2495 EVT VT;
2496 unsigned AS;
2497
2498 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2499 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2500 return false;
2501 VT = LD->getMemoryVT();
2502 AS = LD->getAddressSpace();
2503 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2504 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2505 return false;
2506 VT = ST->getMemoryVT();
2507 AS = ST->getAddressSpace();
2509 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2510 return false;
2511 VT = LD->getMemoryVT();
2512 AS = LD->getAddressSpace();
2514 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2515 return false;
2516 VT = ST->getMemoryVT();
2517 AS = ST->getAddressSpace();
2518 } else {
2519 return false;
2520 }
2521
2523 if (N->isAnyAdd()) {
2524 AM.HasBaseReg = true;
2526 if (Offset)
2527 // [reg +/- imm]
2528 AM.BaseOffs = Offset->getSExtValue();
2529 else
2530 // [reg +/- reg]
2531 AM.Scale = 1;
2532 } else if (N->getOpcode() == ISD::SUB) {
2533 AM.HasBaseReg = true;
2535 if (Offset)
2536 // [reg +/- imm]
2537 AM.BaseOffs = -Offset->getSExtValue();
2538 else
2539 // [reg +/- reg]
2540 AM.Scale = 1;
2541 } else {
2542 return false;
2543 }
2544
2545 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2546 VT.getTypeForEVT(*DAG.getContext()), AS);
2547}
2548
2549/// This inverts a canonicalization in IR that replaces a variable select arm
2550/// with an identity constant. Codegen improves if we re-use the variable
2551/// operand rather than load a constant. This can also be converted into a
2552/// masked vector operation if the target supports it.
2554 bool ShouldCommuteOperands) {
2555 SDValue N0 = N->getOperand(0);
2556 SDValue N1 = N->getOperand(1);
2557
2558 // Match a select as operand 1. The identity constant that we are looking for
2559 // is only valid as operand 1 of a non-commutative binop.
2560 if (ShouldCommuteOperands)
2561 std::swap(N0, N1);
2562
2563 SDValue Cond, TVal, FVal;
2565 m_Value(FVal)))))
2566 return SDValue();
2567
2568 // We can't hoist all instructions because of immediate UB (not speculatable).
2569 // For example div/rem by zero.
2571 return SDValue();
2572
2573 unsigned SelOpcode = N1.getOpcode();
2574 unsigned Opcode = N->getOpcode();
2575 EVT VT = N->getValueType(0);
2576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2577
2578 // This transform increases uses of N0, so freeze it to be safe.
2579 // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
2580 unsigned OpNo = ShouldCommuteOperands ? 0 : 1;
2581 if (DAG.isIdentityElement(Opcode, N->getFlags(), TVal, OpNo) &&
2582 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2583 FVal)) {
2584 SDValue F0 = DAG.getFreeze(N0);
2585 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
2586 return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
2587 }
2588 // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
2589 if (DAG.isIdentityElement(Opcode, N->getFlags(), FVal, OpNo) &&
2590 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2591 TVal)) {
2592 SDValue F0 = DAG.getFreeze(N0);
2593 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
2594 return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
2595 }
2596
2597 return SDValue();
2598}
2599
2600SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
2603 "Unexpected binary operator");
2604
2605 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
2606 return Sel;
2607
2608 if (TLI.isCommutativeBinOp(BO->getOpcode()))
2609 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
2610 return Sel;
2611
2612 // Don't do this unless the old select is going away. We want to eliminate the
2613 // binary operator, not replace a binop with a select.
2614 // TODO: Handle ISD::SELECT_CC.
2615 unsigned SelOpNo = 0;
2616 SDValue Sel = BO->getOperand(0);
2617 auto BinOpcode = BO->getOpcode();
2618 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2619 SelOpNo = 1;
2620 Sel = BO->getOperand(1);
2621
2622 // Peek through trunc to shift amount type.
2623 if ((BinOpcode == ISD::SHL || BinOpcode == ISD::SRA ||
2624 BinOpcode == ISD::SRL) && Sel.hasOneUse()) {
2625 // This is valid when the truncated bits of x are already zero.
2626 SDValue Op;
2627 KnownBits Known;
2628 if (isTruncateOf(DAG, Sel, Op, Known) &&
2629 Known.countMaxActiveBits() < Sel.getScalarValueSizeInBits())
2630 Sel = Op;
2631 }
2632 }
2633
2634 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2635 return SDValue();
2636
2637 SDValue CT = Sel.getOperand(1);
2638 if (!isConstantOrConstantVector(CT, true) &&
2640 return SDValue();
2641
2642 SDValue CF = Sel.getOperand(2);
2643 if (!isConstantOrConstantVector(CF, true) &&
2645 return SDValue();
2646
2647 // Bail out if any constants are opaque because we can't constant fold those.
2648 // The exception is "and" and "or" with either 0 or -1 in which case we can
2649 // propagate non constant operands into select. I.e.:
2650 // and (select Cond, 0, -1), X --> select Cond, 0, X
2651 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2652 bool CanFoldNonConst =
2653 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2656
2657 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2658 if (!CanFoldNonConst &&
2659 !isConstantOrConstantVector(CBO, true) &&
2661 return SDValue();
2662
2663 SDLoc DL(Sel);
2664 SDValue NewCT, NewCF;
2665 EVT VT = BO->getValueType(0);
2666
2667 if (CanFoldNonConst) {
2668 // If CBO is an opaque constant, we can't rely on getNode to constant fold.
2669 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CT)) ||
2670 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CT)))
2671 NewCT = CT;
2672 else
2673 NewCT = CBO;
2674
2675 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CF)) ||
2676 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CF)))
2677 NewCF = CF;
2678 else
2679 NewCF = CBO;
2680 } else {
2681 // We have a select-of-constants followed by a binary operator with a
2682 // constant. Eliminate the binop by pulling the constant math into the
2683 // select. Example: add (select Cond, CT, CF), CBO --> select Cond, CT +
2684 // CBO, CF + CBO
2685 NewCT = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CT})
2686 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CT, CBO});
2687 if (!NewCT)
2688 return SDValue();
2689
2690 NewCF = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CF})
2691 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CF, CBO});
2692 if (!NewCF)
2693 return SDValue();
2694 }
2695
2696 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF, BO->getFlags());
2697}
2698
2700 SelectionDAG &DAG) {
2701 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2702 "Expecting add or sub");
2703
2704 // Match a constant operand and a zext operand for the math instruction:
2705 // add Z, C
2706 // sub C, Z
2707 bool IsAdd = N->getOpcode() == ISD::ADD;
2708 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2709 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2710 auto *CN = dyn_cast<ConstantSDNode>(C);
2711 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2712 return SDValue();
2713
2714 // Match the zext operand as a setcc of a boolean.
2715 if (Z.getOperand(0).getValueType() != MVT::i1)
2716 return SDValue();
2717
2718 // Match the compare as: setcc (X & 1), 0, eq.
2719 if (!sd_match(Z.getOperand(0), m_SetCC(m_And(m_Value(), m_One()), m_Zero(),
2721 return SDValue();
2722
2723 // We are adding/subtracting a constant and an inverted low bit. Turn that
2724 // into a subtract/add of the low bit with incremented/decremented constant:
2725 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2726 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2727 EVT VT = C.getValueType();
2728 SDValue LowBit = DAG.getZExtOrTrunc(Z.getOperand(0).getOperand(0), DL, VT);
2729 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT)
2730 : DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2731 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2732}
2733
2734// Attempt to form avgceil(A, B) from (A | B) - ((A ^ B) >> 1)
2735SDValue DAGCombiner::foldSubToAvg(SDNode *N, const SDLoc &DL) {
2736 SDValue N0 = N->getOperand(0);
2737 EVT VT = N0.getValueType();
2738 SDValue A, B;
2739
2740 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
2742 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2743 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
2744 }
2745 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
2747 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2748 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
2749 }
2750 return SDValue();
2751}
2752
2753/// Try to fold a pointer arithmetic node.
2754/// This needs to be done separately from normal addition, because pointer
2755/// addition is not commutative.
2756SDValue DAGCombiner::visitPTRADD(SDNode *N) {
2757 SDValue N0 = N->getOperand(0);
2758 SDValue N1 = N->getOperand(1);
2759 EVT PtrVT = N0.getValueType();
2760 EVT IntVT = N1.getValueType();
2761 SDLoc DL(N);
2762
2763 // This is already ensured by an assert in SelectionDAG::getNode(). Several
2764 // combines here depend on this assumption.
2765 assert(PtrVT == IntVT &&
2766 "PTRADD with different operand types is not supported");
2767
2768 // fold (ptradd x, 0) -> x
2769 if (isNullConstant(N1))
2770 return N0;
2771
2772 // fold (ptradd 0, x) -> x
2773 if (PtrVT == IntVT && isNullConstant(N0))
2774 return N1;
2775
2776 if (N0.getOpcode() == ISD::PTRADD &&
2777 !reassociationCanBreakAddressingModePattern(ISD::PTRADD, DL, N, N0, N1)) {
2778 SDValue X = N0.getOperand(0);
2779 SDValue Y = N0.getOperand(1);
2780 SDValue Z = N1;
2781 bool N0OneUse = N0.hasOneUse();
2782 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2783 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2784
2785 // (ptradd (ptradd x, y), z) -> (ptradd x, (add y, z)) if:
2786 // * y is a constant and (ptradd x, y) has one use; or
2787 // * y and z are both constants.
2788 if ((YIsConstant && N0OneUse) || (YIsConstant && ZIsConstant)) {
2789 // If both additions in the original were NUW, the new ones are as well.
2790 SDNodeFlags Flags =
2791 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2792 SDValue Add = DAG.getNode(ISD::ADD, DL, IntVT, {Y, Z}, Flags);
2793 AddToWorklist(Add.getNode());
2794 // We can't set InBounds even if both original ptradds were InBounds and
2795 // NUW: SDAG usually represents pointers as integers, therefore, the
2796 // matched pattern behaves as if it had implicit casts:
2797 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds x, y))), z)
2798 // The outer inbounds ptradd might therefore rely on a provenance that x
2799 // does not have.
2800 return DAG.getMemBasePlusOffset(X, Add, DL, Flags);
2801 }
2802 }
2803
2804 // The following combines can turn in-bounds pointer arithmetic out of bounds.
2805 // That is problematic for settings like AArch64's CPA, which checks that
2806 // intermediate results of pointer arithmetic remain in bounds. The target
2807 // therefore needs to opt-in to enable them.
2809 DAG.getMachineFunction().getFunction(), PtrVT))
2810 return SDValue();
2811
2812 if (N0.getOpcode() == ISD::PTRADD && isa<ConstantSDNode>(N1)) {
2813 // Fold (ptradd (ptradd GA, v), c) -> (ptradd (ptradd GA, c) v) with
2814 // global address GA and constant c, such that c can be folded into GA.
2815 // TODO: Support constant vector splats.
2816 SDValue GAValue = N0.getOperand(0);
2817 if (const GlobalAddressSDNode *GA =
2819 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2820 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2821 // If both additions in the original were NUW, reassociation preserves
2822 // that.
2823 SDNodeFlags Flags =
2824 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2825 // We can't set InBounds even if both original ptradds were InBounds and
2826 // NUW: SDAG usually represents pointers as integers, therefore, the
2827 // matched pattern behaves as if it had implicit casts:
2828 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds GA, v))), c)
2829 // The outer inbounds ptradd might therefore rely on a provenance that
2830 // GA does not have.
2831 SDValue Inner = DAG.getMemBasePlusOffset(GAValue, N1, DL, Flags);
2832 AddToWorklist(Inner.getNode());
2833 return DAG.getMemBasePlusOffset(Inner, N0.getOperand(1), DL, Flags);
2834 }
2835 }
2836 }
2837
2838 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse()) {
2839 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if z is a constant,
2840 // y is not, and (add y, z) is used only once.
2841 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if y is a constant,
2842 // z is not, and (add y, z) is used only once.
2843 // The goal is to move constant offsets to the outermost ptradd, to create
2844 // more opportunities to fold offsets into memory instructions.
2845 // Together with the another combine above, this also implements
2846 // (ptradd (ptradd x, y), z) -> (ptradd (ptradd x, z), y)).
2847 SDValue X = N0;
2848 SDValue Y = N1.getOperand(0);
2849 SDValue Z = N1.getOperand(1);
2850 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2851 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2852
2853 // If both additions in the original were NUW, reassociation preserves that.
2854 SDNodeFlags CommonFlags = N->getFlags() & N1->getFlags();
2855 SDNodeFlags ReassocFlags = CommonFlags & SDNodeFlags::NoUnsignedWrap;
2856 if (CommonFlags.hasNoUnsignedWrap()) {
2857 // If both operations are NUW and the PTRADD is inbounds, the offests are
2858 // both non-negative, so the reassociated PTRADDs are also inbounds.
2859 ReassocFlags |= N->getFlags() & SDNodeFlags::InBounds;
2860 }
2861
2862 if (ZIsConstant != YIsConstant) {
2863 if (YIsConstant)
2864 std::swap(Y, Z);
2865 SDValue Inner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
2866 AddToWorklist(Inner.getNode());
2867 return DAG.getMemBasePlusOffset(Inner, Z, DL, ReassocFlags);
2868 }
2869 }
2870
2871 // Transform (ptradd a, b) -> (or disjoint a, b) if it is equivalent and if
2872 // that transformation can't block an offset folding at any use of the ptradd.
2873 // This should be done late, after legalization, so that it doesn't block
2874 // other ptradd combines that could enable more offset folding.
2875 if (LegalOperations && DAG.haveNoCommonBitsSet(N0, N1)) {
2876 bool TransformCannotBreakAddrMode = none_of(N->users(), [&](SDNode *User) {
2877 return canFoldInAddressingMode(N, User, DAG, TLI);
2878 });
2879
2880 if (TransformCannotBreakAddrMode)
2881 return DAG.getNode(ISD::OR, DL, PtrVT, N0, N1, SDNodeFlags::Disjoint);
2882 }
2883
2884 return SDValue();
2885}
2886
2887/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2888/// a shift and add with a different constant.
2890 SelectionDAG &DAG) {
2891 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2892 "Expecting add or sub");
2893
2894 // We need a constant operand for the add/sub, and the other operand is a
2895 // logical shift right: add (srl), C or sub C, (srl).
2896 bool IsAdd = N->getOpcode() == ISD::ADD;
2897 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2898 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2899 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2900 ShiftOp.getOpcode() != ISD::SRL)
2901 return SDValue();
2902
2903 // The shift must be of a 'not' value.
2904 SDValue Not = ShiftOp.getOperand(0);
2905 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2906 return SDValue();
2907
2908 // The shift must be moving the sign bit to the least-significant-bit.
2909 EVT VT = ShiftOp.getValueType();
2910 SDValue ShAmt = ShiftOp.getOperand(1);
2911 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2912 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2913 return SDValue();
2914
2915 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2916 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2917 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2918 if (SDValue NewC = DAG.FoldConstantArithmetic(
2919 IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2920 {ConstantOp, DAG.getConstant(1, DL, VT)})) {
2921 SDValue NewShift = DAG.getNode(IsAdd ? ISD::SRA : ISD::SRL, DL, VT,
2922 Not.getOperand(0), ShAmt);
2923 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2924 }
2925
2926 return SDValue();
2927}
2928
2929static bool
2931 return (isBitwiseNot(Op0) && Op0.getOperand(0) == Op1) ||
2932 (isBitwiseNot(Op1) && Op1.getOperand(0) == Op0);
2933}
2934
2935/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2936/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2937/// are no common bits set in the operands).
2938SDValue DAGCombiner::visitADDLike(SDNode *N) {
2939 SDValue N0 = N->getOperand(0);
2940 SDValue N1 = N->getOperand(1);
2941 EVT VT = N0.getValueType();
2942 SDLoc DL(N);
2943
2944 // fold (add x, undef) -> undef
2945 if (N0.isUndef())
2946 return N0;
2947 if (N1.isUndef())
2948 return N1;
2949
2950 // fold (add c1, c2) -> c1+c2
2951 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
2952 return C;
2953
2954 // canonicalize constant to RHS
2957 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2958
2959 if (areBitwiseNotOfEachother(N0, N1))
2960 return DAG.getConstant(APInt::getAllOnes(VT.getScalarSizeInBits()), DL, VT);
2961
2962 // fold vector ops
2963 if (VT.isVector()) {
2964 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
2965 return FoldedVOp;
2966
2967 // fold (add x, 0) -> x, vector edition
2969 return N0;
2970 }
2971
2972 // fold (add x, 0) -> x
2973 if (isNullConstant(N1))
2974 return N0;
2975
2976 if (N0.getOpcode() == ISD::SUB) {
2977 SDValue N00 = N0.getOperand(0);
2978 SDValue N01 = N0.getOperand(1);
2979
2980 // fold ((A-c1)+c2) -> (A+(c2-c1))
2981 if (SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N01}))
2982 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2983
2984 // fold ((c1-A)+c2) -> (c1+c2)-A
2985 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N00}))
2986 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2987 }
2988
2989 // add (sext i1 X), 1 -> zext (not i1 X)
2990 // We don't transform this pattern:
2991 // add (zext i1 X), -1 -> sext (not i1 X)
2992 // because most (?) targets generate better code for the zext form.
2993 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2994 isOneOrOneSplat(N1)) {
2995 SDValue X = N0.getOperand(0);
2996 if ((!LegalOperations ||
2997 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2999 X.getScalarValueSizeInBits() == 1) {
3000 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
3001 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
3002 }
3003 }
3004
3005 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1))
3006 // iff (or x, c0) is equivalent to (add x, c0).
3007 // Fold (add (xor x, c0), c1) -> (add x, (c0 + c1))
3008 // iff (xor x, c0) is equivalent to (add x, c0).
3009 if (DAG.isADDLike(N0)) {
3010 SDValue N01 = N0.getOperand(1);
3011 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N01}))
3012 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add);
3013 }
3014
3015 if (SDValue NewSel = foldBinOpIntoSelect(N))
3016 return NewSel;
3017
3018 // reassociate add
3019 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N, N0, N1)) {
3020 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
3021 return RADD;
3022
3023 // (X + Y) + X --> Y + (X + X)
3024 SDValue X, Y, InnerAdd;
3025 if (sd_match(
3026 N, m_Add(m_OneUse(m_Value(InnerAdd, m_Add(m_Value(X), m_Value(Y)))),
3027 m_Deferred(X)))) {
3028 if (X != Y) {
3029 // Redistribute shared NUW flag.
3030 // TODO: If NSW+NUW occurs on both adds, that can be redistributed too.
3031 SDNodeFlags NewFlags =
3032 N->getFlags() & InnerAdd->getFlags() & SDNodeFlags::NoUnsignedWrap;
3033 SDValue X2 = DAG.getNode(ISD::ADD, DL, VT, X, X, NewFlags);
3034 return DAG.getNode(ISD::ADD, DL, VT, Y, X2, NewFlags);
3035 }
3036 }
3037
3038 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
3039 // equivalent to (add x, c).
3040 // Reassociate (add (xor x, c), y) -> (add add(x, y), c)) if (xor x, c) is
3041 // equivalent to (add x, c).
3042 // Do this optimization only when adding c does not introduce instructions
3043 // for adding carries.
3044 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
3045 if (DAG.isADDLike(N0) && N0.hasOneUse() &&
3046 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
3047 // If N0's type does not split or is a sign mask, it does not introduce
3048 // add carry.
3049 auto TyActn = TLI.getTypeAction(*DAG.getContext(), N0.getValueType());
3050 bool NoAddCarry = TyActn == TargetLoweringBase::TypeLegal ||
3053 if (NoAddCarry)
3054 return DAG.getNode(
3055 ISD::ADD, DL, VT,
3056 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
3057 N0.getOperand(1));
3058 }
3059 return SDValue();
3060 };
3061 if (SDValue Add = ReassociateAddOr(N0, N1))
3062 return Add;
3063 if (SDValue Add = ReassociateAddOr(N1, N0))
3064 return Add;
3065
3066 // Fold add(vecreduce(x), vecreduce(y)) -> vecreduce(add(x, y))
3067 if (SDValue SD =
3068 reassociateReduction(ISD::VECREDUCE_ADD, ISD::ADD, DL, VT, N0, N1))
3069 return SD;
3070 }
3071
3072 SDValue A, B, C, D;
3073
3074 // fold ((0-A) + B) -> B-A
3075 if (sd_match(N0, m_Neg(m_Value(A))))
3076 return DAG.getNode(ISD::SUB, DL, VT, N1, A);
3077
3078 // fold (A + (0-B)) -> A-B
3079 if (sd_match(N1, m_Neg(m_Value(B))))
3080 return DAG.getNode(ISD::SUB, DL, VT, N0, B);
3081
3082 // fold (A+(B-A)) -> B
3083 if (sd_match(N1, m_Sub(m_Value(B), m_Specific(N0))))
3084 return B;
3085
3086 // fold ((B-A)+A) -> B
3087 if (sd_match(N0, m_Sub(m_Value(B), m_Specific(N1))))
3088 return B;
3089
3090 // fold ((A-B)+(C-A)) -> (C-B)
3091 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3093 return DAG.getNode(ISD::SUB, DL, VT, C, B);
3094
3095 // fold ((A-B)+(B-C)) -> (A-C)
3096 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3098 return DAG.getNode(ISD::SUB, DL, VT, A, C);
3099
3100 // fold (A+(B-(A+C))) to (B-C)
3101 // fold (A+(B-(C+A))) to (B-C)
3102 if (sd_match(N1, m_Sub(m_Value(B), m_Add(m_Specific(N0), m_Value(C)))))
3103 return DAG.getNode(ISD::SUB, DL, VT, B, C);
3104
3105 // fold (A+((B-A)+or-C)) to (B+or-C)
3106 if (sd_match(N1,
3108 m_Sub(m_Sub(m_Value(B), m_Specific(N0)), m_Value(C)))))
3109 return DAG.getNode(N1.getOpcode(), DL, VT, B, C);
3110
3111 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
3112 if (sd_match(N0, m_OneUse(m_Sub(m_Value(A), m_Value(B)))) &&
3113 sd_match(N1, m_OneUse(m_Sub(m_Value(C), m_Value(D)))) &&
3115 return DAG.getNode(ISD::SUB, DL, VT,
3116 DAG.getNode(ISD::ADD, SDLoc(N0), VT, A, C),
3117 DAG.getNode(ISD::ADD, SDLoc(N1), VT, B, D));
3118
3119 // fold (add (umax X, C), -C) --> (usubsat X, C)
3120 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
3121 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
3122 return (!Max && !Op) ||
3123 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
3124 };
3125 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
3126 /*AllowUndefs*/ true))
3127 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
3128 N0.getOperand(1));
3129 }
3130
3132 return SDValue(N, 0);
3133
3134 if (isOneOrOneSplat(N1)) {
3135 // fold (add (xor a, -1), 1) -> (sub 0, a)
3136 if (isBitwiseNot(N0))
3137 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
3138 N0.getOperand(0));
3139
3140 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
3141 if (N0.getOpcode() == ISD::ADD) {
3142 SDValue A, Xor;
3143
3144 if (isBitwiseNot(N0.getOperand(0))) {
3145 A = N0.getOperand(1);
3146 Xor = N0.getOperand(0);
3147 } else if (isBitwiseNot(N0.getOperand(1))) {
3148 A = N0.getOperand(0);
3149 Xor = N0.getOperand(1);
3150 }
3151
3152 if (Xor)
3153 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
3154 }
3155
3156 // Look for:
3157 // add (add x, y), 1
3158 // And if the target does not like this form then turn into:
3159 // sub y, (xor x, -1)
3160 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3161 N0.hasOneUse() &&
3162 // Limit this to after legalization if the add has wrap flags
3163 (Level >= AfterLegalizeDAG || (!N->getFlags().hasNoUnsignedWrap() &&
3164 !N->getFlags().hasNoSignedWrap()))) {
3165 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3166 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
3167 }
3168 }
3169
3170 // (x - y) + -1 -> add (xor y, -1), x
3171 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
3172 isAllOnesOrAllOnesSplat(N1, /*AllowUndefs=*/true)) {
3173 SDValue Not = DAG.getNOT(DL, N0.getOperand(1), VT);
3174 return DAG.getNode(ISD::ADD, DL, VT, Not, N0.getOperand(0));
3175 }
3176
3177 // Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB).
3178 // This can help if the inner add has multiple uses.
3179 APInt CM, CA;
3180 if (ConstantSDNode *CB = dyn_cast<ConstantSDNode>(N1)) {
3181 if (VT.getScalarSizeInBits() <= 64) {
3183 m_ConstInt(CM)))) &&
3185 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3186 SDNodeFlags Flags;
3187 // If all the inputs are nuw, the outputs can be nuw. If all the input
3188 // are _also_ nsw the outputs can be too.
3189 if (N->getFlags().hasNoUnsignedWrap() &&
3190 N0->getFlags().hasNoUnsignedWrap() &&
3193 if (N->getFlags().hasNoSignedWrap() &&
3194 N0->getFlags().hasNoSignedWrap() &&
3197 }
3198 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3199 DAG.getConstant(CM, DL, VT), Flags);
3200 return DAG.getNode(
3201 ISD::ADD, DL, VT, Mul,
3202 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3203 }
3204 // Also look in case there is an intermediate add.
3205 if (sd_match(N0, m_OneUse(m_Add(
3207 m_ConstInt(CM))),
3208 m_Value(B)))) &&
3210 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3211 SDNodeFlags Flags;
3212 // If all the inputs are nuw, the outputs can be nuw. If all the input
3213 // are _also_ nsw the outputs can be too.
3214 SDValue OMul =
3215 N0.getOperand(0) == B ? N0.getOperand(1) : N0.getOperand(0);
3216 if (N->getFlags().hasNoUnsignedWrap() &&
3217 N0->getFlags().hasNoUnsignedWrap() &&
3218 OMul->getFlags().hasNoUnsignedWrap() &&
3219 OMul.getOperand(0)->getFlags().hasNoUnsignedWrap()) {
3221 if (N->getFlags().hasNoSignedWrap() &&
3222 N0->getFlags().hasNoSignedWrap() &&
3223 OMul->getFlags().hasNoSignedWrap() &&
3224 OMul.getOperand(0)->getFlags().hasNoSignedWrap())
3226 }
3227 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3228 DAG.getConstant(CM, DL, VT), Flags);
3229 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N1), VT, Mul, B, Flags);
3230 return DAG.getNode(
3231 ISD::ADD, DL, VT, Add,
3232 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3233 }
3234 }
3235 }
3236
3237 if (SDValue Combined = visitADDLikeCommutative(N0, N1, DL))
3238 return Combined;
3239
3240 if (SDValue Combined = visitADDLikeCommutative(N1, N0, DL))
3241 return Combined;
3242
3243 return SDValue();
3244}
3245
3246// Attempt to form avgfloor(A, B) from (A & B) + ((A ^ B) >> 1)
3247// Attempt to form avgfloor(A, B) from ((A >> 1) + (B >> 1)) + (A & B & 1)
3248// Attempt to form avgceil(A, B) from ((A >> 1) + (B >> 1)) + ((A | B) & 1)
3249SDValue DAGCombiner::foldAddToAvg(SDNode *N, const SDLoc &DL) {
3250 SDValue N0 = N->getOperand(0);
3251 EVT VT = N0.getValueType();
3252 SDValue A, B;
3253
3254 if ((!LegalOperations || hasOperation(ISD::AVGFLOORU, VT)) &&
3255 (sd_match(N,
3257 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3260 m_Srl(m_Deferred(A), m_One()),
3261 m_Srl(m_Deferred(B), m_One()))))) {
3262 return DAG.getNode(ISD::AVGFLOORU, DL, VT, A, B);
3263 }
3264 if ((!LegalOperations || hasOperation(ISD::AVGFLOORS, VT)) &&
3265 (sd_match(N,
3267 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3270 m_Sra(m_Deferred(A), m_One()),
3271 m_Sra(m_Deferred(B), m_One()))))) {
3272 return DAG.getNode(ISD::AVGFLOORS, DL, VT, A, B);
3273 }
3274
3275 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
3276 sd_match(N,
3278 m_Srl(m_Deferred(A), m_One()),
3279 m_Srl(m_Deferred(B), m_One())))) {
3280 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
3281 }
3282 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
3283 sd_match(N,
3285 m_Sra(m_Deferred(A), m_One()),
3286 m_Sra(m_Deferred(B), m_One())))) {
3287 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
3288 }
3289
3290 return SDValue();
3291}
3292
3293SDValue DAGCombiner::visitADD(SDNode *N) {
3294 SDValue N0 = N->getOperand(0);
3295 SDValue N1 = N->getOperand(1);
3296 EVT VT = N0.getValueType();
3297 SDLoc DL(N);
3298
3299 if (SDValue Combined = visitADDLike(N))
3300 return Combined;
3301
3302 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
3303 return V;
3304
3305 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
3306 return V;
3307
3308 if (SDValue V = MatchRotate(N0, N1, SDLoc(N), /*FromAdd=*/true))
3309 return V;
3310
3311 // Try to match AVGFLOOR fixedwidth pattern
3312 if (SDValue V = foldAddToAvg(N, DL))
3313 return V;
3314
3315 // fold (a+b) -> (a|b) iff a and b share no bits.
3316 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
3317 DAG.haveNoCommonBitsSet(N0, N1))
3318 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
3319
3320 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
3321 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
3322 const APInt &C0 = N0->getConstantOperandAPInt(0);
3323 const APInt &C1 = N1->getConstantOperandAPInt(0);
3324 return DAG.getVScale(DL, VT, C0 + C1);
3325 }
3326
3327 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
3328 if (N0.getOpcode() == ISD::ADD &&
3329 N0.getOperand(1).getOpcode() == ISD::VSCALE &&
3330 N1.getOpcode() == ISD::VSCALE) {
3331 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3332 const APInt &VS1 = N1->getConstantOperandAPInt(0);
3333 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
3334 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
3335 }
3336
3337 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
3338 if (N0.getOpcode() == ISD::STEP_VECTOR &&
3339 N1.getOpcode() == ISD::STEP_VECTOR) {
3340 const APInt &C0 = N0->getConstantOperandAPInt(0);
3341 const APInt &C1 = N1->getConstantOperandAPInt(0);
3342 APInt NewStep = C0 + C1;
3343 return DAG.getStepVector(DL, VT, NewStep);
3344 }
3345
3346 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
3347 if (N0.getOpcode() == ISD::ADD &&
3349 N1.getOpcode() == ISD::STEP_VECTOR) {
3350 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3351 const APInt &SV1 = N1->getConstantOperandAPInt(0);
3352 APInt NewStep = SV0 + SV1;
3353 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
3354 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
3355 }
3356
3357 return SDValue();
3358}
3359
3360SDValue DAGCombiner::visitADDSAT(SDNode *N) {
3361 unsigned Opcode = N->getOpcode();
3362 SDValue N0 = N->getOperand(0);
3363 SDValue N1 = N->getOperand(1);
3364 EVT VT = N0.getValueType();
3365 bool IsSigned = Opcode == ISD::SADDSAT;
3366 SDLoc DL(N);
3367
3368 // fold (add_sat x, undef) -> -1
3369 if (N0.isUndef() || N1.isUndef())
3370 return DAG.getAllOnesConstant(DL, VT);
3371
3372 // fold (add_sat c1, c2) -> c3
3373 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
3374 return C;
3375
3376 // canonicalize constant to RHS
3379 return DAG.getNode(Opcode, DL, VT, N1, N0);
3380
3381 // fold vector ops
3382 if (VT.isVector()) {
3383 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
3384 return FoldedVOp;
3385
3386 // fold (add_sat x, 0) -> x, vector edition
3388 return N0;
3389 }
3390
3391 // fold (add_sat x, 0) -> x
3392 if (isNullConstant(N1))
3393 return N0;
3394
3395 // If it cannot overflow, transform into an add.
3396 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3397 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
3398
3399 return SDValue();
3400}
3401
3403 bool ForceCarryReconstruction = false) {
3404 bool Masked = false;
3405
3406 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
3407 while (true) {
3408 if (ForceCarryReconstruction && V.getValueType() == MVT::i1)
3409 return V;
3410
3411 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
3412 V = V.getOperand(0);
3413 continue;
3414 }
3415
3416 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
3417 if (ForceCarryReconstruction)
3418 return V;
3419
3420 Masked = true;
3421 V = V.getOperand(0);
3422 continue;
3423 }
3424
3425 break;
3426 }
3427
3428 // If this is not a carry, return.
3429 if (V.getResNo() != 1)
3430 return SDValue();
3431
3432 if (V.getOpcode() != ISD::UADDO_CARRY && V.getOpcode() != ISD::USUBO_CARRY &&
3433 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
3434 return SDValue();
3435
3436 EVT VT = V->getValueType(0);
3437 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
3438 return SDValue();
3439
3440 // If the result is masked, then no matter what kind of bool it is we can
3441 // return. If it isn't, then we need to make sure the bool type is either 0 or
3442 // 1 and not other values.
3443 if (Masked ||
3444 TLI.getBooleanContents(V.getValueType()) ==
3446 return V;
3447
3448 return SDValue();
3449}
3450
3451/// Given the operands of an add/sub operation, see if the 2nd operand is a
3452/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
3453/// the opcode and bypass the mask operation.
3454static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
3455 SelectionDAG &DAG, const SDLoc &DL) {
3456 if (N1.getOpcode() == ISD::ZERO_EXTEND)
3457 N1 = N1.getOperand(0);
3458
3459 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
3460 return SDValue();
3461
3462 EVT VT = N0.getValueType();
3463 SDValue N10 = N1.getOperand(0);
3464 if (N10.getValueType() != VT && N10.getOpcode() == ISD::TRUNCATE)
3465 N10 = N10.getOperand(0);
3466
3467 if (N10.getValueType() != VT)
3468 return SDValue();
3469
3470 if (DAG.ComputeNumSignBits(N10) != VT.getScalarSizeInBits())
3471 return SDValue();
3472
3473 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
3474 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
3475 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N10);
3476}
3477
3478/// Helper for doing combines based on N0 and N1 being added to each other.
3479SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
3480 const SDLoc &DL) {
3481 EVT VT = N0.getValueType();
3482
3483 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
3484 SDValue Y, N;
3485 if (sd_match(N1, m_Shl(m_Neg(m_Value(Y)), m_Value(N))))
3486 return DAG.getNode(ISD::SUB, DL, VT, N0,
3487 DAG.getNode(ISD::SHL, DL, VT, Y, N));
3488
3489 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
3490 return V;
3491
3492 // Look for:
3493 // add (add x, 1), y
3494 // And if the target does not like this form then turn into:
3495 // sub y, (xor x, -1)
3496 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3497 N0.hasOneUse() && isOneOrOneSplat(N0.getOperand(1)) &&
3498 // Limit this to after legalization if the add has wrap flags
3499 (Level >= AfterLegalizeDAG || (!N0->getFlags().hasNoUnsignedWrap() &&
3500 !N0->getFlags().hasNoSignedWrap()))) {
3501 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3502 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
3503 }
3504
3505 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse()) {
3506 // Hoist one-use subtraction by non-opaque constant:
3507 // (x - C) + y -> (x + y) - C
3508 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3509 if (isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3510 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
3511 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
3512 }
3513 // Hoist one-use subtraction from non-opaque constant:
3514 // (C - x) + y -> (y - x) + C
3515 if (isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3516 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
3517 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
3518 }
3519 }
3520
3521 // add (mul x, C), x -> mul x, C+1
3522 if (N0.getOpcode() == ISD::MUL && N0.getOperand(0) == N1 &&
3523 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true) &&
3524 N0.hasOneUse()) {
3525 SDValue NewC = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
3526 DAG.getConstant(1, DL, VT));
3527 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), NewC);
3528 }
3529
3530 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
3531 // rather than 'add 0/-1' (the zext should get folded).
3532 // add (sext i1 Y), X --> sub X, (zext i1 Y)
3533 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
3534 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
3536 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
3537 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
3538 }
3539
3540 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
3541 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3542 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3543 if (TN->getVT() == MVT::i1) {
3544 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3545 DAG.getConstant(1, DL, VT));
3546 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
3547 }
3548 }
3549
3550 // (add X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3551 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1)) &&
3552 N1.getResNo() == 0)
3553 return DAG.getNode(ISD::UADDO_CARRY, DL, N1->getVTList(),
3554 N0, N1.getOperand(0), N1.getOperand(2));
3555
3556 // (add X, Carry) -> (uaddo_carry X, 0, Carry)
3558 if (SDValue Carry = getAsCarry(TLI, N1))
3559 return DAG.getNode(ISD::UADDO_CARRY, DL,
3560 DAG.getVTList(VT, Carry.getValueType()), N0,
3561 DAG.getConstant(0, DL, VT), Carry);
3562
3563 return SDValue();
3564}
3565
3566SDValue DAGCombiner::visitADDC(SDNode *N) {
3567 SDValue N0 = N->getOperand(0);
3568 SDValue N1 = N->getOperand(1);
3569 EVT VT = N0.getValueType();
3570 SDLoc DL(N);
3571
3572 // If the flag result is dead, turn this into an ADD.
3573 if (!N->hasAnyUseOfValue(1))
3574 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3575 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3576
3577 // canonicalize constant to RHS.
3578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3580 if (N0C && !N1C)
3581 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
3582
3583 // fold (addc x, 0) -> x + no carry out
3584 if (isNullConstant(N1))
3585 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
3586 DL, MVT::Glue));
3587
3588 // If it cannot overflow, transform into an add.
3590 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3591 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3592
3593 return SDValue();
3594}
3595
3596/**
3597 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
3598 * then the flip also occurs if computing the inverse is the same cost.
3599 * This function returns an empty SDValue in case it cannot flip the boolean
3600 * without increasing the cost of the computation. If you want to flip a boolean
3601 * no matter what, use DAG.getLogicalNOT.
3602 */
3604 const TargetLowering &TLI,
3605 bool Force) {
3606 if (Force && isa<ConstantSDNode>(V))
3607 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3608
3609 if (V.getOpcode() != ISD::XOR)
3610 return SDValue();
3611
3612 if (DAG.isBoolConstant(V.getOperand(1)) == true)
3613 return V.getOperand(0);
3614 if (Force && isConstOrConstSplat(V.getOperand(1), false))
3615 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3616 return SDValue();
3617}
3618
3619SDValue DAGCombiner::visitADDO(SDNode *N) {
3620 SDValue N0 = N->getOperand(0);
3621 SDValue N1 = N->getOperand(1);
3622 EVT VT = N0.getValueType();
3623 bool IsSigned = (ISD::SADDO == N->getOpcode());
3624
3625 EVT CarryVT = N->getValueType(1);
3626 SDLoc DL(N);
3627
3628 // If the flag result is dead, turn this into an ADD.
3629 if (!N->hasAnyUseOfValue(1))
3630 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3631 DAG.getUNDEF(CarryVT));
3632
3633 // canonicalize constant to RHS.
3636 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
3637
3638 // fold (addo x, 0) -> x + no carry out
3639 if (isNullOrNullSplat(N1))
3640 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3641
3642 // If it cannot overflow, transform into an add.
3643 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3644 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3645 DAG.getConstant(0, DL, CarryVT));
3646
3647 if (IsSigned) {
3648 // fold (saddo (xor a, -1), 1) -> (ssub 0, a).
3649 if (isBitwiseNot(N0) && isOneOrOneSplat(N1))
3650 return DAG.getNode(ISD::SSUBO, DL, N->getVTList(),
3651 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3652 } else {
3653 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
3654 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
3655 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
3656 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3657 return CombineTo(
3658 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3659 }
3660
3661 if (SDValue Combined = visitUADDOLike(N0, N1, N))
3662 return Combined;
3663
3664 if (SDValue Combined = visitUADDOLike(N1, N0, N))
3665 return Combined;
3666 }
3667
3668 return SDValue();
3669}
3670
3671SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
3672 EVT VT = N0.getValueType();
3673 if (VT.isVector())
3674 return SDValue();
3675
3676 // (uaddo X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3677 // If Y + 1 cannot overflow.
3678 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1))) {
3679 SDValue Y = N1.getOperand(0);
3680 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
3682 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0, Y,
3683 N1.getOperand(2));
3684 }
3685
3686 // (uaddo X, Carry) -> (uaddo_carry X, 0, Carry)
3688 if (SDValue Carry = getAsCarry(TLI, N1))
3689 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0,
3690 DAG.getConstant(0, SDLoc(N), VT), Carry);
3691
3692 return SDValue();
3693}
3694
3695SDValue DAGCombiner::visitADDE(SDNode *N) {
3696 SDValue N0 = N->getOperand(0);
3697 SDValue N1 = N->getOperand(1);
3698 SDValue CarryIn = N->getOperand(2);
3699
3700 // canonicalize constant to RHS
3701 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3703 if (N0C && !N1C)
3704 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
3705 N1, N0, CarryIn);
3706
3707 // fold (adde x, y, false) -> (addc x, y)
3708 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3709 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
3710
3711 return SDValue();
3712}
3713
3714SDValue DAGCombiner::visitUADDO_CARRY(SDNode *N) {
3715 SDValue N0 = N->getOperand(0);
3716 SDValue N1 = N->getOperand(1);
3717 SDValue CarryIn = N->getOperand(2);
3718 SDLoc DL(N);
3719
3720 // canonicalize constant to RHS
3721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3723 if (N0C && !N1C)
3724 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
3725
3726 // fold (uaddo_carry x, y, false) -> (uaddo x, y)
3727 if (isNullConstant(CarryIn)) {
3728 if (!LegalOperations ||
3729 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
3730 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
3731 }
3732
3733 // fold (uaddo_carry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
3734 if (isNullConstant(N0) && isNullConstant(N1)) {
3735 EVT VT = N0.getValueType();
3736 EVT CarryVT = CarryIn.getValueType();
3737 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
3738 AddToWorklist(CarryExt.getNode());
3739 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
3740 DAG.getConstant(1, DL, VT)),
3741 DAG.getConstant(0, DL, CarryVT));
3742 }
3743
3744 if (SDValue Combined = visitUADDO_CARRYLike(N0, N1, CarryIn, N))
3745 return Combined;
3746
3747 if (SDValue Combined = visitUADDO_CARRYLike(N1, N0, CarryIn, N))
3748 return Combined;
3749
3750 // We want to avoid useless duplication.
3751 // TODO: This is done automatically for binary operations. As UADDO_CARRY is
3752 // not a binary operation, this is not really possible to leverage this
3753 // existing mechanism for it. However, if more operations require the same
3754 // deduplication logic, then it may be worth generalize.
3755 SDValue Ops[] = {N1, N0, CarryIn};
3756 SDNode *CSENode =
3757 DAG.getNodeIfExists(ISD::UADDO_CARRY, N->getVTList(), Ops, N->getFlags());
3758 if (CSENode)
3759 return SDValue(CSENode, 0);
3760
3761 return SDValue();
3762}
3763
3764/**
3765 * If we are facing some sort of diamond carry propagation pattern try to
3766 * break it up to generate something like:
3767 * (uaddo_carry X, 0, (uaddo_carry A, B, Z):Carry)
3768 *
3769 * The end result is usually an increase in operation required, but because the
3770 * carry is now linearized, other transforms can kick in and optimize the DAG.
3771 *
3772 * Patterns typically look something like
3773 * (uaddo A, B)
3774 * / \
3775 * Carry Sum
3776 * | \
3777 * | (uaddo_carry *, 0, Z)
3778 * | /
3779 * \ Carry
3780 * | /
3781 * (uaddo_carry X, *, *)
3782 *
3783 * But numerous variation exist. Our goal is to identify A, B, X and Z and
3784 * produce a combine with a single path for carry propagation.
3785 */
3787 SelectionDAG &DAG, SDValue X,
3788 SDValue Carry0, SDValue Carry1,
3789 SDNode *N) {
3790 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
3791 return SDValue();
3792 if (Carry1.getOpcode() != ISD::UADDO)
3793 return SDValue();
3794
3795 SDValue Z;
3796
3797 /**
3798 * First look for a suitable Z. It will present itself in the form of
3799 * (uaddo_carry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
3800 */
3801 if (Carry0.getOpcode() == ISD::UADDO_CARRY &&
3802 isNullConstant(Carry0.getOperand(1))) {
3803 Z = Carry0.getOperand(2);
3804 } else if (Carry0.getOpcode() == ISD::UADDO &&
3805 isOneConstant(Carry0.getOperand(1))) {
3806 EVT VT = Carry0->getValueType(1);
3807 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
3808 } else {
3809 // We couldn't find a suitable Z.
3810 return SDValue();
3811 }
3812
3813
3814 auto cancelDiamond = [&](SDValue A,SDValue B) {
3815 SDLoc DL(N);
3816 SDValue NewY =
3817 DAG.getNode(ISD::UADDO_CARRY, DL, Carry0->getVTList(), A, B, Z);
3818 Combiner.AddToWorklist(NewY.getNode());
3819 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), X,
3820 DAG.getConstant(0, DL, X.getValueType()),
3821 NewY.getValue(1));
3822 };
3823
3824 /**
3825 * (uaddo A, B)
3826 * |
3827 * Sum
3828 * |
3829 * (uaddo_carry *, 0, Z)
3830 */
3831 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3832 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3833 }
3834
3835 /**
3836 * (uaddo_carry A, 0, Z)
3837 * |
3838 * Sum
3839 * |
3840 * (uaddo *, B)
3841 */
3842 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3843 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3844 }
3845
3846 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3847 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3848 }
3849
3850 return SDValue();
3851}
3852
3853// If we are facing some sort of diamond carry/borrow in/out pattern try to
3854// match patterns like:
3855//
3856// (uaddo A, B) CarryIn
3857// | \ |
3858// | \ |
3859// PartialSum PartialCarryOutX /
3860// | | /
3861// | ____|____________/
3862// | / |
3863// (uaddo *, *) \________
3864// | \ \
3865// | \ |
3866// | PartialCarryOutY |
3867// | \ |
3868// | \ /
3869// AddCarrySum | ______/
3870// | /
3871// CarryOut = (or *, *)
3872//
3873// And generate UADDO_CARRY (or USUBO_CARRY) with two result values:
3874//
3875// {AddCarrySum, CarryOut} = (uaddo_carry A, B, CarryIn)
3876//
3877// Our goal is to identify A, B, and CarryIn and produce UADDO_CARRY/USUBO_CARRY
3878// with a single path for carry/borrow out propagation.
3880 SDValue N0, SDValue N1, SDNode *N) {
3881 SDValue Carry0 = getAsCarry(TLI, N0);
3882 if (!Carry0)
3883 return SDValue();
3884 SDValue Carry1 = getAsCarry(TLI, N1);
3885 if (!Carry1)
3886 return SDValue();
3887
3888 unsigned Opcode = Carry0.getOpcode();
3889 if (Opcode != Carry1.getOpcode())
3890 return SDValue();
3891 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3892 return SDValue();
3893 // Guarantee identical type of CarryOut
3894 EVT CarryOutType = N->getValueType(0);
3895 if (CarryOutType != Carry0.getValue(1).getValueType() ||
3896 CarryOutType != Carry1.getValue(1).getValueType())
3897 return SDValue();
3898
3899 // Canonicalize the add/sub of A and B (the top node in the above ASCII art)
3900 // as Carry0 and the add/sub of the carry in as Carry1 (the middle node).
3901 if (Carry1.getNode()->isOperandOf(Carry0.getNode()))
3902 std::swap(Carry0, Carry1);
3903
3904 // Check if nodes are connected in expected way.
3905 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3906 Carry1.getOperand(1) != Carry0.getValue(0))
3907 return SDValue();
3908
3909 // The carry in value must be on the righthand side for subtraction.
3910 unsigned CarryInOperandNum =
3911 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3912 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3913 return SDValue();
3914 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3915
3916 unsigned NewOp = Opcode == ISD::UADDO ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
3917 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3918 return SDValue();
3919
3920 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3921 CarryIn = getAsCarry(TLI, CarryIn, true);
3922 if (!CarryIn)
3923 return SDValue();
3924
3925 SDLoc DL(N);
3926 CarryIn = DAG.getBoolExtOrTrunc(CarryIn, DL, Carry1->getValueType(1),
3927 Carry1->getValueType(0));
3928 SDValue Merged =
3929 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3930 Carry0.getOperand(1), CarryIn);
3931
3932 // Please note that because we have proven that the result of the UADDO/USUBO
3933 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3934 // therefore prove that if the first UADDO/USUBO overflows, the second
3935 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3936 // maximum value.
3937 //
3938 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3939 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3940 //
3941 // This is important because it means that OR and XOR can be used to merge
3942 // carry flags; and that AND can return a constant zero.
3943 //
3944 // TODO: match other operations that can merge flags (ADD, etc)
3945 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3946 if (N->getOpcode() == ISD::AND)
3947 return DAG.getConstant(0, DL, CarryOutType);
3948 return Merged.getValue(1);
3949}
3950
3951// Reconstruct a subtract-with-borrow chain from its canonicalized icmp form:
3952// carry_out = or(icmp ult A, B, and(icmp eq A, B, carry_in))
3953// InstCombine folds usub.with.overflow chains into this, losing the
3954// USUBO_CARRY that lowers to sbb/sbcs.
3956 const TargetLowering &TLI) {
3957 SDValue A, B, CarryIn;
3962 m_Value(CarryIn)))))
3963 return SDValue();
3964
3965 EVT IntVT = A.getValueType();
3966 // Skip vectors: USUBO_CARRY on a vector type has no legalization path and
3967 // would crash.
3968 if (IntVT.isVector() || !TLI.isOperationLegalOrCustom(
3970 *DAG.getContext(), IntVT)))
3971 return SDValue();
3972
3973 SDLoc DL(N);
3974 SDVTList VTs = DAG.getVTList(IntVT, N->getValueType(0));
3975 return DAG.getNode(ISD::USUBO_CARRY, DL, VTs, A, B, CarryIn).getValue(1);
3976}
3977
3978SDValue DAGCombiner::visitUADDO_CARRYLike(SDValue N0, SDValue N1,
3979 SDValue CarryIn, SDNode *N) {
3980 // fold (uaddo_carry (xor a, -1), b, c) -> (usubo_carry b, a, !c) and flip
3981 // carry.
3982 if (isBitwiseNot(N0))
3983 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3984 SDLoc DL(N);
3985 SDValue Sub = DAG.getNode(ISD::USUBO_CARRY, DL, N->getVTList(), N1,
3986 N0.getOperand(0), NotC);
3987 return CombineTo(
3988 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3989 }
3990
3991 // Iff the flag result is dead:
3992 // (uaddo_carry (add|uaddo X, Y), 0, Carry) -> (uaddo_carry X, Y, Carry)
3993 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3994 // or the dependency between the instructions.
3995 if ((N0.getOpcode() == ISD::ADD ||
3996 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3997 N0.getValue(1) != CarryIn)) &&
3998 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3999 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(),
4000 N0.getOperand(0), N0.getOperand(1), CarryIn);
4001
4002 /**
4003 * When one of the uaddo_carry argument is itself a carry, we may be facing
4004 * a diamond carry propagation. In which case we try to transform the DAG
4005 * to ensure linear carry propagation if that is possible.
4006 */
4007 if (auto Y = getAsCarry(TLI, N1)) {
4008 // Because both are carries, Y and Z can be swapped.
4009 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
4010 return R;
4011 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
4012 return R;
4013 }
4014
4015 return SDValue();
4016}
4017
4018SDValue DAGCombiner::visitSADDO_CARRYLike(SDValue N0, SDValue N1,
4019 SDValue CarryIn, SDNode *N) {
4020 // fold (saddo_carry (xor a, -1), b, c) -> (ssubo_carry b, a, !c)
4021 if (isBitwiseNot(N0)) {
4022 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true))
4023 return DAG.getNode(ISD::SSUBO_CARRY, SDLoc(N), N->getVTList(), N1,
4024 N0.getOperand(0), NotC);
4025 }
4026
4027 return SDValue();
4028}
4029
4030SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
4031 SDValue N0 = N->getOperand(0);
4032 SDValue N1 = N->getOperand(1);
4033 SDValue CarryIn = N->getOperand(2);
4034 SDLoc DL(N);
4035
4036 // canonicalize constant to RHS
4037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4039 if (N0C && !N1C)
4040 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
4041
4042 // fold (saddo_carry x, y, false) -> (saddo x, y)
4043 if (isNullConstant(CarryIn)) {
4044 if (!LegalOperations ||
4045 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
4046 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
4047 }
4048
4049 if (SDValue Combined = visitSADDO_CARRYLike(N0, N1, CarryIn, N))
4050 return Combined;
4051
4052 if (SDValue Combined = visitSADDO_CARRYLike(N1, N0, CarryIn, N))
4053 return Combined;
4054
4055 return SDValue();
4056}
4057
4058// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
4059// clamp/truncation if necessary.
4061 SDValue RHS, SelectionDAG &DAG,
4062 const SDLoc &DL) {
4063 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
4064 "Illegal truncation");
4065
4066 if (DstVT == SrcVT)
4067 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4068
4069 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
4070 // clamping RHS.
4072 DstVT.getScalarSizeInBits());
4073 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
4074 return SDValue();
4075
4076 SDValue SatLimit =
4078 DstVT.getScalarSizeInBits()),
4079 DL, SrcVT);
4080 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
4081 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
4082 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
4083 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4084}
4085
4086// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
4087// usubsat(a,b), optionally as a truncated type.
4088SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL) {
4089 if (N->getOpcode() != ISD::SUB ||
4090 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
4091 return SDValue();
4092
4093 EVT SubVT = N->getValueType(0);
4094 SDValue Op0 = N->getOperand(0);
4095 SDValue Op1 = N->getOperand(1);
4096
4097 // Try to find umax(a,b) - b or a - umin(a,b) patterns
4098 // they may be converted to usubsat(a,b).
4099 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4100 SDValue MaxLHS = Op0.getOperand(0);
4101 SDValue MaxRHS = Op0.getOperand(1);
4102 if (MaxLHS == Op1)
4103 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, DL);
4104 if (MaxRHS == Op1)
4105 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, DL);
4106 }
4107
4108 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
4109 SDValue MinLHS = Op1.getOperand(0);
4110 SDValue MinRHS = Op1.getOperand(1);
4111 if (MinLHS == Op0)
4112 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, DL);
4113 if (MinRHS == Op0)
4114 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, DL);
4115 }
4116
4117 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
4118 if (Op1.getOpcode() == ISD::TRUNCATE &&
4119 Op1.getOperand(0).getOpcode() == ISD::UMIN &&
4120 Op1.getOperand(0).hasOneUse()) {
4121 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
4122 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
4123 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
4124 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
4125 DAG, DL);
4126 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
4127 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
4128 DAG, DL);
4129 }
4130
4131 return SDValue();
4132}
4133
4134// Refinement of DAG/Type Legalisation (promotion) when CTLZ is used for
4135// counting leading ones. Broadly, it replaces the substraction with a left
4136// shift.
4137//
4138// * DAG Legalisation Pattern:
4139//
4140// (sub (ctlz (zeroextend (not Src)))
4141// BitWidthDiff)
4142//
4143// if BitWidthDiff == BitWidth(Node) - BitWidth(Src)
4144// -->
4145//
4146// (ctlz_zero_poison (not (shl (anyextend Src)
4147// BitWidthDiff)))
4148//
4149// * Type Legalisation Pattern:
4150//
4151// (sub (ctlz (and (xor Src XorMask)
4152// AndMask))
4153// BitWidthDiff)
4154//
4155// if AndMask has only trailing ones
4156// and MaskBitWidth(AndMask) == BitWidth(Node) - BitWidthDiff
4157// and XorMask has more trailing ones than AndMask
4158// -->
4159//
4160// (ctlz_zero_poison (not (shl Src BitWidthDiff)))
4162 const SDLoc DL(N);
4163 SDValue N0 = N->getOperand(0);
4164 EVT VT = N0.getValueType();
4165 unsigned BitWidth = VT.getScalarSizeInBits();
4166
4167 APInt AndMask;
4168 APInt XorMask;
4169 uint64_t BitWidthDiff;
4170
4171 SDValue CtlzOp;
4172 SDValue Src;
4173
4174 if (!sd_match(N, m_Sub(m_Ctlz(m_Value(CtlzOp)), m_ConstInt(BitWidthDiff))))
4175 return SDValue();
4176
4177 if (sd_match(CtlzOp, m_ZExt(m_Not(m_Value(Src))))) {
4178 // DAG Legalisation Pattern:
4179 // (sub (ctlz (zero_extend (not Op)) BitWidthDiff))
4180 if ((BitWidth - Src.getValueType().getScalarSizeInBits()) != BitWidthDiff)
4181 return SDValue();
4182
4183 Src = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Src);
4184 } else if (sd_match(CtlzOp, m_And(m_Xor(m_Value(Src), m_ConstInt(XorMask)),
4185 m_ConstInt(AndMask)))) {
4186 // Type Legalisation Pattern:
4187 // (sub (ctlz (and (xor Op XorMask) AndMask)) BitWidthDiff)
4188 if (BitWidthDiff >= BitWidth)
4189 return SDValue();
4190 unsigned AndMaskWidth = BitWidth - BitWidthDiff;
4191 if (!(AndMask.isMask(AndMaskWidth) && XorMask.countr_one() >= AndMaskWidth))
4192 return SDValue();
4193 } else
4194 return SDValue();
4195
4196 SDValue ShiftConst = DAG.getShiftAmountConstant(BitWidthDiff, VT, DL);
4197 SDValue LShift = DAG.getNode(ISD::SHL, DL, VT, Src, ShiftConst);
4198 SDValue Not =
4199 DAG.getNode(ISD::XOR, DL, VT, LShift, DAG.getAllOnesConstant(DL, VT));
4200
4201 return DAG.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, Not);
4202}
4203
4204// Fold sub(x, mul(divrem(x,y)[0], y)) to divrem(x, y)[1]
4206 const SDLoc &DL) {
4207 assert(N->getOpcode() == ISD::SUB && "Node must be a SUB");
4208 SDValue Sub0 = N->getOperand(0);
4209 SDValue Sub1 = N->getOperand(1);
4210
4211 auto CheckAndFoldMulCase = [&](SDValue DivRem, SDValue MaybeY) -> SDValue {
4212 if ((DivRem.getOpcode() == ISD::SDIVREM ||
4213 DivRem.getOpcode() == ISD::UDIVREM) &&
4214 DivRem.getResNo() == 0 && DivRem.getOperand(0) == Sub0 &&
4215 DivRem.getOperand(1) == MaybeY) {
4216 return SDValue(DivRem.getNode(), 1);
4217 }
4218 return SDValue();
4219 };
4220
4221 if (Sub1.getOpcode() == ISD::MUL) {
4222 // (sub x, (mul divrem(x,y)[0], y))
4223 SDValue Mul0 = Sub1.getOperand(0);
4224 SDValue Mul1 = Sub1.getOperand(1);
4225
4226 if (SDValue Res = CheckAndFoldMulCase(Mul0, Mul1))
4227 return Res;
4228
4229 if (SDValue Res = CheckAndFoldMulCase(Mul1, Mul0))
4230 return Res;
4231
4232 } else if (Sub1.getOpcode() == ISD::SHL) {
4233 // Handle (sub x, (shl divrem(x,y)[0], C)) where y = 1 << C
4234 SDValue Shl0 = Sub1.getOperand(0);
4235 SDValue Shl1 = Sub1.getOperand(1);
4236 // Check if Shl0 is divrem(x, Y)[0]
4237 if ((Shl0.getOpcode() == ISD::SDIVREM ||
4238 Shl0.getOpcode() == ISD::UDIVREM) &&
4239 Shl0.getResNo() == 0 && Shl0.getOperand(0) == Sub0) {
4240
4241 SDValue Divisor = Shl0.getOperand(1);
4242
4243 ConstantSDNode *DivC = isConstOrConstSplat(Divisor);
4245 if (!DivC || !ShC)
4246 return SDValue();
4247
4248 if (DivC->getAPIntValue().isPowerOf2() &&
4249 DivC->getAPIntValue().logBase2() == ShC->getAPIntValue())
4250 return SDValue(Shl0.getNode(), 1);
4251 }
4252 }
4253 return SDValue();
4254}
4255
4256// Since it may not be valid to emit a fold to zero for vector initializers
4257// check if we can before folding.
4258static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
4259 SelectionDAG &DAG, bool LegalOperations) {
4260 if (!VT.isVector())
4261 return DAG.getConstant(0, DL, VT);
4262 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
4263 return DAG.getConstant(0, DL, VT);
4264 return SDValue();
4265}
4266
4267SDValue DAGCombiner::visitSUB(SDNode *N) {
4268 SDValue N0 = N->getOperand(0);
4269 SDValue N1 = N->getOperand(1);
4270 EVT VT = N0.getValueType();
4271 unsigned BitWidth = VT.getScalarSizeInBits();
4272 SDLoc DL(N);
4273
4274 if (SDValue V = foldSubCtlzNot(N, DAG))
4275 return V;
4276
4277 // fold (sub x, x) -> 0
4278 if (N0 == N1)
4279 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4280
4281 // fold (sub c1, c2) -> c3
4282 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
4283 return C;
4284
4285 // fold vector ops
4286 if (VT.isVector()) {
4287 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4288 return FoldedVOp;
4289
4290 // fold (sub x, 0) -> x, vector edition
4292 return N0;
4293 }
4294
4295 // (sub x, ([v]select (ult x, y), 0, y)) -> (umin x, (sub x, y))
4296 // (sub x, ([v]select (uge x, y), y, 0)) -> (umin x, (sub x, y))
4297 if (N1.hasOneUse() && hasUMin(VT)) {
4298 SDValue Y;
4299 auto MS0 = m_Specific(N0);
4300 auto MVY = m_Value(Y);
4301 auto MZ = m_Zero();
4302 auto MCC1 = m_SpecificCondCode(ISD::SETULT);
4303 auto MCC2 = m_SpecificCondCode(ISD::SETUGE);
4304
4305 if (sd_match(N1, m_SelectCCLike(MS0, MVY, MZ, m_Deferred(Y), MCC1)) ||
4306 sd_match(N1, m_SelectCCLike(MS0, MVY, m_Deferred(Y), MZ, MCC2)) ||
4307 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC1), MZ, m_Deferred(Y))) ||
4308 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC2), m_Deferred(Y), MZ)))
4309
4310 return DAG.getNode(ISD::UMIN, DL, VT, N0,
4311 DAG.getNode(ISD::SUB, DL, VT, N0, Y));
4312 }
4313
4314 if (SDValue NewSel = foldBinOpIntoSelect(N))
4315 return NewSel;
4316
4317 // fold (sub x, c) -> (add x, -c)
4318 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4319 return DAG.getNode(ISD::ADD, DL, VT, N0,
4320 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4321
4322 if (isNullOrNullSplat(N0)) {
4323 // Right-shifting everything out but the sign bit followed by negation is
4324 // the same as flipping arithmetic/logical shift type without the negation:
4325 // -(X >>u 31) -> (X >>s 31)
4326 // -(X >>s 31) -> (X >>u 31)
4327 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
4328 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
4329 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
4330 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
4331 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
4332 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
4333 }
4334 }
4335
4336 // 0 - X --> 0 if the sub is NUW.
4337 if (N->getFlags().hasNoUnsignedWrap())
4338 return N0;
4339
4341 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
4342 // N1 must be 0 because negating the minimum signed value is undefined.
4343 if (N->getFlags().hasNoSignedWrap())
4344 return N0;
4345
4346 // 0 - X --> X if X is 0 or the minimum signed value.
4347 return N1;
4348 }
4349
4350 // Convert 0 - abs(x).
4351 if (ISD::isAbsOpcode(N1.getOpcode()) && N1.hasOneUse() &&
4352 !TLI.isOperationLegalOrCustom(N1.getOpcode(), VT))
4353 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
4354 return Result;
4355
4356 // Similar to the previous rule, but this time targeting an expanded abs.
4357 // (sub 0, (max X, (sub 0, X))) --> (min X, (sub 0, X))
4358 // as well as
4359 // (sub 0, (min X, (sub 0, X))) --> (max X, (sub 0, X))
4360 // Note that these two are applicable to both signed and unsigned min/max.
4361 SDValue X;
4362 SDValue S0;
4363 auto NegPat = m_Value(S0, m_Neg(m_Deferred(X)));
4364 if (sd_match(N1, m_OneUse(m_AnyOf(m_SMax(m_Value(X), NegPat),
4365 m_UMax(m_Value(X), NegPat),
4366 m_SMin(m_Value(X), NegPat),
4367 m_UMin(m_Value(X), NegPat))))) {
4368 unsigned NewOpc = ISD::getInverseMinMaxOpcode(N1->getOpcode());
4369 if (hasOperation(NewOpc, VT))
4370 return DAG.getNode(NewOpc, DL, VT, X, S0);
4371 }
4372
4373 // Fold neg(splat(neg(x)) -> splat(x)
4374 if (VT.isVector()) {
4375 SDValue N1S = DAG.getSplatValue(N1, true);
4376 if (N1S && N1S.getOpcode() == ISD::SUB &&
4377 isNullConstant(N1S.getOperand(0)))
4378 return DAG.getSplat(VT, DL, N1S.getOperand(1));
4379 }
4380
4381 // sub 0, (and x, 1) --> SIGN_EXTEND_INREG x, i1
4382 if (N1.getOpcode() == ISD::AND && N1.hasOneUse() &&
4383 isOneOrOneSplat(N1->getOperand(1))) {
4384 EVT ExtVT = VT.changeElementType(*DAG.getContext(), MVT::i1);
4387 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N1->getOperand(0),
4388 DAG.getValueType(ExtVT));
4389 }
4390 }
4391 }
4392
4393 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
4395 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4396
4397 // fold (A - (0-B)) -> A+B
4398 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
4399 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
4400
4401 // fold A-(A-B) -> B
4402 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
4403 return N1.getOperand(1);
4404
4405 // fold (A+B)-A -> B
4406 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
4407 return N0.getOperand(1);
4408
4409 // fold (A+B)-B -> A
4410 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
4411 return N0.getOperand(0);
4412
4413 // fold (A+C1)-C2 -> A+(C1-C2)
4414 if (N0.getOpcode() == ISD::ADD) {
4415 SDValue N01 = N0.getOperand(1);
4416 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N01, N1}))
4417 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
4418 }
4419
4420 // fold C2-(A+C1) -> (C2-C1)-A
4421 if (N1.getOpcode() == ISD::ADD) {
4422 SDValue N11 = N1.getOperand(1);
4423 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}))
4424 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
4425 }
4426
4427 // fold (A-C1)-C2 -> A-(C1+C2)
4428 if (N0.getOpcode() == ISD::SUB) {
4429 SDValue N01 = N0.getOperand(1);
4430 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N01, N1}))
4431 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
4432 }
4433
4434 // fold (c1-A)-c2 -> (c1-c2)-A
4435 if (N0.getOpcode() == ISD::SUB) {
4436 SDValue N00 = N0.getOperand(0);
4437 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N00, N1}))
4438 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
4439 }
4440
4441 SDValue A, B, C;
4442
4443 // fold ((A+(B+C))-B) -> A+C
4444 if (sd_match(N0, m_Add(m_Value(A), m_Add(m_Specific(N1), m_Value(C)))))
4445 return DAG.getNode(ISD::ADD, DL, VT, A, C);
4446
4447 // fold ((A+(B-C))-B) -> A-C
4448 if (sd_match(N0, m_Add(m_Value(A), m_Sub(m_Specific(N1), m_Value(C)))))
4449 return DAG.getNode(ISD::SUB, DL, VT, A, C);
4450
4451 // fold ((A-(B-C))-C) -> A-B
4452 if (sd_match(N0, m_Sub(m_Value(A), m_Sub(m_Value(B), m_Specific(N1)))))
4453 return DAG.getNode(ISD::SUB, DL, VT, A, B);
4454
4455 // fold (A-(B-C)) -> A+(C-B)
4456 if (sd_match(N1, m_OneUse(m_Sub(m_Value(B), m_Value(C)))))
4457 return DAG.getNode(ISD::ADD, DL, VT, N0,
4458 DAG.getNode(ISD::SUB, DL, VT, C, B));
4459
4460 // A - (A & B) -> A & (~B)
4461 if (sd_match(N1, m_And(m_Specific(N0), m_Value(B))) &&
4462 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true)))
4463 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getNOT(DL, B, VT));
4464
4465 // fold (A - (-B * C)) -> (A + (B * C))
4466 if (sd_match(N1, m_OneUse(m_Mul(m_Neg(m_Value(B)), m_Value(C)))))
4467 return DAG.getNode(ISD::ADD, DL, VT, N0,
4468 DAG.getNode(ISD::MUL, DL, VT, B, C));
4469
4470 // If either operand of a sub is undef, the result is undef
4471 if (N0.isUndef())
4472 return N0;
4473 if (N1.isUndef())
4474 return N1;
4475
4476 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
4477 return V;
4478
4479 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
4480 return V;
4481
4482 // Try to match AVGCEIL fixedwidth pattern
4483 if (SDValue V = foldSubToAvg(N, DL))
4484 return V;
4485
4486 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, DL))
4487 return V;
4488
4489 if (SDValue V = foldSubToUSubSat(VT, N, DL))
4490 return V;
4491
4492 if (SDValue V = foldRemainderIdiom(N, DAG, DL))
4493 return V;
4494
4495 // (A - B) - 1 -> add (xor B, -1), A
4497 m_One(/*AllowUndefs=*/true))))
4498 return DAG.getNode(ISD::ADD, DL, VT, A, DAG.getNOT(DL, B, VT));
4499
4500 // Look for:
4501 // sub y, (xor x, -1)
4502 // And if the target does not like this form then turn into:
4503 // add (add x, y), 1
4504 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
4505 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
4506 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
4507 }
4508
4509 // Hoist one-use addition by non-opaque constant:
4510 // (x + C) - y -> (x - y) + C
4511 if (!reassociationCanBreakAddressingModePattern(ISD::SUB, DL, N, N0, N1) &&
4512 N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
4513 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4514 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4515 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
4516 }
4517 // y - (x + C) -> (y - x) - C
4518 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse() &&
4519 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
4520 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
4521 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
4522 }
4523 // (x - C) - y -> (x - y) - C
4524 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
4525 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4526 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4527 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4528 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
4529 }
4530 // (C - x) - y -> C - (x + y)
4531 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4532 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
4533 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
4534 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
4535 }
4536
4537 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
4538 // rather than 'sub 0/1' (the sext should get folded).
4539 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
4540 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
4541 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
4542 TLI.getBooleanContents(VT) ==
4544 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
4545 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
4546 }
4547
4548 // fold B = sra (A, size(A)-1); sub (xor (A, B), B) -> (abs A)
4549 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
4551 sd_match(N0, m_Xor(m_Specific(A), m_Specific(N1))))
4552 return DAG.getNode(ISD::ABS, DL, VT, A);
4553
4554 // If the relocation model supports it, consider symbol offsets.
4555 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
4556 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
4557 // fold (sub Sym+c1, Sym+c2) -> c1-c2
4558 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
4559 if (GA->getGlobal() == GB->getGlobal())
4560 return DAG.getConstant(
4561 APInt(VT.getScalarSizeInBits(), GA->getOffset() - GB->getOffset(),
4562 /*isSigned=*/false, /*implicitTrunc=*/true),
4563 DL, VT);
4564 }
4565
4566 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
4567 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
4568 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
4569 if (TN->getVT() == MVT::i1) {
4570 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
4571 DAG.getConstant(1, DL, VT));
4572 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
4573 }
4574 }
4575
4576 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C)) if this is the
4577 // only use of the vscale value or if (vscale * -C) is a valid add immediate.
4578 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
4579 if (N1.getOpcode() == ISD::VSCALE) {
4580 const APInt &IntVal = N1.getConstantOperandAPInt(0);
4581 if ((N1.hasOneUse() ||
4582 TLI.isLegalAddScalableImmediate(-IntVal.getSExtValue())) &&
4583 (!IntVal.isPowerOf2() ||
4584 hasOperation(ISD::MUL, N1.getOperand(0).getValueType())))
4585 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
4586 }
4587
4588 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
4589 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
4590 APInt NewStep = -N1.getConstantOperandAPInt(0);
4591 return DAG.getNode(ISD::ADD, DL, VT, N0,
4592 DAG.getStepVector(DL, VT, NewStep));
4593 }
4594
4595 // Prefer an add for more folding potential and possibly better codegen:
4596 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
4597 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
4598 SDValue ShAmt = N1.getOperand(1);
4599 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
4600 if (ShAmtC && ShAmtC->getAPIntValue() == (BitWidth - 1)) {
4601 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
4602 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
4603 }
4604 }
4605
4606 // As with the previous fold, prefer add for more folding potential.
4607 // Subtracting SMIN/0 is the same as adding SMIN/0:
4608 // N0 - (X << BW-1) --> N0 + (X << BW-1)
4609 if (N1.getOpcode() == ISD::SHL) {
4610 ConstantSDNode *ShlC = isConstOrConstSplat(N1.getOperand(1));
4611 if (ShlC && ShlC->getAPIntValue() == (BitWidth - 1))
4612 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
4613 }
4614
4615 // (sub (usubo_carry X, 0, Carry), Y) -> (usubo_carry X, Y, Carry)
4616 if (N0.getOpcode() == ISD::USUBO_CARRY && isNullConstant(N0.getOperand(1)) &&
4617 N0.getResNo() == 0 && N0.hasOneUse())
4618 return DAG.getNode(ISD::USUBO_CARRY, DL, N0->getVTList(),
4619 N0.getOperand(0), N1, N0.getOperand(2));
4620
4622 // (sub Carry, X) -> (uaddo_carry (sub 0, X), 0, Carry)
4623 if (SDValue Carry = getAsCarry(TLI, N0)) {
4624 SDValue X = N1;
4625 SDValue Zero = DAG.getConstant(0, DL, VT);
4626 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
4627 return DAG.getNode(ISD::UADDO_CARRY, DL,
4628 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
4629 Carry);
4630 }
4631 }
4632
4633 if (ConstantSDNode *C0 = isConstOrConstSplat(N0)) {
4634 const APInt &C0Val = C0->getAPIntValue();
4635
4636 // sub nuw C, x --> xor x, C when C is a mask (2^k - 1)
4637 if (N->getFlags().hasNoUnsignedWrap() && C0Val.isMask())
4638 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4639
4640 // If there's no chance of borrowing from adjacent bits, then sub is xor:
4641 // sub C0, X --> xor X, C0
4642 if (!C0->isOpaque()) {
4643 const APInt &MaybeOnes = ~DAG.computeKnownBits(N1).Zero;
4644 if ((C0Val - MaybeOnes) == (C0Val ^ MaybeOnes))
4645 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4646 }
4647 }
4648
4649 // smax(a,b) - smin(a,b) --> abds(a,b)
4650 if ((!LegalOperations || hasOperation(ISD::ABDS, VT)) &&
4651 sd_match(N0, &DAG, m_SMaxLike(m_Value(A), m_Value(B))) &&
4652 sd_match(N1, &DAG, m_SMinLike(m_Specific(A), m_Specific(B))))
4653 return DAG.getNode(ISD::ABDS, DL, VT, A, B);
4654
4655 // smin(a,b) - smax(a,b) --> neg(abds(a,b))
4656 if (hasOperation(ISD::ABDS, VT) &&
4657 sd_match(N0, &DAG, m_SMinLike(m_Value(A), m_Value(B))) &&
4658 sd_match(N1, &DAG, m_SMaxLike(m_Specific(A), m_Specific(B))))
4659 return DAG.getNegative(DAG.getNode(ISD::ABDS, DL, VT, A, B), DL, VT);
4660
4661 // umax(a,b) - umin(a,b) --> abdu(a,b)
4662 if ((!LegalOperations || hasOperation(ISD::ABDU, VT)) &&
4663 sd_match(N0, &DAG, m_UMaxLike(m_Value(A), m_Value(B))) &&
4664 sd_match(N1, &DAG, m_UMinLike(m_Specific(A), m_Specific(B))))
4665 return DAG.getNode(ISD::ABDU, DL, VT, A, B);
4666
4667 // umin(a,b) - umax(a,b) --> neg(abdu(a,b))
4668 if (hasOperation(ISD::ABDU, VT) &&
4669 sd_match(N0, &DAG, m_UMinLike(m_Value(A), m_Value(B))) &&
4670 sd_match(N1, &DAG, m_UMaxLike(m_Specific(A), m_Specific(B))))
4671 return DAG.getNegative(DAG.getNode(ISD::ABDU, DL, VT, A, B), DL, VT);
4672
4673 return SDValue();
4674}
4675
4676SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
4677 unsigned Opcode = N->getOpcode();
4678 SDValue N0 = N->getOperand(0);
4679 SDValue N1 = N->getOperand(1);
4680 EVT VT = N0.getValueType();
4681 bool IsSigned = Opcode == ISD::SSUBSAT;
4682 SDLoc DL(N);
4683
4684 // fold (sub_sat x, undef) -> 0
4685 if (N0.isUndef() || N1.isUndef())
4686 return DAG.getConstant(0, DL, VT);
4687
4688 // fold (sub_sat x, x) -> 0
4689 if (N0 == N1)
4690 return DAG.getConstant(0, DL, VT);
4691
4692 // fold (sub_sat c1, c2) -> c3
4693 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4694 return C;
4695
4696 // fold vector ops
4697 if (VT.isVector()) {
4698 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4699 return FoldedVOp;
4700
4701 // fold (sub_sat x, 0) -> x, vector edition
4703 return N0;
4704 }
4705
4706 // fold (sub_sat x, 0) -> x
4707 if (isNullConstant(N1))
4708 return N0;
4709
4710 // If it cannot overflow, transform into an sub.
4711 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4712 return DAG.getNode(ISD::SUB, DL, VT, N0, N1);
4713
4714 // Narrow a vXiN USUBSAT to a smaller type when both operands are known
4715 // to fit in fewer bits. This allows targets with native narrow USUBSAT
4716 // (e.g. vpsubusb/vpsubusw) to avoid emulation with vpmaxu + vsub.
4717 if (!IsSigned && VT.isVector() && VT.isSimple()) {
4718 unsigned ScalarBits = VT.getScalarSizeInBits();
4719 if (ScalarBits > 8 && isPowerOf2_32(ScalarBits) &&
4720 !TLI.isOperationLegal(ISD::USUBSAT, VT)) {
4721 KnownBits Known0 = DAG.computeKnownBits(N0);
4722 unsigned ActiveBits = Known0.countMaxActiveBits();
4723 for (unsigned NarrowBits = PowerOf2Ceil(ActiveBits);
4724 NarrowBits != 0 && NarrowBits < ScalarBits; NarrowBits *= 2) {
4725 unsigned Scale = ScalarBits / NarrowBits;
4726 ElementCount ScaledEC = VT.getVectorElementCount() * Scale;
4727 MVT NarrowSVT = MVT::getIntegerVT(NarrowBits);
4728 EVT NarrowVT = EVT::getVectorVT(*DAG.getContext(), NarrowSVT, ScaledEC);
4729
4730 if (!TLI.isOperationLegalOrCustom(ISD::USUBSAT, NarrowVT))
4731 continue;
4732 KnownBits Known1 = DAG.computeKnownBits(N1);
4733 if (Known1.countMaxActiveBits() <= NarrowBits) {
4734 SDValue NarrowN0 = DAG.getBitcast(NarrowVT, N0);
4735 SDValue NarrowN1 = DAG.getBitcast(NarrowVT, N1);
4736 SDValue NarrowSub =
4737 DAG.getNode(ISD::USUBSAT, DL, NarrowVT, NarrowN0, NarrowN1);
4738 return DAG.getBitcast(VT, NarrowSub);
4739 }
4740 // TODO: If N1 doesn't fit in NarrowBits, we could OR the upper bits
4741 // of N1 with 1s to force saturation in those lanes, allowing the
4742 // narrow USUBSAT to still be used. This requires a TLI hook to check
4743 // whether the constant can be folded as a broadcast memory operand
4744 // (profitable on AVX512, not on SSE/AVX), to avoid introducing an
4745 // extra register and instruction on non-AVX512 targets.
4746 break;
4747 }
4748 }
4749 }
4750 return SDValue();
4751}
4752
4753SDValue DAGCombiner::visitSUBC(SDNode *N) {
4754 SDValue N0 = N->getOperand(0);
4755 SDValue N1 = N->getOperand(1);
4756 EVT VT = N0.getValueType();
4757 SDLoc DL(N);
4758
4759 // If the flag result is dead, turn this into an SUB.
4760 if (!N->hasAnyUseOfValue(1))
4761 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4762 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4763
4764 // fold (subc x, x) -> 0 + no borrow
4765 if (N0 == N1)
4766 return CombineTo(N, DAG.getConstant(0, DL, VT),
4767 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4768
4769 // fold (subc x, 0) -> x + no borrow
4770 if (isNullConstant(N1))
4771 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4772
4773 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4774 if (isAllOnesConstant(N0))
4775 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4776 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4777
4778 return SDValue();
4779}
4780
4781SDValue DAGCombiner::visitSUBO(SDNode *N) {
4782 SDValue N0 = N->getOperand(0);
4783 SDValue N1 = N->getOperand(1);
4784 EVT VT = N0.getValueType();
4785 bool IsSigned = (ISD::SSUBO == N->getOpcode());
4786
4787 EVT CarryVT = N->getValueType(1);
4788 SDLoc DL(N);
4789
4790 // If the flag result is dead, turn this into an SUB.
4791 if (!N->hasAnyUseOfValue(1))
4792 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4793 DAG.getUNDEF(CarryVT));
4794
4795 // fold (subo x, x) -> 0 + no borrow
4796 if (N0 == N1)
4797 return CombineTo(N, DAG.getConstant(0, DL, VT),
4798 DAG.getConstant(0, DL, CarryVT));
4799
4800 // fold (subox, c) -> (addo x, -c)
4801 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4802 if (IsSigned && !N1C->isMinSignedValue())
4803 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
4804 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4805
4806 // fold (subo x, 0) -> x + no borrow
4807 if (isNullOrNullSplat(N1))
4808 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
4809
4810 // If it cannot overflow, transform into an sub.
4811 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4812 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4813 DAG.getConstant(0, DL, CarryVT));
4814
4815 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4816 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
4817 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4818 DAG.getConstant(0, DL, CarryVT));
4819
4820 return SDValue();
4821}
4822
4823SDValue DAGCombiner::visitSUBE(SDNode *N) {
4824 SDValue N0 = N->getOperand(0);
4825 SDValue N1 = N->getOperand(1);
4826 SDValue CarryIn = N->getOperand(2);
4827
4828 // fold (sube x, y, false) -> (subc x, y)
4829 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
4830 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
4831
4832 return SDValue();
4833}
4834
4835SDValue DAGCombiner::visitUSUBO_CARRY(SDNode *N) {
4836 SDValue N0 = N->getOperand(0);
4837 SDValue N1 = N->getOperand(1);
4838 SDValue CarryIn = N->getOperand(2);
4839
4840 // fold (usubo_carry x, y, false) -> (usubo x, y)
4841 if (isNullConstant(CarryIn)) {
4842 if (!LegalOperations ||
4843 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
4844 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
4845 }
4846
4847 // Iff the flag result is dead:
4848 // (usubo_carry (sub X, Y), 0, Carry) -> (usubo_carry X, Y, Carry)
4849 if (N0.getOpcode() == ISD::SUB && isNullConstant(N1) &&
4850 !N->hasAnyUseOfValue(1))
4851 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), N->getVTList(),
4852 N0.getOperand(0), N0.getOperand(1), CarryIn);
4853
4854 return SDValue();
4855}
4856
4857SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
4858 SDValue N0 = N->getOperand(0);
4859 SDValue N1 = N->getOperand(1);
4860 SDValue CarryIn = N->getOperand(2);
4861
4862 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
4863 if (isNullConstant(CarryIn)) {
4864 if (!LegalOperations ||
4865 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
4866 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
4867 }
4868
4869 return SDValue();
4870}
4871
4872// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
4873// UMULFIXSAT here.
4874SDValue DAGCombiner::visitMULFIX(SDNode *N) {
4875 SDValue N0 = N->getOperand(0);
4876 SDValue N1 = N->getOperand(1);
4877 SDValue Scale = N->getOperand(2);
4878 EVT VT = N0.getValueType();
4879
4880 // fold (mulfix x, undef, scale) -> 0
4881 if (N0.isUndef() || N1.isUndef())
4882 return DAG.getConstant(0, SDLoc(N), VT);
4883
4884 // Canonicalize constant to RHS (vector doesn't have to splat)
4887 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
4888
4889 // fold (mulfix x, 0, scale) -> 0
4890 if (isNullConstant(N1))
4891 return DAG.getConstant(0, SDLoc(N), VT);
4892
4893 return SDValue();
4894}
4895
4896SDValue DAGCombiner::visitMUL(SDNode *N) {
4897 SDValue N0 = N->getOperand(0);
4898 SDValue N1 = N->getOperand(1);
4899 EVT VT = N0.getValueType();
4900 unsigned BitWidth = VT.getScalarSizeInBits();
4901 SDLoc DL(N);
4902
4903 // fold (mul x, undef) -> 0
4904 if (N0.isUndef() || N1.isUndef())
4905 return DAG.getConstant(0, DL, VT);
4906
4907 // fold (mul c1, c2) -> c1*c2
4908 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, DL, VT, {N0, N1}))
4909 return C;
4910
4911 // canonicalize constant to RHS (vector doesn't have to splat)
4914 return DAG.getNode(ISD::MUL, DL, VT, N1, N0);
4915
4916 bool N1IsConst = false;
4917 bool N1IsOpaqueConst = false;
4918 APInt ConstValue1;
4919
4920 // fold vector ops
4921 if (VT.isVector()) {
4922 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4923 return FoldedVOp;
4924
4925 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
4926 assert((!N1IsConst || ConstValue1.getBitWidth() == BitWidth) &&
4927 "Splat APInt should be element width");
4928 } else {
4929 N1IsConst = isa<ConstantSDNode>(N1);
4930 if (N1IsConst) {
4931 ConstValue1 = N1->getAsAPIntVal();
4932 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
4933 }
4934 }
4935
4936 // fold (mul x, 0) -> 0
4937 if (N1IsConst && ConstValue1.isZero())
4938 return N1;
4939
4940 // fold (mul x, 1) -> x
4941 if (N1IsConst && ConstValue1.isOne())
4942 return N0;
4943
4944 if (SDValue NewSel = foldBinOpIntoSelect(N))
4945 return NewSel;
4946
4947 // fold (mul x, -1) -> 0-x
4948 if (N1IsConst && ConstValue1.isAllOnes())
4949 return DAG.getNegative(N0, DL, VT);
4950
4951 // fold (mul x, (1 << c)) -> x << c
4952 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4953 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
4954 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
4955 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4956 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4957 SDNodeFlags Flags;
4958 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap());
4959 // Preserve nsw when the shift amount is strictly less than BitWidth - 1,
4960 // i.e. the multiplier is not the signed minimum value.
4961 if (N->getFlags().hasNoSignedWrap() && N1IsConst &&
4962 ConstValue1.logBase2() < BitWidth - 1)
4963 Flags.setNoSignedWrap(true);
4964 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc, Flags);
4965 }
4966 }
4967
4968 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
4969 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
4970 unsigned Log2Val = (-ConstValue1).logBase2();
4971
4972 // FIXME: If the input is something that is easily negated (e.g. a
4973 // single-use add), we should put the negate there.
4974 return DAG.getNode(
4975 ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4976 DAG.getNode(ISD::SHL, DL, VT, N0,
4977 DAG.getShiftAmountConstant(Log2Val, VT, DL)));
4978 }
4979
4980 // Attempt to reuse an existing umul_lohi/smul_lohi node, but only if the
4981 // hi result is in use in case we hit this mid-legalization.
4982 for (unsigned LoHiOpc : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
4983 if (!LegalOperations || TLI.isOperationLegalOrCustom(LoHiOpc, VT)) {
4984 SDVTList LoHiVT = DAG.getVTList(VT, VT);
4985 // TODO: Can we match commutable operands with getNodeIfExists?
4986 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N0, N1}))
4987 if (LoHi->hasAnyUseOfValue(1))
4988 return SDValue(LoHi, 0);
4989 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N1, N0}))
4990 if (LoHi->hasAnyUseOfValue(1))
4991 return SDValue(LoHi, 0);
4992 }
4993 }
4994
4995 // Try to transform:
4996 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
4997 // mul x, (2^N + 1) --> add (shl x, N), x
4998 // mul x, (2^N - 1) --> sub (shl x, N), x
4999 // Examples: x * 33 --> (x << 5) + x
5000 // x * 15 --> (x << 4) - x
5001 // x * -33 --> -((x << 5) + x)
5002 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
5003 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
5004 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
5005 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
5006 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
5007 // x * 0xf800 --> (x << 16) - (x << 11)
5008 // x * -0x8800 --> -((x << 15) + (x << 11))
5009 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
5010 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
5011 // TODO: We could handle more general decomposition of any constant by
5012 // having the target set a limit on number of ops and making a
5013 // callback to determine that sequence (similar to sqrt expansion).
5014 unsigned MathOp = ISD::DELETED_NODE;
5015 APInt MulC = ConstValue1.abs();
5016 // The constant `2` should be treated as (2^0 + 1).
5017 unsigned TZeros = MulC == 2 ? 0 : MulC.countr_zero();
5018 MulC.lshrInPlace(TZeros);
5019 if ((MulC - 1).isPowerOf2())
5020 MathOp = ISD::ADD;
5021 else if ((MulC + 1).isPowerOf2())
5022 MathOp = ISD::SUB;
5023
5024 if (MathOp != ISD::DELETED_NODE) {
5025 unsigned ShAmt =
5026 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
5027 ShAmt += TZeros;
5028 assert(ShAmt < BitWidth &&
5029 "multiply-by-constant generated out of bounds shift");
5030 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, N0,
5031 DAG.getShiftAmountConstant(ShAmt, VT, DL));
5032 SDValue R = N0;
5033 if (TZeros)
5034 R = DAG.getNode(ISD::SHL, DL, VT, N0,
5035 DAG.getShiftAmountConstant(TZeros, VT, DL));
5036 R = DAG.getNode(MathOp, DL, VT, Shl, R);
5037 if (ConstValue1.isNegative())
5038 R = DAG.getNegative(R, DL, VT);
5039 return R;
5040 }
5041 }
5042
5043 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
5044 {
5045 SDValue X, C1;
5046 if (sd_match(N0, m_Shl(m_Value(X), m_Value(C1))))
5047 if (SDValue C3 = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N1, C1}))
5048 return DAG.getNode(ISD::MUL, DL, VT, X, C3);
5049 }
5050
5051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
5052 // use.
5053 {
5054 SDValue X, C, Y;
5055 if (sd_match(N,
5058 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, X, Y);
5059 return DAG.getNode(ISD::SHL, DL, VT, Mul, C);
5060 }
5061 }
5062
5063 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
5067 return DAG.getNode(
5068 ISD::ADD, DL, VT,
5069 DAG.getNode(ISD::MUL, SDLoc(N0), VT, N0.getOperand(0), N1),
5070 DAG.getNode(ISD::MUL, SDLoc(N1), VT, N0.getOperand(1), N1));
5071
5072 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
5073 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
5074 ConstantSDNode *NC1 = isConstOrConstSplat(N1);
5075 if (N0.getOpcode() == ISD::VSCALE && NC1) {
5076 const APInt &C0 = N0.getConstantOperandAPInt(0);
5077 const APInt &C1 = NC1->getAPIntValue();
5078 if (!C0.isPowerOf2() || C1.isPowerOf2() ||
5079 hasOperation(ISD::MUL, NC1->getValueType(0)))
5080 return DAG.getVScale(DL, VT, C0 * C1);
5081 }
5082
5083 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5084 APInt MulVal;
5085 if (N0.getOpcode() == ISD::STEP_VECTOR &&
5086 ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
5087 const APInt &C0 = N0.getConstantOperandAPInt(0);
5088 APInt NewStep = C0 * MulVal;
5089 return DAG.getStepVector(DL, VT, NewStep);
5090 }
5091
5092 // Fold Y = sra (X, size(X)-1); mul (or (Y, 1), X) -> (abs X)
5093 SDValue X;
5094 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
5096 m_One()),
5097 m_Deferred(X)))) {
5098 return DAG.getNode(ISD::ABS, DL, VT, X);
5099 }
5100
5101 // Fold ((mul x, 0/undef) -> 0,
5102 // (mul x, 1) -> x) -> x)
5103 // -> and(x, mask)
5104 // We can replace vectors with '0' and '1' factors with a clearing mask.
5105 if (VT.isFixedLengthVector()) {
5106 unsigned NumElts = VT.getVectorNumElements();
5107 SmallBitVector ClearMask;
5108 ClearMask.reserve(NumElts);
5109 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
5110 if (!V || V->isZero()) {
5111 ClearMask.push_back(true);
5112 return true;
5113 }
5114 ClearMask.push_back(false);
5115 return V->isOne();
5116 };
5117 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
5118 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
5119 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
5120 EVT LegalSVT = N1.getOperand(0).getValueType();
5121 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
5122 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
5124 for (unsigned I = 0; I != NumElts; ++I)
5125 if (ClearMask[I])
5126 Mask[I] = Zero;
5127 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
5128 }
5129 }
5130
5131 // reassociate mul
5132 if (SDValue RMUL = reassociateOps(ISD::MUL, DL, N0, N1, N->getFlags()))
5133 return RMUL;
5134
5135 // Fold mul(vecreduce(x), vecreduce(y)) -> vecreduce(mul(x, y))
5136 if (SDValue SD =
5137 reassociateReduction(ISD::VECREDUCE_MUL, ISD::MUL, DL, VT, N0, N1))
5138 return SD;
5139
5140 // Simplify the operands using demanded-bits information.
5142 return SDValue(N, 0);
5143
5144 return SDValue();
5145}
5146
5147/// Return true if divmod libcall is available.
5149 const SelectionDAG &DAG) {
5150 RTLIB::Libcall LC;
5151 EVT NodeType = Node->getValueType(0);
5152 if (!NodeType.isSimple())
5153 return false;
5154 switch (NodeType.getSimpleVT().SimpleTy) {
5155 default: return false; // No libcall for vector types.
5156 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
5157 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
5158 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
5159 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
5160 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
5161 }
5162
5163 return DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported;
5164}
5165
5166/// Issue divrem if both quotient and remainder are needed.
5167SDValue DAGCombiner::useDivRem(SDNode *Node) {
5168 if (Node->use_empty())
5169 return SDValue(); // This is a dead node, leave it alone.
5170
5171 unsigned Opcode = Node->getOpcode();
5172 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
5173 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
5174
5175 // DivMod lib calls can still work on non-legal types if using lib-calls.
5176 EVT VT = Node->getValueType(0);
5177 if (VT.isVector() || !VT.isInteger())
5178 return SDValue();
5179
5180 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
5181 return SDValue();
5182
5183 // If DIVREM is going to get expanded into a libcall,
5184 // but there is no libcall available, then don't combine.
5185 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
5187 return SDValue();
5188
5189 // If div is legal, it's better to do the normal expansion
5190 unsigned OtherOpcode = 0;
5191 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
5192 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
5193 if (TLI.isOperationLegalOrCustom(Opcode, VT))
5194 return SDValue();
5195 } else {
5196 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5197 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
5198 return SDValue();
5199 }
5200
5201 SDValue Op0 = Node->getOperand(0);
5202 SDValue Op1 = Node->getOperand(1);
5203 SDValue combined;
5204 for (SDNode *User : Op0->users()) {
5205 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
5206 User->use_empty())
5207 continue;
5208 // Convert the other matching node(s), too;
5209 // otherwise, the DIVREM may get target-legalized into something
5210 // target-specific that we won't be able to recognize.
5211 unsigned UserOpc = User->getOpcode();
5212 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
5213 User->getOperand(0) == Op0 &&
5214 User->getOperand(1) == Op1) {
5215 if (!combined) {
5216 if (UserOpc == OtherOpcode) {
5217 SDVTList VTs = DAG.getVTList(VT, VT);
5218 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
5219 } else if (UserOpc == DivRemOpc) {
5220 combined = SDValue(User, 0);
5221 } else {
5222 assert(UserOpc == Opcode);
5223 continue;
5224 }
5225 }
5226 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
5227 CombineTo(User, combined);
5228 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
5229 CombineTo(User, combined.getValue(1));
5230 }
5231 }
5232 return combined;
5233}
5234
5236 SDValue N0 = N->getOperand(0);
5237 SDValue N1 = N->getOperand(1);
5238 EVT VT = N->getValueType(0);
5239 SDLoc DL(N);
5240
5241 unsigned Opc = N->getOpcode();
5242 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
5243
5244 // X / undef -> undef
5245 // X % undef -> undef
5246 // X / 0 -> undef
5247 // X % 0 -> undef
5248 // NOTE: This includes vectors where any divisor element is zero/undef.
5249 if (DAG.isUndef(Opc, {N0, N1}))
5250 return DAG.getUNDEF(VT);
5251
5252 // undef / X -> 0
5253 // undef % X -> 0
5254 if (N0.isUndef())
5255 return DAG.getConstant(0, DL, VT);
5256
5257 // 0 / X -> 0
5258 // 0 % X -> 0
5260 if (N0C && N0C->isZero())
5261 return N0;
5262
5263 // X / X -> 1
5264 // X % X -> 0
5265 if (N0 == N1)
5266 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
5267
5268 // X / 1 -> X
5269 // X % 1 -> 0
5270 // If this is a boolean op (single-bit element type), we can't have
5271 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
5272 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
5273 // it's a 1.
5274 if (isOneOrOneSplat(N1) || (VT.getScalarType() == MVT::i1))
5275 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
5276
5277 return SDValue();
5278}
5279
5280SDValue DAGCombiner::visitSDIV(SDNode *N) {
5281 SDValue N0 = N->getOperand(0);
5282 SDValue N1 = N->getOperand(1);
5283 EVT VT = N->getValueType(0);
5284 EVT CCVT = getSetCCResultType(VT);
5285 SDLoc DL(N);
5286
5287 // fold (sdiv c1, c2) -> c1/c2
5288 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
5289 return C;
5290
5291 // fold vector ops
5292 if (VT.isVector())
5293 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5294 return FoldedVOp;
5295
5296 // fold (sdiv X, -1) -> 0-X
5297 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5298 if (N1C && N1C->isAllOnes())
5299 return DAG.getNegative(N0, DL, VT);
5300
5301 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
5302 if (N1C && N1C->isMinSignedValue())
5303 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5304 DAG.getConstant(1, DL, VT),
5305 DAG.getConstant(0, DL, VT));
5306
5307 if (SDValue V = simplifyDivRem(N, DAG))
5308 return V;
5309
5310 if (SDValue NewSel = foldBinOpIntoSelect(N))
5311 return NewSel;
5312
5313 // If we know the sign bits of both operands are zero, strength reduce to a
5314 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
5315 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5316 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
5317
5318 if (SDValue V = visitSDIVLike(N0, N1, N)) {
5319 // If the corresponding remainder node exists, update its users with
5320 // (Dividend - (Quotient * Divisor).
5321 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
5322 { N0, N1 })) {
5323 // If the sdiv has the exact flag we shouldn't propagate it to the
5324 // remainder node.
5325 if (!N->getFlags().hasExact()) {
5326 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5327 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5328 AddToWorklist(Mul.getNode());
5329 AddToWorklist(Sub.getNode());
5330 CombineTo(RemNode, Sub);
5331 }
5332 }
5333 return V;
5334 }
5335
5336 // sdiv, srem -> sdivrem
5337 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5338 // true. Otherwise, we break the simplification logic in visitREM().
5339 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5340 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5341 if (SDValue DivRem = useDivRem(N))
5342 return DivRem;
5343
5344 return SDValue();
5345}
5346
5347static bool isDivisorPowerOfTwo(SDValue Divisor) {
5348 // Helper for determining whether a value is a power-2 constant scalar or a
5349 // vector of such elements.
5350 auto IsPowerOfTwo = [](ConstantSDNode *C) {
5351 if (C->isZero() || C->isOpaque())
5352 return false;
5353 if (C->getAPIntValue().isPowerOf2())
5354 return true;
5355 if (C->getAPIntValue().isNegatedPowerOf2())
5356 return true;
5357 return false;
5358 };
5359
5360 return ISD::matchUnaryPredicate(Divisor, IsPowerOfTwo, /*AllowUndefs=*/false,
5361 /*AllowTruncation=*/true);
5362}
5363
5364SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5365 SDLoc DL(N);
5366 EVT VT = N->getValueType(0);
5367 EVT CCVT = getSetCCResultType(VT);
5368 unsigned BitWidth = VT.getScalarSizeInBits();
5369 unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();
5370
5371 // fold (sdiv X, pow2) -> simple ops after legalize
5372 // FIXME: We check for the exact bit here because the generic lowering gives
5373 // better results in that case. The target-specific lowering should learn how
5374 // to handle exact sdivs efficiently. An exception is made for large bitwidths
5375 // exceeding what the target can natively support, as division expansion was
5376 // skipped in favor of this optimization.
5377 if ((!N->getFlags().hasExact() || BitWidth > MaxLegalDivRemBitWidth) &&
5378 isDivisorPowerOfTwo(N1)) {
5379 // Target-specific implementation of sdiv x, pow2.
5380 if (SDValue Res = BuildSDIVPow2(N))
5381 return Res;
5382
5383 // Create constants that are functions of the shift amount value.
5384 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
5385 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
5386 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
5387 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
5388 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
5389 if (!isConstantOrConstantVector(Inexact))
5390 return SDValue();
5391
5392 // Splat the sign bit into the register
5393 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
5394 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
5395 AddToWorklist(Sign.getNode());
5396
5397 // Add (N0 < 0) ? abs2 - 1 : 0;
5398 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
5399 AddToWorklist(Srl.getNode());
5400 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
5401 AddToWorklist(Add.getNode());
5402 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
5403 AddToWorklist(Sra.getNode());
5404
5405 // Special case: (sdiv X, 1) -> X
5406 // Special Case: (sdiv X, -1) -> 0-X
5407 SDValue One = DAG.getConstant(1, DL, VT);
5409 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
5410 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
5411 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
5412 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
5413
5414 // If dividing by a positive value, we're done. Otherwise, the result must
5415 // be negated.
5416 SDValue Zero = DAG.getConstant(0, DL, VT);
5417 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
5418
5419 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
5420 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
5421 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
5422 return Res;
5423 }
5424
5425 // If integer divide is expensive and we satisfy the requirements, emit an
5426 // alternate sequence. Targets may check function attributes for size/speed
5427 // trade-offs.
5428 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5429 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5430 /*AllowTruncation=*/true) &&
5431 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5432 if (SDValue Op = BuildSDIV(N))
5433 return Op;
5434
5435 return SDValue();
5436}
5437
5438SDValue DAGCombiner::visitUDIV(SDNode *N) {
5439 SDValue N0 = N->getOperand(0);
5440 SDValue N1 = N->getOperand(1);
5441 EVT VT = N->getValueType(0);
5442 EVT CCVT = getSetCCResultType(VT);
5443 SDLoc DL(N);
5444
5445 // fold (udiv c1, c2) -> c1/c2
5446 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
5447 return C;
5448
5449 // fold vector ops
5450 if (VT.isVector())
5451 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5452 return FoldedVOp;
5453
5454 // fold (udiv X, -1) -> select(X == -1, 1, 0)
5455 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5456 if (N1C && N1C->isAllOnes() && CCVT.isVector() == VT.isVector()) {
5457 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5458 DAG.getConstant(1, DL, VT),
5459 DAG.getConstant(0, DL, VT));
5460 }
5461
5462 if (SDValue V = simplifyDivRem(N, DAG))
5463 return V;
5464
5465 if (SDValue NewSel = foldBinOpIntoSelect(N))
5466 return NewSel;
5467
5468 if (SDValue V = visitUDIVLike(N0, N1, N)) {
5469 // If the corresponding remainder node exists, update its users with
5470 // (Dividend - (Quotient * Divisor).
5471 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
5472 { N0, N1 })) {
5473 // If the udiv has the exact flag we shouldn't propagate it to the
5474 // remainder node.
5475 if (!N->getFlags().hasExact()) {
5476 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5477 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5478 AddToWorklist(Mul.getNode());
5479 AddToWorklist(Sub.getNode());
5480 CombineTo(RemNode, Sub);
5481 }
5482 }
5483 return V;
5484 }
5485
5486 // sdiv, srem -> sdivrem
5487 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5488 // true. Otherwise, we break the simplification logic in visitREM().
5489 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5490 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5491 if (SDValue DivRem = useDivRem(N))
5492 return DivRem;
5493
5494 // Simplify the operands using demanded-bits information.
5495 // We don't have demanded bits support for UDIV so this just enables constant
5496 // folding based on known bits.
5498 return SDValue(N, 0);
5499
5500 return SDValue();
5501}
5502
5503SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5504 SDLoc DL(N);
5505 EVT VT = N->getValueType(0);
5506
5507 // fold (udiv x, (1 << c)) -> x >>u c
5508 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5509 /*AllowTruncation=*/true)) {
5510 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5511 AddToWorklist(LogBase2.getNode());
5512
5513 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5514 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
5515 AddToWorklist(Trunc.getNode());
5516 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5517 }
5518 }
5519
5520 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
5521 if (N1.getOpcode() == ISD::SHL) {
5522 SDValue N10 = N1.getOperand(0);
5523 if (isConstantOrConstantVector(N10, /*NoOpaques=*/true,
5524 /*AllowTruncation=*/true)) {
5525 if (SDValue LogBase2 = BuildLogBase2(N10, DL)) {
5526 AddToWorklist(LogBase2.getNode());
5527
5528 EVT ADDVT = N1.getOperand(1).getValueType();
5529 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
5530 AddToWorklist(Trunc.getNode());
5531 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
5532 AddToWorklist(Add.getNode());
5533 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
5534 }
5535 }
5536 }
5537
5538 // fold (udiv x, c) -> alternate
5539 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5540 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5541 /*AllowTruncation=*/true) &&
5542 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5543 if (SDValue Op = BuildUDIV(N))
5544 return Op;
5545
5546 return SDValue();
5547}
5548
5549SDValue DAGCombiner::buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N) {
5550 if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1) &&
5551 !DAG.doesNodeExist(ISD::SDIV, N->getVTList(), {N0, N1})) {
5552 // Target-specific implementation of srem x, pow2.
5553 if (SDValue Res = BuildSREMPow2(N))
5554 return Res;
5555 }
5556 return SDValue();
5557}
5558
5559// handles ISD::SREM and ISD::UREM
5560SDValue DAGCombiner::visitREM(SDNode *N) {
5561 unsigned Opcode = N->getOpcode();
5562 SDValue N0 = N->getOperand(0);
5563 SDValue N1 = N->getOperand(1);
5564 EVT VT = N->getValueType(0);
5565 EVT CCVT = getSetCCResultType(VT);
5566
5567 bool isSigned = (Opcode == ISD::SREM);
5568 SDLoc DL(N);
5569
5570 // fold (rem c1, c2) -> c1%c2
5571 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5572 return C;
5573
5574 // fold (urem X, -1) -> select(FX == -1, 0, FX)
5575 // Freeze the numerator to avoid a miscompile with an undefined value.
5576 if (!isSigned && llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false) &&
5577 CCVT.isVector() == VT.isVector()) {
5578 SDValue F0 = DAG.getFreeze(N0);
5579 SDValue EqualsNeg1 = DAG.getSetCC(DL, CCVT, F0, N1, ISD::SETEQ);
5580 return DAG.getSelect(DL, VT, EqualsNeg1, DAG.getConstant(0, DL, VT), F0);
5581 }
5582
5583 if (SDValue V = simplifyDivRem(N, DAG))
5584 return V;
5585
5586 if (SDValue NewSel = foldBinOpIntoSelect(N))
5587 return NewSel;
5588
5589 if (isSigned) {
5590 // If we know the sign bits of both operands are zero, strength reduce to a
5591 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
5592 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5593 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
5594 } else {
5595 if (DAG.isKnownToBeAPowerOfTwo(N1, /*OrZero=*/true)) {
5596 // fold (urem x, pow2) -> (and x, pow2-1)
5597 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
5598 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
5599 AddToWorklist(Add.getNode());
5600 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
5601 }
5602 }
5603
5604 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5605
5606 // If X/C can be simplified by the division-by-constant logic, lower
5607 // X%C to the equivalent of X-X/C*C.
5608 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
5609 // speculative DIV must not cause a DIVREM conversion. We guard against this
5610 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
5611 // combine will not return a DIVREM. Regardless, checking cheapness here
5612 // makes sense since the simplification results in fatter code.
5613 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
5614 if (isSigned) {
5615 // check if we can build faster implementation for srem
5616 if (SDValue OptimizedRem = buildOptimizedSREM(N0, N1, N))
5617 return OptimizedRem;
5618 }
5619
5620 SDValue OptimizedDiv =
5621 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
5622 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
5623 // If the equivalent Div node also exists, update its users.
5624 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5625 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
5626 { N0, N1 }))
5627 CombineTo(DivNode, OptimizedDiv);
5628 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
5629 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5630 AddToWorklist(OptimizedDiv.getNode());
5631 AddToWorklist(Mul.getNode());
5632 return Sub;
5633 }
5634 }
5635
5636 // sdiv, srem -> sdivrem
5637 if (SDValue DivRem = useDivRem(N))
5638 return DivRem.getValue(1);
5639
5640 // fold urem(urem(A, BCst), Op1Cst) -> urem(A, Op1Cst)
5641 // iff urem(BCst, Op1Cst) == 0
5642 SDValue A;
5643 APInt Op1Cst, BCst;
5644 if (sd_match(N, m_URem(m_URem(m_Value(A), m_ConstInt(BCst)),
5645 m_ConstInt(Op1Cst))) &&
5646 BCst.urem(Op1Cst).isZero()) {
5647 return DAG.getNode(ISD::UREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5648 }
5649
5650 // fold srem(srem(A, BCst), Op1Cst) -> srem(A, Op1Cst)
5651 // iff srem(BCst, Op1Cst) == 0 && Op1Cst != 1
5652 if (sd_match(N, m_SRem(m_SRem(m_Value(A), m_ConstInt(BCst)),
5653 m_ConstInt(Op1Cst))) &&
5654 BCst.srem(Op1Cst).isZero() && !Op1Cst.isAllOnes()) {
5655 return DAG.getNode(ISD::SREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5656 }
5657
5658 return SDValue();
5659}
5660
5661SDValue DAGCombiner::visitMULHS(SDNode *N) {
5662 SDValue N0 = N->getOperand(0);
5663 SDValue N1 = N->getOperand(1);
5664 EVT VT = N->getValueType(0);
5665 SDLoc DL(N);
5666
5667 // fold (mulhs c1, c2)
5668 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
5669 return C;
5670
5671 // canonicalize constant to RHS.
5674 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
5675
5676 if (VT.isVector()) {
5677 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5678 return FoldedVOp;
5679
5680 // fold (mulhs x, 0) -> 0
5681 // do not return N1, because undef node may exist.
5683 return DAG.getConstant(0, DL, VT);
5684 }
5685
5686 // fold (mulhs x, 0) -> 0
5687 if (isNullConstant(N1))
5688 return N1;
5689
5690 // fold (mulhs x, 1) -> (sra x, size(x)-1)
5691 if (isOneConstant(N1))
5692 return DAG.getNode(
5693 ISD::SRA, DL, VT, N0,
5695
5696 // fold (mulhs x, undef) -> 0
5697 if (N0.isUndef() || N1.isUndef())
5698 return DAG.getConstant(0, DL, VT);
5699
5700 // If the type twice as wide is legal, transform the mulhs to a wider multiply
5701 // plus a shift.
5702 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
5703 !VT.isVector()) {
5704 MVT Simple = VT.getSimpleVT();
5705 unsigned SimpleSize = Simple.getSizeInBits();
5706 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5707 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5708 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
5709 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
5710 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5711 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5712 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5713 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5714 }
5715 }
5716
5717 return SDValue();
5718}
5719
5720SDValue DAGCombiner::visitMULHU(SDNode *N) {
5721 SDValue N0 = N->getOperand(0);
5722 SDValue N1 = N->getOperand(1);
5723 EVT VT = N->getValueType(0);
5724 SDLoc DL(N);
5725
5726 // fold (mulhu c1, c2)
5727 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
5728 return C;
5729
5730 // canonicalize constant to RHS.
5733 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
5734
5735 if (VT.isVector()) {
5736 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5737 return FoldedVOp;
5738
5739 // fold (mulhu x, 0) -> 0
5740 // do not return N1, because undef node may exist.
5742 return DAG.getConstant(0, DL, VT);
5743 }
5744
5745 // fold (mulhu x, 0) -> 0
5746 if (isNullConstant(N1))
5747 return N1;
5748
5749 // fold (mulhu x, 1) -> 0
5750 if (isOneConstant(N1))
5751 return DAG.getConstant(0, DL, VT);
5752
5753 // fold (mulhu x, undef) -> 0
5754 if (N0.isUndef() || N1.isUndef())
5755 return DAG.getConstant(0, DL, VT);
5756
5757 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
5758 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5759 /*AllowTruncation=*/true) &&
5760 (!LegalOperations || hasOperation(ISD::SRL, VT))) {
5761 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5762 unsigned NumEltBits = VT.getScalarSizeInBits();
5763 SDValue SRLAmt = DAG.getNode(
5764 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
5765 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5766 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
5767 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5768 }
5769 }
5770
5771 // If the type twice as wide is legal, transform the mulhu to a wider multiply
5772 // plus a shift.
5773 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
5774 !VT.isVector()) {
5775 MVT Simple = VT.getSimpleVT();
5776 unsigned SimpleSize = Simple.getSizeInBits();
5777 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5778 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5779 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
5780 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
5781 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5782 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5783 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5784 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5785 }
5786 }
5787
5788 // Simplify the operands using demanded-bits information.
5789 // We don't have demanded bits support for MULHU so this just enables constant
5790 // folding based on known bits.
5792 return SDValue(N, 0);
5793
5794 return SDValue();
5795}
5796
5797SDValue DAGCombiner::visitAVG(SDNode *N) {
5798 unsigned Opcode = N->getOpcode();
5799 SDValue N0 = N->getOperand(0);
5800 SDValue N1 = N->getOperand(1);
5801 EVT VT = N->getValueType(0);
5802 SDLoc DL(N);
5803 bool IsSigned = Opcode == ISD::AVGCEILS || Opcode == ISD::AVGFLOORS;
5804
5805 // fold (avg c1, c2)
5806 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5807 return C;
5808
5809 // canonicalize constant to RHS.
5812 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5813
5814 if (VT.isVector())
5815 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5816 return FoldedVOp;
5817
5818 // fold (avg x, undef) -> x
5819 if (N0.isUndef())
5820 return N1;
5821 if (N1.isUndef())
5822 return N0;
5823
5824 // fold (avg x, x) --> x
5825 if (N0 == N1 && Level >= AfterLegalizeTypes)
5826 return N0;
5827
5828 // fold (avgfloor x, 0) -> x >> 1
5829 SDValue X, Y;
5831 return DAG.getNode(ISD::SRA, DL, VT, X,
5832 DAG.getShiftAmountConstant(1, VT, DL));
5834 return DAG.getNode(ISD::SRL, DL, VT, X,
5835 DAG.getShiftAmountConstant(1, VT, DL));
5836
5837 // fold avgu(zext(x), zext(y)) -> zext(avgu(x, y))
5838 // fold avgs(sext(x), sext(y)) -> sext(avgs(x, y))
5839 if (!IsSigned &&
5840 sd_match(N, m_BinOp(Opcode, m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
5841 X.getValueType() == Y.getValueType() &&
5842 hasOperation(Opcode, X.getValueType())) {
5843 SDValue AvgU = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5844 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, AvgU);
5845 }
5846 if (IsSigned &&
5847 sd_match(N, m_BinOp(Opcode, m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
5848 X.getValueType() == Y.getValueType() &&
5849 hasOperation(Opcode, X.getValueType())) {
5850 SDValue AvgS = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5851 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, AvgS);
5852 }
5853
5854 // Fold avgflooru(x,y) -> avgceilu(x,y-1) iff y != 0
5855 // Fold avgflooru(x,y) -> avgceilu(x-1,y) iff x != 0
5856 // Check if avgflooru isn't legal/custom but avgceilu is.
5857 if (Opcode == ISD::AVGFLOORU && !hasOperation(ISD::AVGFLOORU, VT) &&
5858 (!LegalOperations || hasOperation(ISD::AVGCEILU, VT))) {
5859 if (DAG.isKnownNeverZero(N1))
5860 return DAG.getNode(
5861 ISD::AVGCEILU, DL, VT, N0,
5862 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getAllOnesConstant(DL, VT)));
5863 if (DAG.isKnownNeverZero(N0))
5864 return DAG.getNode(
5865 ISD::AVGCEILU, DL, VT, N1,
5866 DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getAllOnesConstant(DL, VT)));
5867 }
5868
5869 // Fold avgfloor((add nw x,y), 1) -> avgceil(x,y)
5870 // Fold avgfloor((add nw x,1), y) -> avgceil(x,y)
5871 if ((Opcode == ISD::AVGFLOORU && hasOperation(ISD::AVGCEILU, VT)) ||
5872 (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGCEILS, VT))) {
5873 SDValue Add;
5874 if (sd_match(N,
5875 m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_Value(Y))),
5876 m_One())) ||
5877 sd_match(N, m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_One())),
5878 m_Value(Y)))) {
5879
5880 if (IsSigned && Add->getFlags().hasNoSignedWrap())
5881 return DAG.getNode(ISD::AVGCEILS, DL, VT, X, Y);
5882
5883 if (!IsSigned && Add->getFlags().hasNoUnsignedWrap())
5884 return DAG.getNode(ISD::AVGCEILU, DL, VT, X, Y);
5885 }
5886 }
5887
5888 // Fold avgfloors(x,y) -> avgflooru(x,y) if both x and y are non-negative
5889 if (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGFLOORU, VT)) {
5890 if (DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5891 return DAG.getNode(ISD::AVGFLOORU, DL, VT, N0, N1);
5892 }
5893
5894 return SDValue();
5895}
5896
5897SDValue DAGCombiner::visitABD(SDNode *N) {
5898 unsigned Opcode = N->getOpcode();
5899 SDValue N0 = N->getOperand(0);
5900 SDValue N1 = N->getOperand(1);
5901 EVT VT = N->getValueType(0);
5902 SDLoc DL(N);
5903
5904 // fold (abd c1, c2)
5905 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5906 return C;
5907
5908 // canonicalize constant to RHS.
5911 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5912
5913 if (VT.isVector())
5914 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5915 return FoldedVOp;
5916
5917 // fold (abd x, undef) -> 0
5918 if (N0.isUndef() || N1.isUndef())
5919 return DAG.getConstant(0, DL, VT);
5920
5921 // fold (abd x, x) -> 0
5922 if (N0 == N1)
5923 return DAG.getConstant(0, DL, VT);
5924
5925 SDValue X, Y;
5926
5927 // fold (abds x, 0) -> abs x
5929 (!LegalOperations || hasOperation(ISD::ABS, VT)))
5930 return DAG.getNode(ISD::ABS, DL, VT, X);
5931
5932 // fold (abdu x, 0) -> x
5934 return X;
5935
5936 // fold (abds x, y) -> (abdu x, y) iff both args are known positive
5937 if (Opcode == ISD::ABDS && hasOperation(ISD::ABDU, VT) &&
5938 DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5939 return DAG.getNode(ISD::ABDU, DL, VT, N1, N0);
5940
5941 // fold (abd? (?ext x), (?ext y)) -> (zext (abd? x, y))
5944 EVT SmallVT = X.getScalarValueSizeInBits() > Y.getScalarValueSizeInBits()
5945 ? X.getValueType()
5946 : Y.getValueType();
5947 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5948 SDValue ExtedX = DAG.getExtOrTrunc(X, SDLoc(X), SmallVT, N0->getOpcode());
5949 SDValue ExtedY = DAG.getExtOrTrunc(Y, SDLoc(Y), SmallVT, N0->getOpcode());
5950 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {ExtedX, ExtedY});
5951 SDValue ZExted = DAG.getZExtOrTrunc(SmallABD, DL, VT);
5952 return ZExted;
5953 }
5954 }
5955
5956 // fold (abd? (?ext ty:x), small_const:c) -> (zext (abd? x, c))
5959 EVT SmallVT = X.getValueType();
5960 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5961 uint64_t Bits = SmallVT.getScalarSizeInBits();
5962 unsigned RelevantBits =
5963 (Opcode == ISD::ABDS) ? DAG.ComputeMaxSignificantBits(Y)
5965 bool TruncatingYIsCheap = TLI.isTruncateFree(Y, SmallVT) ||
5967 Y,
5968 [&](auto *C) {
5969 if (!C)
5970 return true;
5971 const APInt &YConst = C->getAsAPIntVal();
5972 return (Opcode == ISD::ABDS)
5973 ? YConst.isSignedIntN(Bits)
5974 : YConst.isIntN(Bits);
5975 },
5976 /*AllowUndefs=*/true);
5977
5978 if (RelevantBits <= Bits && TruncatingYIsCheap) {
5979 SDValue NewY = DAG.getNode(ISD::TRUNCATE, SDLoc(Y), SmallVT, Y);
5980 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {X, NewY});
5981 return DAG.getZExtOrTrunc(SmallABD, DL, VT);
5982 }
5983 }
5984 }
5985
5986 return SDValue();
5987}
5988
5989/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
5990/// give the opcodes for the two computations that are being performed. Return
5991/// true if a simplification was made.
5992SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
5993 unsigned HiOp) {
5994 // If the high half is not needed, just compute the low half.
5995 bool HiExists = N->hasAnyUseOfValue(1);
5996 if (!HiExists && (!LegalOperations ||
5997 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
5998 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5999 return CombineTo(N, Res, Res);
6000 }
6001
6002 // If the low half is not needed, just compute the high half.
6003 bool LoExists = N->hasAnyUseOfValue(0);
6004 if (!LoExists && (!LegalOperations ||
6005 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
6006 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
6007 return CombineTo(N, Res, Res);
6008 }
6009
6010 // If both halves are used, return as it is.
6011 if (LoExists && HiExists)
6012 return SDValue();
6013
6014 // If the two computed results can be simplified separately, separate them.
6015 if (LoExists) {
6016 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
6017 AddToWorklist(Lo.getNode());
6018 SDValue LoOpt = combine(Lo.getNode());
6019 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
6020 (!LegalOperations ||
6021 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
6022 return CombineTo(N, LoOpt, LoOpt);
6023 }
6024
6025 if (HiExists) {
6026 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
6027 AddToWorklist(Hi.getNode());
6028 SDValue HiOpt = combine(Hi.getNode());
6029 if (HiOpt.getNode() && HiOpt != Hi &&
6030 (!LegalOperations ||
6031 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
6032 return CombineTo(N, HiOpt, HiOpt);
6033 }
6034
6035 return SDValue();
6036}
6037
6038SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
6039 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
6040 return Res;
6041
6042 SDValue N0 = N->getOperand(0);
6043 SDValue N1 = N->getOperand(1);
6044 EVT VT = N->getValueType(0);
6045 SDLoc DL(N);
6046
6047 // Constant fold.
6049 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N0, N1);
6050
6051 // canonicalize constant to RHS (vector doesn't have to splat)
6054 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N1, N0);
6055
6056 // If the type is twice as wide is legal, transform the mulhu to a wider
6057 // multiply plus a shift.
6058 if (VT.isSimple() && !VT.isVector()) {
6059 MVT Simple = VT.getSimpleVT();
6060 unsigned SimpleSize = Simple.getSizeInBits();
6061 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6062 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6063 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
6064 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
6065 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6066 // Compute the high part as N1.
6067 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6068 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6069 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6070 // Compute the low part as N0.
6071 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6072 return CombineTo(N, Lo, Hi);
6073 }
6074 }
6075
6076 return SDValue();
6077}
6078
6079SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
6080 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
6081 return Res;
6082
6083 SDValue N0 = N->getOperand(0);
6084 SDValue N1 = N->getOperand(1);
6085 EVT VT = N->getValueType(0);
6086 SDLoc DL(N);
6087
6088 // Constant fold.
6090 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N0, N1);
6091
6092 // canonicalize constant to RHS (vector doesn't have to splat)
6095 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N1, N0);
6096
6097 // (umul_lohi N0, 0) -> (0, 0)
6098 if (isNullConstant(N1)) {
6099 SDValue Zero = DAG.getConstant(0, DL, VT);
6100 return CombineTo(N, Zero, Zero);
6101 }
6102
6103 // (umul_lohi N0, 1) -> (N0, 0)
6104 if (isOneConstant(N1)) {
6105 SDValue Zero = DAG.getConstant(0, DL, VT);
6106 return CombineTo(N, N0, Zero);
6107 }
6108
6109 // If the type is twice as wide is legal, transform the mulhu to a wider
6110 // multiply plus a shift.
6111 if (VT.isSimple() && !VT.isVector()) {
6112 MVT Simple = VT.getSimpleVT();
6113 unsigned SimpleSize = Simple.getSizeInBits();
6114 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6115 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6116 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
6117 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
6118 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6119 // Compute the high part as N1.
6120 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6121 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6122 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6123 // Compute the low part as N0.
6124 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6125 return CombineTo(N, Lo, Hi);
6126 }
6127 }
6128
6129 return SDValue();
6130}
6131
6132SDValue DAGCombiner::visitMULO(SDNode *N) {
6133 SDValue N0 = N->getOperand(0);
6134 SDValue N1 = N->getOperand(1);
6135 EVT VT = N0.getValueType();
6136 bool IsSigned = (ISD::SMULO == N->getOpcode());
6137
6138 EVT CarryVT = N->getValueType(1);
6139 SDLoc DL(N);
6140
6141 ConstantSDNode *N0C = isConstOrConstSplat(N0);
6142 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6143
6144 // fold operation with constant operands.
6145 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
6146 // multiple results.
6147 if (N0C && N1C) {
6148 bool Overflow;
6149 APInt Result =
6150 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
6151 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
6152 return CombineTo(N, DAG.getConstant(Result, DL, VT),
6153 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
6154 }
6155
6156 // canonicalize constant to RHS.
6159 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
6160
6161 // fold (mulo x, 0) -> 0 + no carry out
6162 if (isNullOrNullSplat(N1))
6163 return CombineTo(N, DAG.getConstant(0, DL, VT),
6164 DAG.getConstant(0, DL, CarryVT));
6165
6166 // (mulo x, 2) -> (addo x, x)
6167 // FIXME: This needs a freeze.
6168 if (N1C && N1C->getAPIntValue() == 2 &&
6169 (!IsSigned || VT.getScalarSizeInBits() > 2))
6170 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
6171 N->getVTList(), N0, N0);
6172
6173 // A 1 bit SMULO overflows if both inputs are 1.
6174 if (IsSigned && VT.getScalarSizeInBits() == 1) {
6175 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
6176 SDValue Cmp = DAG.getSetCC(DL, CarryVT, And,
6177 DAG.getConstant(0, DL, VT), ISD::SETNE);
6178 return CombineTo(N, And, Cmp);
6179 }
6180
6181 // If it cannot overflow, transform into a mul.
6182 if (DAG.willNotOverflowMul(IsSigned, N0, N1))
6183 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
6184 DAG.getConstant(0, DL, CarryVT));
6185 return SDValue();
6186}
6187
6188// Function to calculate whether the Min/Max pair of SDNodes (potentially
6189// swapped around) make a signed saturate pattern, clamping to between a signed
6190// saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
6191// Returns the node being clamped and the bitwidth of the clamp in BW. Should
6192// work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
6193// same as SimplifySelectCC. N0<N1 ? N2 : N3.
6195 SDValue N3, ISD::CondCode CC, unsigned &BW,
6196 bool &Unsigned, SelectionDAG &DAG) {
6197 auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
6198 ISD::CondCode CC) {
6199 // The compare and select operand should be the same or the select operands
6200 // should be truncated versions of the comparison.
6201 if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
6202 return 0;
6203 // The constants need to be the same or a truncated version of each other.
6206 if (!N1C || !N3C)
6207 return 0;
6208 const APInt &C1 = N1C->getAPIntValue().trunc(N1.getScalarValueSizeInBits());
6209 const APInt &C2 = N3C->getAPIntValue().trunc(N3.getScalarValueSizeInBits());
6210 if (C1.getBitWidth() < C2.getBitWidth() || C1 != C2.sext(C1.getBitWidth()))
6211 return 0;
6212 return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
6213 };
6214
6215 // Check the initial value is a SMIN/SMAX equivalent.
6216 unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
6217 if (!Opcode0)
6218 return SDValue();
6219
6220 // We could only need one range check, if the fptosi could never produce
6221 // the upper value.
6222 if (N0.getOpcode() == ISD::FP_TO_SINT && Opcode0 == ISD::SMAX) {
6223 if (isNullOrNullSplat(N3)) {
6224 EVT IntVT = N0.getValueType().getScalarType();
6225 EVT FPVT = N0.getOperand(0).getValueType().getScalarType();
6226 if (FPVT.isSimple()) {
6227 Type *InputTy = FPVT.getTypeForEVT(*DAG.getContext());
6228 const fltSemantics &Semantics = InputTy->getFltSemantics();
6229 uint32_t MinBitWidth =
6230 APFloatBase::semanticsIntSizeInBits(Semantics, /*isSigned*/ true);
6231 if (IntVT.getSizeInBits() >= MinBitWidth) {
6232 Unsigned = true;
6233 BW = PowerOf2Ceil(MinBitWidth);
6234 return N0;
6235 }
6236 }
6237 }
6238 }
6239
6240 SDValue N00, N01, N02, N03;
6241 ISD::CondCode N0CC;
6242 switch (N0.getOpcode()) {
6243 case ISD::SMIN:
6244 case ISD::SMAX:
6245 N00 = N02 = N0.getOperand(0);
6246 N01 = N03 = N0.getOperand(1);
6247 N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
6248 break;
6249 case ISD::SELECT_CC:
6250 N00 = N0.getOperand(0);
6251 N01 = N0.getOperand(1);
6252 N02 = N0.getOperand(2);
6253 N03 = N0.getOperand(3);
6254 N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
6255 break;
6256 case ISD::SELECT:
6257 case ISD::VSELECT:
6258 if (N0.getOperand(0).getOpcode() != ISD::SETCC)
6259 return SDValue();
6260 N00 = N0.getOperand(0).getOperand(0);
6261 N01 = N0.getOperand(0).getOperand(1);
6262 N02 = N0.getOperand(1);
6263 N03 = N0.getOperand(2);
6264 N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
6265 break;
6266 default:
6267 return SDValue();
6268 }
6269
6270 unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
6271 if (!Opcode1 || Opcode0 == Opcode1)
6272 return SDValue();
6273
6274 ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
6275 ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
6276 if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
6277 return SDValue();
6278
6279 const APInt &MinC = MinCOp->getAPIntValue();
6280 const APInt &MaxC = MaxCOp->getAPIntValue();
6281 APInt MinCPlus1 = MinC + 1;
6282 if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
6283 BW = MinCPlus1.exactLogBase2() + 1;
6284 Unsigned = false;
6285 return N02;
6286 }
6287
6288 if (MaxC == 0 && MinC != 0 && MinCPlus1.isPowerOf2()) {
6289 BW = MinCPlus1.exactLogBase2();
6290 Unsigned = true;
6291 return N02;
6292 }
6293
6294 return SDValue();
6295}
6296
6298 SDValue N3, ISD::CondCode CC,
6299 SelectionDAG &DAG) {
6300 unsigned BW;
6301 bool Unsigned;
6302 SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned, DAG);
6303 if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
6304 return SDValue();
6305 EVT FPVT = Fp.getOperand(0).getValueType();
6306 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6307 EVT::getIntegerVT(*DAG.getContext(), BW));
6308 unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
6309 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
6310 return SDValue();
6311 SDLoc DL(Fp);
6312 SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
6313 DAG.getValueType(NewVT.getScalarType()));
6314 return DAG.getExtOrTrunc(!Unsigned, Sat, DL, N2->getValueType(0));
6315}
6316
6318 SDValue N3, ISD::CondCode CC,
6319 SelectionDAG &DAG) {
6320 // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
6321 // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
6322 // be truncated versions of the setcc (N0/N1).
6323 if ((N0 != N2 &&
6324 (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
6325 N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
6326 return SDValue();
6329 if (!N1C || !N3C)
6330 return SDValue();
6331 const APInt &C1 = N1C->getAPIntValue();
6332 const APInt &C3 = N3C->getAPIntValue();
6333 if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
6334 C1 != C3.zext(C1.getBitWidth()))
6335 return SDValue();
6336
6337 unsigned BW = (C1 + 1).exactLogBase2();
6338 EVT FPVT = N0.getOperand(0).getValueType();
6339 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6340 EVT::getIntegerVT(*DAG.getContext(), BW));
6342 FPVT, NewVT))
6343 return SDValue();
6344
6345 SDValue Sat =
6346 DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
6347 DAG.getValueType(NewVT.getScalarType()));
6348 return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
6349}
6350
6351// Fold a NaN-guard select of fp_to_sint/fp_to_uint into the saturating
6352// variant, which returns 0 for NaN.
6354 EVT VT = N->getValueType(0);
6355 SDLoc DL(N);
6356
6357 // Match an isnan-guarded select, requiring the compare to be single-use.
6358 // The guarded value is fp_to_sint/fp_to_uint of X, optionally masked by an
6359 // AND:
6360 // select (setcc X, 0.0, uno), 0, (fp_to_sint/uint X)
6361 // select (setcc X, 0.0, ord), (fp_to_sint/uint X), 0
6362 // select (setcc X, 0.0, uno), 0, (and (fp_to_sint/uint X), M)
6363 // select (setcc X, 0.0, ord), (and (fp_to_sint/uint X), M), 0
6364 SDValue X, GuardedVal;
6365 if (!sd_match(N,
6368 m_Zero(), m_Value(GuardedVal))) &&
6369 !sd_match(N,
6372 m_Value(GuardedVal), m_Zero())))
6373 return SDValue();
6374
6375 // The guarded value must be fp_to_sint/fp_to_uint of the same X, optionally
6376 // masked by a (commutative) AND.
6377 SDValue Mask;
6378 unsigned NewOpc;
6379 if (sd_match(GuardedVal, m_FPToSI(m_Specific(X))) ||
6380 sd_match(GuardedVal, m_And(m_FPToSI(m_Specific(X)), m_Value(Mask))))
6381 NewOpc = ISD::FP_TO_SINT_SAT;
6382 else if (sd_match(GuardedVal, m_FPToUI(m_Specific(X))) ||
6383 sd_match(GuardedVal, m_And(m_FPToUI(m_Specific(X)), m_Value(Mask))))
6384 NewOpc = ISD::FP_TO_UINT_SAT;
6385 else
6386 return SDValue();
6387
6389 X.getValueType(), VT))
6390 return SDValue();
6391
6392 SDValue Sat =
6393 DAG.getNode(NewOpc, DL, VT, X, DAG.getValueType(VT.getScalarType()));
6394 if (Mask) {
6395 // For NaN inputs the saturating conversion yields 0, so (and 0, Mask) must
6396 // stay 0 to match the original select. A poison Mask would make it poison,
6397 // so freeze Mask to guarantee a defined value.
6398 Sat = DAG.getNode(ISD::AND, DL, VT, Sat, DAG.getFreeze(Mask));
6399 }
6400 return Sat;
6401}
6402
6403SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
6404 SDValue N0 = N->getOperand(0);
6405 SDValue N1 = N->getOperand(1);
6406 EVT VT = N0.getValueType();
6407 unsigned Opcode = N->getOpcode();
6408 SDLoc DL(N);
6409
6410 // fold operation with constant operands.
6411 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
6412 return C;
6413
6414 // If the operands are the same, this is a no-op.
6415 if (N0 == N1)
6416 return N0;
6417
6418 // canonicalize constant to RHS
6421 return DAG.getNode(Opcode, DL, VT, N1, N0);
6422
6423 // fold vector ops
6424 if (VT.isVector())
6425 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
6426 return FoldedVOp;
6427
6428 // reassociate minmax
6429 if (SDValue RMINMAX = reassociateOps(Opcode, DL, N0, N1, N->getFlags()))
6430 return RMINMAX;
6431
6432 // Fold sign-extension masks using arithmetic shift:
6433 // smax(X, -1) -> or(X, ashr(X, BW-1))
6434 // smin(X, 0) -> and(X, ashr(X, BW-1))
6435 // ashr(X, BW-1) sign-extends the sign bit: 0 for X>=0, -1 for X<0.
6436 // OR with X yields X (non-negative) or -1 (negative) = smax(X,-1).
6437 // AND with X yields 0 (non-negative) or X (negative) = smin(X, 0).
6438 // Both reduce to two instructions vs. a compare+cmov on x86-64.
6439 // Only fold when the target has no native SMAX/SMIN instruction for this
6440 // type (isOperationExpand), the type is legal (not needing splitting),
6441 // the operand is not a min/max chain (preserving target combine patterns
6442 // that fold smax(smin(x,C),D) into a single saturation instruction), and
6443 // for smax(X,-1) the operand is not a sign extension (doubling its use
6444 // count can cause the target to lower the extension less efficiently).
6445 APInt C;
6446 if (TLI.isTypeLegal(VT) &&
6448 sd_match(N1, m_ConstInt(C))) {
6449 if (Opcode == ISD::SMAX && TLI.isOperationExpand(ISD::SMAX, VT) &&
6450 N0.getOpcode() != ISD::SMIN && N0.getOpcode() != ISD::SIGN_EXTEND &&
6451 C.isAllOnes()) {
6452 SDValue ShiftAmt =
6454 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6455 return DAG.getNode(ISD::OR, DL, VT, N0, Shift);
6456 }
6457 if (Opcode == ISD::SMIN && TLI.isOperationExpand(ISD::SMIN, VT) &&
6458 N0.getOpcode() != ISD::SMAX && C.isZero()) {
6459 SDValue ShiftAmt =
6461 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6462 return DAG.getNode(ISD::AND, DL, VT, N0, Shift);
6463 }
6464 }
6465
6466 // If both operands are known to have the same sign (both non-negative or both
6467 // negative), flip between UMIN/UMAX and SMIN/SMAX.
6468 // Only do this if:
6469 // 1. The current op isn't legal and the flipped is.
6470 // 2. The saturation pattern is broken by canonicalization in InstCombine.
6471 bool IsOpIllegal = !TLI.isOperationLegal(Opcode, VT);
6472 bool IsSatBroken = Opcode == ISD::UMIN && N0.getOpcode() == ISD::SMAX;
6473
6474 if (IsSatBroken || IsOpIllegal) {
6475 auto HasKnownSameSign = [&](SDValue A, SDValue B) {
6476 if (A.isUndef() || B.isUndef())
6477 return true;
6478
6479 KnownBits KA = DAG.computeKnownBits(A);
6480 if (!KA.isNonNegative() && !KA.isNegative())
6481 return false;
6482
6483 KnownBits KB = DAG.computeKnownBits(B);
6484 if (KA.isNonNegative())
6485 return KB.isNonNegative();
6486 return KB.isNegative();
6487 };
6488
6489 if (HasKnownSameSign(N0, N1)) {
6490 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
6491 if ((IsSatBroken && IsOpIllegal) || TLI.isOperationLegal(AltOpcode, VT))
6492 return DAG.getNode(AltOpcode, DL, VT, N0, N1);
6493 }
6494 }
6495
6496 if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
6498 N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
6499 return S;
6500 if (Opcode == ISD::UMIN)
6501 if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
6502 return S;
6503
6504 // Fold min/max(vecreduce(x), vecreduce(y)) -> vecreduce(min/max(x, y))
6505 auto ReductionOpcode = [](unsigned Opcode) {
6506 switch (Opcode) {
6507 case ISD::SMIN:
6508 return ISD::VECREDUCE_SMIN;
6509 case ISD::SMAX:
6510 return ISD::VECREDUCE_SMAX;
6511 case ISD::UMIN:
6512 return ISD::VECREDUCE_UMIN;
6513 case ISD::UMAX:
6514 return ISD::VECREDUCE_UMAX;
6515 default:
6516 llvm_unreachable("Unexpected opcode");
6517 }
6518 };
6519 if (SDValue SD = reassociateReduction(ReductionOpcode(Opcode), Opcode,
6520 SDLoc(N), VT, N0, N1))
6521 return SD;
6522
6523 // Fold operation with vscale operands.
6524 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
6525 uint64_t C0 = N0->getConstantOperandVal(0);
6526 uint64_t C1 = N1->getConstantOperandVal(0);
6527 if (Opcode == ISD::UMAX)
6528 return C0 > C1 ? N0 : N1;
6529 else if (Opcode == ISD::UMIN)
6530 return C0 > C1 ? N1 : N0;
6531 }
6532
6533 // If we know the range of vscale, see if we can fold it given a constant.
6534 if (N0.getOpcode() == ISD::VSCALE) {
6535 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
6536 bool ForSigned = (Opcode == ISD::SMAX || Opcode == ISD::SMIN);
6537 ConstantRange Range = DAG.computeConstantRange(N0, ForSigned);
6538
6539 const APInt &C1V = C1->getAPIntValue();
6540 if ((Opcode == ISD::UMAX && Range.getUnsignedMax().ule(C1V)) ||
6541 (Opcode == ISD::UMIN && Range.getUnsignedMin().uge(C1V)) ||
6542 (Opcode == ISD::SMAX && Range.getSignedMax().sle(C1V)) ||
6543 (Opcode == ISD::SMIN && Range.getSignedMin().sge(C1V))) {
6544 return N1;
6545 }
6546 }
6547 }
6548
6549 // Simplify the operands using demanded-bits information.
6551 return SDValue(N, 0);
6552
6553 return SDValue();
6554}
6555
6556/// If this is a bitwise logic instruction and both operands have the same
6557/// opcode, try to sink the other opcode after the logic instruction.
6558SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
6559 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
6560 EVT VT = N0.getValueType();
6561 unsigned LogicOpcode = N->getOpcode();
6562 unsigned HandOpcode = N0.getOpcode();
6563 assert(ISD::isBitwiseLogicOp(LogicOpcode) && "Expected logic opcode");
6564 assert(HandOpcode == N1.getOpcode() && "Bad input!");
6565
6566 // Bail early if none of these transforms apply.
6567 if (N0.getNumOperands() == 0)
6568 return SDValue();
6569
6570 // FIXME: We should check number of uses of the operands to not increase
6571 // the instruction count for all transforms.
6572
6573 // Handle size-changing casts (or sign_extend_inreg).
6574 SDValue X = N0.getOperand(0);
6575 SDValue Y = N1.getOperand(0);
6576 EVT XVT = X.getValueType();
6577 SDLoc DL(N);
6578 if (ISD::isExtOpcode(HandOpcode) || ISD::isExtVecInRegOpcode(HandOpcode) ||
6579 (HandOpcode == ISD::SIGN_EXTEND_INREG &&
6580 N0.getOperand(1) == N1.getOperand(1))) {
6581 // If both operands have other uses, this transform would create extra
6582 // instructions without eliminating anything.
6583 if (!N0.hasOneUse() && !N1.hasOneUse())
6584 return SDValue();
6585 // We need matching integer source types.
6586 if (XVT != Y.getValueType())
6587 return SDValue();
6588 // Don't create an illegal op during or after legalization. Don't ever
6589 // create an unsupported vector op.
6590 if ((VT.isVector() || LegalOperations) &&
6591 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
6592 return SDValue();
6593 // Avoid infinite looping with PromoteIntBinOp.
6594 // TODO: Should we apply desirable/legal constraints to all opcodes?
6595 if ((HandOpcode == ISD::ANY_EXTEND ||
6596 HandOpcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
6597 LegalTypes && !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
6598 return SDValue();
6599 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
6600 SDNodeFlags LogicFlags;
6601 LogicFlags.setDisjoint(N->getFlags().hasDisjoint() &&
6602 ISD::isExtOpcode(HandOpcode));
6603 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y, LogicFlags);
6604 if (HandOpcode == ISD::SIGN_EXTEND_INREG)
6605 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6606 return DAG.getNode(HandOpcode, DL, VT, Logic);
6607 }
6608
6609 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
6610 if (HandOpcode == ISD::TRUNCATE) {
6611 // If both operands have other uses, this transform would create extra
6612 // instructions without eliminating anything.
6613 if (!N0.hasOneUse() && !N1.hasOneUse())
6614 return SDValue();
6615 // We need matching source types.
6616 if (XVT != Y.getValueType())
6617 return SDValue();
6618 // Don't create an illegal op during or after legalization.
6619 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
6620 return SDValue();
6621 // Be extra careful sinking truncate. If it's free, there's no benefit in
6622 // widening a binop. Also, don't create a logic op on an illegal type.
6623 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
6624 return SDValue();
6625 if (!TLI.isTypeLegal(XVT))
6626 return SDValue();
6627 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6628 return DAG.getNode(HandOpcode, DL, VT, Logic);
6629 }
6630
6631 // For binops SHL/SRL/SRA/AND:
6632 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
6633 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
6634 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
6635 N0.getOperand(1) == N1.getOperand(1)) {
6636 // If either operand has other uses, this transform is not an improvement.
6637 if (!N0.hasOneUse() || !N1.hasOneUse())
6638 return SDValue();
6639 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6640 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6641 }
6642
6643 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
6644 if (HandOpcode == ISD::BSWAP) {
6645 // If either operand has other uses, this transform is not an improvement.
6646 if (!N0.hasOneUse() || !N1.hasOneUse())
6647 return SDValue();
6648 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6649 return DAG.getNode(HandOpcode, DL, VT, Logic);
6650 }
6651
6652 // For funnel shifts FSHL/FSHR:
6653 // logic_op (OP x, x1, s), (OP y, y1, s) -->
6654 // --> OP (logic_op x, y), (logic_op, x1, y1), s
6655 if ((HandOpcode == ISD::FSHL || HandOpcode == ISD::FSHR) &&
6656 N0.getOperand(2) == N1.getOperand(2)) {
6657 if (!N0.hasOneUse() || !N1.hasOneUse())
6658 return SDValue();
6659 SDValue X1 = N0.getOperand(1);
6660 SDValue Y1 = N1.getOperand(1);
6661 SDValue S = N0.getOperand(2);
6662 SDValue Logic0 = DAG.getNode(LogicOpcode, DL, VT, X, Y);
6663 SDValue Logic1 = DAG.getNode(LogicOpcode, DL, VT, X1, Y1);
6664 return DAG.getNode(HandOpcode, DL, VT, Logic0, Logic1, S);
6665 }
6666
6667 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
6668 // Only perform this optimization up until type legalization, before
6669 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
6670 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
6671 // we don't want to undo this promotion.
6672 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
6673 // on scalars.
6674 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
6675 Level <= AfterLegalizeTypes) {
6676 // Input types must be integer and the same.
6677 if (XVT.isInteger() && XVT == Y.getValueType() &&
6678 !(VT.isVector() && TLI.isTypeLegal(VT) &&
6679 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
6680 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6681 return DAG.getNode(HandOpcode, DL, VT, Logic);
6682 }
6683 }
6684
6685 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
6686 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
6687 // If both shuffles use the same mask, and both shuffle within a single
6688 // vector, then it is worthwhile to move the swizzle after the operation.
6689 // The type-legalizer generates this pattern when loading illegal
6690 // vector types from memory. In many cases this allows additional shuffle
6691 // optimizations.
6692 // There are other cases where moving the shuffle after the xor/and/or
6693 // is profitable even if shuffles don't perform a swizzle.
6694 // If both shuffles use the same mask, and both shuffles have the same first
6695 // or second operand, then it might still be profitable to move the shuffle
6696 // after the xor/and/or operation.
6697 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
6698 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
6699 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
6700 assert(X.getValueType() == Y.getValueType() &&
6701 "Inputs to shuffles are not the same type");
6702
6703 // Check that both shuffles use the same mask. The masks are known to be of
6704 // the same length because the result vector type is the same.
6705 // Check also that shuffles have only one use to avoid introducing extra
6706 // instructions.
6707 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
6708 !SVN0->getMask().equals(SVN1->getMask()))
6709 return SDValue();
6710
6711 // Don't try to fold this node if it requires introducing a
6712 // build vector of all zeros that might be illegal at this stage.
6713 SDValue ShOp = N0.getOperand(1);
6714 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6715 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6716
6717 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
6718 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
6719 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
6720 N0.getOperand(0), N1.getOperand(0));
6721 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
6722 }
6723
6724 // Don't try to fold this node if it requires introducing a
6725 // build vector of all zeros that might be illegal at this stage.
6726 ShOp = N0.getOperand(0);
6727 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6728 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6729
6730 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
6731 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
6732 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
6733 N1.getOperand(1));
6734 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
6735 }
6736 }
6737
6738 return SDValue();
6739}
6740
6741/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
6742SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
6743 const SDLoc &DL) {
6744 SDValue LL, LR, RL, RR, N0CC, N1CC;
6745 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
6746 !isSetCCEquivalent(N1, RL, RR, N1CC))
6747 return SDValue();
6748
6749 assert(N0.getValueType() == N1.getValueType() &&
6750 "Unexpected operand types for bitwise logic op");
6751 assert(LL.getValueType() == LR.getValueType() &&
6752 RL.getValueType() == RR.getValueType() &&
6753 "Unexpected operand types for setcc");
6754
6755 // If we're here post-legalization or the logic op type is not i1, the logic
6756 // op type must match a setcc result type. Also, all folds require new
6757 // operations on the left and right operands, so those types must match.
6758 EVT VT = N0.getValueType();
6759 EVT OpVT = LL.getValueType();
6760 if (LegalOperations || VT.getScalarType() != MVT::i1)
6761 if (VT != getSetCCResultType(OpVT))
6762 return SDValue();
6763 if (OpVT != RL.getValueType())
6764 return SDValue();
6765
6766 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
6767 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
6768 bool IsInteger = OpVT.isInteger();
6769 if (LR == RR && CC0 == CC1 && IsInteger) {
6770 bool IsZero = isNullOrNullSplat(LR);
6771 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
6772
6773 // All bits clear?
6774 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
6775 // All sign bits clear?
6776 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
6777 // Any bits set?
6778 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
6779 // Any sign bits set?
6780 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
6781
6782 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
6783 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
6784 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
6785 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
6786 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
6787 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
6788 AddToWorklist(Or.getNode());
6789 return DAG.getSetCC(DL, VT, Or, LR, CC1);
6790 }
6791
6792 // All bits set?
6793 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
6794 // All sign bits set?
6795 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
6796 // Any bits clear?
6797 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
6798 // Any sign bits clear?
6799 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
6800
6801 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
6802 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
6803 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
6804 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
6805 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
6806 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
6807 AddToWorklist(And.getNode());
6808 return DAG.getSetCC(DL, VT, And, LR, CC1);
6809 }
6810 }
6811
6812 // (and (setne (and X, LL1), 0), (setne (and X, RL1), 0))
6813 // --> (seteq (and X, (LL1|RL1)), (LL1|RL1))
6814 // (or (seteq (and X, LL1), 0), (seteq (and X, RL1), 0))
6815 // --> (setne (and X, (LL1|RL1)), (LL1|RL1))
6816 if (LL.getOpcode() == ISD::AND && RL.getOpcode() == ISD::AND &&
6817 isNullConstant(LR) && isNullConstant(RR) && CC0 == CC1 &&
6818 (CC0 == ISD::SETNE || CC0 == ISD::SETEQ)) {
6819 SDValue LL0, LL1, RL0, RL1;
6820 LL0 = LL.getOperand(0);
6821 RL0 = RL.getOperand(0);
6822 LL1 = LL.getOperand(1);
6823 RL1 = RL.getOperand(1);
6824 if (LL0 == RL0 && DAG.isKnownToBeAPowerOfTwo(LL1) &&
6825 DAG.isKnownToBeAPowerOfTwo(RL1)) {
6826 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL1, RL1);
6827 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL0, Or);
6828 return DAG.getSetCC(DL, VT, And, Or, IsAnd ? ISD::SETEQ : ISD::SETNE);
6829 }
6830 }
6831
6832 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
6833 // (or (seteq X, 0), (seteq X, -1)) --> (setult (add X, 1), 2)
6834 if (LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && IsInteger &&
6835 ((IsAnd && CC0 == ISD::SETNE) || (!IsAnd && CC0 == ISD::SETEQ)) &&
6836 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
6837 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
6838 SDValue One = DAG.getConstant(1, DL, OpVT);
6839 SDValue Two = DAG.getConstant(2, DL, OpVT);
6840 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
6841 AddToWorklist(Add.getNode());
6842 return DAG.getSetCC(DL, VT, Add, Two, IsAnd ? ISD::SETUGE : ISD::SETULT);
6843 }
6844
6845 // Try more general transforms if the predicates match and the only user of
6846 // the compares is the 'and' or 'or'.
6847 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
6848 N0.hasOneUse() && N1.hasOneUse()) {
6849 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
6850 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
6851 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
6852 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
6853 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
6854 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
6855 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6856 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
6857 }
6858
6859 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
6860 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
6861 // Match a shared variable operand and 2 non-opaque constant operands.
6862 auto MatchDiffPow2 = [&](ConstantSDNode *C0, ConstantSDNode *C1) {
6863 // The difference of the constants must be a single bit.
6864 const APInt &CMax =
6865 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
6866 const APInt &CMin =
6867 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
6868 return !C0->isOpaque() && !C1->isOpaque() && (CMax - CMin).isPowerOf2();
6869 };
6870 if (LL == RL && ISD::matchBinaryPredicate(LR, RR, MatchDiffPow2)) {
6871 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
6872 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
6873 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
6874 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
6875 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
6876 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
6877 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
6878 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
6879 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6880 return DAG.getSetCC(DL, VT, And, Zero, CC0);
6881 }
6882 }
6883 }
6884
6885 // Canonicalize equivalent operands to LL == RL.
6886 if (LL == RR && LR == RL) {
6888 std::swap(RL, RR);
6889 }
6890
6891 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6892 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6893 if (LL == RL && LR == RR) {
6894 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
6895 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
6896 if (NewCC != ISD::SETCC_INVALID &&
6897 (!LegalOperations ||
6898 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
6899 TLI.isOperationLegal(ISD::SETCC, OpVT))))
6900 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
6901 }
6902
6903 return SDValue();
6904}
6905
6906static bool arebothOperandsNotSNan(SDValue Operand1, SDValue Operand2,
6907 SelectionDAG &DAG) {
6908 return DAG.isKnownNeverSNaN(Operand2) && DAG.isKnownNeverSNaN(Operand1);
6909}
6910
6911static bool arebothOperandsNotNan(SDValue Operand1, SDValue Operand2,
6912 SelectionDAG &DAG) {
6913 return DAG.isKnownNeverNaN(Operand2) && DAG.isKnownNeverNaN(Operand1);
6914}
6915
6916/// Returns an appropriate FP min/max opcode for clamping operations.
6917static unsigned getMinMaxOpcodeForClamp(bool IsMin, SDValue Operand1,
6918 SDValue Operand2, SelectionDAG &DAG,
6919 const TargetLowering &TLI) {
6920 EVT VT = Operand1.getValueType();
6921 unsigned IEEEOp = IsMin ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6922 if (TLI.isOperationLegalOrCustom(IEEEOp, VT) &&
6923 arebothOperandsNotNan(Operand1, Operand2, DAG))
6924 return IEEEOp;
6925 unsigned PreferredOp = IsMin ? ISD::FMINNUM : ISD::FMAXNUM;
6926 if (TLI.isOperationLegalOrCustom(PreferredOp, VT))
6927 return PreferredOp;
6928 return ISD::DELETED_NODE;
6929}
6930
6931// FIXME: use FMINIMUMNUM if possible, such as for RISC-V.
6933 SDValue Operand1, SDValue Operand2, bool SetCCNoNaNs, ISD::CondCode CC,
6934 unsigned OrAndOpcode, SelectionDAG &DAG, bool isFMAXNUMFMINNUM_IEEE,
6935 bool isFMAXNUMFMINNUM) {
6936 // The optimization cannot be applied for all the predicates because
6937 // of the way FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle
6938 // NaNs. For FMINNUM_IEEE/FMAXNUM_IEEE, the optimization cannot be
6939 // applied at all if one of the operands is a signaling NaN.
6940
6941 // It is safe to use FMINNUM_IEEE/FMAXNUM_IEEE if all the operands
6942 // are non NaN values.
6943 if (((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::OR)) ||
6944 ((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::AND))) {
6945 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6946 isFMAXNUMFMINNUM_IEEE
6949 }
6950
6951 if (((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::OR)) ||
6952 ((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::AND))) {
6953 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6954 isFMAXNUMFMINNUM_IEEE
6957 }
6958
6959 // Both FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle quiet
6960 // NaNs in the same way. But, FMINNUM/FMAXNUM and FMINNUM_IEEE/
6961 // FMAXNUM_IEEE handle signaling NaNs differently. If we cannot prove
6962 // that there are not any sNaNs, then the optimization is not valid
6963 // for FMINNUM_IEEE/FMAXNUM_IEEE. In the presence of sNaNs, we apply
6964 // the optimization using FMINNUM/FMAXNUM for the following cases. If
6965 // we can prove that we do not have any sNaNs, then we can do the
6966 // optimization using FMINNUM_IEEE/FMAXNUM_IEEE for the following
6967 // cases.
6968 if (((CC == ISD::SETOLT || CC == ISD::SETOLE) && (OrAndOpcode == ISD::OR)) ||
6969 ((CC == ISD::SETUGT || CC == ISD::SETUGE) && (OrAndOpcode == ISD::AND))) {
6970 return isFMAXNUMFMINNUM ? ISD::FMINNUM
6971 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6972 isFMAXNUMFMINNUM_IEEE
6975 }
6976
6977 if (((CC == ISD::SETOGT || CC == ISD::SETOGE) && (OrAndOpcode == ISD::OR)) ||
6978 ((CC == ISD::SETULT || CC == ISD::SETULE) && (OrAndOpcode == ISD::AND))) {
6979 return isFMAXNUMFMINNUM ? ISD::FMAXNUM
6980 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6981 isFMAXNUMFMINNUM_IEEE
6984 }
6985
6986 return ISD::DELETED_NODE;
6987}
6988
6991 assert(
6992 (LogicOp->getOpcode() == ISD::AND || LogicOp->getOpcode() == ISD::OR) &&
6993 "Invalid Op to combine SETCC with");
6994
6995 // TODO: Search past casts/truncates.
6996 SDValue LHS = LogicOp->getOperand(0);
6997 SDValue RHS = LogicOp->getOperand(1);
6998 if (LHS->getOpcode() != ISD::SETCC || RHS->getOpcode() != ISD::SETCC ||
6999 !LHS->hasOneUse() || !RHS->hasOneUse())
7000 return SDValue();
7001
7002 SDNodeFlags LHSSetCCFlags = LHS->getFlags();
7003 SDNodeFlags RHSSetCCFlags = RHS->getFlags();
7004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7006 LogicOp, LHS.getNode(), RHS.getNode());
7007
7008 SDValue LHS0 = LHS->getOperand(0);
7009 SDValue RHS0 = RHS->getOperand(0);
7010 SDValue LHS1 = LHS->getOperand(1);
7011 SDValue RHS1 = RHS->getOperand(1);
7012 // TODO: We don't actually need a splat here, for vectors we just need the
7013 // invariants to hold for each element.
7014 auto *LHS1C = isConstOrConstSplat(LHS1);
7015 auto *RHS1C = isConstOrConstSplat(RHS1);
7016 ISD::CondCode CCL = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7017 ISD::CondCode CCR = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7018 EVT VT = LogicOp->getValueType(0);
7019 EVT OpVT = LHS0.getValueType();
7020 SDLoc DL(LogicOp);
7021
7022 // Check if the operands of an and/or operation are comparisons and if they
7023 // compare against the same value. Replace the and/or-cmp-cmp sequence with
7024 // min/max cmp sequence. If LHS1 is equal to RHS1, then the or-cmp-cmp
7025 // sequence will be replaced with min-cmp sequence:
7026 // (LHS0 < LHS1) | (RHS0 < RHS1) -> min(LHS0, RHS0) < LHS1
7027 // and and-cmp-cmp will be replaced with max-cmp sequence:
7028 // (LHS0 < LHS1) & (RHS0 < RHS1) -> max(LHS0, RHS0) < LHS1
7029 // The optimization does not work for `==` or `!=` .
7030 // The two comparisons should have either the same predicate or the
7031 // predicate of one of the comparisons is the opposite of the other one.
7032 bool isFMAXNUMFMINNUM_IEEE = TLI.isOperationLegal(ISD::FMAXNUM_IEEE, OpVT) &&
7034 bool isFMAXNUMFMINNUM = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, OpVT) &&
7036 if (((OpVT.isInteger() && TLI.isOperationLegal(ISD::UMAX, OpVT) &&
7037 TLI.isOperationLegal(ISD::SMAX, OpVT) &&
7038 TLI.isOperationLegal(ISD::UMIN, OpVT) &&
7039 TLI.isOperationLegal(ISD::SMIN, OpVT)) ||
7040 (OpVT.isFloatingPoint() &&
7041 (isFMAXNUMFMINNUM_IEEE || isFMAXNUMFMINNUM))) &&
7043 CCL != ISD::SETFALSE && CCL != ISD::SETO && CCL != ISD::SETUO &&
7044 CCL != ISD::SETTRUE &&
7045 (CCL == CCR || CCL == ISD::getSetCCSwappedOperands(CCR))) {
7046
7047 SDValue CommonValue, Operand1, Operand2;
7049 if (CCL == CCR) {
7050 if (LHS0 == RHS0) {
7051 CommonValue = LHS0;
7052 Operand1 = LHS1;
7053 Operand2 = RHS1;
7055 } else if (LHS1 == RHS1) {
7056 CommonValue = LHS1;
7057 Operand1 = LHS0;
7058 Operand2 = RHS0;
7059 CC = CCL;
7060 }
7061 } else {
7062 assert(CCL == ISD::getSetCCSwappedOperands(CCR) && "Unexpected CC");
7063 if (LHS0 == RHS1) {
7064 CommonValue = LHS0;
7065 Operand1 = LHS1;
7066 Operand2 = RHS0;
7067 CC = CCR;
7068 } else if (RHS0 == LHS1) {
7069 CommonValue = LHS1;
7070 Operand1 = LHS0;
7071 Operand2 = RHS1;
7072 CC = CCL;
7073 }
7074 }
7075
7076 // Don't do this transform for sign bit tests. Let foldLogicOfSetCCs
7077 // handle it using OR/AND.
7078 if (CC == ISD::SETLT && isNullOrNullSplat(CommonValue))
7079 CC = ISD::SETCC_INVALID;
7080 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CommonValue))
7081 CC = ISD::SETCC_INVALID;
7082
7083 if (CC != ISD::SETCC_INVALID) {
7084 unsigned NewOpcode = ISD::DELETED_NODE;
7085 bool IsSigned = isSignedIntSetCC(CC);
7086 if (OpVT.isInteger()) {
7087 bool IsLess = (CC == ISD::SETLE || CC == ISD::SETULE ||
7088 CC == ISD::SETLT || CC == ISD::SETULT);
7089 bool IsOr = (LogicOp->getOpcode() == ISD::OR);
7090 if (IsLess == IsOr)
7091 NewOpcode = IsSigned ? ISD::SMIN : ISD::UMIN;
7092 else
7093 NewOpcode = IsSigned ? ISD::SMAX : ISD::UMAX;
7094 } else if (OpVT.isFloatingPoint())
7096 Operand1, Operand2,
7097 LHSSetCCFlags.hasNoNaNs() && RHSSetCCFlags.hasNoNaNs(), CC,
7098 LogicOp->getOpcode(), DAG, isFMAXNUMFMINNUM_IEEE, isFMAXNUMFMINNUM);
7099
7100 if (NewOpcode != ISD::DELETED_NODE) {
7101 // Propagate fast-math flags from setcc.
7102 SDNodeFlags Flags = LHS->getFlags() & RHS->getFlags();
7103 SDValue MinMaxValue =
7104 DAG.getNode(NewOpcode, DL, OpVT, Operand1, Operand2, Flags);
7105 return DAG.getSetCC(DL, VT, MinMaxValue, CommonValue, CC, /*Chain=*/{},
7106 /*IsSignaling=*/false, Flags);
7107 }
7108 }
7109 }
7110
7111 if (LHS0 == LHS1 && RHS0 == RHS1 && CCL == CCR &&
7112 LHS0.getValueType() == RHS0.getValueType() &&
7113 ((LogicOp->getOpcode() == ISD::AND && CCL == ISD::SETO) ||
7114 (LogicOp->getOpcode() == ISD::OR && CCL == ISD::SETUO)))
7115 return DAG.getSetCC(DL, VT, LHS0, RHS0, CCL);
7116
7117 if (TargetPreference == AndOrSETCCFoldKind::None)
7118 return SDValue();
7119
7120 if (CCL == CCR &&
7121 CCL == (LogicOp->getOpcode() == ISD::AND ? ISD::SETNE : ISD::SETEQ) &&
7122 LHS0 == RHS0 && LHS1C && RHS1C && OpVT.isInteger()) {
7123 const APInt &APLhs = LHS1C->getAPIntValue();
7124 const APInt &APRhs = RHS1C->getAPIntValue();
7125
7126 // Preference is to use ISD::ABS or we already have an ISD::ABS (in which
7127 // case this is just a compare).
7128 if (APLhs == (-APRhs) &&
7129 ((TargetPreference & AndOrSETCCFoldKind::ABS) ||
7130 DAG.doesNodeExist(ISD::ABS, DAG.getVTList(OpVT), {LHS0}))) {
7131 const APInt &C = APLhs.isNegative() ? APRhs : APLhs;
7132 // (icmp eq A, C) | (icmp eq A, -C)
7133 // -> (icmp eq Abs(A), C)
7134 // (icmp ne A, C) & (icmp ne A, -C)
7135 // -> (icmp ne Abs(A), C)
7136 SDValue AbsOp = DAG.getNode(ISD::ABS, DL, OpVT, LHS0);
7137 return DAG.getNode(ISD::SETCC, DL, VT, AbsOp,
7138 DAG.getConstant(C, DL, OpVT), LHS.getOperand(2));
7139 } else if (TargetPreference &
7141
7142 // AndOrSETCCFoldKind::AddAnd:
7143 // A == C0 | A == C1
7144 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7145 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) == 0
7146 // A != C0 & A != C1
7147 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7148 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) != 0
7149
7150 // AndOrSETCCFoldKind::NotAnd:
7151 // A == C0 | A == C1
7152 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7153 // -> ~A & smin(C0, C1) == 0
7154 // A != C0 & A != C1
7155 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7156 // -> ~A & smin(C0, C1) != 0
7157
7158 const APInt &MaxC = APIntOps::smax(APRhs, APLhs);
7159 const APInt &MinC = APIntOps::smin(APRhs, APLhs);
7160 APInt Dif = MaxC - MinC;
7161 if (!Dif.isZero() && Dif.isPowerOf2()) {
7162 if (MaxC.isAllOnes() &&
7163 (TargetPreference & AndOrSETCCFoldKind::NotAnd)) {
7164 SDValue NotOp = DAG.getNOT(DL, LHS0, OpVT);
7165 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, NotOp,
7166 DAG.getConstant(MinC, DL, OpVT));
7167 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7168 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7169 } else if (TargetPreference & AndOrSETCCFoldKind::AddAnd) {
7170
7171 SDValue AddOp = DAG.getNode(ISD::ADD, DL, OpVT, LHS0,
7172 DAG.getConstant(-MinC, DL, OpVT));
7173 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, AddOp,
7174 DAG.getConstant(~Dif, DL, OpVT));
7175 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7176 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7177 }
7178 }
7179 }
7180 }
7181
7182 return SDValue();
7183}
7184
7185// Combine `(select c, (X & 1), 0)` -> `(and (zext c), X)`.
7186// We canonicalize to the `select` form in the middle end, but the `and` form
7187// gets better codegen and all tested targets (arm, x86, riscv)
7189 const SDLoc &DL, SelectionDAG &DAG) {
7190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7191 if (!isNullConstant(F))
7192 return SDValue();
7193
7194 EVT CondVT = Cond.getValueType();
7195 if (TLI.getBooleanContents(CondVT) !=
7197 return SDValue();
7198
7199 if (T.getOpcode() != ISD::AND)
7200 return SDValue();
7201
7202 if (!isOneConstant(T.getOperand(1)))
7203 return SDValue();
7204
7205 EVT OpVT = T.getValueType();
7206
7207 SDValue CondMask =
7208 OpVT == CondVT ? Cond : DAG.getBoolExtOrTrunc(Cond, DL, OpVT, CondVT);
7209 return DAG.getNode(ISD::AND, DL, OpVT, CondMask, T.getOperand(0));
7210}
7211
7212/// This contains all DAGCombine rules which reduce two values combined by
7213/// an And operation to a single value. This makes them reusable in the context
7214/// of visitSELECT(). Rules involving constants are not included as
7215/// visitSELECT() already handles those cases.
7216SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
7217 EVT VT = N1.getValueType();
7218 SDLoc DL(N);
7219
7220 // fold (and x, undef) -> 0
7221 if (N0.isUndef() || N1.isUndef())
7222 return DAG.getConstant(0, DL, VT);
7223
7224 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
7225 return V;
7226
7227 // Canonicalize:
7228 // and(x, add) -> and(add, x)
7229 if (N1.getOpcode() == ISD::ADD)
7230 std::swap(N0, N1);
7231
7232 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
7233 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
7234 VT.isScalarInteger() && VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
7235 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7236 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
7237 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
7238 // immediate for an add, but it is legal if its top c2 bits are set,
7239 // transform the ADD so the immediate doesn't need to be materialized
7240 // in a register.
7241 APInt ADDC = ADDI->getAPIntValue();
7242 APInt SRLC = SRLI->getAPIntValue();
7243 if (ADDC.getSignificantBits() <= 64 && SRLC.ult(VT.getSizeInBits()) &&
7244 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7246 SRLC.getZExtValue());
7247 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
7248 ADDC |= Mask;
7249 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7250 SDLoc DL0(N0);
7251 SDValue NewAdd =
7252 DAG.getNode(ISD::ADD, DL0, VT,
7253 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
7254 CombineTo(N0.getNode(), NewAdd);
7255 // Return N so it doesn't get rechecked!
7256 return SDValue(N, 0);
7257 }
7258 }
7259 }
7260 }
7261 }
7262 }
7263
7264 return SDValue();
7265}
7266
7267bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
7268 EVT LoadResultTy, EVT &ExtVT) {
7269 if (!AndC->getAPIntValue().isMask())
7270 return false;
7271
7272 unsigned ActiveBits = AndC->getAPIntValue().countr_one();
7273
7274 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7275 EVT LoadedVT = LoadN->getMemoryVT();
7276
7277 if (ExtVT == LoadedVT &&
7278 (!LegalOperations ||
7279 TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7280 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))) {
7281 // ZEXTLOAD will match without needing to change the size of the value being
7282 // loaded.
7283 return true;
7284 }
7285
7286 // Do not change the width of a volatile or atomic loads.
7287 if (!LoadN->isSimple())
7288 return false;
7289
7290 // Do not generate loads of non-round integer types since these can
7291 // be expensive (and would be wrong if the type is not byte sized).
7292 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
7293 return false;
7294
7295 if (LegalOperations &&
7296 !TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7297 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))
7298 return false;
7299
7300 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT, /*ByteOffset=*/0))
7301 return false;
7302
7303 return true;
7304}
7305
7306bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
7307 ISD::LoadExtType ExtType, EVT &MemVT,
7308 unsigned ShAmt) {
7309 if (!LDST)
7310 return false;
7311
7312 // Only allow byte offsets.
7313 if (ShAmt % 8)
7314 return false;
7315 const unsigned ByteShAmt = ShAmt / 8;
7316
7317 // Do not generate loads of non-round integer types since these can
7318 // be expensive (and would be wrong if the type is not byte sized).
7319 if (!MemVT.isRound())
7320 return false;
7321
7322 // Don't change the width of a volatile or atomic loads.
7323 if (!LDST->isSimple())
7324 return false;
7325
7326 EVT LdStMemVT = LDST->getMemoryVT();
7327
7328 // Bail out when changing the scalable property, since we can't be sure that
7329 // we're actually narrowing here.
7330 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
7331 return false;
7332
7333 // Verify that we are actually reducing a load width here.
7334 if (LdStMemVT.bitsLT(MemVT))
7335 return false;
7336
7337 // Ensure that this isn't going to produce an unsupported memory access.
7338 if (ShAmt) {
7339 const Align LDSTAlign = LDST->getAlign();
7340 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
7341 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7342 LDST->getAddressSpace(), NarrowAlign,
7343 LDST->getMemOperand()->getFlags()))
7344 return false;
7345 }
7346
7347 // It's not possible to generate a constant of extended or untyped type.
7348 EVT PtrType = LDST->getBasePtr().getValueType();
7349 if (PtrType == MVT::Untyped || PtrType.isExtended())
7350 return false;
7351
7352 if (isa<LoadSDNode>(LDST)) {
7353 LoadSDNode *Load = cast<LoadSDNode>(LDST);
7354 // Don't transform one with multiple uses, this would require adding a new
7355 // load.
7356 if (!SDValue(Load, 0).hasOneUse())
7357 return false;
7358
7359 if (LegalOperations &&
7360 !TLI.isLoadLegal(Load->getValueType(0), MemVT, Load->getAlign(),
7361 Load->getAddressSpace(), ExtType, false))
7362 return false;
7363
7364 // For the transform to be legal, the load must produce only two values
7365 // (the value loaded and the chain). Don't transform a pre-increment
7366 // load, for example, which produces an extra value. Otherwise the
7367 // transformation is not equivalent, and the downstream logic to replace
7368 // uses gets things wrong.
7369 if (Load->getNumValues() > 2)
7370 return false;
7371
7372 // If the load that we're shrinking is an extload and we're not just
7373 // discarding the extension we can't simply shrink the load. Bail.
7374 // TODO: It would be possible to merge the extensions in some cases.
7375 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
7376 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7377 return false;
7378
7379 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT, ByteShAmt))
7380 return false;
7381 } else {
7382 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
7383 StoreSDNode *Store = cast<StoreSDNode>(LDST);
7384 // Can't write outside the original store
7385 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7386 return false;
7387
7388 if (LegalOperations &&
7389 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT,
7390 Store->getAlign(), Store->getAddressSpace()))
7391 return false;
7392 }
7393 return true;
7394}
7395
7396bool DAGCombiner::SearchForAndLoads(SDNode *N,
7397 SmallVectorImpl<LoadSDNode*> &Loads,
7398 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
7399 ConstantSDNode *Mask,
7400 SDNode *&NodeToMask) {
7401 // Recursively search for the operands, looking for loads which can be
7402 // narrowed.
7403 for (SDValue Op : N->op_values()) {
7404 if (Op.getValueType().isVector())
7405 return false;
7406
7407 // Some constants may need fixing up later if they are too large.
7408 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7409 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
7410 "Expected bitwise logic operation");
7411 if (!C->getAPIntValue().isSubsetOf(Mask->getAPIntValue()))
7412 NodesWithConsts.insert(N);
7413 continue;
7414 }
7415
7416 if (!Op.hasOneUse())
7417 return false;
7418
7419 switch(Op.getOpcode()) {
7420 case ISD::LOAD: {
7421 auto *Load = cast<LoadSDNode>(Op);
7422 EVT ExtVT;
7423 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
7424 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
7425
7426 // ZEXTLOAD is already small enough.
7427 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
7428 ExtVT.bitsGE(Load->getMemoryVT()))
7429 continue;
7430
7431 // Use LE to convert equal sized loads to zext.
7432 if (ExtVT.bitsLE(Load->getMemoryVT()))
7433 Loads.push_back(Load);
7434
7435 continue;
7436 }
7437 return false;
7438 }
7439 case ISD::ZERO_EXTEND:
7440 case ISD::AssertZext: {
7441 unsigned ActiveBits = Mask->getAPIntValue().countr_one();
7442 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7443 EVT VT = Op.getOpcode() == ISD::AssertZext ?
7444 cast<VTSDNode>(Op.getOperand(1))->getVT() :
7445 Op.getOperand(0).getValueType();
7446
7447 // We can accept extending nodes if the mask is wider or an equal
7448 // width to the original type.
7449 if (ExtVT.bitsGE(VT))
7450 continue;
7451 break;
7452 }
7453 case ISD::OR:
7454 case ISD::XOR:
7455 case ISD::AND:
7456 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
7457 NodeToMask))
7458 return false;
7459 continue;
7460 }
7461
7462 // Allow one node which will masked along with any loads found.
7463 if (NodeToMask)
7464 return false;
7465
7466 // Also ensure that the node to be masked only produces one data result.
7467 NodeToMask = Op.getNode();
7468 if (NodeToMask->getNumValues() > 1) {
7469 bool HasValue = false;
7470 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
7471 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
7472 if (VT != MVT::Glue && VT != MVT::Other) {
7473 if (HasValue) {
7474 NodeToMask = nullptr;
7475 return false;
7476 }
7477 HasValue = true;
7478 }
7479 }
7480 assert(HasValue && "Node to be masked has no data result?");
7481 }
7482 }
7483 return true;
7484}
7485
7486bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
7487 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
7488 if (!Mask)
7489 return false;
7490
7491 if (!Mask->getAPIntValue().isMask())
7492 return false;
7493
7494 // No need to do anything if the and directly uses a load.
7495 if (isa<LoadSDNode>(N->getOperand(0)))
7496 return false;
7497
7499 SmallPtrSet<SDNode*, 2> NodesWithConsts;
7500 SDNode *FixupNode = nullptr;
7501 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
7502 if (Loads.empty())
7503 return false;
7504
7505 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
7506 SDValue MaskOp = N->getOperand(1);
7507
7508 // If it exists, fixup the single node we allow in the tree that needs
7509 // masking.
7510 if (FixupNode) {
7511 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
7512 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
7513 FixupNode->getValueType(0),
7514 SDValue(FixupNode, 0), MaskOp);
7515 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
7516 if (And.getOpcode() == ISD ::AND)
7517 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
7518 }
7519
7520 // Narrow any constants that need it.
7521 for (auto *LogicN : NodesWithConsts) {
7522 SDValue Op0 = LogicN->getOperand(0);
7523 SDValue Op1 = LogicN->getOperand(1);
7524
7525 // We only need to fix AND if both inputs are constants. And we only need
7526 // to fix one of the constants.
7527 if (LogicN->getOpcode() == ISD::AND &&
7529 continue;
7530
7531 if (isa<ConstantSDNode>(Op0) && LogicN->getOpcode() != ISD::AND)
7532 Op0 =
7533 DAG.getNode(ISD::AND, SDLoc(Op0), Op0.getValueType(), Op0, MaskOp);
7534
7535 if (isa<ConstantSDNode>(Op1))
7536 Op1 =
7537 DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), Op1, MaskOp);
7538
7539 if (isa<ConstantSDNode>(Op0) && !isa<ConstantSDNode>(Op1))
7540 std::swap(Op0, Op1);
7541
7542 DAG.UpdateNodeOperands(LogicN, Op0, Op1);
7543 }
7544
7545 // Create narrow loads.
7546 for (auto *Load : Loads) {
7547 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
7548 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
7549 SDValue(Load, 0), MaskOp);
7551 if (And.getOpcode() == ISD ::AND)
7552 And = SDValue(
7553 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
7554 SDValue NewLoad = reduceLoadWidth(And.getNode());
7555 assert(NewLoad &&
7556 "Shouldn't be masking the load if it can't be narrowed");
7557 CombineTo(Load, NewLoad, NewLoad.getValue(1));
7558 }
7559 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
7560 return true;
7561 }
7562 return false;
7563}
7564
7565// Unfold
7566// x & (-1 'logical shift' y)
7567// To
7568// (x 'opposite logical shift' y) 'logical shift' y
7569// if it is better for performance.
7570SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
7571 assert(N->getOpcode() == ISD::AND);
7572
7573 SDValue N0 = N->getOperand(0);
7574 SDValue N1 = N->getOperand(1);
7575
7576 // Do we actually prefer shifts over mask?
7578 return SDValue();
7579
7580 // Try to match (-1 '[outer] logical shift' y)
7581 unsigned OuterShift;
7582 unsigned InnerShift; // The opposite direction to the OuterShift.
7583 SDValue Y; // Shift amount.
7584 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
7585 if (!M.hasOneUse())
7586 return false;
7587 OuterShift = M->getOpcode();
7588 if (OuterShift == ISD::SHL)
7589 InnerShift = ISD::SRL;
7590 else if (OuterShift == ISD::SRL)
7591 InnerShift = ISD::SHL;
7592 else
7593 return false;
7594 if (!isAllOnesConstant(M->getOperand(0)))
7595 return false;
7596 Y = M->getOperand(1);
7597 return true;
7598 };
7599
7600 SDValue X;
7601 if (matchMask(N1))
7602 X = N0;
7603 else if (matchMask(N0))
7604 X = N1;
7605 else
7606 return SDValue();
7607
7608 SDLoc DL(N);
7609 EVT VT = N->getValueType(0);
7610
7611 // tmp = x 'opposite logical shift' y
7612 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
7613 // ret = tmp 'logical shift' y
7614 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
7615
7616 return T1;
7617}
7618
7619/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
7620/// For a target with a bit test, this is expected to become test + set and save
7621/// at least 1 instruction.
7623 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
7624
7625 // Look through an optional extension.
7626 SDValue And0 = And->getOperand(0), And1 = And->getOperand(1);
7627 if (And0.getOpcode() == ISD::ANY_EXTEND && And0.hasOneUse())
7628 And0 = And0.getOperand(0);
7629 if (!isOneConstant(And1) || !And0.hasOneUse())
7630 return SDValue();
7631
7632 SDValue Src = And0;
7633
7634 // Attempt to find a 'not' op.
7635 // TODO: Should we favor test+set even without the 'not' op?
7636 bool FoundNot = false;
7637 if (isBitwiseNot(Src)) {
7638 FoundNot = true;
7639 Src = Src.getOperand(0);
7640
7641 // Look though an optional truncation. The source operand may not be the
7642 // same type as the original 'and', but that is ok because we are masking
7643 // off everything but the low bit.
7644 if (Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse())
7645 Src = Src.getOperand(0);
7646 }
7647
7648 // Match a shift-right by constant.
7649 if (Src.getOpcode() != ISD::SRL || !Src.hasOneUse())
7650 return SDValue();
7651
7652 // This is probably not worthwhile without a supported type.
7653 EVT SrcVT = Src.getValueType();
7654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7655 if (!TLI.isTypeLegal(SrcVT))
7656 return SDValue();
7657
7658 // We might have looked through casts that make this transform invalid.
7659 unsigned BitWidth = SrcVT.getScalarSizeInBits();
7660 SDValue ShiftAmt = Src.getOperand(1);
7661 auto *ShiftAmtC = dyn_cast<ConstantSDNode>(ShiftAmt);
7662 if (!ShiftAmtC || !ShiftAmtC->getAPIntValue().ult(BitWidth))
7663 return SDValue();
7664
7665 // Set source to shift source.
7666 Src = Src.getOperand(0);
7667
7668 // Try again to find a 'not' op.
7669 // TODO: Should we favor test+set even with two 'not' ops?
7670 if (!FoundNot) {
7671 if (!isBitwiseNot(Src))
7672 return SDValue();
7673 Src = Src.getOperand(0);
7674 }
7675
7676 if (!TLI.hasBitTest(Src, ShiftAmt))
7677 return SDValue();
7678
7679 // Turn this into a bit-test pattern using mask op + setcc:
7680 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
7681 // and (srl (not X), C)), 1 --> (and X, 1<<C) == 0
7682 SDLoc DL(And);
7683 SDValue X = DAG.getZExtOrTrunc(Src, DL, SrcVT);
7684 EVT CCVT =
7685 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7686 SDValue Mask = DAG.getConstant(
7687 APInt::getOneBitSet(BitWidth, ShiftAmtC->getZExtValue()), DL, SrcVT);
7688 SDValue NewAnd = DAG.getNode(ISD::AND, DL, SrcVT, X, Mask);
7689 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
7690 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
7691 return DAG.getZExtOrTrunc(Setcc, DL, And->getValueType(0));
7692}
7693
7694/// For targets that support usubsat, match a bit-hack form of that operation
7695/// that ends in 'and' and convert it.
7697 EVT VT = N->getValueType(0);
7698 unsigned BitWidth = VT.getScalarSizeInBits();
7699 APInt SignMask = APInt::getSignMask(BitWidth);
7700
7701 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
7702 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
7703 // xor/add with SMIN (signmask) are logically equivalent.
7704 SDValue X;
7705 if (!sd_match(N, m_And(m_OneUse(m_Xor(m_Value(X), m_SpecificInt(SignMask))),
7707 m_SpecificInt(BitWidth - 1))))) &&
7710 m_SpecificInt(BitWidth - 1))))))
7711 return SDValue();
7712
7713 return DAG.getNode(ISD::USUBSAT, DL, VT, X,
7714 DAG.getConstant(SignMask, DL, VT));
7715}
7716
7717/// Given a bitwise logic operation N with a matching bitwise logic operand,
7718/// fold a pattern where 2 of the source operands are identically shifted
7719/// values. For example:
7720/// ((X0 << Y) | Z) | (X1 << Y) --> ((X0 | X1) << Y) | Z
7722 SelectionDAG &DAG) {
7723 unsigned LogicOpcode = N->getOpcode();
7724 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7725 "Expected bitwise logic operation");
7726
7727 if (!LogicOp.hasOneUse() || !ShiftOp.hasOneUse())
7728 return SDValue();
7729
7730 // Match another bitwise logic op and a shift.
7731 unsigned ShiftOpcode = ShiftOp.getOpcode();
7732 if (LogicOp.getOpcode() != LogicOpcode ||
7733 !(ShiftOpcode == ISD::SHL || ShiftOpcode == ISD::SRL ||
7734 ShiftOpcode == ISD::SRA))
7735 return SDValue();
7736
7737 // Match another shift op inside the first logic operand. Handle both commuted
7738 // possibilities.
7739 // LOGIC (LOGIC (SH X0, Y), Z), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7740 // LOGIC (LOGIC Z, (SH X0, Y)), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7741 SDValue X1 = ShiftOp.getOperand(0);
7742 SDValue Y = ShiftOp.getOperand(1);
7743 SDValue X0, Z;
7744 if (LogicOp.getOperand(0).getOpcode() == ShiftOpcode &&
7745 LogicOp.getOperand(0).getOperand(1) == Y) {
7746 X0 = LogicOp.getOperand(0).getOperand(0);
7747 Z = LogicOp.getOperand(1);
7748 } else if (LogicOp.getOperand(1).getOpcode() == ShiftOpcode &&
7749 LogicOp.getOperand(1).getOperand(1) == Y) {
7750 X0 = LogicOp.getOperand(1).getOperand(0);
7751 Z = LogicOp.getOperand(0);
7752 } else {
7753 return SDValue();
7754 }
7755
7756 EVT VT = N->getValueType(0);
7757 SDLoc DL(N);
7758 SDValue LogicX = DAG.getNode(LogicOpcode, DL, VT, X0, X1);
7759 SDValue NewShift = DAG.getNode(ShiftOpcode, DL, VT, LogicX, Y);
7760 return DAG.getNode(LogicOpcode, DL, VT, NewShift, Z);
7761}
7762
7763/// Given a tree of logic operations with shape like
7764/// (LOGIC (LOGIC (X, Y), LOGIC (Z, Y)))
7765/// try to match and fold shift operations with the same shift amount.
7766/// For example:
7767/// LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W) -->
7768/// --> LOGIC (SH (LOGIC X0, X1), Y), (LOGIC Z, W)
7770 SDValue RightHand, SelectionDAG &DAG) {
7771 unsigned LogicOpcode = N->getOpcode();
7772 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7773 "Expected bitwise logic operation");
7774 if (LeftHand.getOpcode() != LogicOpcode ||
7775 RightHand.getOpcode() != LogicOpcode)
7776 return SDValue();
7777 if (!LeftHand.hasOneUse() || !RightHand.hasOneUse())
7778 return SDValue();
7779
7780 // Try to match one of following patterns:
7781 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W)
7782 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC W, (SH X1, Y))
7783 // Note that foldLogicOfShifts will handle commuted versions of the left hand
7784 // itself.
7785 SDValue CombinedShifts, W;
7786 SDValue R0 = RightHand.getOperand(0);
7787 SDValue R1 = RightHand.getOperand(1);
7788 if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R0, DAG)))
7789 W = R1;
7790 else if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R1, DAG)))
7791 W = R0;
7792 else
7793 return SDValue();
7794
7795 EVT VT = N->getValueType(0);
7796 SDLoc DL(N);
7797 return DAG.getNode(LogicOpcode, DL, VT, CombinedShifts, W);
7798}
7799
7800/// Fold "masked merge" expressions like `(m & x) | (~m & y)` and its DeMorgan
7801/// variant `(~m | x) & (m | y)` into the equivalent `((x ^ y) & m) ^ y)`
7802/// pattern. This is typically a better representation for targets without a
7803/// fused "and-not" operation.
7805 const TargetLowering &TLI, const SDLoc &DL) {
7806 // Note that masked-merge variants using XOR or ADD expressions are
7807 // normalized to OR by InstCombine so we only check for OR or AND.
7808 assert((Node->getOpcode() == ISD::OR || Node->getOpcode() == ISD::AND) &&
7809 "Must be called with ISD::OR or ISD::AND node");
7810
7811 // If the target supports and-not, don't fold this.
7812 if (TLI.hasAndNot(SDValue(Node, 0)))
7813 return SDValue();
7814
7815 SDValue M, X, Y;
7816
7817 if (sd_match(Node,
7819 m_OneUse(m_And(m_Deferred(M), m_Value(X))))) ||
7820 sd_match(Node,
7822 m_OneUse(m_Or(m_Deferred(M), m_Value(Y)))))) {
7823 EVT VT = M.getValueType();
7824 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, Y);
7825 SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor, M);
7826 return DAG.getNode(ISD::XOR, DL, VT, And, Y);
7827 }
7828 return SDValue();
7829}
7830
7831SDValue DAGCombiner::visitAND(SDNode *N) {
7832 SDValue N0 = N->getOperand(0);
7833 SDValue N1 = N->getOperand(1);
7834 EVT VT = N1.getValueType();
7835 SDLoc DL(N);
7836
7837 // x & x --> x
7838 if (N0 == N1)
7839 return N0;
7840
7841 // fold (and c1, c2) -> c1&c2
7842 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N0, N1}))
7843 return C;
7844
7845 // canonicalize constant to RHS
7848 return DAG.getNode(ISD::AND, DL, VT, N1, N0);
7849
7850 if (areBitwiseNotOfEachother(N0, N1))
7851 return DAG.getConstant(APInt::getZero(VT.getScalarSizeInBits()), DL, VT);
7852
7853 // fold vector ops
7854 if (VT.isVector()) {
7855 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
7856 return FoldedVOp;
7857
7858 // fold (and x, 0) -> 0, vector edition
7860 // do not return N1, because undef node may exist in N1
7862 N1.getValueType());
7863
7864 // fold (and x, -1) -> x, vector edition
7866 return N0;
7867
7868 // fold (and buildvector(x,0,-1,w), buildvector(0,y,z,w))
7869 // --> buildvector(0,0,z,w)
7870 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
7871 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7872 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
7873 N0.hasOneUse() && N1.hasOneUse() &&
7874 BV0->getOperand(0).getValueType() ==
7875 BV1->getOperand(0).getValueType()) {
7876 SmallVector<SDValue> MergedOps;
7877 unsigned NumElts = VT.getVectorNumElements();
7878 EVT EltVT = BV0->getOperand(0).getValueType();
7879 for (unsigned I = 0; I != NumElts; ++I) {
7880 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
7881 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
7882 if (C0 && C1)
7883 MergedOps.push_back(DAG.getConstant(
7884 C0->getAPIntValue() & C1->getAPIntValue(), DL, EltVT));
7885 else if (C0 && C0->isZero())
7886 MergedOps.push_back(BV0->getOperand(I));
7887 else if (C1 && C1->isZero())
7888 MergedOps.push_back(BV1->getOperand(I));
7889 else if (C0 && C0->isAllOnes())
7890 MergedOps.push_back(BV1->getOperand(I));
7891 else if (C1 && C1->isAllOnes())
7892 MergedOps.push_back(BV0->getOperand(I));
7893 else if (BV0->getOperand(I) == BV1->getOperand(I))
7894 MergedOps.push_back(BV0->getOperand(I));
7895 else
7896 break;
7897 }
7898 if (MergedOps.size() == NumElts)
7899 return DAG.getBuildVector(VT, DL, MergedOps);
7900 }
7901
7902 // fold (and (masked_load) (splat_vec (x, ...))) to zext_masked_load
7903 bool Frozen = N0.getOpcode() == ISD::FREEZE;
7904 auto *MLoad = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0);
7905 ConstantSDNode *Splat = isConstOrConstSplat(N1, true, true);
7906 if (MLoad && MLoad->getExtensionType() == ISD::EXTLOAD && Splat) {
7907 EVT MemVT = MLoad->getMemoryVT();
7908 if (TLI.isLoadLegal(VT, MemVT, MLoad->getAlign(),
7909 MLoad->getAddressSpace(), ISD::ZEXTLOAD, false)) {
7910 // For this AND to be a zero extension of the masked load the elements
7911 // of the BuildVec must mask the bottom bits of the extended element
7912 // type
7913 if (Splat->getAPIntValue().isMask(MemVT.getScalarSizeInBits())) {
7914 SDValue NewLoad = DAG.getMaskedLoad(
7915 VT, DL, MLoad->getChain(), MLoad->getBasePtr(),
7916 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), MemVT,
7917 MLoad->getMemOperand(), MLoad->getAddressingMode(), ISD::ZEXTLOAD,
7918 MLoad->isExpandingLoad());
7919 CombineTo(N, Frozen ? N0 : NewLoad);
7920 CombineTo(MLoad, NewLoad, NewLoad.getValue(1));
7921 return SDValue(N, 0);
7922 }
7923 }
7924 }
7925 }
7926
7927 // fold (and x, -1) -> x
7928 if (isAllOnesConstant(N1))
7929 return N0;
7930
7931 // if (and x, c) is known to be zero, return 0
7932 unsigned BitWidth = VT.getScalarSizeInBits();
7933 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7935 return DAG.getConstant(0, DL, VT);
7936
7937 if (SDValue R = foldAndOrOfSETCC(N, DAG))
7938 return R;
7939
7940 if (SDValue NewSel = foldBinOpIntoSelect(N))
7941 return NewSel;
7942
7943 // reassociate and
7944 if (SDValue RAND = reassociateOps(ISD::AND, DL, N0, N1, N->getFlags()))
7945 return RAND;
7946
7947 // Fold and(vecreduce(x), vecreduce(y)) -> vecreduce(and(x, y))
7948 if (SDValue SD =
7949 reassociateReduction(ISD::VECREDUCE_AND, ISD::AND, DL, VT, N0, N1))
7950 return SD;
7951
7952 // fold (and (or x, C), D) -> D if (C & D) == D
7953 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7954 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
7955 };
7956 if (N0.getOpcode() == ISD::OR &&
7957 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
7958 return N1;
7959
7960 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
7961 SDValue N0Op0 = N0.getOperand(0);
7962 EVT SrcVT = N0Op0.getValueType();
7963 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
7964 APInt Mask = ~N1C->getAPIntValue();
7965 Mask = Mask.trunc(SrcBitWidth);
7966
7967 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
7968 if (DAG.MaskedValueIsZero(N0Op0, Mask))
7969 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0Op0);
7970
7971 // fold (and (any_ext V), c) -> (zero_ext (and V, c)) if profitable, when
7972 // the zext is free or the anyext costs the same as the zext.
7973 if (N1C->getAPIntValue().countLeadingZeros() >= (BitWidth - SrcBitWidth) &&
7974 (TLI.isZExtFree(SrcVT, VT) || !TLI.isAnyExtFree(SrcVT, VT)) &&
7975 TLI.isTypeDesirableForOp(ISD::AND, SrcVT) &&
7976 TLI.isNarrowingProfitable(N, VT, SrcVT))
7977 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT,
7978 DAG.getNode(ISD::AND, DL, SrcVT, N0Op0,
7979 DAG.getZExtOrTrunc(N1, DL, SrcVT)));
7980 }
7981
7982 // fold (and (ext (and V, c1)), c2) -> (and (ext V), (and c1, (ext c2)))
7983 if (ISD::isExtOpcode(N0.getOpcode())) {
7984 unsigned ExtOpc = N0.getOpcode();
7985 SDValue N0Op0 = N0.getOperand(0);
7986 if (N0Op0.getOpcode() == ISD::AND &&
7987 (ExtOpc != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0Op0, VT)) &&
7988 N0->hasOneUse() && N0Op0->hasOneUse()) {
7989 if (SDValue NewExt = DAG.FoldConstantArithmetic(ExtOpc, DL, VT,
7990 {N0Op0.getOperand(1)})) {
7991 if (SDValue NewMask =
7992 DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N1, NewExt})) {
7993 return DAG.getNode(ISD::AND, DL, VT,
7994 DAG.getNode(ExtOpc, DL, VT, N0Op0.getOperand(0)),
7995 NewMask);
7996 }
7997 }
7998 }
7999 }
8000
8001 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
8002 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
8003 // already be zero by virtue of the width of the base type of the load.
8004 //
8005 // the 'X' node here can either be nothing or an extract_vector_elt to catch
8006 // more cases.
8007 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8009 N0.getOperand(0).getOpcode() == ISD::LOAD &&
8010 N0.getOperand(0).getResNo() == 0) ||
8011 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
8012 auto *Load =
8013 cast<LoadSDNode>((N0.getOpcode() == ISD::LOAD) ? N0 : N0.getOperand(0));
8014
8015 // Get the constant (if applicable) the zero'th operand is being ANDed with.
8016 // This can be a pure constant or a vector splat, in which case we treat the
8017 // vector as a scalar and use the splat value.
8018 APInt Constant = APInt::getZero(1);
8019 if (const ConstantSDNode *C = isConstOrConstSplat(
8020 N1, /*AllowUndefs=*/false, /*AllowTruncation=*/true)) {
8021 Constant = C->getAPIntValue();
8022 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
8023 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
8024 APInt SplatValue, SplatUndef;
8025 unsigned SplatBitSize;
8026 bool HasAnyUndefs;
8027 // Endianness should not matter here. Code below makes sure that we only
8028 // use the result if the SplatBitSize is a multiple of the vector element
8029 // size. And after that we AND all element sized parts of the splat
8030 // together. So the end result should be the same regardless of in which
8031 // order we do those operations.
8032 const bool IsBigEndian = false;
8033 bool IsSplat =
8034 Vector->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8035 HasAnyUndefs, EltBitWidth, IsBigEndian);
8036
8037 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
8038 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
8039 if (IsSplat && (SplatBitSize % EltBitWidth) == 0) {
8040 // Undef bits can contribute to a possible optimisation if set, so
8041 // set them.
8042 SplatValue |= SplatUndef;
8043
8044 // The splat value may be something like "0x00FFFFFF", which means 0 for
8045 // the first vector value and FF for the rest, repeating. We need a mask
8046 // that will apply equally to all members of the vector, so AND all the
8047 // lanes of the constant together.
8048 Constant = APInt::getAllOnes(EltBitWidth);
8049 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
8050 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
8051 }
8052 }
8053
8054 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
8055 // actually legal and isn't going to get expanded, else this is a false
8056 // optimisation.
8057 bool CanZextLoadProfitably = TLI.isLoadLegal(
8058 Load->getValueType(0), Load->getMemoryVT(), Load->getAlign(),
8059 Load->getAddressSpace(), ISD::ZEXTLOAD, false);
8060
8061 // Resize the constant to the same size as the original memory access before
8062 // extension. If it is still the AllOnesValue then this AND is completely
8063 // unneeded.
8064 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
8065
8066 bool B;
8067 switch (Load->getExtensionType()) {
8068 default: B = false; break;
8069 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
8070 case ISD::ZEXTLOAD:
8071 case ISD::NON_EXTLOAD: B = true; break;
8072 }
8073
8074 if (B && Constant.isAllOnes()) {
8075 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
8076 // preserve semantics once we get rid of the AND.
8077 SDValue NewLoad(Load, 0);
8078
8079 // Fold the AND away. NewLoad may get replaced immediately.
8080 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
8081
8082 if (Load->getExtensionType() == ISD::EXTLOAD) {
8083 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
8084 Load->getValueType(0), SDLoc(Load),
8085 Load->getChain(), Load->getBasePtr(),
8086 Load->getOffset(), Load->getMemoryVT(),
8087 Load->getMemOperand());
8088 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
8089 if (Load->getNumValues() == 3) {
8090 // PRE/POST_INC loads have 3 values.
8091 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
8092 NewLoad.getValue(2) };
8093 CombineTo(Load, To, 3, true);
8094 } else {
8095 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
8096 }
8097 }
8098
8099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8100 }
8101 }
8102
8103 // Try to convert a constant mask AND into a shuffle clear mask.
8104 if (VT.isVector())
8105 if (SDValue Shuffle = XformToShuffleWithZero(N))
8106 return Shuffle;
8107
8108 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
8109 return Combined;
8110
8111 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() && N1C &&
8113 SDValue Ext = N0.getOperand(0);
8114 EVT ExtVT = Ext->getValueType(0);
8115 SDValue Extendee = Ext->getOperand(0);
8116
8117 unsigned ScalarWidth = Extendee.getValueType().getScalarSizeInBits();
8118 if (N1C->getAPIntValue().isMask(ScalarWidth) &&
8119 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, ExtVT))) {
8120 // (and (extract_subvector (zext|anyext|sext v) _) iN_mask)
8121 // => (extract_subvector (iN_zeroext v))
8122 SDValue ZeroExtExtendee =
8123 DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Extendee);
8124
8125 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ZeroExtExtendee,
8126 N0.getOperand(1));
8127 }
8128 }
8129
8130 // fold (and (masked_gather x)) -> (zext_masked_gather x)
8131 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
8132 EVT MemVT = GN0->getMemoryVT();
8133 EVT ScalarVT = MemVT.getScalarType();
8134
8135 if (SDValue(GN0, 0).hasOneUse() &&
8136 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
8138 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
8139 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
8140
8141 SDValue ZExtLoad = DAG.getMaskedGather(
8142 DAG.getVTList(VT, MVT::Other), MemVT, DL, Ops, GN0->getMemOperand(),
8143 GN0->getIndexType(), ISD::ZEXTLOAD);
8144
8145 CombineTo(N, ZExtLoad);
8146 AddToWorklist(ZExtLoad.getNode());
8147 // Avoid recheck of N.
8148 return SDValue(N, 0);
8149 }
8150 }
8151
8152 // fold (and (load x), 255) -> (zextload x, i8)
8153 // fold (and (extload x, i16), 255) -> (zextload x, i8)
8154 // fold (and (freeze (load x)), 255) -> (freeze (zextload x, i8))
8155 // fold (and (freeze (extload x, i16)), 255) -> (freeze (zextload x, i8))
8156 if (N1C && !VT.isVector()) {
8157 SDValue Inner = peekThroughFreeze(N0);
8158 if (Inner.getOpcode() == ISD::LOAD)
8159 if (SDValue Res = reduceLoadWidth(N))
8160 return Res;
8161 }
8162
8163 if (LegalTypes) {
8164 // Attempt to propagate the AND back up to the leaves which, if they're
8165 // loads, can be combined to narrow loads and the AND node can be removed.
8166 // Perform after legalization so that extend nodes will already be
8167 // combined into the loads.
8168 if (BackwardsPropagateMask(N))
8169 return SDValue(N, 0);
8170 }
8171
8172 if (SDValue Combined = visitANDLike(N0, N1, N))
8173 return Combined;
8174
8175 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
8176 if (N0.getOpcode() == N1.getOpcode())
8177 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
8178 return V;
8179
8180 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
8181 return R;
8182 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
8183 return R;
8184
8185 // Fold (and X, (bswap (not Y))) -> (and X, (not (bswap Y)))
8186 // Fold (and X, (bitreverse (not Y))) -> (and X, (not (bitreverse Y)))
8187 SDValue X, Y, Z, NotY;
8188 for (unsigned Opc : {ISD::BSWAP, ISD::BITREVERSE})
8189 if (sd_match(N,
8190 m_And(m_Value(X), m_OneUse(m_UnaryOp(Opc, m_Value(NotY))))) &&
8191 sd_match(NotY, m_Not(m_Value(Y))) &&
8192 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8193 return DAG.getNode(ISD::AND, DL, VT, X,
8194 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y), VT));
8195
8196 // Fold (and X, (rot (not Y), Z)) -> (and X, (not (rot Y, Z)))
8197 for (unsigned Opc : {ISD::ROTL, ISD::ROTR})
8198 if (sd_match(N, m_And(m_Value(X),
8199 m_OneUse(m_BinOp(Opc, m_Value(NotY), m_Value(Z))))) &&
8200 sd_match(NotY, m_Not(m_Value(Y))) &&
8201 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8202 return DAG.getNode(ISD::AND, DL, VT, X,
8203 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y, Z), VT));
8204
8205 // Fold (and X, (add (not Y), Z)) -> (and X, (not (sub Y, Z)))
8206 // Fold (and X, (sub (not Y), Z)) -> (and X, (not (add Y, Z)))
8207 if (TLI.hasAndNot(SDValue(N, 0)))
8208 if (SDValue Folded = foldBitwiseOpWithNeg(N, DL, VT))
8209 return Folded;
8210
8211 // Fold (and (srl X, C), 1) -> (srl X, BW-1) for signbit extraction
8212 // If we are shifting down an extended sign bit, see if we can simplify
8213 // this to shifting the MSB directly to expose further simplifications.
8214 // This pattern often appears after sext_inreg legalization.
8215 APInt Amt;
8216 if (sd_match(N, m_And(m_Srl(m_Value(X), m_ConstInt(Amt)), m_One())) &&
8217 Amt.ult(BitWidth - 1) && Amt.uge(BitWidth - DAG.ComputeNumSignBits(X)))
8218 return DAG.getNode(ISD::SRL, DL, VT, X,
8219 DAG.getShiftAmountConstant(BitWidth - 1, VT, DL));
8220
8221 // Masking the negated extension of a boolean is just the zero-extended
8222 // boolean:
8223 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
8224 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
8225 //
8226 // Note: the SimplifyDemandedBits fold below can make an information-losing
8227 // transform, and then we have no way to find this better fold.
8228 if (sd_match(N, m_And(m_Sub(m_Zero(), m_Value(X)), m_One()))) {
8229 if (X.getOpcode() == ISD::ZERO_EXTEND &&
8230 X.getOperand(0).getScalarValueSizeInBits() == 1)
8231 return X;
8232 if (X.getOpcode() == ISD::SIGN_EXTEND &&
8233 X.getOperand(0).getScalarValueSizeInBits() == 1)
8234 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, X.getOperand(0));
8235 }
8236
8237 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
8238 // fold (and (sra)) -> (and (srl)) when possible.
8240 return SDValue(N, 0);
8241
8242 // fold (zext_inreg (extload x)) -> (zextload x)
8243 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
8244 if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
8245 (ISD::isEXTLoad(N0.getNode()) ||
8246 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
8247 auto *LN0 = cast<LoadSDNode>(N0);
8248 EVT MemVT = LN0->getMemoryVT();
8249 // If we zero all the possible extended bits, then we can turn this into
8250 // a zextload if we are running before legalize or the operation is legal.
8251 unsigned ExtBitSize = N1.getScalarValueSizeInBits();
8252 unsigned MemBitSize = MemVT.getScalarSizeInBits();
8253 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
8254 if (DAG.MaskedValueIsZero(N1, ExtBits) &&
8255 ((!LegalOperations && LN0->isSimple()) ||
8256 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
8257 ISD::ZEXTLOAD, false))) {
8258 SDValue ExtLoad =
8259 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
8260 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
8261 AddToWorklist(N);
8262 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8263 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8264 }
8265 }
8266
8267 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
8268 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
8269 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8270 N0.getOperand(1), false))
8271 return BSwap;
8272 }
8273
8274 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
8275 return Shifts;
8276
8277 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
8278 return V;
8279
8280 // Recognize the following pattern:
8281 //
8282 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
8283 //
8284 // where bitmask is a mask that clears the upper bits of AndVT. The
8285 // number of bits in bitmask must be a power of two.
8286 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
8287 if (LHS->getOpcode() != ISD::SIGN_EXTEND)
8288 return false;
8289
8290 auto *C = isConstOrConstSplat(RHS, false, true);
8291 if (!C)
8292 return false;
8293
8294 if (!C->getAPIntValue().isMask(
8295 LHS.getOperand(0).getValueType().getScalarSizeInBits()))
8296 return false;
8297
8298 return true;
8299 };
8300
8301 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
8302 if (IsAndZeroExtMask(N0, N1) &&
8303 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)))
8304 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
8305
8306 if (hasOperation(ISD::USUBSAT, VT))
8307 if (SDValue V = foldAndToUsubsat(N, DAG, DL))
8308 return V;
8309
8310 // Postpone until legalization completed to avoid interference with bswap
8311 // folding
8312 if (LegalOperations || VT.isVector())
8313 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
8314 return R;
8315
8316 if (VT.isScalarInteger() && VT != MVT::i1)
8317 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
8318 return R;
8319
8320 return SDValue();
8321}
8322
8323/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
8324SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
8325 bool DemandHighBits) {
8326 if (!LegalOperations)
8327 return SDValue();
8328
8329 EVT VT = N->getValueType(0);
8330 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
8331 return SDValue();
8333 return SDValue();
8334
8335 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
8336 bool LookPassAnd0 = false;
8337 bool LookPassAnd1 = false;
8338 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
8339 std::swap(N0, N1);
8340 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
8341 std::swap(N0, N1);
8342 if (N0.getOpcode() == ISD::AND) {
8343 if (!N0->hasOneUse())
8344 return SDValue();
8345 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8346 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
8347 // This is needed for X86.
8348 if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
8349 N01C->getZExtValue() != 0xFFFF))
8350 return SDValue();
8351 N0 = N0.getOperand(0);
8352 LookPassAnd0 = true;
8353 }
8354
8355 if (N1.getOpcode() == ISD::AND) {
8356 if (!N1->hasOneUse())
8357 return SDValue();
8358 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8359 if (!N11C || N11C->getZExtValue() != 0xFF)
8360 return SDValue();
8361 N1 = N1.getOperand(0);
8362 LookPassAnd1 = true;
8363 }
8364
8365 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
8366 std::swap(N0, N1);
8367 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
8368 return SDValue();
8369 if (!N0->hasOneUse() || !N1->hasOneUse())
8370 return SDValue();
8371
8372 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8373 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8374 if (!N01C || !N11C)
8375 return SDValue();
8376 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
8377 return SDValue();
8378
8379 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
8380 SDValue N00 = N0->getOperand(0);
8381 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
8382 if (!N00->hasOneUse())
8383 return SDValue();
8384 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
8385 if (!N001C || N001C->getZExtValue() != 0xFF)
8386 return SDValue();
8387 N00 = N00.getOperand(0);
8388 LookPassAnd0 = true;
8389 }
8390
8391 SDValue N10 = N1->getOperand(0);
8392 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
8393 if (!N10->hasOneUse())
8394 return SDValue();
8395 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
8396 // Also allow 0xFFFF since the bits will be shifted out. This is needed
8397 // for X86.
8398 if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
8399 N101C->getZExtValue() != 0xFFFF))
8400 return SDValue();
8401 N10 = N10.getOperand(0);
8402 LookPassAnd1 = true;
8403 }
8404
8405 if (N00 != N10)
8406 return SDValue();
8407
8408 // Make sure everything beyond the low halfword gets set to zero since the SRL
8409 // 16 will clear the top bits.
8410 unsigned OpSizeInBits = VT.getSizeInBits();
8411 if (OpSizeInBits > 16) {
8412 // If the left-shift isn't masked out then the only way this is a bswap is
8413 // if all bits beyond the low 8 are 0. In that case the entire pattern
8414 // reduces to a left shift anyway: leave it for other parts of the combiner.
8415 if (DemandHighBits && !LookPassAnd0)
8416 return SDValue();
8417
8418 // However, if the right shift isn't masked out then it might be because
8419 // it's not needed. See if we can spot that too. If the high bits aren't
8420 // demanded, we only need bits 23:16 to be zero. Otherwise, we need all
8421 // upper bits to be zero.
8422 if (!LookPassAnd1) {
8423 unsigned HighBit = DemandHighBits ? OpSizeInBits : 24;
8424 if (!DAG.MaskedValueIsZero(N10,
8425 APInt::getBitsSet(OpSizeInBits, 16, HighBit)))
8426 return SDValue();
8427 }
8428 }
8429
8430 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
8431 if (OpSizeInBits > 16) {
8432 SDLoc DL(N);
8433 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
8434 DAG.getShiftAmountConstant(OpSizeInBits - 16, VT, DL));
8435 }
8436 return Res;
8437}
8438
8439/// Return true if the specified node is an element that makes up a 32-bit
8440/// packed halfword byteswap.
8441/// ((x & 0x000000ff) << 8) |
8442/// ((x & 0x0000ff00) >> 8) |
8443/// ((x & 0x00ff0000) << 8) |
8444/// ((x & 0xff000000) >> 8)
8446 if (!N->hasOneUse())
8447 return false;
8448
8449 unsigned Opc = N.getOpcode();
8450 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
8451 return false;
8452
8453 SDValue N0 = N.getOperand(0);
8454 unsigned Opc0 = N0.getOpcode();
8455 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
8456 return false;
8457
8458 ConstantSDNode *N1C = nullptr;
8459 // SHL or SRL: look upstream for AND mask operand
8460 if (Opc == ISD::AND)
8461 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8462 else if (Opc0 == ISD::AND)
8464 if (!N1C)
8465 return false;
8466
8467 unsigned MaskByteOffset;
8468 switch (N1C->getZExtValue()) {
8469 default:
8470 return false;
8471 case 0xFF: MaskByteOffset = 0; break;
8472 case 0xFF00: MaskByteOffset = 1; break;
8473 case 0xFFFF:
8474 // In case demanded bits didn't clear the bits that will be shifted out.
8475 // This is needed for X86.
8476 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
8477 MaskByteOffset = 1;
8478 break;
8479 }
8480 return false;
8481 case 0xFF0000: MaskByteOffset = 2; break;
8482 case 0xFF000000: MaskByteOffset = 3; break;
8483 }
8484
8485 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
8486 if (Opc == ISD::AND) {
8487 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
8488 // (x >> 8) & 0xff
8489 // (x >> 8) & 0xff0000
8490 if (Opc0 != ISD::SRL)
8491 return false;
8493 if (!C || C->getZExtValue() != 8)
8494 return false;
8495 } else {
8496 // (x << 8) & 0xff00
8497 // (x << 8) & 0xff000000
8498 if (Opc0 != ISD::SHL)
8499 return false;
8501 if (!C || C->getZExtValue() != 8)
8502 return false;
8503 }
8504 } else if (Opc == ISD::SHL) {
8505 // (x & 0xff) << 8
8506 // (x & 0xff0000) << 8
8507 if (MaskByteOffset != 0 && MaskByteOffset != 2)
8508 return false;
8509 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8510 if (!C || C->getZExtValue() != 8)
8511 return false;
8512 } else { // Opc == ISD::SRL
8513 // (x & 0xff00) >> 8
8514 // (x & 0xff000000) >> 8
8515 if (MaskByteOffset != 1 && MaskByteOffset != 3)
8516 return false;
8517 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8518 if (!C || C->getZExtValue() != 8)
8519 return false;
8520 }
8521
8522 if (Parts[MaskByteOffset])
8523 return false;
8524
8525 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
8526 return true;
8527}
8528
8529// Match 2 elements of a packed halfword bswap.
8531 if (N.getOpcode() == ISD::OR)
8532 return isBSwapHWordElement(N.getOperand(0), Parts) &&
8533 isBSwapHWordElement(N.getOperand(1), Parts);
8534
8535 if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
8536 ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
8537 if (!C || C->getAPIntValue() != 16)
8538 return false;
8539 Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
8540 return true;
8541 }
8542
8543 return false;
8544}
8545
8546// Match this pattern:
8547// (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
8548// And rewrite this to:
8549// (rotr (bswap A), 16)
8551 SelectionDAG &DAG, SDNode *N, SDValue N0,
8552 SDValue N1, EVT VT) {
8553 assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
8554 "MatchBSwapHWordOrAndAnd: expecting i32");
8555 if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
8556 return SDValue();
8557 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
8558 return SDValue();
8559 // TODO: this is too restrictive; lifting this restriction requires more tests
8560 if (!N0->hasOneUse() || !N1->hasOneUse())
8561 return SDValue();
8564 if (!Mask0 || !Mask1)
8565 return SDValue();
8566 if (Mask0->getAPIntValue() != 0xff00ff00 ||
8567 Mask1->getAPIntValue() != 0x00ff00ff)
8568 return SDValue();
8569 SDValue Shift0 = N0.getOperand(0);
8570 SDValue Shift1 = N1.getOperand(0);
8571 if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
8572 return SDValue();
8573 ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
8574 ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
8575 if (!ShiftAmt0 || !ShiftAmt1)
8576 return SDValue();
8577 if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
8578 return SDValue();
8579 if (Shift0.getOperand(0) != Shift1.getOperand(0))
8580 return SDValue();
8581
8582 SDLoc DL(N);
8583 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
8584 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8585 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8586}
8587
8588/// Match a 32-bit packed halfword bswap. That is
8589/// ((x & 0x000000ff) << 8) |
8590/// ((x & 0x0000ff00) >> 8) |
8591/// ((x & 0x00ff0000) << 8) |
8592/// ((x & 0xff000000) >> 8)
8593/// => (rotl (bswap x), 16)
8594SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
8595 if (!LegalOperations)
8596 return SDValue();
8597
8598 EVT VT = N->getValueType(0);
8599 if (VT != MVT::i32)
8600 return SDValue();
8602 return SDValue();
8603
8604 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT))
8605 return BSwap;
8606
8607 // Try again with commuted operands.
8608 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT))
8609 return BSwap;
8610
8611
8612 // Look for either
8613 // (or (bswaphpair), (bswaphpair))
8614 // (or (or (bswaphpair), (and)), (and))
8615 // (or (or (and), (bswaphpair)), (and))
8616 SDNode *Parts[4] = {};
8617
8618 if (isBSwapHWordPair(N0, Parts)) {
8619 // (or (or (and), (and)), (or (and), (and)))
8620 if (!isBSwapHWordPair(N1, Parts))
8621 return SDValue();
8622 } else if (N0.getOpcode() == ISD::OR) {
8623 // (or (or (or (and), (and)), (and)), (and))
8624 if (!isBSwapHWordElement(N1, Parts))
8625 return SDValue();
8626 SDValue N00 = N0.getOperand(0);
8627 SDValue N01 = N0.getOperand(1);
8628 if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
8629 !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
8630 return SDValue();
8631 } else {
8632 return SDValue();
8633 }
8634
8635 // Make sure the parts are all coming from the same node.
8636 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
8637 return SDValue();
8638
8639 SDLoc DL(N);
8640 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
8641 SDValue(Parts[0], 0));
8642
8643 // Result of the bswap should be rotated by 16. If it's not legal, then
8644 // do (x << 16) | (x >> 16).
8645 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8647 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
8649 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8650 return DAG.getNode(ISD::OR, DL, VT,
8651 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
8652 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
8653}
8654
8655/// This contains all DAGCombine rules which reduce two values combined by
8656/// an Or operation to a single value \see visitANDLike().
8657SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, const SDLoc &DL) {
8658 EVT VT = N1.getValueType();
8659
8660 // fold (or x, undef) -> -1
8661 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
8662 return DAG.getAllOnesConstant(DL, VT);
8663
8664 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
8665 return V;
8666
8667 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
8668 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
8669 // Don't increase # computations.
8670 (N0->hasOneUse() || N1->hasOneUse())) {
8671 // We can only do this xform if we know that bits from X that are set in C2
8672 // but not in C1 are already zero. Likewise for Y.
8673 if (const ConstantSDNode *N0O1C =
8675 if (const ConstantSDNode *N1O1C =
8677 // We can only do this xform if we know that bits from X that are set in
8678 // C2 but not in C1 are already zero. Likewise for Y.
8679 const APInt &LHSMask = N0O1C->getAPIntValue();
8680 const APInt &RHSMask = N1O1C->getAPIntValue();
8681
8682 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
8683 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
8684 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8685 N0.getOperand(0), N1.getOperand(0));
8686 return DAG.getNode(ISD::AND, DL, VT, X,
8687 DAG.getConstant(LHSMask | RHSMask, DL, VT));
8688 }
8689 }
8690 }
8691 }
8692
8693 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
8694 if (N0.getOpcode() == ISD::AND &&
8695 N1.getOpcode() == ISD::AND &&
8696 N0.getOperand(0) == N1.getOperand(0) &&
8697 // Don't increase # computations.
8698 (N0->hasOneUse() || N1->hasOneUse())) {
8699 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8700 N0.getOperand(1), N1.getOperand(1));
8701 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
8702 }
8703
8704 return SDValue();
8705}
8706
8707/// OR combines for which the commuted variant will be tried as well.
8709 SDNode *N) {
8710 EVT VT = N0.getValueType();
8711 unsigned BW = VT.getScalarSizeInBits();
8712 SDLoc DL(N);
8713
8714 auto peekThroughResize = [](SDValue V) {
8715 if (V->getOpcode() == ISD::ZERO_EXTEND || V->getOpcode() == ISD::TRUNCATE)
8716 return V->getOperand(0);
8717 return V;
8718 };
8719
8720 SDValue N0Resized = peekThroughResize(N0);
8721 if (N0Resized.getOpcode() == ISD::AND) {
8722 SDValue N1Resized = peekThroughResize(N1);
8723 SDValue N00 = N0Resized.getOperand(0);
8724 SDValue N01 = N0Resized.getOperand(1);
8725
8726 // fold or (and x, y), x --> x
8727 if (N00 == N1Resized || N01 == N1Resized)
8728 return N1;
8729
8730 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
8731 // TODO: Set AllowUndefs = true.
8732 if (SDValue NotOperand = getBitwiseNotOperand(N01, N00,
8733 /* AllowUndefs */ false)) {
8734 if (peekThroughResize(NotOperand) == N1Resized)
8735 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N00, DL, VT),
8736 N1);
8737 }
8738
8739 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
8740 if (SDValue NotOperand = getBitwiseNotOperand(N00, N01,
8741 /* AllowUndefs */ false)) {
8742 if (peekThroughResize(NotOperand) == N1Resized)
8743 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N01, DL, VT),
8744 N1);
8745 }
8746 }
8747
8748 SDValue X, Y;
8749
8750 // fold or (xor X, N1), N1 --> or X, N1
8751 if (sd_match(N0, m_Xor(m_Value(X), m_Specific(N1))))
8752 return DAG.getNode(ISD::OR, DL, VT, X, N1);
8753
8754 // fold or (xor x, y), (x and/or y) --> or x, y
8755 if (sd_match(N0, m_Xor(m_Value(X), m_Value(Y))) &&
8756 (sd_match(N1, m_And(m_Specific(X), m_Specific(Y))) ||
8758 return DAG.getNode(ISD::OR, DL, VT, X, Y);
8759
8760 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
8761 return R;
8762
8763 auto peekThroughZext = [](SDValue V) {
8764 if (V->getOpcode() == ISD::ZERO_EXTEND)
8765 return V->getOperand(0);
8766 return V;
8767 };
8768
8769 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::SHL &&
8770 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8771 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
8772 if (N0.getOperand(0) == N1.getOperand(0))
8773 return N0;
8774 // (fshl A, X, Y) | (shl X, Y) --> fshl (A|X), X, Y
8775 if (N0.getOperand(1) == N1.getOperand(0) && N0.hasOneUse() &&
8776 N1.hasOneUse()) {
8777 SDValue A = N0.getOperand(0);
8778 SDValue X = N1.getOperand(0);
8779 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, X);
8780 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, X, N0.getOperand(2));
8781 }
8782 }
8783
8784 if (N0.getOpcode() == ISD::FSHR && N1.getOpcode() == ISD::SRL &&
8785 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8786 // (fshr ?, X, Y) | (srl X, Y) --> fshr ?, X, Y
8787 if (N0.getOperand(1) == N1.getOperand(0))
8788 return N0;
8789 // (fshr X, B, Y) | (srl X, Y) --> fshr X, (X|B), Y
8790 if (N0.getOperand(0) == N1.getOperand(0) && N0.hasOneUse() &&
8791 N1.hasOneUse()) {
8792 SDValue X = N1.getOperand(0);
8793 SDValue B = N0.getOperand(1);
8794 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, X, B);
8795 return DAG.getNode(ISD::FSHR, DL, VT, X, NewRHS, N0.getOperand(2));
8796 }
8797 }
8798
8799 // (fshl A, B, S0) | (fshr C, D, S1) --> fshl (A|C), (B|D), S0
8800 // iff S0 + S1 == bitwidth(S1)
8801 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::FSHR &&
8802 N0.hasOneUse() && N1.hasOneUse()) {
8803 auto *S0 = dyn_cast<ConstantSDNode>(N0.getOperand(2));
8804 auto *S1 = dyn_cast<ConstantSDNode>(N1.getOperand(2));
8805 if (S0 && S1 && S0->getZExtValue() < BW && S1->getZExtValue() < BW &&
8806 S0->getZExtValue() == (BW - S1->getZExtValue())) {
8807 SDValue A = N0.getOperand(0);
8808 SDValue B = N0.getOperand(1);
8809 SDValue C = N1.getOperand(0);
8810 SDValue D = N1.getOperand(1);
8811 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, C);
8812 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, B, D);
8813 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, NewRHS, N0.getOperand(2));
8814 }
8815 }
8816
8817 // Attempt to match a legalized build_pair-esque pattern:
8818 // or(shl(aext(Hi),BW/2),zext(Lo))
8819 SDValue Lo, Hi;
8820 if (sd_match(N0,
8822 sd_match(N1, m_ZExt(m_Value(Lo))) &&
8823 Lo.getScalarValueSizeInBits() == (BW / 2) &&
8824 Lo.getValueType() == Hi.getValueType()) {
8825 // Fold build_pair(not(Lo),not(Hi)) -> not(build_pair(Lo,Hi)).
8826 SDValue NotLo, NotHi;
8827 if (sd_match(Lo, m_OneUse(m_Not(m_Value(NotLo)))) &&
8828 sd_match(Hi, m_OneUse(m_Not(m_Value(NotHi))))) {
8829 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotLo);
8830 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NotHi);
8831 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
8832 DAG.getShiftAmountConstant(BW / 2, VT, DL));
8833 return DAG.getNOT(DL, DAG.getNode(ISD::OR, DL, VT, Lo, Hi), VT);
8834 }
8835 }
8836
8837 return SDValue();
8838}
8839
8840SDValue DAGCombiner::visitOR(SDNode *N) {
8841 SDValue N0 = N->getOperand(0);
8842 SDValue N1 = N->getOperand(1);
8843 EVT VT = N1.getValueType();
8844 SDLoc DL(N);
8845
8846 // x | x --> x
8847 if (N0 == N1)
8848 return N0;
8849
8850 // fold (or c1, c2) -> c1|c2
8851 if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, DL, VT, {N0, N1}))
8852 return C;
8853
8854 // canonicalize constant to RHS
8857 return DAG.getNode(ISD::OR, DL, VT, N1, N0);
8858
8859 // fold vector ops
8860 if (VT.isVector()) {
8861 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
8862 return FoldedVOp;
8863
8864 // fold (or x, 0) -> x, vector edition
8866 return N0;
8867
8868 // fold (or x, -1) -> -1, vector edition
8870 // do not return N1, because undef node may exist in N1
8871 return DAG.getAllOnesConstant(DL, N1.getValueType());
8872
8873 // fold (or buildvector(x,0,-1,w), buildvector(0,y,z,w))
8874 // --> buildvector(x,y,-1,w)
8875 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
8876 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8877 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
8878 N0.hasOneUse() && N1.hasOneUse() &&
8879 BV0->getOperand(0).getValueType() ==
8880 BV1->getOperand(0).getValueType()) {
8881 SmallVector<SDValue> MergedOps;
8882 unsigned NumElts = VT.getVectorNumElements();
8883 EVT EltVT = BV0->getOperand(0).getValueType();
8884 for (unsigned I = 0; I != NumElts; ++I) {
8885 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
8886 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
8887 if (C0 && C1)
8888 MergedOps.push_back(DAG.getConstant(
8889 C0->getAPIntValue() | C1->getAPIntValue(), DL, EltVT));
8890 else if (C0 && C0->isZero())
8891 MergedOps.push_back(BV1->getOperand(I));
8892 else if (C1 && C1->isZero())
8893 MergedOps.push_back(BV0->getOperand(I));
8894 else if (C0 && C0->isAllOnes())
8895 MergedOps.push_back(BV0->getOperand(I));
8896 else if (C1 && C1->isAllOnes())
8897 MergedOps.push_back(BV1->getOperand(I));
8898 else if (BV0->getOperand(I) == BV1->getOperand(I))
8899 MergedOps.push_back(BV0->getOperand(I));
8900 else
8901 break;
8902 }
8903 if (MergedOps.size() == NumElts)
8904 return DAG.getBuildVector(VT, DL, MergedOps);
8905 }
8906
8907 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
8908 // Do this only if the resulting type / shuffle is legal.
8909 auto *SV0 = dyn_cast<ShuffleVectorSDNode>(N0);
8910 auto *SV1 = dyn_cast<ShuffleVectorSDNode>(N1);
8911 if (SV0 && SV1 && TLI.isTypeLegal(VT)) {
8912 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
8913 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
8914 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
8915 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
8916 // Ensure both shuffles have a zero input.
8917 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
8918 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
8919 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
8920 bool CanFold = true;
8921 int NumElts = VT.getVectorNumElements();
8922 SmallVector<int, 4> Mask(NumElts, -1);
8923
8924 for (int i = 0; i != NumElts; ++i) {
8925 int M0 = SV0->getMaskElt(i);
8926 int M1 = SV1->getMaskElt(i);
8927
8928 // Determine if either index is pointing to a zero vector.
8929 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
8930 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
8931
8932 // If one element is zero and the otherside is undef, keep undef.
8933 // This also handles the case that both are undef.
8934 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0))
8935 continue;
8936
8937 // Make sure only one of the elements is zero.
8938 if (M0Zero == M1Zero) {
8939 CanFold = false;
8940 break;
8941 }
8942
8943 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
8944
8945 // We have a zero and non-zero element. If the non-zero came from
8946 // SV0 make the index a LHS index. If it came from SV1, make it
8947 // a RHS index. We need to mod by NumElts because we don't care
8948 // which operand it came from in the original shuffles.
8949 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
8950 }
8951
8952 if (CanFold) {
8953 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
8954 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
8955 SDValue LegalShuffle =
8956 TLI.buildLegalVectorShuffle(VT, DL, NewLHS, NewRHS, Mask, DAG);
8957 if (LegalShuffle)
8958 return LegalShuffle;
8959 }
8960 }
8961 }
8962 }
8963
8964 // fold (or x, 0) -> x
8965 if (isNullConstant(N1))
8966 return N0;
8967
8968 // fold (or x, -1) -> -1
8969 if (isAllOnesConstant(N1))
8970 return N1;
8971
8972 if (SDValue NewSel = foldBinOpIntoSelect(N))
8973 return NewSel;
8974
8975 // fold (or x, c) -> c iff (x & ~c) == 0
8976 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8977 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
8978 return N1;
8979
8980 if (SDValue R = foldAndOrOfSETCC(N, DAG))
8981 return R;
8982
8983 if (SDValue Combined = visitORLike(N0, N1, DL))
8984 return Combined;
8985
8986 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
8987 return Combined;
8988
8989 if (SDValue Combined = combineOrOfSetCCToUSUBOCarry(N, DAG, TLI))
8990 return Combined;
8991
8992 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
8993 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
8994 return BSwap;
8995 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
8996 return BSwap;
8997
8998 // reassociate or
8999 if (SDValue ROR = reassociateOps(ISD::OR, DL, N0, N1, N->getFlags()))
9000 return ROR;
9001
9002 // Fold or(vecreduce(x), vecreduce(y)) -> vecreduce(or(x, y))
9003 if (SDValue SD =
9004 reassociateReduction(ISD::VECREDUCE_OR, ISD::OR, DL, VT, N0, N1))
9005 return SD;
9006
9007 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
9008 // iff (c1 & c2) != 0 or c1/c2 are undef.
9009 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
9010 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
9011 };
9012 if (N0.getOpcode() == ISD::AND && N0->hasOneUse() &&
9013 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
9014 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
9015 {N1, N0.getOperand(1)})) {
9016 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
9017 AddToWorklist(IOR.getNode());
9018 return DAG.getNode(ISD::AND, DL, VT, COR, IOR);
9019 }
9020 }
9021
9022 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
9023 return Combined;
9024 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
9025 return Combined;
9026
9027 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
9028 if (N0.getOpcode() == N1.getOpcode())
9029 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
9030 return V;
9031
9032 // See if this is some rotate idiom.
9033 if (SDValue Rot = MatchRotate(N0, N1, DL, /*FromAdd=*/false))
9034 return Rot;
9035
9036 if (SDValue Load = MatchLoadCombine(N))
9037 return Load;
9038
9039 // Simplify the operands using demanded-bits information.
9041 return SDValue(N, 0);
9042
9043 // If OR can be rewritten into ADD, try combines based on ADD.
9044 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
9045 DAG.isADDLike(SDValue(N, 0)))
9046 if (SDValue Combined = visitADDLike(N))
9047 return Combined;
9048
9049 // Postpone until legalization completed to avoid interference with bswap
9050 // folding
9051 if (LegalOperations || VT.isVector())
9052 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
9053 return R;
9054
9055 if (VT.isScalarInteger() && VT != MVT::i1)
9056 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
9057 return R;
9058
9059 return SDValue();
9060}
9061
9063 SDValue &Mask) {
9064 if (Op.getOpcode() == ISD::AND &&
9065 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
9066 Mask = Op.getOperand(1);
9067 return Op.getOperand(0);
9068 }
9069 return Op;
9070}
9071
9072/// Match "(X shl/srl V1) & V2" where V2 may not be present.
9073static bool matchRotateHalf(const SelectionDAG &DAG, SDValue Op, SDValue &Shift,
9074 SDValue &Mask) {
9075 Op = stripConstantMask(DAG, Op, Mask);
9076 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
9077 Shift = Op;
9078 return true;
9079 }
9080 return false;
9081}
9082
9083/// Helper function for visitOR to extract the needed side of a rotate idiom
9084/// from a shl/srl/mul/udiv. This is meant to handle cases where
9085/// InstCombine merged some outside op with one of the shifts from
9086/// the rotate pattern.
9087/// \returns An empty \c SDValue if the needed shift couldn't be extracted.
9088/// Otherwise, returns an expansion of \p ExtractFrom based on the following
9089/// patterns:
9090///
9091/// (or (add v v) (shrl v bitwidth-1)):
9092/// expands (add v v) -> (shl v 1)
9093///
9094/// (or (mul v c0) (shrl (mul v c1) c2)):
9095/// expands (mul v c0) -> (shl (mul v c1) c3)
9096///
9097/// (or (udiv v c0) (shl (udiv v c1) c2)):
9098/// expands (udiv v c0) -> (shrl (udiv v c1) c3)
9099///
9100/// (or (shl v c0) (shrl (shl v c1) c2)):
9101/// expands (shl v c0) -> (shl (shl v c1) c3)
9102///
9103/// (or (shrl v c0) (shl (shrl v c1) c2)):
9104/// expands (shrl v c0) -> (shrl (shrl v c1) c3)
9105///
9106/// Such that in all cases, c3+c2==bitwidth(op v c1).
9108 SDValue ExtractFrom, SDValue &Mask,
9109 const SDLoc &DL) {
9110 assert(OppShift && ExtractFrom && "Empty SDValue");
9111 if (OppShift.getOpcode() != ISD::SHL && OppShift.getOpcode() != ISD::SRL)
9112 return SDValue();
9113
9114 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
9115
9116 // Value and Type of the shift.
9117 SDValue OppShiftLHS = OppShift.getOperand(0);
9118 EVT ShiftedVT = OppShiftLHS.getValueType();
9119
9120 // Amount of the existing shift.
9121 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
9122
9123 // (add v v) -> (shl v 1)
9124 // TODO: Should this be a general DAG canonicalization?
9125 if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
9126 ExtractFrom.getOpcode() == ISD::ADD &&
9127 ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
9128 ExtractFrom.getOperand(0) == OppShiftLHS &&
9129 OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
9130 return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
9131 DAG.getShiftAmountConstant(1, ShiftedVT, DL));
9132
9133 // Preconditions:
9134 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
9135 //
9136 // Find opcode of the needed shift to be extracted from (op0 v c0).
9137 unsigned Opcode = ISD::DELETED_NODE;
9138 bool IsMulOrDiv = false;
9139 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
9140 // opcode or its arithmetic (mul or udiv) variant.
9141 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
9142 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
9143 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
9144 return false;
9145 Opcode = NeededShift;
9146 return true;
9147 };
9148 // op0 must be either the needed shift opcode or the mul/udiv equivalent
9149 // that the needed shift can be extracted from.
9150 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
9151 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
9152 return SDValue();
9153
9154 // op0 must be the same opcode on both sides, have the same LHS argument,
9155 // and produce the same value type.
9156 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
9157 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
9158 ShiftedVT != ExtractFrom.getValueType())
9159 return SDValue();
9160
9161 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
9162 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
9163 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
9164 ConstantSDNode *ExtractFromCst =
9165 isConstOrConstSplat(ExtractFrom.getOperand(1));
9166 // TODO: We should be able to handle non-uniform constant vectors for these values
9167 // Check that we have constant values.
9168 if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
9169 !OppLHSCst || !OppLHSCst->getAPIntValue() ||
9170 !ExtractFromCst || !ExtractFromCst->getAPIntValue())
9171 return SDValue();
9172
9173 // Compute the shift amount we need to extract to complete the rotate.
9174 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
9175 if (OppShiftCst->getAPIntValue().ugt(VTWidth))
9176 return SDValue();
9177 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
9178 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
9179 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
9180 APInt OppLHSAmt = OppLHSCst->getAPIntValue();
9181 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
9182
9183 // Now try extract the needed shift from the ExtractFrom op and see if the
9184 // result matches up with the existing shift's LHS op.
9185 if (IsMulOrDiv) {
9186 // Op to extract from is a mul or udiv by a constant.
9187 // Check:
9188 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
9189 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
9190 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
9191 NeededShiftAmt.getZExtValue());
9192 APInt ResultAmt;
9193 APInt Rem;
9194 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
9195 if (Rem != 0 || ResultAmt != OppLHSAmt)
9196 return SDValue();
9197 } else {
9198 // Op to extract from is a shift by a constant.
9199 // Check:
9200 // c2 - (bitwidth(op0 v c0) - c1) == c0
9201 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
9202 ExtractFromAmt.getBitWidth()))
9203 return SDValue();
9204 }
9205
9206 // Return the expanded shift op that should allow a rotate to be formed.
9207 EVT ShiftVT = OppShift.getOperand(1).getValueType();
9208 EVT ResVT = ExtractFrom.getValueType();
9209 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
9210 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
9211}
9212
9213// Return true if we can prove that, whenever Neg and Pos are both in the
9214// range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
9215// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
9216//
9217// (or (shift1 X, Neg), (shift2 X, Pos))
9218//
9219// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
9220// in direction shift1 by Neg. The range [0, EltSize) means that we only need
9221// to consider shift amounts with defined behavior.
9222//
9223// The IsRotate flag should be set when the LHS of both shifts is the same.
9224// Otherwise if matching a general funnel shift, it should be clear.
9225static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
9226 SelectionDAG &DAG, bool IsRotate, bool FromAdd) {
9227 const auto &TLI = DAG.getTargetLoweringInfo();
9228 // If EltSize is a power of 2 then:
9229 //
9230 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
9231 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
9232 //
9233 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
9234 // for the stronger condition:
9235 //
9236 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
9237 //
9238 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
9239 // we can just replace Neg with Neg' for the rest of the function.
9240 //
9241 // In other cases we check for the even stronger condition:
9242 //
9243 // Neg == EltSize - Pos [B]
9244 //
9245 // for all Neg and Pos. Note that the (or ...) then invokes undefined
9246 // behavior if Pos == 0 (and consequently Neg == EltSize).
9247 //
9248 // We could actually use [A] whenever EltSize is a power of 2, but the
9249 // only extra cases that it would match are those uninteresting ones
9250 // where Neg and Pos are never in range at the same time. E.g. for
9251 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
9252 // as well as (sub 32, Pos), but:
9253 //
9254 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
9255 //
9256 // always invokes undefined behavior for 32-bit X.
9257 //
9258 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
9259 // This allows us to peek through any operations that only affect Mask's
9260 // un-demanded bits.
9261 //
9262 // NOTE: We can only do this when matching operations which won't modify the
9263 // least Log2(EltSize) significant bits and not a general funnel shift.
9264 unsigned MaskLoBits = 0;
9265 if (IsRotate && !FromAdd && isPowerOf2_64(EltSize)) {
9266 unsigned Bits = Log2_64(EltSize);
9267 unsigned NegBits = Neg.getScalarValueSizeInBits();
9268 if (NegBits >= Bits) {
9269 APInt DemandedBits = APInt::getLowBitsSet(NegBits, Bits);
9270 if (SDValue Inner =
9272 Neg = Inner;
9273 MaskLoBits = Bits;
9274 }
9275 }
9276 }
9277
9278 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
9279 if (Neg.getOpcode() != ISD::SUB)
9280 return false;
9282 if (!NegC)
9283 return false;
9284 SDValue NegOp1 = Neg.getOperand(1);
9285
9286 // On the RHS of [A], if Pos is the result of operation on Pos' that won't
9287 // affect Mask's demanded bits, just replace Pos with Pos'. These operations
9288 // are redundant for the purpose of the equality.
9289 if (MaskLoBits) {
9290 unsigned PosBits = Pos.getScalarValueSizeInBits();
9291 if (PosBits >= MaskLoBits) {
9292 APInt DemandedBits = APInt::getLowBitsSet(PosBits, MaskLoBits);
9293 if (SDValue Inner =
9295 Pos = Inner;
9296 }
9297 }
9298 }
9299
9300 // The condition we need is now:
9301 //
9302 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
9303 //
9304 // If NegOp1 == Pos then we need:
9305 //
9306 // EltSize & Mask == NegC & Mask
9307 //
9308 // (because "x & Mask" is a truncation and distributes through subtraction).
9309 //
9310 // We also need to account for a potential truncation of NegOp1 if the amount
9311 // has already been legalized to a shift amount type.
9312 APInt Width;
9313 if ((Pos == NegOp1) ||
9314 (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
9315 Width = NegC->getAPIntValue();
9316
9317 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
9318 // Then the condition we want to prove becomes:
9319 //
9320 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
9321 //
9322 // which, again because "x & Mask" is a truncation, becomes:
9323 //
9324 // NegC & Mask == (EltSize - PosC) & Mask
9325 // EltSize & Mask == (NegC + PosC) & Mask
9326 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
9327 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
9328 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
9329 else
9330 return false;
9331 } else
9332 return false;
9333
9334 // Now we just need to check that EltSize & Mask == Width & Mask.
9335 if (MaskLoBits)
9336 // EltSize & Mask is 0 since Mask is EltSize - 1.
9337 return Width.getLoBits(MaskLoBits) == 0;
9338 return Width == EltSize;
9339}
9340
9341// A subroutine of MatchRotate used once we have found an OR of two opposite
9342// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
9343// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
9344// former being preferred if supported. InnerPos and InnerNeg are Pos and
9345// Neg with outer conversions stripped away.
9346SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
9347 SDValue Neg, SDValue InnerPos,
9348 SDValue InnerNeg, bool FromAdd,
9349 bool HasPos, unsigned PosOpcode,
9350 unsigned NegOpcode, const SDLoc &DL) {
9351 // fold (or/add (shl x, (*ext y)),
9352 // (srl x, (*ext (sub 32, y)))) ->
9353 // (rotl x, y) or (rotr x, (sub 32, y))
9354 //
9355 // fold (or/add (shl x, (*ext (sub 32, y))),
9356 // (srl x, (*ext y))) ->
9357 // (rotr x, y) or (rotl x, (sub 32, y))
9358 EVT VT = Shifted.getValueType();
9359 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG,
9360 /*IsRotate*/ true, FromAdd))
9361 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
9362 HasPos ? Pos : Neg);
9363
9364 return SDValue();
9365}
9366
9367// A subroutine of MatchRotate used once we have found an OR of two opposite
9368// shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces
9369// to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
9370// former being preferred if supported. InnerPos and InnerNeg are Pos and
9371// Neg with outer conversions stripped away.
9372// TODO: Merge with MatchRotatePosNeg.
9373SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
9374 SDValue Neg, SDValue InnerPos,
9375 SDValue InnerNeg, bool FromAdd,
9376 bool HasPos, unsigned PosOpcode,
9377 unsigned NegOpcode, const SDLoc &DL) {
9378 EVT VT = N0.getValueType();
9379 unsigned EltBits = VT.getScalarSizeInBits();
9380
9381 // fold (or/add (shl x0, (*ext y)),
9382 // (srl x1, (*ext (sub 32, y)))) ->
9383 // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
9384 //
9385 // fold (or/add (shl x0, (*ext (sub 32, y))),
9386 // (srl x1, (*ext y))) ->
9387 // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
9388 if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1,
9389 FromAdd))
9390 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
9391 HasPos ? Pos : Neg);
9392
9393 // Matching the shift+xor cases, we can't easily use the xor'd shift amount
9394 // so for now just use the PosOpcode case if its legal.
9395 // TODO: When can we use the NegOpcode case?
9396 if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
9397 SDValue X;
9398 // fold (or/add (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
9399 // -> (fshl x0, x1, y)
9400 if (sd_match(N1, m_Srl(m_Value(X), m_One())) &&
9401 sd_match(InnerNeg,
9402 m_Xor(m_Specific(InnerPos), m_SpecificInt(EltBits - 1))) &&
9404 return DAG.getNode(ISD::FSHL, DL, VT, N0, X, Pos);
9405 }
9406
9407 // fold (or/add (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
9408 // -> (fshr x0, x1, y)
9409 if (sd_match(N0, m_Shl(m_Value(X), m_One())) &&
9410 sd_match(InnerPos,
9411 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9413 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9414 }
9415
9416 // fold (or/add (shl (add x0, x0), (xor y, 31)), (srl x1, y))
9417 // -> (fshr x0, x1, y)
9418 // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
9419 if (sd_match(N0, m_Add(m_Value(X), m_Deferred(X))) &&
9420 sd_match(InnerPos,
9421 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9423 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9424 }
9425 }
9426
9427 return SDValue();
9428}
9429
9430// MatchRotate - Handle an 'or' or 'add' of two operands. If this is one of the
9431// many idioms for rotate, and if the target supports rotation instructions,
9432// generate a rot[lr]. This also matches funnel shift patterns, similar to
9433// rotation but with different shifted sources.
9434SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
9435 bool FromAdd) {
9436 EVT VT = LHS.getValueType();
9437
9438 // The target must have at least one rotate/funnel flavor.
9439 // We still try to match rotate by constant pre-legalization.
9440 // TODO: Support pre-legalization funnel-shift by constant.
9441 bool HasROTL = hasOperation(ISD::ROTL, VT);
9442 bool HasROTR = hasOperation(ISD::ROTR, VT);
9443 bool HasFSHL = hasOperation(ISD::FSHL, VT);
9444 bool HasFSHR = hasOperation(ISD::FSHR, VT);
9445
9446 // If the type is going to be promoted and the target has enabled custom
9447 // lowering for rotate, allow matching rotate by non-constants. Only allow
9448 // this for scalar types.
9449 if (VT.isScalarInteger() && TLI.getTypeAction(*DAG.getContext(), VT) ==
9453 }
9454
9455 if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9456 return SDValue();
9457
9458 // Check for truncated rotate.
9459 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
9460 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
9461 assert(LHS.getValueType() == RHS.getValueType());
9462 if (SDValue Rot =
9463 MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL, FromAdd))
9464 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
9465 }
9466
9467 // Match "(X shl/srl V1) & V2" where V2 may not be present.
9468 SDValue LHSShift; // The shift.
9469 SDValue LHSMask; // AND value if any.
9470 matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
9471
9472 SDValue RHSShift; // The shift.
9473 SDValue RHSMask; // AND value if any.
9474 matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
9475
9476 // If neither side matched a rotate half, bail
9477 if (!LHSShift && !RHSShift)
9478 return SDValue();
9479
9480 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
9481 // side of the rotate, so try to handle that here. In all cases we need to
9482 // pass the matched shift from the opposite side to compute the opcode and
9483 // needed shift amount to extract. We still want to do this if both sides
9484 // matched a rotate half because one half may be a potential overshift that
9485 // can be broken down (ie if InstCombine merged two shl or srl ops into a
9486 // single one).
9487
9488 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
9489 if (LHSShift)
9490 if (SDValue NewRHSShift =
9491 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
9492 RHSShift = NewRHSShift;
9493 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
9494 if (RHSShift)
9495 if (SDValue NewLHSShift =
9496 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
9497 LHSShift = NewLHSShift;
9498
9499 // If a side is still missing, nothing else we can do.
9500 if (!RHSShift || !LHSShift)
9501 return SDValue();
9502
9503 // At this point we've matched or extracted a shift op on each side.
9504
9505 if (LHSShift.getOpcode() == RHSShift.getOpcode())
9506 return SDValue(); // Shifts must disagree.
9507
9508 // Canonicalize shl to left side in a shl/srl pair.
9509 if (RHSShift.getOpcode() == ISD::SHL) {
9510 std::swap(LHS, RHS);
9511 std::swap(LHSShift, RHSShift);
9512 std::swap(LHSMask, RHSMask);
9513 }
9514
9515 // Something has gone wrong - we've lost the shl/srl pair - bail.
9516 if (LHSShift.getOpcode() != ISD::SHL || RHSShift.getOpcode() != ISD::SRL)
9517 return SDValue();
9518
9519 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9520 SDValue LHSShiftArg = LHSShift.getOperand(0);
9521 SDValue LHSShiftAmt = LHSShift.getOperand(1);
9522 SDValue RHSShiftArg = RHSShift.getOperand(0);
9523 SDValue RHSShiftAmt = RHSShift.getOperand(1);
9524
9525 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
9526 ConstantSDNode *RHS) {
9527 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
9528 };
9529
9530 auto ApplyMasks = [&](SDValue Res) {
9531 // If there is an AND of either shifted operand, apply it to the result.
9532 if (LHSMask.getNode() || RHSMask.getNode()) {
9535
9536 if (LHSMask.getNode()) {
9537 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
9538 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9539 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
9540 }
9541 if (RHSMask.getNode()) {
9542 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
9543 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9544 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
9545 }
9546
9547 Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
9548 }
9549
9550 return Res;
9551 };
9552
9553 // TODO: Support pre-legalization funnel-shift by constant.
9554 bool IsRotate = LHSShiftArg == RHSShiftArg;
9555 if (!IsRotate && !(HasFSHL || HasFSHR)) {
9556 if (TLI.isTypeLegal(VT) && LHS.hasOneUse() && RHS.hasOneUse() &&
9557 ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9558 // Look for a disguised rotate by constant.
9559 // The common shifted operand X may be hidden inside another 'or'.
9560 SDValue X, Y;
9561 auto matchOr = [&X, &Y](SDValue Or, SDValue CommonOp) {
9562 if (!Or.hasOneUse() || Or.getOpcode() != ISD::OR)
9563 return false;
9564 if (CommonOp == Or.getOperand(0)) {
9565 X = CommonOp;
9566 Y = Or.getOperand(1);
9567 return true;
9568 }
9569 if (CommonOp == Or.getOperand(1)) {
9570 X = CommonOp;
9571 Y = Or.getOperand(0);
9572 return true;
9573 }
9574 return false;
9575 };
9576
9577 SDValue Res;
9578 if (matchOr(LHSShiftArg, RHSShiftArg)) {
9579 // (shl (X | Y), C1) | (srl X, C2) --> (rotl X, C1) | (shl Y, C1)
9580 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9581 SDValue ShlY = DAG.getNode(ISD::SHL, DL, VT, Y, LHSShiftAmt);
9582 Res = DAG.getNode(ISD::OR, DL, VT, RotX, ShlY);
9583 } else if (matchOr(RHSShiftArg, LHSShiftArg)) {
9584 // (shl X, C1) | (srl (X | Y), C2) --> (rotl X, C1) | (srl Y, C2)
9585 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9586 SDValue SrlY = DAG.getNode(ISD::SRL, DL, VT, Y, RHSShiftAmt);
9587 Res = DAG.getNode(ISD::OR, DL, VT, RotX, SrlY);
9588 } else {
9589 return SDValue();
9590 }
9591
9592 return ApplyMasks(Res);
9593 }
9594
9595 return SDValue(); // Requires funnel shift support.
9596 }
9597
9598 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotl x, C1)
9599 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotr x, C2)
9600 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
9601 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
9602 // iff C1+C2 == EltSizeInBits
9603 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9604 SDValue Res;
9605 if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) {
9606 bool UseROTL = !LegalOperations || HasROTL;
9607 Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
9608 UseROTL ? LHSShiftAmt : RHSShiftAmt);
9609 } else {
9610 bool UseFSHL = !LegalOperations || HasFSHL;
9611 Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
9612 RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt);
9613 }
9614
9615 return ApplyMasks(Res);
9616 }
9617
9618 // Even pre-legalization, we can't easily rotate/funnel-shift by a variable
9619 // shift.
9620 if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9621 return SDValue();
9622
9623 // If there is a mask here, and we have a variable shift, we can't be sure
9624 // that we're masking out the right stuff.
9625 if (LHSMask.getNode() || RHSMask.getNode())
9626 return SDValue();
9627
9628 // If the shift amount is sign/zext/any-extended just peel it off.
9629 SDValue LExtOp0 = LHSShiftAmt;
9630 SDValue RExtOp0 = RHSShiftAmt;
9631 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9632 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9633 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9634 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
9635 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9636 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9637 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9638 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
9639 LExtOp0 = LHSShiftAmt.getOperand(0);
9640 RExtOp0 = RHSShiftAmt.getOperand(0);
9641 }
9642
9643 if (IsRotate && (HasROTL || HasROTR)) {
9644 if (SDValue TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
9645 LExtOp0, RExtOp0, FromAdd, HasROTL,
9647 return TryL;
9648
9649 if (SDValue TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
9650 RExtOp0, LExtOp0, FromAdd, HasROTR,
9652 return TryR;
9653 }
9654
9655 if (SDValue TryL = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt,
9656 RHSShiftAmt, LExtOp0, RExtOp0, FromAdd,
9657 HasFSHL, ISD::FSHL, ISD::FSHR, DL))
9658 return TryL;
9659
9660 if (SDValue TryR = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt,
9661 LHSShiftAmt, RExtOp0, LExtOp0, FromAdd,
9662 HasFSHR, ISD::FSHR, ISD::FSHL, DL))
9663 return TryR;
9664
9665 return SDValue();
9666}
9667
9668/// Recursively traverses the expression calculating the origin of the requested
9669/// byte of the given value. Returns std::nullopt if the provider can't be
9670/// calculated.
9671///
9672/// For all the values except the root of the expression, we verify that the
9673/// value has exactly one use and if not then return std::nullopt. This way if
9674/// the origin of the byte is returned it's guaranteed that the values which
9675/// contribute to the byte are not used outside of this expression.
9676
9677/// However, there is a special case when dealing with vector loads -- we allow
9678/// more than one use if the load is a vector type. Since the values that
9679/// contribute to the byte ultimately come from the ExtractVectorElements of the
9680/// Load, we don't care if the Load has uses other than ExtractVectorElements,
9681/// because those operations are independent from the pattern to be combined.
9682/// For vector loads, we simply care that the ByteProviders are adjacent
9683/// positions of the same vector, and their index matches the byte that is being
9684/// provided. This is captured by the \p VectorIndex algorithm. \p VectorIndex
9685/// is the index used in an ExtractVectorElement, and \p StartingIndex is the
9686/// byte position we are trying to provide for the LoadCombine. If these do
9687/// not match, then we can not combine the vector loads. \p Index uses the
9688/// byte position we are trying to provide for and is matched against the
9689/// shl and load size. The \p Index algorithm ensures the requested byte is
9690/// provided for by the pattern, and the pattern does not over provide bytes.
9691///
9692///
9693/// The supported LoadCombine pattern for vector loads is as follows
9694/// or
9695/// / \
9696/// or shl
9697/// / \ |
9698/// or shl zext
9699/// / \ | |
9700/// shl zext zext EVE*
9701/// | | | |
9702/// zext EVE* EVE* LOAD
9703/// | | |
9704/// EVE* LOAD LOAD
9705/// |
9706/// LOAD
9707///
9708/// *ExtractVectorElement
9710
9711static std::optional<SDByteProvider>
9712calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
9713 std::optional<uint64_t> VectorIndex,
9714 unsigned StartingIndex = 0,
9715 MutableArrayRef<uint8_t> ByteMask = {}) {
9716
9717 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
9718 if (Depth == 10)
9719 return std::nullopt;
9720
9721 // Only allow multiple uses if the instruction is a vector load (in which
9722 // case we will use the load for every ExtractVectorElement)
9723 if (Depth && !Op.hasOneUse() &&
9724 (Op.getOpcode() != ISD::LOAD || !Op.getValueType().isVector()))
9725 return std::nullopt;
9726
9727 // Fail to combine if we have encountered anything but a LOAD after handling
9728 // an ExtractVectorElement.
9729 if (Op.getOpcode() != ISD::LOAD && VectorIndex.has_value())
9730 return std::nullopt;
9731
9732 unsigned BitWidth = Op.getScalarValueSizeInBits();
9733 if (BitWidth % 8 != 0)
9734 return std::nullopt;
9735 unsigned ByteWidth = BitWidth / 8;
9736 assert(Index < ByteWidth && "invalid index requested");
9737 (void) ByteWidth;
9738
9739 switch (Op.getOpcode()) {
9740 case ISD::OR: {
9741 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
9742 VectorIndex, StartingIndex, ByteMask);
9743 if (!LHS)
9744 return std::nullopt;
9745 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1,
9746 VectorIndex, StartingIndex, ByteMask);
9747 if (!RHS)
9748 return std::nullopt;
9749
9750 if (LHS->isConstantZero())
9751 return RHS;
9752 if (RHS->isConstantZero())
9753 return LHS;
9754 return std::nullopt;
9755 }
9756 case ISD::SHL: {
9757 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9758 if (!ShiftOp)
9759 return std::nullopt;
9760
9761 uint64_t BitShift = ShiftOp->getZExtValue();
9762
9763 if (BitShift % 8 != 0)
9764 return std::nullopt;
9765 uint64_t ByteShift = BitShift / 8;
9766
9767 // If we are shifting by an amount greater than the index we are trying to
9768 // provide, then do not provide anything. Otherwise, subtract the index by
9769 // the amount we shifted by.
9770 return Index < ByteShift
9772 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
9773 Depth + 1, VectorIndex, Index, ByteMask);
9774 }
9775 case ISD::ANY_EXTEND:
9776 case ISD::SIGN_EXTEND:
9777 case ISD::ZERO_EXTEND: {
9778 SDValue NarrowOp = Op->getOperand(0);
9779 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9780 if (NarrowBitWidth % 8 != 0)
9781 return std::nullopt;
9782 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9783
9784 if (Index >= NarrowByteWidth)
9785 return Op.getOpcode() == ISD::ZERO_EXTEND
9786 ? std::optional<SDByteProvider>(
9788 : std::nullopt;
9789 return calculateByteProvider(NarrowOp, Index, Depth + 1, VectorIndex,
9790 StartingIndex, ByteMask);
9791 }
9792 case ISD::BSWAP:
9793 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
9794 Depth + 1, VectorIndex, StartingIndex,
9795 ByteMask);
9796 case ISD::AND: {
9797 // Constants are canonicalized to the RHS of AND, so only operand 1 needs
9798 // to be checked.
9799 auto *MaskOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9800 if (!MaskOp)
9801 return std::nullopt;
9802
9803 uint8_t MaskByte =
9804 MaskOp->getAPIntValue().extractBitsAsZExtValue(8, Index * 8);
9805
9806 if (MaskByte == 0x00)
9808
9809 auto Result = calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
9810 VectorIndex, StartingIndex, ByteMask);
9811 if (!Result)
9812 return std::nullopt;
9813
9814 // Only record the mask if this byte is actually provided (not zero).
9815 // A ConstantZero result may be discarded by the OR handler in favor of
9816 // the other operand, so writing the mask here would corrupt ByteMask.
9817 if (MaskByte != 0xFF && !ByteMask.empty() && !Result->isConstantZero())
9818 ByteMask[StartingIndex] &= MaskByte;
9819
9820 return Result;
9821 }
9823 auto OffsetOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9824 if (!OffsetOp)
9825 return std::nullopt;
9826
9827 VectorIndex = OffsetOp->getZExtValue();
9828
9829 SDValue NarrowOp = Op->getOperand(0);
9830 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9831 if (NarrowBitWidth % 8 != 0)
9832 return std::nullopt;
9833 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9834 // EXTRACT_VECTOR_ELT can extend the element type to the width of the return
9835 // type, leaving the high bits undefined.
9836 if (Index >= NarrowByteWidth)
9837 return std::nullopt;
9838
9839 // Check to see if the position of the element in the vector corresponds
9840 // with the byte we are trying to provide for. In the case of a vector of
9841 // i8, this simply means the VectorIndex == StartingIndex. For non i8 cases,
9842 // the element will provide a range of bytes. For example, if we have a
9843 // vector of i16s, each element provides two bytes (V[1] provides byte 2 and
9844 // 3).
9845 if (*VectorIndex * NarrowByteWidth > StartingIndex)
9846 return std::nullopt;
9847 if ((*VectorIndex + 1) * NarrowByteWidth <= StartingIndex)
9848 return std::nullopt;
9849
9850 return calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
9851 VectorIndex, StartingIndex, ByteMask);
9852 }
9853 case ISD::LOAD: {
9854 auto L = cast<LoadSDNode>(Op.getNode());
9855 if (!L->isSimple() || L->isIndexed())
9856 return std::nullopt;
9857
9858 unsigned NarrowBitWidth = L->getMemoryVT().getScalarSizeInBits();
9859 if (NarrowBitWidth % 8 != 0)
9860 return std::nullopt;
9861 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9862
9863 // If the width of the load does not reach byte we are trying to provide for
9864 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
9865 // question
9866 if (Index >= NarrowByteWidth)
9867 return L->getExtensionType() == ISD::ZEXTLOAD
9868 ? std::optional<SDByteProvider>(
9870 : std::nullopt;
9871
9872 unsigned BPVectorIndex = VectorIndex.value_or(0U);
9873 return SDByteProvider::getSrc(L, Index, BPVectorIndex);
9874 }
9875 }
9876
9877 return std::nullopt;
9878}
9879
9880static unsigned littleEndianByteAt(unsigned BW, unsigned i) {
9881 return i;
9882}
9883
9884static unsigned bigEndianByteAt(unsigned BW, unsigned i) {
9885 return BW - i - 1;
9886}
9887
9888// Check if the bytes offsets we are looking at match with either big or
9889// little endian value loaded. Return true for big endian, false for little
9890// endian, and std::nullopt if match failed.
9891static std::optional<bool> isBigEndian(ArrayRef<int64_t> ByteOffsets,
9892 int64_t FirstOffset) {
9893 // The endian can be decided only when it is 2 bytes at least.
9894 unsigned Width = ByteOffsets.size();
9895 if (Width < 2)
9896 return std::nullopt;
9897
9898 bool BigEndian = true, LittleEndian = true;
9899 for (unsigned i = 0; i < Width; i++) {
9900 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
9901 LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i);
9902 BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i);
9903 if (!BigEndian && !LittleEndian)
9904 return std::nullopt;
9905 }
9906
9907 assert((BigEndian != LittleEndian) && "It should be either big endian or"
9908 "little endian");
9909 return BigEndian;
9910}
9911
9912// Look through one layer of truncate or extend.
9914 switch (Value.getOpcode()) {
9915 case ISD::TRUNCATE:
9916 case ISD::ZERO_EXTEND:
9917 case ISD::SIGN_EXTEND:
9918 case ISD::ANY_EXTEND:
9919 return Value.getOperand(0);
9920 }
9921 return SDValue();
9922}
9923
9924/// Match a pattern where a wide type scalar value is stored by several narrow
9925/// stores. Fold it into a single store or a BSWAP and a store if the targets
9926/// supports it.
9927///
9928/// Assuming little endian target:
9929/// i8 *p = ...
9930/// i32 val = ...
9931/// p[0] = (val >> 0) & 0xFF;
9932/// p[1] = (val >> 8) & 0xFF;
9933/// p[2] = (val >> 16) & 0xFF;
9934/// p[3] = (val >> 24) & 0xFF;
9935/// =>
9936/// *((i32)p) = val;
9937///
9938/// i8 *p = ...
9939/// i32 val = ...
9940/// p[0] = (val >> 24) & 0xFF;
9941/// p[1] = (val >> 16) & 0xFF;
9942/// p[2] = (val >> 8) & 0xFF;
9943/// p[3] = (val >> 0) & 0xFF;
9944/// =>
9945/// *((i32)p) = BSWAP(val);
9946SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) {
9947 // The matching looks for "store (trunc x)" patterns that appear early but are
9948 // likely to be replaced by truncating store nodes during combining.
9949 // TODO: If there is evidence that running this later would help, this
9950 // limitation could be removed. Legality checks may need to be added
9951 // for the created store and optional bswap/rotate.
9952 if (LegalOperations || OptLevel == CodeGenOptLevel::None)
9953 return SDValue();
9954
9955 // We only handle merging simple stores of 1-4 bytes.
9956 // TODO: Allow unordered atomics when wider type is legal (see D66309)
9957 EVT MemVT = N->getMemoryVT();
9958 if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) ||
9959 !N->isSimple() || N->isIndexed())
9960 return SDValue();
9961
9962 // Collect all of the stores in the chain, upto the maximum store width (i64).
9963 SDValue Chain = N->getChain();
9965 unsigned NarrowNumBits = MemVT.getScalarSizeInBits();
9966 unsigned MaxWideNumBits = 64;
9967 unsigned MaxStores = MaxWideNumBits / NarrowNumBits;
9968 while (auto *Store = dyn_cast<StoreSDNode>(Chain)) {
9969 // All stores must be the same size to ensure that we are writing all of the
9970 // bytes in the wide value.
9971 // This store should have exactly one use as a chain operand for another
9972 // store in the merging set. If there are other chain uses, then the
9973 // transform may not be safe because order of loads/stores outside of this
9974 // set may not be preserved.
9975 // TODO: We could allow multiple sizes by tracking each stored byte.
9976 if (Store->getMemoryVT() != MemVT || !Store->isSimple() ||
9977 Store->isIndexed() || !Store->hasOneUse())
9978 return SDValue();
9979 Stores.push_back(Store);
9980 Chain = Store->getChain();
9981 if (MaxStores < Stores.size())
9982 return SDValue();
9983 }
9984 // There is no reason to continue if we do not have at least a pair of stores.
9985 if (Stores.size() < 2)
9986 return SDValue();
9987
9988 // Handle simple types only.
9989 LLVMContext &Context = *DAG.getContext();
9990 unsigned NumStores = Stores.size();
9991 unsigned WideNumBits = NumStores * NarrowNumBits;
9992 if (WideNumBits != 16 && WideNumBits != 32 && WideNumBits != 64)
9993 return SDValue();
9994
9995 // Check if all bytes of the source value that we are looking at are stored
9996 // to the same base address. Collect offsets from Base address into OffsetMap.
9997 SDValue SourceValue;
9998 SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX);
9999 int64_t FirstOffset = INT64_MAX;
10000 StoreSDNode *FirstStore = nullptr;
10001 std::optional<BaseIndexOffset> Base;
10002 for (auto *Store : Stores) {
10003 // All the stores store different parts of the CombinedValue. A truncate is
10004 // required to get the partial value.
10005 SDValue Trunc = Store->getValue();
10006 if (Trunc.getOpcode() != ISD::TRUNCATE)
10007 return SDValue();
10008 // Other than the first/last part, a shift operation is required to get the
10009 // offset.
10010 int64_t Offset = 0;
10011 SDValue WideVal = Trunc.getOperand(0);
10012 if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) &&
10013 isa<ConstantSDNode>(WideVal.getOperand(1))) {
10014 // The shift amount must be a constant multiple of the narrow type.
10015 // It is translated to the offset address in the wide source value "y".
10016 //
10017 // x = srl y, ShiftAmtC
10018 // i8 z = trunc x
10019 // store z, ...
10020 uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1);
10021 if (ShiftAmtC % NarrowNumBits != 0)
10022 return SDValue();
10023
10024 // Make sure we aren't reading bits that are shifted in.
10025 if (ShiftAmtC > WideVal.getScalarValueSizeInBits() - NarrowNumBits)
10026 return SDValue();
10027
10028 Offset = ShiftAmtC / NarrowNumBits;
10029 WideVal = WideVal.getOperand(0);
10030 }
10031
10032 // Stores must share the same source value with different offsets.
10033 if (!SourceValue)
10034 SourceValue = WideVal;
10035 else if (SourceValue != WideVal) {
10036 // Truncate and extends can be stripped to see if the values are related.
10037 if (stripTruncAndExt(SourceValue) != WideVal &&
10038 stripTruncAndExt(WideVal) != SourceValue)
10039 return SDValue();
10040
10041 if (WideVal.getScalarValueSizeInBits() >
10042 SourceValue.getScalarValueSizeInBits())
10043 SourceValue = WideVal;
10044
10045 // Give up if the source value type is smaller than the store size.
10046 if (SourceValue.getScalarValueSizeInBits() < WideNumBits)
10047 return SDValue();
10048 }
10049
10050 // Stores must share the same base address.
10051 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
10052 int64_t ByteOffsetFromBase = 0;
10053 if (!Base)
10054 Base = Ptr;
10055 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
10056 return SDValue();
10057
10058 // Remember the first store.
10059 if (ByteOffsetFromBase < FirstOffset) {
10060 FirstStore = Store;
10061 FirstOffset = ByteOffsetFromBase;
10062 }
10063 // Map the offset in the store and the offset in the combined value, and
10064 // early return if it has been set before.
10065 if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX)
10066 return SDValue();
10067 OffsetMap[Offset] = ByteOffsetFromBase;
10068 }
10069
10070 EVT WideVT = EVT::getIntegerVT(Context, WideNumBits);
10071
10072 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
10073 assert(FirstStore && "First store must be set");
10074
10075 // Check that a store of the wide type is both allowed and fast on the target
10076 const DataLayout &Layout = DAG.getDataLayout();
10077 unsigned Fast = 0;
10078 bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT,
10079 *FirstStore->getMemOperand(), &Fast);
10080 if (!Allowed || !Fast)
10081 return SDValue();
10082
10083 // Check if the pieces of the value are going to the expected places in memory
10084 // to merge the stores.
10085 auto checkOffsets = [&](bool MatchLittleEndian) {
10086 if (MatchLittleEndian) {
10087 for (unsigned i = 0; i != NumStores; ++i)
10088 if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset)
10089 return false;
10090 } else { // MatchBigEndian by reversing loop counter.
10091 for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j)
10092 if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset)
10093 return false;
10094 }
10095 return true;
10096 };
10097
10098 // Check if the offsets line up for the native data layout of this target.
10099 bool NeedBswap = false;
10100 bool NeedRotate = false;
10101 if (!checkOffsets(Layout.isLittleEndian())) {
10102 // Special-case: check if byte offsets line up for the opposite endian.
10103 if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian()))
10104 NeedBswap = true;
10105 else if (NumStores == 2 && checkOffsets(Layout.isBigEndian()))
10106 NeedRotate = true;
10107 else
10108 return SDValue();
10109 }
10110
10111 SDLoc DL(N);
10112 if (WideVT != SourceValue.getValueType()) {
10113 assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&
10114 "Unexpected store value to merge");
10115 SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue);
10116 }
10117
10118 // Before legalize we can introduce illegal bswaps/rotates which will be later
10119 // converted to an explicit bswap sequence. This way we end up with a single
10120 // store and byte shuffling instead of several stores and byte shuffling.
10121 if (NeedBswap) {
10122 SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue);
10123 } else if (NeedRotate) {
10124 assert(WideNumBits % 2 == 0 && "Unexpected type for rotate");
10125 SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT);
10126 SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt);
10127 }
10128
10129 SDValue NewStore =
10130 DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(),
10131 FirstStore->getPointerInfo(), FirstStore->getAlign());
10132
10133 // Rely on other DAG combine rules to remove the other individual stores.
10134 DAG.ReplaceAllUsesWith(N, NewStore.getNode());
10135 return NewStore;
10136}
10137
10138/// Match a pattern where a wide type scalar value is loaded by several narrow
10139/// loads and combined by shifts and ors. Fold it into a single load or a load
10140/// and a BSWAP if the targets supports it.
10141///
10142/// Assuming little endian target:
10143/// i8 *a = ...
10144/// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
10145/// =>
10146/// i32 val = *((i32)a)
10147///
10148/// i8 *a = ...
10149/// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
10150/// =>
10151/// i32 val = BSWAP(*((i32)a))
10152///
10153/// TODO: This rule matches complex patterns with OR node roots and doesn't
10154/// interact well with the worklist mechanism. When a part of the pattern is
10155/// updated (e.g. one of the loads) its direct users are put into the worklist,
10156/// but the root node of the pattern which triggers the load combine is not
10157/// necessarily a direct user of the changed node. For example, once the address
10158/// of t28 load is reassociated load combine won't be triggered:
10159/// t25: i32 = add t4, Constant:i32<2>
10160/// t26: i64 = sign_extend t25
10161/// t27: i64 = add t2, t26
10162/// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
10163/// t29: i32 = zero_extend t28
10164/// t32: i32 = shl t29, Constant:i8<8>
10165/// t33: i32 = or t23, t32
10166/// As a possible fix visitLoad can check if the load can be a part of a load
10167/// combine pattern and add corresponding OR roots to the worklist.
10168SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
10169 assert(N->getOpcode() == ISD::OR &&
10170 "Can only match load combining against OR nodes");
10171
10172 // Handles simple types only
10173 EVT VT = N->getValueType(0);
10174 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10175 return SDValue();
10176 unsigned ByteWidth = VT.getSizeInBits() / 8;
10177
10178 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
10179 auto MemoryByteOffset = [&](SDByteProvider P) {
10180 assert(P.hasSrc() && "Must be a memory byte provider");
10181 auto *Load = cast<LoadSDNode>(P.Src.value());
10182
10183 unsigned LoadBitWidth = Load->getMemoryVT().getScalarSizeInBits();
10184
10185 assert(LoadBitWidth % 8 == 0 &&
10186 "can only analyze providers for individual bytes not bit");
10187 unsigned LoadByteWidth = LoadBitWidth / 8;
10188 return IsBigEndianTarget ? bigEndianByteAt(LoadByteWidth, P.DestOffset)
10189 : littleEndianByteAt(LoadByteWidth, P.DestOffset);
10190 };
10191
10192 std::optional<BaseIndexOffset> Base;
10193 SDValue Chain;
10194
10195 SmallPtrSet<LoadSDNode *, 8> Loads;
10196 std::optional<SDByteProvider> FirstByteProvider;
10197 int64_t FirstOffset = INT64_MAX;
10198
10199 // Check if all the bytes of the OR we are looking at are loaded from the same
10200 // base address. Collect bytes offsets from Base address in ByteOffsets.
10201 SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
10202 SmallVector<uint8_t, 8> ByteMasks(ByteWidth, 0xFF);
10203 unsigned ZeroExtendedBytes = 0;
10204 for (int i = ByteWidth - 1; i >= 0; --i) {
10205 auto P =
10206 calculateByteProvider(SDValue(N, 0), i, 0, /*VectorIndex*/ std::nullopt,
10207 /*StartingIndex*/ i, ByteMasks);
10208 if (!P)
10209 return SDValue();
10210
10211 if (P->isConstantZero()) {
10212 // It's OK for the N most significant bytes to be 0, we can just
10213 // zero-extend the load.
10214 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
10215 return SDValue();
10216 continue;
10217 }
10218 assert(P->hasSrc() && "provenance should either be memory or zero");
10219 auto *L = cast<LoadSDNode>(P->Src.value());
10220
10221 // All loads must share the same chain
10222 SDValue LChain = L->getChain();
10223 if (!Chain)
10224 Chain = LChain;
10225 else if (Chain != LChain)
10226 return SDValue();
10227
10228 // Loads must share the same base address
10229 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
10230 int64_t ByteOffsetFromBase = 0;
10231
10232 // For vector loads, the expected load combine pattern will have an
10233 // ExtractElement for each index in the vector. While each of these
10234 // ExtractElements will be accessing the same base address as determined
10235 // by the load instruction, the actual bytes they interact with will differ
10236 // due to different ExtractElement indices. To accurately determine the
10237 // byte position of an ExtractElement, we offset the base load ptr with
10238 // the index multiplied by the byte size of each element in the vector.
10239 if (L->getMemoryVT().isVector()) {
10240 unsigned LoadWidthInBit = L->getMemoryVT().getScalarSizeInBits();
10241 if (LoadWidthInBit % 8 != 0)
10242 return SDValue();
10243 unsigned ByteOffsetFromVector = P->SrcOffset * LoadWidthInBit / 8;
10244 Ptr.addToOffset(ByteOffsetFromVector);
10245 }
10246
10247 if (!Base)
10248 Base = Ptr;
10249
10250 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
10251 return SDValue();
10252
10253 // Calculate the offset of the current byte from the base address
10254 ByteOffsetFromBase += MemoryByteOffset(*P);
10255 ByteOffsets[i] = ByteOffsetFromBase;
10256
10257 // Remember the first byte load
10258 if (ByteOffsetFromBase < FirstOffset) {
10259 FirstByteProvider = P;
10260 FirstOffset = ByteOffsetFromBase;
10261 }
10262
10263 Loads.insert(L);
10264 }
10265
10266 assert(!Loads.empty() && "All the bytes of the value must be loaded from "
10267 "memory, so there must be at least one load which produces the value");
10268 assert(Base && "Base address of the accessed memory location must be set");
10269 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
10270
10271 bool NeedsZext = ZeroExtendedBytes > 0;
10272
10273 EVT MemVT =
10274 EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
10275
10276 if (!MemVT.isSimple())
10277 return SDValue();
10278
10279 // Check if the bytes of the OR we are looking at match with either big or
10280 // little endian value load
10281 std::optional<bool> IsBigEndian = isBigEndian(
10282 ArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
10283 if (!IsBigEndian)
10284 return SDValue();
10285
10286 assert(FirstByteProvider && "must be set");
10287
10288 // Ensure that the first byte is loaded from zero offset of the first load.
10289 // So the combined value can be loaded from the first load address.
10290 if (MemoryByteOffset(*FirstByteProvider) != 0)
10291 return SDValue();
10292 auto *FirstLoad = cast<LoadSDNode>(FirstByteProvider->Src.value());
10293
10294 // Before legalization we allow introducing loads that are wider than legal,
10295 // which will later be split into legally sized loads. This enables us to
10296 // combine, for example, i8 loads forming an i64 into an i64 load, which get
10297 // then gets split up into couple of i32 loads on 32 bit targets.
10298 if (LegalOperations &&
10299 !TLI.isLoadLegal(VT, MemVT, FirstLoad->getAlign(),
10300 FirstLoad->getAddressSpace(),
10301 NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, false))
10302 return SDValue();
10303
10304 // The node we are looking at matches with the pattern, check if we can
10305 // replace it with a single (possibly zero-extended) load and bswap + shift if
10306 // needed.
10307
10308 // If the load needs byte swap check if the target supports it
10309 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
10310
10311 // Before legalize we can introduce illegal bswaps which will be later
10312 // converted to an explicit bswap sequence. This way we end up with a single
10313 // load and byte shuffling instead of several loads and byte shuffling.
10314 // We do not introduce illegal bswaps when zero-extending as this tends to
10315 // introduce too many arithmetic instructions.
10316 if (NeedsBswap && (LegalOperations || NeedsZext) &&
10317 !TLI.isOperationLegal(ISD::BSWAP, VT))
10318 return SDValue();
10319
10320 // If we need to bswap and zero extend, we have to insert a shift. Check that
10321 // it is legal.
10322 if (NeedsBswap && NeedsZext && LegalOperations &&
10323 !TLI.isOperationLegal(ISD::SHL, VT))
10324 return SDValue();
10325
10326 // Check that a load of the wide type is both allowed and fast on the target
10327 unsigned Fast = 0;
10328 bool Allowed =
10329 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
10330 *FirstLoad->getMemOperand(), &Fast);
10331 if (!Allowed || !Fast)
10332 return SDValue();
10333
10334 SDValue NewLoad =
10335 DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT,
10336 Chain, FirstLoad->getBasePtr(),
10337 FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign());
10338
10339 // Transfer chain users from old loads to the new load.
10340 for (LoadSDNode *L : Loads)
10341 DAG.makeEquivalentMemoryOrdering(L, NewLoad);
10342
10343 // Apply combined mask if any bytes were partially masked by AND operations.
10344 bool HasPartialMask = false;
10345 uint64_t CombinedMask = 0;
10346 for (unsigned i = 0; i < ByteWidth; ++i) {
10347 CombinedMask |= (uint64_t)ByteMasks[i] << (i * 8);
10348 if (ByteMasks[i] != 0xFF)
10349 HasPartialMask = true;
10350 }
10351
10352 if (!NeedsBswap) {
10353 if (HasPartialMask)
10354 NewLoad = DAG.getNode(ISD::AND, SDLoc(N), VT, NewLoad,
10355 DAG.getConstant(CombinedMask, SDLoc(N), VT));
10356 return NewLoad;
10357 }
10358
10359 SDValue ShiftedLoad =
10360 NeedsZext ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
10361 DAG.getShiftAmountConstant(ZeroExtendedBytes * 8,
10362 VT, SDLoc(N)))
10363 : NewLoad;
10364 SDValue Result = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
10365
10366 // The mask is built in final-result byte order (ByteMasks[i] corresponds to
10367 // byte i of the result), so it is correct to apply after the bswap.
10368 if (HasPartialMask)
10369 Result = DAG.getNode(ISD::AND, SDLoc(N), VT, Result,
10370 DAG.getConstant(CombinedMask, SDLoc(N), VT));
10371
10372 return Result;
10373}
10374
10375// If the target has andn, bsl, or a similar bit-select instruction,
10376// we want to unfold masked merge, with canonical pattern of:
10377// | A | |B|
10378// ((x ^ y) & m) ^ y
10379// | D |
10380// Into:
10381// (x & m) | (y & ~m)
10382// If y is a constant, m is not a 'not', and the 'andn' does not work with
10383// immediates, we unfold into a different pattern:
10384// ~(~x & m) & (m | y)
10385// If x is a constant, m is a 'not', and the 'andn' does not work with
10386// immediates, we unfold into a different pattern:
10387// (x | ~m) & ~(~m & ~y)
10388// NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
10389// the very least that breaks andnpd / andnps patterns, and because those
10390// patterns are simplified in IR and shouldn't be created in the DAG
10391SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
10392 assert(N->getOpcode() == ISD::XOR);
10393
10394 // Don't touch 'not' (i.e. where y = -1).
10395 if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
10396 return SDValue();
10397
10398 EVT VT = N->getValueType(0);
10399
10400 // There are 3 commutable operators in the pattern,
10401 // so we have to deal with 8 possible variants of the basic pattern.
10402 SDValue X, Y, M;
10403 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
10404 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
10405 return false;
10406 SDValue Xor = And.getOperand(XorIdx);
10407 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
10408 return false;
10409 SDValue Xor0 = Xor.getOperand(0);
10410 SDValue Xor1 = Xor.getOperand(1);
10411 // Don't touch 'not' (i.e. where y = -1).
10412 if (isAllOnesOrAllOnesSplat(Xor1))
10413 return false;
10414 if (Other == Xor0)
10415 std::swap(Xor0, Xor1);
10416 if (Other != Xor1)
10417 return false;
10418 X = Xor0;
10419 Y = Xor1;
10420 M = And.getOperand(XorIdx ? 0 : 1);
10421 return true;
10422 };
10423
10424 SDValue N0 = N->getOperand(0);
10425 SDValue N1 = N->getOperand(1);
10426 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
10427 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
10428 return SDValue();
10429
10430 // Don't do anything if the mask is constant. This should not be reachable.
10431 // InstCombine should have already unfolded this pattern, and DAGCombiner
10432 // probably shouldn't produce it, too.
10433 if (isa<ConstantSDNode>(M.getNode()))
10434 return SDValue();
10435
10436 // We can transform if the target has AndNot
10437 if (!TLI.hasAndNot(M))
10438 return SDValue();
10439
10440 SDLoc DL(N);
10441
10442 // If Y is a constant, check that 'andn' works with immediates. Unless M is
10443 // a bitwise not that would already allow ANDN to be used.
10444 if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) {
10445 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
10446 // If not, we need to do a bit more work to make sure andn is still used.
10447 SDValue NotX = DAG.getNOT(DL, X, VT);
10448 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
10449 SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
10450 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
10451 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
10452 }
10453
10454 // If X is a constant and M is a bitwise not, check that 'andn' works with
10455 // immediates.
10456 if (!TLI.hasAndNot(X) && isBitwiseNot(M)) {
10457 assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable.");
10458 // If not, we need to do a bit more work to make sure andn is still used.
10459 SDValue NotM = M.getOperand(0);
10460 SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM);
10461 SDValue NotY = DAG.getNOT(DL, Y, VT);
10462 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY);
10463 SDValue NotRHS = DAG.getNOT(DL, RHS, VT);
10464 return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS);
10465 }
10466
10467 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
10468 SDValue NotM = DAG.getNOT(DL, M, VT);
10469 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
10470
10471 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
10472}
10473
10474SDValue DAGCombiner::visitXOR(SDNode *N) {
10475 SDValue N0 = N->getOperand(0);
10476 SDValue N1 = N->getOperand(1);
10477 EVT VT = N0.getValueType();
10478 SDLoc DL(N);
10479
10480 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
10481 if (N0.isUndef() && N1.isUndef())
10482 return DAG.getConstant(0, DL, VT);
10483
10484 // fold (xor x, undef) -> undef
10485 if (N0.isUndef())
10486 return N0;
10487 if (N1.isUndef())
10488 return N1;
10489
10490 // fold (xor c1, c2) -> c1^c2
10491 if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
10492 return C;
10493
10494 // canonicalize constant to RHS
10497 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
10498
10499 // fold vector ops
10500 if (VT.isVector()) {
10501 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
10502 return FoldedVOp;
10503
10504 // fold (xor x, 0) -> x, vector edition
10506 return N0;
10507 }
10508
10509 // fold (xor x, 0) -> x
10510 if (isNullConstant(N1))
10511 return N0;
10512
10513 if (SDValue NewSel = foldBinOpIntoSelect(N))
10514 return NewSel;
10515
10516 // reassociate xor
10517 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
10518 return RXOR;
10519
10520 // Fold xor(vecreduce(x), vecreduce(y)) -> vecreduce(xor(x, y))
10521 if (SDValue SD =
10522 reassociateReduction(ISD::VECREDUCE_XOR, ISD::XOR, DL, VT, N0, N1))
10523 return SD;
10524
10525 // fold (a^b) -> (a|b) iff a and b share no bits.
10526 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
10527 DAG.haveNoCommonBitsSet(N0, N1))
10528 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
10529
10530 // look for 'add-like' folds:
10531 // XOR(N0,MIN_SIGNED_VALUE) == ADD(N0,MIN_SIGNED_VALUE)
10532 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
10534 if (SDValue Combined = visitADDLike(N))
10535 return Combined;
10536
10537 // fold not (setcc x, y, cc) -> setcc x y !cc
10538 // Avoid breaking: and (not(setcc x, y, cc), z) -> andn for vec
10539 unsigned N0Opcode = N0.getOpcode();
10540 SDValue LHS, RHS, CC;
10541 if (TLI.isConstTrueVal(N1) &&
10542 isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/ true) &&
10543 !(VT.isVector() && TLI.hasAndNot(SDValue(N, 0)) && N->hasOneUse() &&
10544 N->use_begin()->getUser()->getOpcode() == ISD::AND)) {
10546 LHS.getValueType());
10547 if (!LegalOperations ||
10548 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
10549 // Propagate fast-math-flags.
10550 SDNodeFlags Flags = N0->getFlags();
10551 switch (N0Opcode) {
10552 default:
10553 llvm_unreachable("Unhandled SetCC Equivalent!");
10554 case ISD::SETCC:
10555 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, SDValue(),
10556 /*IsSignaling=*/false, Flags);
10557 case ISD::SELECT_CC:
10558 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
10559 N0.getOperand(3), NotCC, Flags);
10560 case ISD::STRICT_FSETCC:
10561 case ISD::STRICT_FSETCCS: {
10562 if (N0.hasOneUse()) {
10563 // FIXME Can we handle multiple uses? Could we token factor the chain
10564 // results from the new/old setcc?
10565 SDValue SetCC =
10566 DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, N0.getOperand(0),
10567 N0Opcode == ISD::STRICT_FSETCCS, Flags);
10568 CombineTo(N, SetCC);
10569 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
10570 recursivelyDeleteUnusedNodes(N0.getNode());
10571 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10572 }
10573 break;
10574 }
10575 }
10576 }
10577 }
10578
10579 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
10580 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
10581 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
10582 SDValue V = N0.getOperand(0);
10583 SDLoc DL0(N0);
10584 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
10585 DAG.getConstant(1, DL0, V.getValueType()));
10586 AddToWorklist(V.getNode());
10587 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
10588 }
10589
10590 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
10591 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are setcc
10592 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
10593 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10594 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10595 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
10596 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10597 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10598 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10599 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10600 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10601 }
10602 }
10603 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
10604 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are constants
10605 if (isAllOnesConstant(N1) && N0.hasOneUse() &&
10606 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10607 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10608 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
10609 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10610 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10611 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10612 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10613 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10614 }
10615 }
10616
10617 // fold (not (sub Y, X)) -> (add X, ~Y) if Y is a constant
10618 if (N0.getOpcode() == ISD::SUB && isAllOnesConstant(N1)) {
10619 SDValue Y = N0.getOperand(0);
10620 SDValue X = N0.getOperand(1);
10621
10622 if (auto *YConst = dyn_cast<ConstantSDNode>(Y)) {
10623 APInt NotYValue = ~YConst->getAPIntValue();
10624 SDValue NotY = DAG.getConstant(NotYValue, DL, VT);
10625 return DAG.getNode(ISD::ADD, DL, VT, X, NotY, N->getFlags());
10626 }
10627 }
10628
10629 // fold (not (add X, -1)) -> (neg X)
10630 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && isAllOnesConstant(N1) &&
10632 return DAG.getNegative(N0.getOperand(0), DL, VT);
10633 }
10634
10635 // fold (xor (and x, y), y) -> (and (not x), y)
10636 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
10637 SDValue X = N0.getOperand(0);
10638 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
10639 AddToWorklist(NotX.getNode());
10640 return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
10641 }
10642
10643 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
10644 if (!LegalOperations || hasOperation(ISD::ABS, VT)) {
10645 SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
10646 SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
10647 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
10648 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
10649 SDValue S0 = S.getOperand(0);
10650 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0))
10651 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
10652 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
10653 return DAG.getNode(ISD::ABS, DL, VT, S0);
10654 }
10655 }
10656
10657 // fold (xor x, x) -> 0
10658 if (N0 == N1)
10659 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
10660
10661 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
10662 // Here is a concrete example of this equivalence:
10663 // i16 x == 14
10664 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
10665 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
10666 //
10667 // =>
10668 //
10669 // i16 ~1 == 0b1111111111111110
10670 // i16 rol(~1, 14) == 0b1011111111111111
10671 //
10672 // Some additional tips to help conceptualize this transform:
10673 // - Try to see the operation as placing a single zero in a value of all ones.
10674 // - There exists no value for x which would allow the result to contain zero.
10675 // - Values of x larger than the bitwidth are undefined and do not require a
10676 // consistent result.
10677 // - Pushing the zero left requires shifting one bits in from the right.
10678 // A rotate left of ~1 is a nice way of achieving the desired result.
10679 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
10681 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getSignedConstant(~1, DL, VT),
10682 N0.getOperand(1));
10683 }
10684
10685 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
10686 if (N0Opcode == N1.getOpcode())
10687 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
10688 return V;
10689
10690 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
10691 return R;
10692 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
10693 return R;
10694 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
10695 return R;
10696
10697 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
10698 if (SDValue MM = unfoldMaskedMerge(N))
10699 return MM;
10700
10701 // Simplify the expression using non-local knowledge.
10703 return SDValue(N, 0);
10704
10705 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
10706 return Combined;
10707
10708 // fold (xor (smin(x, C), C)) -> select (x < C), xor(x, C), 0
10709 // fold (xor (smax(x, C), C)) -> select (x > C), xor(x, C), 0
10710 // fold (xor (umin(x, C), C)) -> select (x < C), xor(x, C), 0
10711 // fold (xor (umax(x, C), C)) -> select (x > C), xor(x, C), 0
10712 SDValue Op0;
10713 if (sd_match(N0, m_OneUse(m_AnyOf(m_SMin(m_Value(Op0), m_Specific(N1)),
10714 m_SMax(m_Value(Op0), m_Specific(N1)),
10715 m_UMin(m_Value(Op0), m_Specific(N1)),
10716 m_UMax(m_Value(Op0), m_Specific(N1)))))) {
10717
10718 if (isa<ConstantSDNode>(N1) ||
10720 // For vectors, only optimize when the constant is zero or all-ones to
10721 // avoid generating more instructions
10722 if (VT.isVector()) {
10723 ConstantSDNode *N1C = isConstOrConstSplat(N1);
10724 if (!N1C || (!N1C->isZero() && !N1C->isAllOnes()))
10725 return SDValue();
10726 }
10727
10728 // Avoid the fold if the minmax operation is legal and select is expensive
10729 if (TLI.isOperationLegal(N0.getOpcode(), VT) &&
10731 return SDValue();
10732
10733 EVT CCVT = getSetCCResultType(VT);
10734 ISD::CondCode CC;
10735 switch (N0.getOpcode()) {
10736 case ISD::SMIN:
10737 CC = ISD::SETLT;
10738 break;
10739 case ISD::SMAX:
10740 CC = ISD::SETGT;
10741 break;
10742 case ISD::UMIN:
10743 CC = ISD::SETULT;
10744 break;
10745 case ISD::UMAX:
10746 CC = ISD::SETUGT;
10747 break;
10748 }
10749 SDValue FN1 = DAG.getFreeze(N1);
10750 SDValue Cmp = DAG.getSetCC(DL, CCVT, Op0, FN1, CC);
10751 SDValue XorXC = DAG.getNode(ISD::XOR, DL, VT, Op0, FN1);
10752 SDValue Zero = DAG.getConstant(0, DL, VT);
10753 return DAG.getSelect(DL, VT, Cmp, XorXC, Zero);
10754 }
10755 }
10756
10757 return SDValue();
10758}
10759
10760/// If we have a shift-by-constant of a bitwise logic op that itself has a
10761/// shift-by-constant operand with identical opcode, we may be able to convert
10762/// that into 2 independent shifts followed by the logic op. This is a
10763/// throughput improvement.
10765 // Match a one-use bitwise logic op.
10766 SDValue LogicOp = Shift->getOperand(0);
10767 if (!LogicOp.hasOneUse())
10768 return SDValue();
10769
10770 unsigned LogicOpcode = LogicOp.getOpcode();
10771 if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
10772 LogicOpcode != ISD::XOR)
10773 return SDValue();
10774
10775 // Find a matching one-use shift by constant.
10776 unsigned ShiftOpcode = Shift->getOpcode();
10777 SDValue C1 = Shift->getOperand(1);
10778 ConstantSDNode *C1Node = isConstOrConstSplat(C1);
10779 assert(C1Node && "Expected a shift with constant operand");
10780 const APInt &C1Val = C1Node->getAPIntValue();
10781 auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
10782 const APInt *&ShiftAmtVal) {
10783 if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
10784 return false;
10785
10786 ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
10787 if (!ShiftCNode)
10788 return false;
10789
10790 // Capture the shifted operand and shift amount value.
10791 ShiftOp = V.getOperand(0);
10792 ShiftAmtVal = &ShiftCNode->getAPIntValue();
10793
10794 // Shift amount types do not have to match their operand type, so check that
10795 // the constants are the same width.
10796 if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
10797 return false;
10798
10799 // The fold is not valid if the sum of the shift values doesn't fit in the
10800 // given shift amount type.
10801 bool Overflow = false;
10802 APInt NewShiftAmt = C1Val.uadd_ov(*ShiftAmtVal, Overflow);
10803 if (Overflow)
10804 return false;
10805
10806 // The fold is not valid if the sum of the shift values exceeds bitwidth.
10807 if (NewShiftAmt.uge(V.getScalarValueSizeInBits()))
10808 return false;
10809
10810 return true;
10811 };
10812
10813 // Logic ops are commutative, so check each operand for a match.
10814 SDValue X, Y;
10815 const APInt *C0Val;
10816 if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
10817 Y = LogicOp.getOperand(1);
10818 else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
10819 Y = LogicOp.getOperand(0);
10820 else
10821 return SDValue();
10822
10823 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
10824 SDLoc DL(Shift);
10825 EVT VT = Shift->getValueType(0);
10826 EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
10827 SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
10828 SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
10829 SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
10830 return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2,
10831 LogicOp->getFlags());
10832}
10833
10834/// Handle transforms common to the three shifts, when the shift amount is a
10835/// constant.
10836/// We are looking for: (shift being one of shl/sra/srl)
10837/// shift (binop X, C0), C1
10838/// And want to transform into:
10839/// binop (shift X, C1), (shift C0, C1)
10840SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
10841 assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
10842
10843 // Do not turn a 'not' into a regular xor.
10844 if (isBitwiseNot(N->getOperand(0)))
10845 return SDValue();
10846
10847 // The inner binop must be one-use, since we want to replace it.
10848 SDValue LHS = N->getOperand(0);
10849 if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
10850 return SDValue();
10851
10852 // Fold shift(bitop(shift(x,c1),y), c2) -> bitop(shift(x,c1+c2),shift(y,c2)).
10853 if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
10854 return R;
10855
10856 // We want to pull some binops through shifts, so that we have (and (shift))
10857 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
10858 // thing happens with address calculations, so it's important to canonicalize
10859 // it.
10860 switch (LHS.getOpcode()) {
10861 default:
10862 return SDValue();
10863 case ISD::OR:
10864 case ISD::XOR:
10865 case ISD::AND:
10866 break;
10867 case ISD::ADD:
10868 if (N->getOpcode() != ISD::SHL)
10869 return SDValue(); // only shl(add) not sr[al](add).
10870 break;
10871 }
10872
10873 // FIXME: disable this unless the input to the binop is a shift by a constant
10874 // or is copy/select. Enable this in other cases when figure out it's exactly
10875 // profitable.
10876 SDValue BinOpLHSVal = LHS.getOperand(0);
10877 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
10878 BinOpLHSVal.getOpcode() == ISD::SRA ||
10879 BinOpLHSVal.getOpcode() == ISD::SRL) &&
10880 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
10881 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
10882 BinOpLHSVal.getOpcode() == ISD::SELECT;
10883
10884 if (!IsShiftByConstant && !IsCopyOrSelect)
10885 return SDValue();
10886
10887 if (IsCopyOrSelect && N->hasOneUse())
10888 return SDValue();
10889
10890 // Attempt to fold the constants, shifting the binop RHS by the shift amount.
10891 SDLoc DL(N);
10892 EVT VT = N->getValueType(0);
10893 if (SDValue NewRHS = DAG.FoldConstantArithmetic(
10894 N->getOpcode(), DL, VT, {LHS.getOperand(1), N->getOperand(1)})) {
10895 SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
10896 N->getOperand(1));
10897 return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
10898 }
10899
10900 return SDValue();
10901}
10902
10903SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
10904 assert(N->getOpcode() == ISD::TRUNCATE);
10905 assert(N->getOperand(0).getOpcode() == ISD::AND);
10906
10907 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
10908 EVT TruncVT = N->getValueType(0);
10909 if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
10910 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
10911 SDValue N01 = N->getOperand(0).getOperand(1);
10912 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
10913 SDLoc DL(N);
10914 SDValue N00 = N->getOperand(0).getOperand(0);
10915 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
10916 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
10917 AddToWorklist(Trunc00.getNode());
10918 AddToWorklist(Trunc01.getNode());
10919 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
10920 }
10921 }
10922
10923 return SDValue();
10924}
10925
10926SDValue DAGCombiner::visitRotate(SDNode *N) {
10927 SDLoc dl(N);
10928 SDValue N0 = N->getOperand(0);
10929 SDValue N1 = N->getOperand(1);
10930 EVT VT = N->getValueType(0);
10931 unsigned Bitsize = VT.getScalarSizeInBits();
10932
10933 // fold (rot x, 0) -> x
10934 if (isNullOrNullSplat(N1))
10935 return N0;
10936
10937 // fold (rot x, c) -> x iff (c % BitSize) == 0
10938 if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
10939 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
10940 if (DAG.MaskedValueIsZero(N1, ModuloMask))
10941 return N0;
10942 }
10943
10944 // fold (rot x, c) -> (rot x, c % BitSize)
10945 bool OutOfRange = false;
10946 auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
10947 OutOfRange |= C->getAPIntValue().uge(Bitsize);
10948 return true;
10949 };
10950 if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
10951 EVT AmtVT = N1.getValueType();
10952 SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
10953 if (SDValue Amt =
10954 DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
10955 return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
10956 }
10957
10958 // rot i16 X, 8 --> bswap X
10959 auto *RotAmtC = isConstOrConstSplat(N1);
10960 if (RotAmtC && RotAmtC->getAPIntValue() == 8 &&
10961 VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT))
10962 return DAG.getNode(ISD::BSWAP, dl, VT, N0);
10963
10964 // Simplify the operands using demanded-bits information.
10966 return SDValue(N, 0);
10967
10968 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
10969 if (N1.getOpcode() == ISD::TRUNCATE &&
10970 N1.getOperand(0).getOpcode() == ISD::AND) {
10971 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
10972 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
10973 }
10974
10975 unsigned NextOp = N0.getOpcode();
10976
10977 // fold (rot* (rot* x, c2), c1)
10978 // -> (rot* x, ((c1 % bitsize) +- (c2 % bitsize) + bitsize) % bitsize)
10979 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
10980 bool C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
10982 if (C1 && C2 && N1.getValueType() == N0.getOperand(1).getValueType()) {
10983 EVT ShiftVT = N1.getValueType();
10984 bool SameSide = (N->getOpcode() == NextOp);
10985 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
10986 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
10987 SDValue Norm1 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10988 {N1, BitsizeC});
10989 SDValue Norm2 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10990 {N0.getOperand(1), BitsizeC});
10991 if (Norm1 && Norm2)
10992 if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
10993 CombineOp, dl, ShiftVT, {Norm1, Norm2})) {
10994 CombinedShift = DAG.FoldConstantArithmetic(ISD::ADD, dl, ShiftVT,
10995 {CombinedShift, BitsizeC});
10996 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
10997 ISD::UREM, dl, ShiftVT, {CombinedShift, BitsizeC});
10998 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
10999 CombinedShiftNorm);
11000 }
11001 }
11002 }
11003 return SDValue();
11004}
11005
11006SDValue DAGCombiner::visitSHL(SDNode *N) {
11007 SDValue N0 = N->getOperand(0);
11008 SDValue N1 = N->getOperand(1);
11009 if (SDValue V = DAG.simplifyShift(N0, N1))
11010 return V;
11011
11012 SDLoc DL(N);
11013 EVT VT = N0.getValueType();
11014 EVT ShiftVT = N1.getValueType();
11015 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11016
11017 // fold (shl c1, c2) -> c1<<c2
11018 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N0, N1}))
11019 return C;
11020
11021 // fold vector ops
11022 if (VT.isVector()) {
11023 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11024 return FoldedVOp;
11025
11026 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
11027 // If setcc produces all-one true value then:
11028 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
11029 if (N1CV && N1CV->isConstant()) {
11030 if (N0.getOpcode() == ISD::AND) {
11031 SDValue N00 = N0->getOperand(0);
11032 SDValue N01 = N0->getOperand(1);
11033 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
11034
11035 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
11038 if (SDValue C =
11039 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N01, N1}))
11040 return DAG.getNode(ISD::AND, DL, VT, N00, C);
11041 }
11042 }
11043 }
11044 }
11045
11046 if (SDValue NewSel = foldBinOpIntoSelect(N))
11047 return NewSel;
11048
11049 // if (shl x, c) is known to be zero, return 0
11050 if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
11051 return DAG.getConstant(0, DL, VT);
11052
11053 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
11054 if (N1.getOpcode() == ISD::TRUNCATE &&
11055 N1.getOperand(0).getOpcode() == ISD::AND) {
11056 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11057 return DAG.getNode(ISD::SHL, DL, VT, N0, NewOp1);
11058 }
11059
11060 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
11061 if (N0.getOpcode() == ISD::SHL) {
11062 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
11063 ConstantSDNode *RHS) {
11064 APInt c1 = LHS->getAPIntValue();
11065 APInt c2 = RHS->getAPIntValue();
11066 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11067 return (c1 + c2).uge(OpSizeInBits);
11068 };
11069 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
11070 return DAG.getConstant(0, DL, VT);
11071
11072 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
11073 ConstantSDNode *RHS) {
11074 APInt c1 = LHS->getAPIntValue();
11075 APInt c2 = RHS->getAPIntValue();
11076 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11077 return (c1 + c2).ult(OpSizeInBits);
11078 };
11079 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
11080 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
11081 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
11082 }
11083 }
11084
11085 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
11086 // For this to be valid, the second form must not preserve any of the bits
11087 // that are shifted out by the inner shift in the first form. This means
11088 // the outer shift size must be >= the number of bits added by the ext.
11089 // As a corollary, we don't care what kind of ext it is.
11090 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
11091 N0.getOpcode() == ISD::ANY_EXTEND ||
11092 N0.getOpcode() == ISD::SIGN_EXTEND) &&
11093 N0.getOperand(0).getOpcode() == ISD::SHL) {
11094 SDValue N0Op0 = N0.getOperand(0);
11095 SDValue InnerShiftAmt = N0Op0.getOperand(1);
11096 EVT InnerVT = N0Op0.getValueType();
11097 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
11098
11099 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
11100 ConstantSDNode *RHS) {
11101 APInt c1 = LHS->getAPIntValue();
11102 APInt c2 = RHS->getAPIntValue();
11103 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11104 return c2.uge(OpSizeInBits - InnerBitwidth) &&
11105 (c1 + c2).uge(OpSizeInBits);
11106 };
11107 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
11108 /*AllowUndefs*/ false,
11109 /*AllowTypeMismatch*/ true))
11110 return DAG.getConstant(0, DL, VT);
11111
11112 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
11113 ConstantSDNode *RHS) {
11114 APInt c1 = LHS->getAPIntValue();
11115 APInt c2 = RHS->getAPIntValue();
11116 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11117 return c2.uge(OpSizeInBits - InnerBitwidth) &&
11118 (c1 + c2).ult(OpSizeInBits);
11119 };
11120 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
11121 /*AllowUndefs*/ false,
11122 /*AllowTypeMismatch*/ true)) {
11123 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
11124 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
11125 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
11126 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
11127 }
11128 }
11129
11130 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
11131 // Only fold this if the inner zext has no other uses to avoid increasing
11132 // the total number of instructions.
11133 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
11134 N0.getOperand(0).getOpcode() == ISD::SRL) {
11135 SDValue N0Op0 = N0.getOperand(0);
11136 SDValue InnerShiftAmt = N0Op0.getOperand(1);
11137
11138 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
11139 APInt c1 = LHS->getAPIntValue();
11140 APInt c2 = RHS->getAPIntValue();
11141 zeroExtendToMatch(c1, c2);
11142 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
11143 };
11144 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
11145 /*AllowUndefs*/ false,
11146 /*AllowTypeMismatch*/ true)) {
11147 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
11148 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
11149 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
11150 AddToWorklist(NewSHL.getNode());
11151 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
11152 }
11153 }
11154
11155 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) {
11156 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
11157 ConstantSDNode *RHS) {
11158 const APInt &LHSC = LHS->getAPIntValue();
11159 const APInt &RHSC = RHS->getAPIntValue();
11160 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
11161 LHSC.getZExtValue() <= RHSC.getZExtValue();
11162 };
11163
11164 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
11165 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 >= C2
11166 if (N0->getFlags().hasExact()) {
11167 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11168 /*AllowUndefs*/ false,
11169 /*AllowTypeMismatch*/ true)) {
11170 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11171 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11172 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11173 }
11174 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11175 /*AllowUndefs*/ false,
11176 /*AllowTypeMismatch*/ true)) {
11177 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11178 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11179 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Diff);
11180 }
11181 }
11182
11183 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
11184 // (and (srl x, (sub c1, c2), MASK)
11185 // Only fold this if the inner shift has no other uses -- if it does,
11186 // folding this will increase the total number of instructions.
11187 if (N0.getOpcode() == ISD::SRL &&
11188 (N0.getOperand(1) == N1 || N0.hasOneUse()) &&
11190 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11191 /*AllowUndefs*/ false,
11192 /*AllowTypeMismatch*/ true)) {
11193 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11194 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11195 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11196 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N01);
11197 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, Diff);
11198 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
11199 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11200 }
11201 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11202 /*AllowUndefs*/ false,
11203 /*AllowTypeMismatch*/ true)) {
11204 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11205 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11206 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11207 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N1);
11208 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11209 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11210 }
11211 }
11212 }
11213
11214 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
11215 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
11216 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
11217 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
11218 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
11219 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
11220 }
11221
11222 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11223 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
11224 // Variant of version done on multiply, except mul by a power of 2 is turned
11225 // into a shift.
11226 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
11227 TLI.isDesirableToCommuteWithShift(N, Level)) {
11228 SDValue N01 = N0.getOperand(1);
11229 if (SDValue Shl1 =
11230 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1})) {
11231 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
11232 AddToWorklist(Shl0.getNode());
11233 SDNodeFlags Flags;
11234 // Preserve the disjoint flag for Or.
11235 if (N0.getOpcode() == ISD::OR && N0->getFlags().hasDisjoint())
11237 return DAG.getNode(N0.getOpcode(), DL, VT, Shl0, Shl1, Flags);
11238 }
11239 }
11240
11241 // fold (shl (sext (add_nsw x, c1)), c2) -> (add (shl (sext x), c2), c1 << c2)
11242 // TODO: Add zext/add_nuw variant with suitable test coverage
11243 // TODO: Should we limit this with isLegalAddImmediate?
11244 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
11245 N0.getOperand(0).getOpcode() == ISD::ADD &&
11246 N0.getOperand(0)->getFlags().hasNoSignedWrap() &&
11247 TLI.isDesirableToCommuteWithShift(N, Level)) {
11248 SDValue Add = N0.getOperand(0);
11249 SDLoc DL(N0);
11250 if (SDValue ExtC = DAG.FoldConstantArithmetic(N0.getOpcode(), DL, VT,
11251 {Add.getOperand(1)})) {
11252 if (SDValue ShlC =
11253 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {ExtC, N1})) {
11254 SDValue ExtX = DAG.getNode(N0.getOpcode(), DL, VT, Add.getOperand(0));
11255 SDValue ShlX = DAG.getNode(ISD::SHL, DL, VT, ExtX, N1);
11256 return DAG.getNode(ISD::ADD, DL, VT, ShlX, ShlC);
11257 }
11258 }
11259 }
11260
11261 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
11262 if (N0.getOpcode() == ISD::MUL && N0->hasOneUse()) {
11263 SDValue N01 = N0.getOperand(1);
11264 if (SDValue Shl =
11265 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1}))
11266 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), Shl);
11267 }
11268
11269 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11270 if (N1C && !N1C->isOpaque())
11271 if (SDValue NewSHL = visitShiftByConstant(N))
11272 return NewSHL;
11273
11274 // fold (shl X, cttz(Y)) -> (mul (Y & -Y), X) if cttz is unsupported on the
11275 // target.
11276 if (((N1.getOpcode() == ISD::CTTZ &&
11277 VT.getScalarSizeInBits() <= ShiftVT.getScalarSizeInBits()) ||
11279 N1.hasOneUse() && !TLI.isOperationLegalOrCustom(ISD::CTTZ, ShiftVT) &&
11281 SDValue Y = N1.getOperand(0);
11282 SDLoc DL(N);
11283 SDValue NegY = DAG.getNegative(Y, DL, ShiftVT);
11284 SDValue And =
11285 DAG.getZExtOrTrunc(DAG.getNode(ISD::AND, DL, ShiftVT, Y, NegY), DL, VT);
11286 return DAG.getNode(ISD::MUL, DL, VT, And, N0);
11287 }
11288
11290 return SDValue(N, 0);
11291
11292 // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
11293 if (N0.getOpcode() == ISD::VSCALE && N1C) {
11294 const APInt &C0 = N0.getConstantOperandAPInt(0);
11295 const APInt &C1 = N1C->getAPIntValue();
11296 return DAG.getVScale(DL, VT, C0 << C1);
11297 }
11298
11299 SDValue X;
11300 APInt VS0;
11301
11302 // fold (shl (X * vscale(VS0)), C1) -> (X * vscale(VS0 << C1))
11303 if (N1C && sd_match(N0, m_Mul(m_Value(X), m_VScale(m_ConstInt(VS0))))) {
11304 SDNodeFlags Flags;
11305 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
11306 N0->getFlags().hasNoUnsignedWrap());
11307
11308 SDValue VScale = DAG.getVScale(DL, VT, VS0 << N1C->getAPIntValue());
11309 return DAG.getNode(ISD::MUL, DL, VT, X, VScale, Flags);
11310 }
11311
11312 // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)).
11313 APInt ShlVal;
11314 if (N0.getOpcode() == ISD::STEP_VECTOR &&
11315 ISD::isConstantSplatVector(N1.getNode(), ShlVal)) {
11316 const APInt &C0 = N0.getConstantOperandAPInt(0);
11317 if (ShlVal.ult(C0.getBitWidth())) {
11318 APInt NewStep = C0 << ShlVal;
11319 return DAG.getStepVector(DL, VT, NewStep);
11320 }
11321 }
11322
11323 return SDValue();
11324}
11325
11326// Transform a right shift of a multiply into a multiply-high.
11327// Examples:
11328// (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b)
11329// (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b)
11331 const TargetLowering &TLI) {
11332 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
11333 "SRL or SRA node is required here!");
11334
11335 // Check the shift amount. Proceed with the transformation if the shift
11336 // amount is constant.
11337 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
11338 if (!ShiftAmtSrc)
11339 return SDValue();
11340
11341 // The operation feeding into the shift must be a multiply.
11342 SDValue ShiftOperand = N->getOperand(0);
11343 if (ShiftOperand.getOpcode() != ISD::MUL)
11344 return SDValue();
11345
11346 // Both operands must be equivalent extend nodes.
11347 SDValue LeftOp = ShiftOperand.getOperand(0);
11348 SDValue RightOp = ShiftOperand.getOperand(1);
11349
11350 if (LeftOp.getOpcode() != ISD::SIGN_EXTEND &&
11351 LeftOp.getOpcode() != ISD::ZERO_EXTEND)
11352 std::swap(LeftOp, RightOp);
11353
11354 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
11355 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
11356
11357 if (!IsSignExt && !IsZeroExt)
11358 return SDValue();
11359
11360 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
11361 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
11362
11363 // return true if U may use the lower bits of its operands
11364 auto UserOfLowerBits = [NarrowVTSize](SDNode *U) {
11365 if (U->getOpcode() != ISD::SRL && U->getOpcode() != ISD::SRA) {
11366 return true;
11367 }
11368 ConstantSDNode *UShiftAmtSrc = isConstOrConstSplat(U->getOperand(1));
11369 if (!UShiftAmtSrc) {
11370 return true;
11371 }
11372 unsigned UShiftAmt = UShiftAmtSrc->getZExtValue();
11373 return UShiftAmt < NarrowVTSize;
11374 };
11375
11376 // If the lower part of the MUL is also used and MUL_LOHI is supported
11377 // do not introduce the MULH in favor of MUL_LOHI
11378 unsigned MulLoHiOp = IsSignExt ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
11379 if (!ShiftOperand.hasOneUse() &&
11380 TLI.isOperationLegalOrCustom(MulLoHiOp, NarrowVT) &&
11381 llvm::any_of(ShiftOperand->users(), UserOfLowerBits)) {
11382 return SDValue();
11383 }
11384
11385 SDValue MulhRightOp;
11386 if (LeftOp.getOpcode() != RightOp.getOpcode()) {
11387 if (IsZeroExt && ShiftOperand.hasOneUse() &&
11388 DAG.computeKnownBits(RightOp).countMaxActiveBits() <= NarrowVTSize) {
11389 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11390 } else if (IsSignExt && ShiftOperand.hasOneUse() &&
11391 DAG.ComputeMaxSignificantBits(RightOp) <= NarrowVTSize) {
11392 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11393 } else {
11394 return SDValue();
11395 }
11396 } else {
11397 // Check that the two extend nodes are the same type.
11398 if (NarrowVT != RightOp.getOperand(0).getValueType())
11399 return SDValue();
11400 MulhRightOp = RightOp.getOperand(0);
11401 }
11402
11403 EVT WideVT = LeftOp.getValueType();
11404 // Proceed with the transformation if the wide types match.
11405 assert((WideVT == RightOp.getValueType()) &&
11406 "Cannot have a multiply node with two different operand types.");
11407
11408 // Proceed with the transformation if the wide type is twice as large
11409 // as the narrow type.
11410 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
11411 return SDValue();
11412
11413 // Check the shift amount with the narrow type size.
11414 // Proceed with the transformation if the shift amount is the width
11415 // of the narrow type.
11416 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
11417 if (ShiftAmt != NarrowVTSize)
11418 return SDValue();
11419
11420 // If the operation feeding into the MUL is a sign extend (sext),
11421 // we use mulhs. Othewise, zero extends (zext) use mulhu.
11422 unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU;
11423
11424 // Combine to mulh if mulh is legal/custom for the narrow type on the target
11425 // or if it is a vector type then we could transform to an acceptable type and
11426 // rely on legalization to split/combine the result.
11427 EVT TransformVT = NarrowVT;
11428 if (NarrowVT.isVector()) {
11429 TransformVT = TLI.getLegalTypeToTransformTo(*DAG.getContext(), NarrowVT);
11430 if (TransformVT.getScalarType() != NarrowVT.getScalarType())
11431 return SDValue();
11432 }
11433 if (!TLI.isOperationLegalOrCustom(MulhOpcode, TransformVT))
11434 return SDValue();
11435
11436 SDValue Result =
11437 DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp);
11438 bool IsSigned = N->getOpcode() == ISD::SRA;
11439 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
11440}
11441
11442// fold (bswap (logic_op(bswap(x),y))) -> logic_op(x,bswap(y))
11443// This helper function accept SDNode with opcode ISD::BSWAP and ISD::BITREVERSE
11445 unsigned Opcode = N->getOpcode();
11446 if (Opcode != ISD::BSWAP && Opcode != ISD::BITREVERSE)
11447 return SDValue();
11448
11449 SDValue N0 = N->getOperand(0);
11450 EVT VT = N->getValueType(0);
11451 SDLoc DL(N);
11452 SDValue X, Y;
11453
11454 // If both operands are bswap/bitreverse, ignore the multiuse
11456 m_UnaryOp(Opcode, m_Value(Y))))))
11457 return DAG.getNode(N0.getOpcode(), DL, VT, X, Y);
11458
11459 // Otherwise need to ensure logic_op and bswap/bitreverse(x) have one use.
11461 m_OneUse(m_UnaryOp(Opcode, m_Value(X))), m_Value(Y))))) {
11462 SDValue NewBitReorder = DAG.getNode(Opcode, DL, VT, Y);
11463 return DAG.getNode(N0.getOpcode(), DL, VT, X, NewBitReorder);
11464 }
11465
11466 return SDValue();
11467}
11468
11469SDValue DAGCombiner::visitSRA(SDNode *N) {
11470 SDValue N0 = N->getOperand(0);
11471 SDValue N1 = N->getOperand(1);
11472 if (SDValue V = DAG.simplifyShift(N0, N1))
11473 return V;
11474
11475 SDLoc DL(N);
11476 EVT VT = N0.getValueType();
11477 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11478
11479 // fold (sra c1, c2) -> (sra c1, c2)
11480 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, DL, VT, {N0, N1}))
11481 return C;
11482
11483 // Arithmetic shifting an all-sign-bit value is a no-op.
11484 // fold (sra 0, x) -> 0
11485 // fold (sra -1, x) -> -1
11486 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
11487 return N0;
11488
11489 // fold vector ops
11490 if (VT.isVector())
11491 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11492 return FoldedVOp;
11493
11494 if (SDValue NewSel = foldBinOpIntoSelect(N))
11495 return NewSel;
11496
11497 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11498
11499 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
11500 // clamp (add c1, c2) to max shift.
11501 if (N0.getOpcode() == ISD::SRA) {
11502 EVT ShiftVT = N1.getValueType();
11503 EVT ShiftSVT = ShiftVT.getScalarType();
11504 SmallVector<SDValue, 16> ShiftValues;
11505
11506 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
11507 APInt c1 = LHS->getAPIntValue();
11508 APInt c2 = RHS->getAPIntValue();
11509 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11510 APInt Sum = c1 + c2;
11511 unsigned ShiftSum =
11512 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
11513 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
11514 return true;
11515 };
11516 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
11517 SDValue ShiftValue;
11518 if (N1.getOpcode() == ISD::BUILD_VECTOR)
11519 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
11520 else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
11521 assert(ShiftValues.size() == 1 &&
11522 "Expected matchBinaryPredicate to return one element for "
11523 "SPLAT_VECTORs");
11524 ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]);
11525 } else
11526 ShiftValue = ShiftValues[0];
11527 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
11528 }
11529 }
11530
11531 // fold (sra (xor (sra x, c1), -1), c2) -> (xor (sra x, c3), -1)
11532 // This allows merging two arithmetic shifts even when there's a NOT in
11533 // between.
11534 SDValue X;
11535 APInt C1;
11536 if (N1C && sd_match(N0, m_OneUse(m_Not(
11537 m_OneUse(m_Sra(m_Value(X), m_ConstInt(C1))))))) {
11538 APInt C2 = N1C->getAPIntValue();
11539 zeroExtendToMatch(C1, C2, 1 /* Overflow Bit */);
11540 APInt Sum = C1 + C2;
11541 unsigned ShiftSum = Sum.getLimitedValue(OpSizeInBits - 1);
11542 SDValue NewShift = DAG.getNode(
11543 ISD::SRA, DL, VT, X, DAG.getShiftAmountConstant(ShiftSum, VT, DL));
11544 return DAG.getNOT(DL, NewShift, VT);
11545 }
11546
11547 // fold (sra (shl X, m), (sub result_size, n))
11548 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
11549 // result_size - n != m.
11550 // If truncate is free for the target sext(shl) is likely to result in better
11551 // code.
11552 if (N0.getOpcode() == ISD::SHL && N1C) {
11553 // Get the two constants of the shifts, CN0 = m, CN = n.
11554 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
11555 if (N01C) {
11556 LLVMContext &Ctx = *DAG.getContext();
11557 // Determine what the truncate's result bitsize and type would be.
11558 EVT TruncVT = VT.changeElementType(
11559 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()));
11560
11561 // Determine the residual right-shift amount.
11562 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
11563
11564 // If the shift is not a no-op (in which case this should be just a sign
11565 // extend already), the truncated to type is legal, sign_extend is legal
11566 // on that type, and the truncate to that type is both legal and free,
11567 // perform the transform.
11568 if ((ShiftAmt > 0) &&
11571 TLI.isTruncateFree(VT, TruncVT)) {
11572 SDValue Amt = DAG.getShiftAmountConstant(ShiftAmt, VT, DL);
11573 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
11574 N0.getOperand(0), Amt);
11575 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
11576 Shift);
11577 return DAG.getNode(ISD::SIGN_EXTEND, DL,
11578 N->getValueType(0), Trunc);
11579 }
11580 }
11581 }
11582
11583 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
11584 // sra (add (shl X, N1C), AddC), N1C -->
11585 // sext (add (trunc X to (width - N1C)), AddC')
11586 // sra (sub AddC, (shl X, N1C)), N1C -->
11587 // sext (sub AddC1',(trunc X to (width - N1C)))
11588 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB) && N1C &&
11589 N0.hasOneUse()) {
11590 bool IsAdd = N0.getOpcode() == ISD::ADD;
11591 SDValue Shl = N0.getOperand(IsAdd ? 0 : 1);
11592 if (Shl.getOpcode() == ISD::SHL && Shl.getOperand(1) == N1 &&
11593 Shl.hasOneUse()) {
11594 // TODO: AddC does not need to be a splat.
11595 if (ConstantSDNode *AddC =
11596 isConstOrConstSplat(N0.getOperand(IsAdd ? 1 : 0))) {
11597 // Determine what the truncate's type would be and ask the target if
11598 // that is a free operation.
11599 LLVMContext &Ctx = *DAG.getContext();
11600 unsigned ShiftAmt = N1C->getZExtValue();
11601 EVT TruncVT = VT.changeElementType(
11602 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt));
11603
11604 // TODO: The simple type check probably belongs in the default hook
11605 // implementation and/or target-specific overrides (because
11606 // non-simple types likely require masking when legalized), but
11607 // that restriction may conflict with other transforms.
11608 if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
11609 TLI.isTruncateFree(VT, TruncVT)) {
11610 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
11611 SDValue ShiftC =
11612 DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).trunc(
11613 TruncVT.getScalarSizeInBits()),
11614 DL, TruncVT);
11615 SDValue Add;
11616 if (IsAdd)
11617 Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
11618 else
11619 Add = DAG.getNode(ISD::SUB, DL, TruncVT, ShiftC, Trunc);
11620 return DAG.getSExtOrTrunc(Add, DL, VT);
11621 }
11622 }
11623 }
11624 }
11625
11626 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
11627 if (N1.getOpcode() == ISD::TRUNCATE &&
11628 N1.getOperand(0).getOpcode() == ISD::AND) {
11629 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11630 return DAG.getNode(ISD::SRA, DL, VT, N0, NewOp1);
11631 }
11632
11633 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
11634 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
11635 // if c1 is equal to the number of bits the trunc removes
11636 // TODO - support non-uniform vector shift amounts.
11637 if (N0.getOpcode() == ISD::TRUNCATE &&
11638 (N0.getOperand(0).getOpcode() == ISD::SRL ||
11639 N0.getOperand(0).getOpcode() == ISD::SRA) &&
11640 N0.getOperand(0).hasOneUse() &&
11641 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
11642 SDValue N0Op0 = N0.getOperand(0);
11643 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
11644 EVT LargeVT = N0Op0.getValueType();
11645 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
11646 if (LargeShift->getAPIntValue() == TruncBits) {
11647 EVT LargeShiftVT = getShiftAmountTy(LargeVT);
11648 SDValue Amt = DAG.getZExtOrTrunc(N1, DL, LargeShiftVT);
11649 Amt = DAG.getNode(ISD::ADD, DL, LargeShiftVT, Amt,
11650 DAG.getConstant(TruncBits, DL, LargeShiftVT));
11651 SDValue SRA =
11652 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
11653 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
11654 }
11655 }
11656 }
11657
11658 // fold (sra (add nsw X, C), D) -> (add nsw (sra X, D), C s>> D)
11659 // when C has D trailing zeros (so C s>> D is exact).
11660 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11661 N0->getFlags().hasNoSignedWrap()) {
11662 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11663 const APInt &ShAmt = N1C->getAPIntValue();
11664 const APInt &AddVal = AddC->getAPIntValue();
11665 if (ShAmt.ult(AddVal.countr_zero())) {
11666 SDNodeFlags ShiftFlags = N->getFlags();
11667 SDValue NewSra =
11668 DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11669 SDValue NewC = DAG.getConstant(AddVal.ashr(ShAmt), DL, VT);
11670 SDNodeFlags AddFlags = N0->getFlags();
11671 return DAG.getNode(ISD::ADD, DL, VT, NewSra, NewC, AddFlags);
11672 }
11673 }
11674 }
11675
11676 // Simplify, based on bits shifted out of the LHS.
11678 return SDValue(N, 0);
11679
11680 // If the sign bit is known to be zero, switch this to a SRL.
11681 if (DAG.SignBitIsZero(N0))
11682 return DAG.getNode(ISD::SRL, DL, VT, N0, N1);
11683
11684 if (N1C && !N1C->isOpaque())
11685 if (SDValue NewSRA = visitShiftByConstant(N))
11686 return NewSRA;
11687
11688 // Try to transform this shift into a multiply-high if
11689 // it matches the appropriate pattern detected in combineShiftToMULH.
11690 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
11691 return MULH;
11692
11693 // Attempt to convert a sra of a load into a narrower sign-extending load.
11694 if (SDValue NarrowLoad = reduceLoadWidth(N))
11695 return NarrowLoad;
11696
11697 if (SDValue AVG = foldShiftToAvg(N, DL))
11698 return AVG;
11699
11700 return SDValue();
11701}
11702
11703SDValue DAGCombiner::visitSRL(SDNode *N) {
11704 SDValue N0 = N->getOperand(0);
11705 SDValue N1 = N->getOperand(1);
11706 if (SDValue V = DAG.simplifyShift(N0, N1))
11707 return V;
11708
11709 SDLoc DL(N);
11710 EVT VT = N0.getValueType();
11711 EVT ShiftVT = N1.getValueType();
11712 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11713
11714 // fold (srl c1, c2) -> c1 >>u c2
11715 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, DL, VT, {N0, N1}))
11716 return C;
11717
11718 // fold vector ops
11719 if (VT.isVector())
11720 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11721 return FoldedVOp;
11722
11723 if (SDValue NewSel = foldBinOpIntoSelect(N))
11724 return NewSel;
11725
11726 // if (srl x, c) is known to be zero, return 0
11727 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11728 if (N1C &&
11729 DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
11730 return DAG.getConstant(0, DL, VT);
11731
11732 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
11733 if (N0.getOpcode() == ISD::SRL) {
11734 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
11735 ConstantSDNode *RHS) {
11736 APInt c1 = LHS->getAPIntValue();
11737 APInt c2 = RHS->getAPIntValue();
11738 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11739 return (c1 + c2).uge(OpSizeInBits);
11740 };
11741 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
11742 return DAG.getConstant(0, DL, VT);
11743
11744 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
11745 ConstantSDNode *RHS) {
11746 APInt c1 = LHS->getAPIntValue();
11747 APInt c2 = RHS->getAPIntValue();
11748 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11749 return (c1 + c2).ult(OpSizeInBits);
11750 };
11751 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
11752 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
11753 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
11754 }
11755 }
11756
11757 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
11758 N0.getOperand(0).getOpcode() == ISD::SRL) {
11759 SDValue InnerShift = N0.getOperand(0);
11760 // TODO - support non-uniform vector shift amounts.
11761 if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
11762 uint64_t c1 = N001C->getZExtValue();
11763 uint64_t c2 = N1C->getZExtValue();
11764 EVT InnerShiftVT = InnerShift.getValueType();
11765 EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
11766 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
11767 // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
11768 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
11769 if (c1 + OpSizeInBits == InnerShiftSize) {
11770 if (c1 + c2 >= InnerShiftSize)
11771 return DAG.getConstant(0, DL, VT);
11772 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11773 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11774 InnerShift.getOperand(0), NewShiftAmt);
11775 return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
11776 }
11777 // In the more general case, we can clear the high bits after the shift:
11778 // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
11779 if (N0.hasOneUse() && InnerShift.hasOneUse() &&
11780 c1 + c2 < InnerShiftSize) {
11781 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11782 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11783 InnerShift.getOperand(0), NewShiftAmt);
11784 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
11785 OpSizeInBits - c2),
11786 DL, InnerShiftVT);
11787 SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
11788 return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
11789 }
11790 }
11791 }
11792
11793 if (N0.getOpcode() == ISD::SHL) {
11794 // fold (srl (shl nuw x, c), c) -> x
11795 if (N0.getOperand(1) == N1 && N0->getFlags().hasNoUnsignedWrap())
11796 return N0.getOperand(0);
11797
11798 // fold (srl (shl x, c1), c2) -> (and (shl x, (sub c1, c2), MASK) or
11799 // (and (srl x, (sub c2, c1), MASK)
11800 if ((N0.getOperand(1) == N1 || N0->hasOneUse()) &&
11802 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
11803 ConstantSDNode *RHS) {
11804 const APInt &LHSC = LHS->getAPIntValue();
11805 const APInt &RHSC = RHS->getAPIntValue();
11806 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
11807 LHSC.getZExtValue() <= RHSC.getZExtValue();
11808 };
11809 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11810 /*AllowUndefs*/ false,
11811 /*AllowTypeMismatch*/ true)) {
11812 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11813 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11814 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11815 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N01);
11816 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, Diff);
11817 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11818 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11819 }
11820 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11821 /*AllowUndefs*/ false,
11822 /*AllowTypeMismatch*/ true)) {
11823 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11824 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11825 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11826 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N1);
11827 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
11828 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11829 }
11830 }
11831 }
11832
11833 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
11834 // TODO - support non-uniform vector shift amounts.
11835 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
11836 // Shifting in all undef bits?
11837 EVT SmallVT = N0.getOperand(0).getValueType();
11838 unsigned BitSize = SmallVT.getScalarSizeInBits();
11839 if (N1C->getAPIntValue().uge(BitSize))
11840 return DAG.getUNDEF(VT);
11841
11842 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
11843 uint64_t ShiftAmt = N1C->getZExtValue();
11844 SDLoc DL0(N0);
11845 SDValue SmallShift =
11846 DAG.getNode(ISD::SRL, DL0, SmallVT, N0.getOperand(0),
11847 DAG.getShiftAmountConstant(ShiftAmt, SmallVT, DL0));
11848 AddToWorklist(SmallShift.getNode());
11849 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
11850 return DAG.getNode(ISD::AND, DL, VT,
11851 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
11852 DAG.getConstant(Mask, DL, VT));
11853 }
11854 }
11855
11856 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
11857 // bit, which is unmodified by sra.
11858 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
11859 if (N0.getOpcode() == ISD::SRA)
11860 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
11861 }
11862
11863 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit), and x has a power
11864 // of two bitwidth. The "5" represents (log2 (bitwidth x)).
11865 if (N1C && N0.getOpcode() == ISD::CTLZ &&
11866 isPowerOf2_32(OpSizeInBits) &&
11867 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
11868 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
11869
11870 // If any of the input bits are KnownOne, then the input couldn't be all
11871 // zeros, thus the result of the srl will always be zero.
11872 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
11873
11874 // If all of the bits input the to ctlz node are known to be zero, then
11875 // the result of the ctlz is "32" and the result of the shift is one.
11876 APInt UnknownBits = ~Known.Zero;
11877 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
11878
11879 // Otherwise, check to see if there is exactly one bit input to the ctlz.
11880 if (UnknownBits.isPowerOf2()) {
11881 // Okay, we know that only that the single bit specified by UnknownBits
11882 // could be set on input to the CTLZ node. If this bit is set, the SRL
11883 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
11884 // to an SRL/XOR pair, which is likely to simplify more.
11885 unsigned ShAmt = UnknownBits.countr_zero();
11886 SDValue Op = N0.getOperand(0);
11887
11888 if (ShAmt) {
11889 SDLoc DL(N0);
11890 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
11891 DAG.getShiftAmountConstant(ShAmt, VT, DL));
11892 AddToWorklist(Op.getNode());
11893 }
11894 return DAG.getNode(ISD::XOR, DL, VT, Op, DAG.getConstant(1, DL, VT));
11895 }
11896 }
11897
11898 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
11899 if (N1.getOpcode() == ISD::TRUNCATE &&
11900 N1.getOperand(0).getOpcode() == ISD::AND) {
11901 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11902 return DAG.getNode(ISD::SRL, DL, VT, N0, NewOp1);
11903 }
11904
11905 // fold (srl (logic_op x, (shl (zext y), c1)), c1)
11906 // -> (logic_op (srl x, c1), (zext y))
11907 // c1 <= leadingzeros(zext(y))
11908 // TODO: Replace c1 with valuetracking?
11909 SDValue X, ZExtY;
11910 if (sd_match(
11911 N0,
11913 m_Value(X),
11915 m_Specific(N1))))))) {
11916 unsigned NumLeadingZeros = ZExtY.getScalarValueSizeInBits() -
11918 if (N1C && N1C->getZExtValue() <= NumLeadingZeros)
11919 return DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
11920 DAG.getNode(ISD::SRL, SDLoc(N0), VT, X, N1), ZExtY);
11921 }
11922
11923 // fold (srl (bitcast (build_vector e1, ..., eN)), (N-1) * eltsize)
11924 // -> (zext eN)
11925 if (N1C && VT.isScalarInteger() && DAG.getDataLayout().isLittleEndian()) {
11927 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
11928 EVT BVVT = BV.getValueType();
11929 unsigned EltSizeInBits = BVVT.getScalarSizeInBits();
11930 unsigned NumElts = BVVT.getVectorNumElements();
11931 if (N1C->getZExtValue() == (NumElts - 1) * EltSizeInBits) {
11932 SDValue LastElt = BV.getOperand(NumElts - 1);
11933 assert(LastElt.getScalarValueSizeInBits() >= EltSizeInBits &&
11934 "Expected BUILD_VECTOR operand as wide as element type");
11935 EVT IntEltVT = LastElt.getValueType().changeTypeToInteger();
11936 if (!LegalTypes || TLI.isTypeLegal(IntEltVT)) {
11937 LastElt = DAG.getBitcast(IntEltVT, LastElt);
11938 SDValue Ext = DAG.getZExtOrTrunc(LastElt, DL, VT);
11939 APInt Mask = APInt::getLowBitsSet(VT.getSizeInBits(), EltSizeInBits);
11940 return DAG.getNode(ISD::AND, DL, VT, Ext,
11941 DAG.getConstant(Mask, DL, VT));
11942 }
11943 }
11944 }
11945 }
11946
11947 // fold (srl (add nuw X, C), D) -> (add nuw (srl X, D), C u>> D)
11948 // when C has D trailing zeros (so C >> D is exact).
11949 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11950 N0->getFlags().hasNoUnsignedWrap()) {
11951 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11952 const APInt &ShAmt = N1C->getAPIntValue();
11953 const APInt &AddVal = AddC->getAPIntValue();
11954 if (ShAmt.ult(AddVal.countr_zero())) {
11955 SDNodeFlags ShiftFlags = N->getFlags();
11956 SDValue NewSrl =
11957 DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11958 SDValue NewC = DAG.getConstant(AddVal.lshr(ShAmt), DL, VT);
11959 SDNodeFlags AddFlags = N0->getFlags();
11960 return DAG.getNode(ISD::ADD, DL, VT, NewSrl, NewC, AddFlags);
11961 }
11962 }
11963 }
11964
11965 // fold operands of srl based on knowledge that the low bits are not
11966 // demanded.
11968 return SDValue(N, 0);
11969
11970 if (N1C && !N1C->isOpaque())
11971 if (SDValue NewSRL = visitShiftByConstant(N))
11972 return NewSRL;
11973
11974 // Attempt to convert a srl of a load into a narrower zero-extending load.
11975 if (SDValue NarrowLoad = reduceLoadWidth(N))
11976 return NarrowLoad;
11977
11978 // Here is a common situation. We want to optimize:
11979 //
11980 // %a = ...
11981 // %b = and i32 %a, 2
11982 // %c = srl i32 %b, 1
11983 // brcond i32 %c ...
11984 //
11985 // into
11986 //
11987 // %a = ...
11988 // %b = and %a, 2
11989 // %c = setcc eq %b, 0
11990 // brcond %c ...
11991 //
11992 // However when after the source operand of SRL is optimized into AND, the SRL
11993 // itself may not be optimized further. Look for it and add the BRCOND into
11994 // the worklist.
11995 //
11996 // The also tends to happen for binary operations when SimplifyDemandedBits
11997 // is involved.
11998 //
11999 // FIXME: This is unecessary if we process the DAG in topological order,
12000 // which we plan to do. This workaround can be removed once the DAG is
12001 // processed in topological order.
12002 if (N->hasOneUse()) {
12003 SDNode *User = *N->user_begin();
12004
12005 // Look pass the truncate.
12006 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse())
12007 User = *User->user_begin();
12008
12009 if (User->getOpcode() == ISD::BRCOND || User->getOpcode() == ISD::AND ||
12010 User->getOpcode() == ISD::OR || User->getOpcode() == ISD::XOR)
12011 AddToWorklist(User);
12012 }
12013
12014 // Try to transform this shift into a multiply-high if
12015 // it matches the appropriate pattern detected in combineShiftToMULH.
12016 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
12017 return MULH;
12018
12019 if (SDValue AVG = foldShiftToAvg(N, DL))
12020 return AVG;
12021
12022 SDValue Y;
12023 if (VT.getScalarSizeInBits() % 2 == 0 && N1C) {
12024 // Fold clmul(zext(x), zext(y)) >> (BW - 1 | BW) -> clmul(r|h)(x, y).
12025 unsigned HalfBW = VT.getScalarSizeInBits() / 2;
12026 if (sd_match(N0, m_Clmul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
12027 X.getScalarValueSizeInBits() == HalfBW &&
12028 Y.getScalarValueSizeInBits() == HalfBW) {
12029 if (N1C->getZExtValue() == HalfBW - 1 &&
12030 (!LegalOperations ||
12031 TLI.isOperationLegalOrCustom(ISD::CLMULR, X.getValueType())))
12032 return DAG.getNode(
12033 ISD::ZERO_EXTEND, DL, VT,
12034 DAG.getNode(ISD::CLMULR, DL, X.getValueType(), X, Y));
12035 if (N1C->getZExtValue() == HalfBW &&
12036 (!LegalOperations ||
12037 TLI.isOperationLegalOrCustom(ISD::CLMULH, X.getValueType())))
12038 return DAG.getNode(
12039 ISD::ZERO_EXTEND, DL, VT,
12040 DAG.getNode(ISD::CLMULH, DL, X.getValueType(), X, Y));
12041 }
12042 }
12043
12044 // Fold bitreverse(clmul(bitreverse(x), bitreverse(y))) >> 1 ->
12045 // clmulh(x, y).
12046 if (N1C && N1C->getZExtValue() == 1 &&
12048 m_BitReverse(m_Value(Y))))))
12049 return DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
12050
12051 return SDValue();
12052}
12053
12054SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
12055 EVT VT = N->getValueType(0);
12056 SDValue N0 = N->getOperand(0);
12057 SDValue N1 = N->getOperand(1);
12058 SDValue N2 = N->getOperand(2);
12059 bool IsFSHL = N->getOpcode() == ISD::FSHL;
12060 unsigned BitWidth = VT.getScalarSizeInBits();
12061 SDLoc DL(N);
12062
12063 // fold (fshl/fshr C0, C1, C2) -> C3
12064 if (SDValue C =
12065 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
12066 return C;
12067
12068 // fold (fshl N0, N1, 0) -> N0
12069 // fold (fshr N0, N1, 0) -> N1
12071 if (DAG.MaskedValueIsZero(
12072 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
12073 return IsFSHL ? N0 : N1;
12074
12075 auto IsUndefOrZero = [](SDValue V) {
12076 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
12077 };
12078
12079 // TODO - support non-uniform vector shift amounts.
12080 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
12081 EVT ShAmtTy = N2.getValueType();
12082
12083 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
12084 if (Cst->getAPIntValue().uge(BitWidth)) {
12085 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
12086 return DAG.getNode(N->getOpcode(), DL, VT, N0, N1,
12087 DAG.getConstant(RotAmt, DL, ShAmtTy));
12088 }
12089
12090 unsigned ShAmt = Cst->getZExtValue();
12091 if (ShAmt == 0)
12092 return IsFSHL ? N0 : N1;
12093
12094 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
12095 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
12096 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
12097 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
12098 if (IsUndefOrZero(N0))
12099 return DAG.getNode(
12100 ISD::SRL, DL, VT, N1,
12101 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, DL, ShAmtTy));
12102 if (IsUndefOrZero(N1))
12103 return DAG.getNode(
12104 ISD::SHL, DL, VT, N0,
12105 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, DL, ShAmtTy));
12106
12107 // fold fshl(N0, N1, c) -> x and fshr(N0, N1, c) -> x
12108 // where N0 is any node that contributes "x >> C0" to the result:
12109 // lshr(x, C0) | fshr(_, x, C0) | fshl(_, x, C1)
12110 // and N1 is any node that contributes "x << C1" to the result:
12111 // shl(x, C1) | fshl(x, _, C1) | fshr(x, _, C0)
12112 // with C0 = IsFSHL ? amnt : BW-amnt, C1 = BW - C0
12113
12114 // ShAmt == 0 was handled above; uge(BitWidth) was reduced via modulo above.
12115 assert(ShAmt >= 1 && ShAmt < BitWidth &&
12116 "ShAmt must be in [1, BW-1] for the identity fold to be valid");
12117 SDValue Val;
12118 unsigned C0Expected = IsFSHL ? ShAmt : BitWidth - ShAmt;
12119 unsigned C1Expected = IsFSHL ? BitWidth - ShAmt : ShAmt;
12120
12121 if ((sd_match(N0, m_Srl(m_Value(Val), m_SpecificInt(C0Expected))) ||
12123 m_SpecificInt(C0Expected))) ||
12125 m_SpecificInt(C1Expected)))) &&
12126 (sd_match(N1, m_Shl(m_Specific(Val), m_SpecificInt(C1Expected))) ||
12128 m_SpecificInt(C1Expected))) ||
12130 m_SpecificInt(C0Expected)))))
12131 return Val;
12132
12133 // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
12134 // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
12135 // TODO - bigendian support once we have test coverage.
12136 // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
12137 // TODO - permit LHS EXTLOAD if extensions are shifted out.
12138 if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
12139 !DAG.getDataLayout().isBigEndian()) {
12140 auto *LHS = dyn_cast<LoadSDNode>(N0);
12141 auto *RHS = dyn_cast<LoadSDNode>(N1);
12142 if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
12143 LHS->getAddressSpace() == RHS->getAddressSpace() &&
12144 (LHS->hasNUsesOfValue(1, 0) || RHS->hasNUsesOfValue(1, 0)) &&
12146 if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
12147 SDLoc DL(RHS);
12148 uint64_t PtrOff =
12149 IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
12150 Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff);
12151 unsigned Fast = 0;
12152 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
12153 RHS->getAddressSpace(), NewAlign,
12154 RHS->getMemOperand()->getFlags(), &Fast) &&
12155 Fast) {
12156 SDValue NewPtr = DAG.getMemBasePlusOffset(
12157 RHS->getBasePtr(), TypeSize::getFixed(PtrOff), DL);
12158 AddToWorklist(NewPtr.getNode());
12159 SDValue Load = DAG.getLoad(
12160 VT, DL, RHS->getChain(), NewPtr,
12161 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12162 RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
12163 DAG.makeEquivalentMemoryOrdering(LHS, Load.getValue(1));
12164 DAG.makeEquivalentMemoryOrdering(RHS, Load.getValue(1));
12165 return Load;
12166 }
12167 }
12168 }
12169 }
12170 }
12171
12172 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
12173 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
12174 // iff We know the shift amount is in range.
12175 // TODO: when is it worth doing SUB(BW, N2) as well?
12176 if (isPowerOf2_32(BitWidth)) {
12177 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
12178 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
12179 return DAG.getNode(ISD::SRL, DL, VT, N1, N2);
12180 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
12181 return DAG.getNode(ISD::SHL, DL, VT, N0, N2);
12182 }
12183
12184 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
12185 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
12186 // TODO: Investigate flipping this rotate if only one is legal.
12187 // If funnel shift is legal as well we might be better off avoiding
12188 // non-constant (BW - N2).
12189 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
12190 if (N0 == N1 && hasOperation(RotOpc, VT))
12191 return DAG.getNode(RotOpc, DL, VT, N0, N2);
12192
12193 // Simplify, based on bits shifted out of N0/N1.
12195 return SDValue(N, 0);
12196
12197 return SDValue();
12198}
12199
12200SDValue DAGCombiner::visitSHLSAT(SDNode *N) {
12201 SDValue N0 = N->getOperand(0);
12202 SDValue N1 = N->getOperand(1);
12203 if (SDValue V = DAG.simplifyShift(N0, N1))
12204 return V;
12205
12206 SDLoc DL(N);
12207 EVT VT = N0.getValueType();
12208
12209 // fold (*shlsat c1, c2) -> c1<<c2
12210 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
12211 return C;
12212
12213 ConstantSDNode *N1C = isConstOrConstSplat(N1);
12214
12215 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) {
12216 // fold (sshlsat x, c) -> (shl x, c)
12217 if (N->getOpcode() == ISD::SSHLSAT && N1C &&
12218 N1C->getAPIntValue().ult(DAG.ComputeNumSignBits(N0)))
12219 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
12220
12221 // fold (ushlsat x, c) -> (shl x, c)
12222 if (N->getOpcode() == ISD::USHLSAT && N1C &&
12223 N1C->getAPIntValue().ule(
12225 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
12226 }
12227
12228 return SDValue();
12229}
12230
12231// Given a ABS node, detect the following patterns:
12232// (ABS (SUB (EXTEND a), (EXTEND b))).
12233// (TRUNC (ABS (SUB (EXTEND a), (EXTEND b)))).
12234// Generates UABD/SABD instruction.
12235SDValue DAGCombiner::foldABSToABD(SDNode *N, const SDLoc &DL) {
12236 EVT SrcVT = N->getValueType(0);
12237
12238 if (N->getOpcode() == ISD::TRUNCATE)
12239 N = N->getOperand(0).getNode();
12240
12241 EVT VT = N->getValueType(0);
12242 SDValue Op0, Op1;
12243
12244 if (!sd_match(N, m_Abs(m_AnyOf(m_Sub(m_Value(Op0), m_Value(Op1)),
12245 m_Add(m_Value(Op0), m_Value(Op1))))))
12246 return SDValue();
12247
12248 SDValue AbsOp0 = N->getOperand(0);
12249 bool IsAdd = AbsOp0.getOpcode() == ISD::ADD;
12250 // Make sure (abs B) is positive.
12251 if (IsAdd) {
12252 // Elements of Op1 must be constant and != VT.minSignedValue() (or undef)
12253 auto IsNotMinSignedInt = [VT](ConstantSDNode *C) {
12254 if (C == nullptr)
12255 return true;
12256 return !C->getAPIntValue()
12257 .trunc(VT.getScalarSizeInBits())
12258 .isMinSignedValue();
12259 };
12260
12261 if (!ISD::matchUnaryPredicate(Op1, IsNotMinSignedInt, /*AllowUndefs=*/true,
12262 /*AllowTruncation=*/true))
12263 return SDValue();
12264 }
12265
12266 unsigned Opc0 = Op0.getOpcode();
12267
12268 // Check if the operands of the sub are (zero|sign)-extended, otherwise
12269 // fallback to ValueTracking.
12270 if (Opc0 != Op1.getOpcode() ||
12271 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND &&
12272 Opc0 != ISD::SIGN_EXTEND_INREG)) {
12273
12274 auto CreateZextedAbd = [&](unsigned AbdOpc) {
12275 if (IsAdd)
12276 Op1 = DAG.getNegative(Op1, SDLoc(Op1), VT);
12277 SDValue ABD = DAG.getNode(AbdOpc, DL, VT, Op0, Op1);
12278 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12279 };
12280
12281 // fold (abs (sub nsw x, y)) -> abds(x, y)
12282 // fold (abs (add nsw x, -y)) -> abds(x, y)
12283 bool AbsOpWillNSW =
12284 AbsOp0->getFlags().hasNoSignedWrap() ||
12285 (IsAdd ? DAG.willNotOverflowAdd(/*IsSigned=*/true, Op0, Op1)
12286 : DAG.willNotOverflowSub(/*IsSigned=*/true, Op0, Op1));
12287
12288 // Don't fold this for unsupported types as we lose the NSW handling.
12289 if (hasOperation(ISD::ABDS, VT) && TLI.preferABDSToABSWithNSW(VT) &&
12290 AbsOpWillNSW)
12291 return CreateZextedAbd(ISD::ABDS);
12292
12293 // fold (abs (sub x, y)) -> abdu(x, y)
12294 bool AbsOpWillNUW =
12295 !IsAdd && DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1);
12296
12297 if (hasOperation(ISD::ABDU, VT) && AbsOpWillNUW)
12298 return CreateZextedAbd(ISD::ABDU);
12299
12300 return SDValue();
12301 }
12302
12303 // The IsAdd case explicitly checks for const/bv-of-const. This implies either
12304 // (Opc0 != Op1.getOpcode() || Opc0 is not in {zext/sext/sign_ext_inreg}. This
12305 // implies it was alrady handled by the above if statement.
12306 assert(!IsAdd && "Unexpected abs(add(x,y)) pattern");
12307
12308 EVT VT0, VT1;
12309 if (Opc0 == ISD::SIGN_EXTEND_INREG) {
12310 VT0 = cast<VTSDNode>(Op0.getOperand(1))->getVT();
12311 VT1 = cast<VTSDNode>(Op1.getOperand(1))->getVT();
12312 } else {
12313 VT0 = Op0.getOperand(0).getValueType();
12314 VT1 = Op1.getOperand(0).getValueType();
12315 }
12316 unsigned ABDOpcode = (Opc0 == ISD::ZERO_EXTEND) ? ISD::ABDU : ISD::ABDS;
12317
12318 // fold abs(sext(x) - sext(y)) -> zext(abds(x, y))
12319 // fold abs(zext(x) - zext(y)) -> zext(abdu(x, y))
12320 EVT MaxVT = VT0.bitsGT(VT1) ? VT0 : VT1;
12321 if ((VT0 == MaxVT || Op0->hasOneUse()) &&
12322 (VT1 == MaxVT || Op1->hasOneUse()) &&
12323 (!LegalTypes || hasOperation(ABDOpcode, MaxVT))) {
12324 SDValue ABD = DAG.getNode(ABDOpcode, DL, MaxVT,
12325 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op0),
12326 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op1));
12327 ABD = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ABD);
12328 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12329 }
12330
12331 // fold abs(sext(x) - sext(y)) -> abds(sext(x), sext(y))
12332 // fold abs(zext(x) - zext(y)) -> abdu(zext(x), zext(y))
12333 if (!LegalOperations || hasOperation(ABDOpcode, VT)) {
12334 SDValue ABD = DAG.getNode(ABDOpcode, DL, VT, Op0, Op1);
12335 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12336 }
12337
12338 return SDValue();
12339}
12340
12341SDValue DAGCombiner::visitABS(SDNode *N) {
12342 SDValue N0 = N->getOperand(0);
12343 EVT VT = N->getValueType(0);
12344 SDLoc DL(N);
12345
12346 // fold (abs c1) -> c2
12347 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ABS, DL, VT, {N0}))
12348 return C;
12349 // fold (abs (abs x)) -> (abs x)
12350 // fold (abs (abs_min_poison x)) -> (abs_min_poison x)
12351 if (ISD::isAbsOpcode(N0.getOpcode()))
12352 return N0;
12353 // fold (abs x) -> x iff not-negative
12354 if (DAG.SignBitIsZero(N0))
12355 return N0;
12356
12357 if (SDValue ABD = foldABSToABD(N, DL))
12358 return ABD;
12359
12360 // fold (abs (sign_extend_inreg x)) -> (zero_extend (abs (truncate x)))
12361 // iff zero_extend/truncate are free.
12362 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12363 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12364 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12365 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12366 hasOperation(ISD::ABS, ExtVT)) {
12367 return DAG.getNode(
12368 ISD::ZERO_EXTEND, DL, VT,
12369 DAG.getNode(ISD::ABS, DL, ExtVT,
12370 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12371 }
12372 }
12373
12374 return SDValue();
12375}
12376
12377SDValue DAGCombiner::visitABS_MIN_POISON(SDNode *N) {
12378 SDValue N0 = N->getOperand(0);
12379 EVT VT = N->getValueType(0);
12380 SDLoc DL(N);
12381
12382 // fold (abs_min_poison c1) -> c2 (or poison if c1 == INT_MIN)
12384 return C;
12385 // fold (abs_min_poison (abs_min_poison x)) -> (abs_min_poison x)
12386 // fold (abs_min_poison (abs x)) -> (abs x)
12387 // fold (abs_min_poison (freeze (abs x))) -> (freeze (abs x))
12388 // fold (abs_min_poison (freeze (abs_min_poison x))) ->
12389 // (freeze (abs_min_poison x))
12390 //
12391 // Freeze case is valid because: for x != INT_MIN both sides equal abs(x);
12392 // for x == INT_MIN both forms produce a non-deterministic but well-defined
12393 // value since freeze already consumed the poison.
12395 return N0;
12396 // fold (abs_min_poison x) -> x iff not-negative
12397 if (DAG.SignBitIsZero(N0))
12398 return N0;
12399
12400 if (SDValue ABD = foldABSToABD(N, DL))
12401 return ABD;
12402
12403 // fold (abs_min_poison (sign_extend_inreg x)) ->
12404 // (zero_extend (abs (truncate x)))
12405 // iff zero_extend/truncate are free. The sign_extend_inreg keeps the value
12406 // in the narrow type's range, so the wide abs_min_poison is never actually
12407 // poison.
12408 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12409 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12410 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12411 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12412 hasOperation(ISD::ABS, ExtVT)) {
12413 return DAG.getNode(
12414 ISD::ZERO_EXTEND, DL, VT,
12415 DAG.getNode(ISD::ABS, DL, ExtVT,
12416 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12417 }
12418 }
12419
12420 return SDValue();
12421}
12422
12423SDValue DAGCombiner::visitCLMUL(SDNode *N) {
12424 unsigned Opcode = N->getOpcode();
12425 SDValue N0 = N->getOperand(0);
12426 SDValue N1 = N->getOperand(1);
12427 EVT VT = N->getValueType(0);
12428 SDLoc DL(N);
12429
12430 // fold (clmul c1, c2)
12431 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
12432 return C;
12433
12434 // canonicalize constant to RHS
12437 return DAG.getNode(Opcode, DL, VT, N1, N0);
12438
12439 // fold (clmul x, 0) -> 0
12441 return DAG.getConstant(0, DL, VT);
12442
12443 // fold (clmul x, c_pow2) -> (shl x, log2(c_pow2))
12444 // This also handles (clmul x, 1) -> x since (shl x, 0) simplifies to x.
12445 if (Opcode == ISD::CLMUL) {
12446 if (ConstantSDNode *C = isConstOrConstSplat(N1)) {
12447 APInt CV = C->getAPIntValue().trunc(VT.getScalarSizeInBits());
12448 if (CV.isPowerOf2() &&
12449 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)))
12450 return DAG.getNode(ISD::SHL, DL, VT, N0,
12451 DAG.getShiftAmountConstant(CV.logBase2(), VT, DL));
12452 }
12453 }
12454
12455 return SDValue();
12456}
12457
12458SDValue DAGCombiner::visitPEXT(SDNode *N) {
12459 EVT VT = N->getValueType(0);
12460 SDValue N0 = N->getOperand(0);
12461 SDValue N1 = N->getOperand(1);
12462 SDLoc DL(N);
12463
12464 // pext(x, 0) -> 0
12465 if (isNullOrNullSplat(N1))
12466 return DAG.getConstant(0, DL, VT);
12467 // pext(x, -1) -> x (all bits selected, packed into low positions = x)
12469 return N0;
12470 // fold pext(c1, c2) -> c3
12471 if (SDValue C = DAG.FoldConstantArithmetic(ISD::PEXT, DL, VT, {N0, N1}))
12472 return C;
12473 return SDValue();
12474}
12475
12476SDValue DAGCombiner::visitPDEP(SDNode *N) {
12477 EVT VT = N->getValueType(0);
12478 SDValue N0 = N->getOperand(0);
12479 SDValue N1 = N->getOperand(1);
12480 SDLoc DL(N);
12481
12482 // pdep(x, 0) -> 0
12483 if (isNullOrNullSplat(N1))
12484 return DAG.getConstant(0, DL, VT);
12485
12486 // pdep(x, -1) -> x (all positions selected, bits deposited at identity)
12488 return N0;
12489
12490 // fold pdep(c1, c2) -> c3
12491 if (SDValue C = DAG.FoldConstantArithmetic(ISD::PDEP, DL, VT, {N0, N1}))
12492 return C;
12493
12495 return SDValue(N, 0);
12496
12497 return SDValue();
12498}
12499
12500SDValue DAGCombiner::visitBSWAP(SDNode *N) {
12501 SDValue N0 = N->getOperand(0);
12502 EVT VT = N->getValueType(0);
12503 SDLoc DL(N);
12504
12505 // fold (bswap c1) -> c2
12506 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BSWAP, DL, VT, {N0}))
12507 return C;
12508 // fold (bswap (bswap x)) -> x
12509 if (N0.getOpcode() == ISD::BSWAP)
12510 return N0.getOperand(0);
12511
12512 // Canonicalize bswap(bitreverse(x)) -> bitreverse(bswap(x)). If bitreverse
12513 // isn't supported, it will be expanded to bswap followed by a manual reversal
12514 // of bits in each byte. By placing bswaps before bitreverse, we can remove
12515 // the two bswaps if the bitreverse gets expanded.
12516 if (N0.getOpcode() == ISD::BITREVERSE && N0.hasOneUse()) {
12517 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12518 return DAG.getNode(ISD::BITREVERSE, DL, VT, BSwap);
12519 }
12520
12521 unsigned BW = VT.getScalarSizeInBits();
12522 // fold (bswap shl(x,c)) -> (zext(bswap(trunc(shl(x,sub(c,bw/2))))))
12523 // iff x >= bw/2 (i.e. lower half is known zero)
12524 if (BW >= 32 && N0.getOpcode() == ISD::SHL && N0.hasOneUse()) {
12525 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12526 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), BW / 2);
12527 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12528 ShAmt->getZExtValue() >= (BW / 2) && (ShAmt->getZExtValue() % 8) == 0 &&
12529 TLI.isTypeLegal(HalfVT) && TLI.isTruncateFree(VT, HalfVT) &&
12530 (!LegalOperations || hasOperation(ISD::BSWAP, HalfVT))) {
12531 SDValue Res = N0.getOperand(0);
12532 if (uint64_t NewShAmt = (ShAmt->getZExtValue() - (BW / 2)))
12533 Res = DAG.getNode(ISD::SHL, DL, VT, Res,
12534 DAG.getShiftAmountConstant(NewShAmt, VT, DL));
12535 Res = DAG.getZExtOrTrunc(Res, DL, HalfVT);
12536 Res = DAG.getNode(ISD::BSWAP, DL, HalfVT, Res);
12537 return DAG.getZExtOrTrunc(Res, DL, VT);
12538 }
12539 }
12540
12541 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
12542 // inverse-shift-of-bswap:
12543 // bswap (X u<< C) --> (bswap X) u>> C
12544 // bswap (X u>> C) --> (bswap X) u<< C
12545 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
12546 N0.hasOneUse()) {
12547 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12548 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12549 ShAmt->getZExtValue() % 8 == 0) {
12550 SDValue NewSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12551 unsigned InverseShift = N0.getOpcode() == ISD::SHL ? ISD::SRL : ISD::SHL;
12552 return DAG.getNode(InverseShift, DL, VT, NewSwap, N0.getOperand(1));
12553 }
12554 }
12555
12556 if (SDValue V = foldBitOrderCrossLogicOp(N, DAG))
12557 return V;
12558
12559 // Folds that depend on computeKnownBits of the operand.
12560 KnownBits Known = DAG.computeKnownBits(N0);
12561 // bswap(0) = 0. Catch cases that computeKnownBits can prove are zero but
12562 // that structural combines haven't simplified to a constant yet
12563 // (e.g. and of disjoint byte masks).
12564 if (Known.isZero())
12565 return DAG.getConstant(0, DL, VT);
12566 // If only one byte of the operand may be nonzero, bswap becomes a shift
12567 // to the mirror byte.
12568 unsigned TZ = alignDown(Known.countMinTrailingZeros(), 8);
12569 unsigned LZ = alignDown(Known.countMinLeadingZeros(), 8);
12570 if (BW - (LZ + TZ) == 8) {
12571 unsigned Opc = LZ > TZ ? ISD::SHL : ISD::SRL;
12572 // Skip if the target would re-expand the produced shift post-legalize.
12573 // Targets that custom-lower byte-multiple shifts via bswap (e.g. MSP430
12574 // for shl i16) would loop with this combine.
12575 if (!LegalOperations || hasOperation(Opc, VT)) {
12576 unsigned Amt = AbsoluteDifference(LZ, TZ);
12577 SDNodeFlags Flags =
12579 return DAG.getNode(Opc, DL, VT, N0,
12580 DAG.getShiftAmountConstant(Amt, VT, DL), Flags);
12581 }
12582 }
12583
12584 return SDValue();
12585}
12586
12587SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
12588 SDValue N0 = N->getOperand(0);
12589 EVT VT = N->getValueType(0);
12590 SDLoc DL(N);
12591
12592 // fold (bitreverse c1) -> c2
12593 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BITREVERSE, DL, VT, {N0}))
12594 return C;
12595
12596 // fold (bitreverse (bitreverse x)) -> x
12597 if (N0.getOpcode() == ISD::BITREVERSE)
12598 return N0.getOperand(0);
12599
12600 SDValue X, Y;
12601
12602 // fold (bitreverse (lshr (bitreverse x), y)) -> (shl x, y)
12603 if ((!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
12605 return DAG.getNode(ISD::SHL, DL, VT, X, Y);
12606
12607 // fold (bitreverse (shl (bitreverse x), y)) -> (lshr x, y)
12608 if ((!LegalOperations || TLI.isOperationLegal(ISD::SRL, VT)) &&
12610 return DAG.getNode(ISD::SRL, DL, VT, X, Y);
12611
12612 // fold bitreverse(clmul(bitreverse(x), bitreverse(y))) -> clmulr(x, y)
12613 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::CLMULR, VT)) &&
12615 return DAG.getNode(ISD::CLMULR, DL, VT, X, Y);
12616
12617 return SDValue();
12618}
12619
12620// Fold (ctlz (xor x, (sra x, bitwidth-1))) -> (add (ctls x), 1).
12621// Fold (ctlz (or (shl (xor x, (sra x, bitwidth-1)), 1), 1) -> (ctls x)
12622SDValue DAGCombiner::foldCTLZToCTLS(SDValue Src, const SDLoc &DL) {
12623 EVT VT = Src.getValueType();
12624
12625 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
12626 if ((LK.first != TargetLoweringBase::TypeLegal &&
12628 !TLI.isOperationLegalOrCustom(ISD::CTLS, LK.second))
12629 return SDValue();
12630
12631 unsigned BitWidth = VT.getScalarSizeInBits();
12632
12633 bool NeedAdd = true;
12634
12635 SDValue X;
12636 if (sd_match(Src,
12638 NeedAdd = false;
12639 Src = X;
12640 }
12641
12642 if (!sd_match(Src,
12645 m_SpecificInt(BitWidth - 1)))))))
12646 return SDValue();
12647
12648 SDValue Res = DAG.getNode(ISD::CTLS, DL, VT, X);
12649 if (!NeedAdd)
12650 return Res;
12651
12652 return DAG.getNode(ISD::ADD, DL, VT, Res, DAG.getConstant(1, DL, VT));
12653}
12654
12655SDValue DAGCombiner::visitCTLZ(SDNode *N) {
12656 SDValue N0 = N->getOperand(0);
12657 EVT VT = N->getValueType(0);
12658 SDLoc DL(N);
12659
12660 // fold (ctlz c1) -> c2
12661 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTLZ, DL, VT, {N0}))
12662 return C;
12663
12664 // If the value is known never to be zero, switch to the poison version.
12665 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_POISON, VT))
12666 if (DAG.isKnownNeverZero(N0))
12667 return DAG.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, N0);
12668
12669 if (SDValue V = foldCTLZToCTLS(N0, DL))
12670 return V;
12671
12672 return SDValue();
12673}
12674
12675SDValue DAGCombiner::visitCTLZ_ZERO_POISON(SDNode *N) {
12676 SDValue N0 = N->getOperand(0);
12677 EVT VT = N->getValueType(0);
12678 SDLoc DL(N);
12679
12680 // fold (ctlz_zero_poison c1) -> c2
12681 if (SDValue C =
12683 return C;
12684
12685 if (SDValue V = foldCTLZToCTLS(N0, DL))
12686 return V;
12687
12688 return SDValue();
12689}
12690
12691SDValue DAGCombiner::visitCTTZ(SDNode *N) {
12692 SDValue N0 = N->getOperand(0);
12693 EVT VT = N->getValueType(0);
12694 SDLoc DL(N);
12695
12696 // fold (cttz c1) -> c2
12697 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTTZ, DL, VT, {N0}))
12698 return C;
12699
12700 // If the value is known never to be zero, switch to the poison version.
12701 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_POISON, VT))
12702 if (DAG.isKnownNeverZero(N0))
12703 return DAG.getNode(ISD::CTTZ_ZERO_POISON, DL, VT, N0);
12704
12705 return SDValue();
12706}
12707
12708SDValue DAGCombiner::visitCTTZ_ZERO_POISON(SDNode *N) {
12709 SDValue N0 = N->getOperand(0);
12710 EVT VT = N->getValueType(0);
12711 SDLoc DL(N);
12712
12713 // fold (cttz_zero_poison c1) -> c2
12714 if (SDValue C =
12716 return C;
12717 return SDValue();
12718}
12719
12720SDValue DAGCombiner::visitCTPOP(SDNode *N) {
12721 SDValue N0 = N->getOperand(0);
12722 EVT VT = N->getValueType(0);
12723 unsigned NumBits = VT.getScalarSizeInBits();
12724 SDLoc DL(N);
12725
12726 // fold (ctpop c1) -> c2
12727 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTPOP, DL, VT, {N0}))
12728 return C;
12729
12730 // If the source is being shifted, but doesn't affect any active bits,
12731 // then we can call CTPOP on the shift source directly.
12732 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SHL) {
12733 if (ConstantSDNode *AmtC = isConstOrConstSplat(N0.getOperand(1))) {
12734 const APInt &Amt = AmtC->getAPIntValue();
12735 if (Amt.ult(NumBits)) {
12736 KnownBits KnownSrc = DAG.computeKnownBits(N0.getOperand(0));
12737 if ((N0.getOpcode() == ISD::SRL &&
12738 Amt.ule(KnownSrc.countMinTrailingZeros())) ||
12739 (N0.getOpcode() == ISD::SHL &&
12740 Amt.ule(KnownSrc.countMinLeadingZeros()))) {
12741 return DAG.getNode(ISD::CTPOP, DL, VT, N0.getOperand(0));
12742 }
12743 }
12744 }
12745 }
12746
12747 // If the upper bits are known to be zero, then see if its profitable to
12748 // only count the lower bits.
12749 if (VT.isScalarInteger() && NumBits > 8 && (NumBits & 1) == 0) {
12750 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), NumBits / 2);
12751 if (hasOperation(ISD::CTPOP, HalfVT) &&
12752 TLI.isTypeDesirableForOp(ISD::CTPOP, HalfVT) &&
12753 TLI.isTruncateFree(N0, HalfVT) && TLI.isZExtFree(HalfVT, VT)) {
12754 APInt UpperBits = APInt::getHighBitsSet(NumBits, NumBits / 2);
12755 if (DAG.MaskedValueIsZero(N0, UpperBits)) {
12756 SDValue PopCnt = DAG.getNode(ISD::CTPOP, DL, HalfVT,
12757 DAG.getZExtOrTrunc(N0, DL, HalfVT));
12758 return DAG.getZExtOrTrunc(PopCnt, DL, VT);
12759 }
12760 }
12761 }
12762
12763 return SDValue();
12764}
12765
12767 SDValue RHS,
12768 const SDNodeFlags SelectFlags,
12769 const SDNodeFlags CmpFlags,
12770 const TargetLowering &TLI) {
12771 EVT VT = LHS.getValueType();
12772 if (!VT.isFloatingPoint())
12773 return false;
12774
12775 return SelectFlags.hasNoSignedZeros() &&
12777 (SelectFlags.hasNoNaNs() || CmpFlags.hasNoNaNs() ||
12778 (DAG.isKnownNeverNaN(RHS) && DAG.isKnownNeverNaN(LHS)));
12779}
12780
12782 SDValue RHS, SDValue True, SDValue False,
12783 ISD::CondCode CC,
12784 const TargetLowering &TLI,
12785 SelectionDAG &DAG) {
12786 EVT TransformVT = TLI.getLegalTypeToTransformTo(*DAG.getContext(), VT);
12787
12788 // We have checked nnan and nsz as pre-conditions for the transform.
12790
12791 switch (CC) {
12792 case ISD::SETOLT:
12793 case ISD::SETOLE:
12794 case ISD::SETLT:
12795 case ISD::SETLE:
12796 case ISD::SETULT:
12797 case ISD::SETULE: {
12798 // Since it's known never nan to get here already, either fminnum or
12799 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
12800 // expanded in terms of it.
12801 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
12802 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12803 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS, Flags);
12804
12805 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
12806 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12807 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Flags);
12808 return SDValue();
12809 }
12810 case ISD::SETOGT:
12811 case ISD::SETOGE:
12812 case ISD::SETGT:
12813 case ISD::SETGE:
12814 case ISD::SETUGT:
12815 case ISD::SETUGE: {
12816 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
12817 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12818 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS, Flags);
12819
12820 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
12821 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12822 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Flags);
12823 return SDValue();
12824 }
12825 default:
12826 return SDValue();
12827 }
12828}
12829
12830// Convert (sr[al] (add n[su]w x, y)) -> (avgfloor[su] x, y)
12831SDValue DAGCombiner::foldShiftToAvg(SDNode *N, const SDLoc &DL) {
12832 const unsigned Opcode = N->getOpcode();
12833 if (Opcode != ISD::SRA && Opcode != ISD::SRL)
12834 return SDValue();
12835
12836 EVT VT = N->getValueType(0);
12837 bool IsUnsigned = Opcode == ISD::SRL;
12838
12839 // Captured values.
12840 SDValue A, B;
12841
12842 // Match floor average as it is common to both floor/ceil avgs, ensure the add
12843 // doesn't wrap.
12844 SDNodeFlags Flags =
12846 if (sd_match(N, m_BinOp(Opcode,
12847 m_c_BinOp(ISD::ADD, m_Value(A), m_Value(B), Flags),
12848 m_One()))) {
12849 // Decide whether signed or unsigned.
12850 unsigned FloorISD = IsUnsigned ? ISD::AVGFLOORU : ISD::AVGFLOORS;
12851 if (hasOperation(FloorISD, VT))
12852 return DAG.getNode(FloorISD, DL, VT, {A, B});
12853 }
12854
12855 return SDValue();
12856}
12857
12858SDValue DAGCombiner::foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT) {
12859 unsigned Opc = N->getOpcode();
12860 SDValue X, Y, Z;
12861 if (sd_match(
12863 return DAG.getNode(Opc, DL, VT, X,
12864 DAG.getNOT(DL, DAG.getNode(ISD::SUB, DL, VT, Y, Z), VT));
12865
12867 m_Value(Z)))))
12868 return DAG.getNode(Opc, DL, VT, X,
12869 DAG.getNOT(DL, DAG.getNode(ISD::ADD, DL, VT, Y, Z), VT));
12870
12871 return SDValue();
12872}
12873
12874/// Generate Min/Max node
12875SDValue DAGCombiner::combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
12876 SDValue RHS, SDValue True,
12877 SDValue False, ISD::CondCode CC) {
12878 if ((LHS == True && RHS == False) || (LHS == False && RHS == True))
12879 return combineMinNumMaxNumImpl(DL, VT, LHS, RHS, True, False, CC, TLI, DAG);
12880
12881 // If we can't directly match this, try to see if we can pull an fneg out of
12882 // the select.
12884 True, DAG, LegalOperations, ForCodeSize);
12885 if (!NegTrue)
12886 return SDValue();
12887
12888 HandleSDNode NegTrueHandle(NegTrue);
12889
12890 // Try to unfold an fneg from the select if we are comparing the negated
12891 // constant.
12892 //
12893 // select (setcc x, K) (fneg x), -K -> fneg(minnum(x, K))
12894 //
12895 // TODO: Handle fabs
12896 if (LHS == NegTrue) {
12897 // If we can't directly match this, try to see if we can pull an fneg out of
12898 // the select.
12900 RHS, DAG, LegalOperations, ForCodeSize);
12901 if (NegRHS) {
12902 HandleSDNode NegRHSHandle(NegRHS);
12903 if (NegRHS == False) {
12904 SDValue Combined = combineMinNumMaxNumImpl(DL, VT, LHS, RHS, NegTrue,
12905 False, CC, TLI, DAG);
12906 if (Combined)
12907 return DAG.getNode(ISD::FNEG, DL, VT, Combined);
12908 }
12909 }
12910 }
12911
12912 return SDValue();
12913}
12914
12915/// If a (v)select has a condition value that is a sign-bit test, try to smear
12916/// the condition operand sign-bit across the value width and use it as a mask.
12918 SelectionDAG &DAG) {
12919 SDValue Cond = N->getOperand(0);
12920 SDValue C1 = N->getOperand(1);
12921 SDValue C2 = N->getOperand(2);
12923 return SDValue();
12924
12925 EVT VT = N->getValueType(0);
12926 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
12927 VT != Cond.getOperand(0).getValueType())
12928 return SDValue();
12929
12930 // The inverted-condition + commuted-select variants of these patterns are
12931 // canonicalized to these forms in IR.
12932 SDValue X = Cond.getOperand(0);
12933 SDValue CondC = Cond.getOperand(1);
12934 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12935 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
12937 // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
12938 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12939 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12940 return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
12941 }
12942 if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
12943 // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
12944 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12945 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12946 return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
12947 }
12948 return SDValue();
12949}
12950
12952 const TargetLowering &TLI) {
12953 if (!TLI.convertSelectOfConstantsToMath(VT))
12954 return false;
12955
12956 if (Cond.getOpcode() != ISD::SETCC || !Cond->hasOneUse())
12957 return true;
12959 return true;
12960
12961 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12962 if (CC == ISD::SETLT && isNullOrNullSplat(Cond.getOperand(1)))
12963 return true;
12964 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond.getOperand(1)))
12965 return true;
12966
12967 return false;
12968}
12969
12970SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
12971 SDValue Cond = N->getOperand(0);
12972 SDValue N1 = N->getOperand(1);
12973 SDValue N2 = N->getOperand(2);
12974 EVT VT = N->getValueType(0);
12975 EVT CondVT = Cond.getValueType();
12976 SDLoc DL(N);
12977
12978 if (!VT.isInteger())
12979 return SDValue();
12980
12981 auto *C1 = dyn_cast<ConstantSDNode>(N1);
12982 auto *C2 = dyn_cast<ConstantSDNode>(N2);
12983 if (!C1 || !C2)
12984 return SDValue();
12985
12986 if (CondVT != MVT::i1 || LegalOperations) {
12987 // We can't do this reliably if integer based booleans have different contents
12988 // to floating point based booleans. This is because we can't tell whether we
12989 // have an integer-based boolean or a floating-point-based boolean unless we
12990 // can find the SETCC that produced it and inspect its operands. This is
12991 // fairly easy if C is the SETCC node, but it can potentially be
12992 // undiscoverable (or not reasonably discoverable). For example, it could be
12993 // in another basic block or it could require searching a complicated
12994 // expression.
12995 if (CondVT.isInteger() &&
12996 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
12998 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
13000 // fold (select Cond, 0, 1) -> (xor Cond, 1)
13001 if (C1->isZero() && C2->isOne()) {
13002 SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
13003 DAG.getConstant(1, DL, CondVT));
13004 if (VT.bitsEq(CondVT))
13005 return NotCond;
13006 return DAG.getZExtOrTrunc(NotCond, DL, VT);
13007 }
13008
13009 // fold (select Cond, 1, 0) -> Cond
13010 if (C1->isOne() && C2->isZero() && CondVT == VT)
13011 return Cond;
13012 }
13013
13014 return SDValue();
13015 }
13016
13017 // Only do this before legalization to avoid conflicting with target-specific
13018 // transforms in the other direction (create a select from a zext/sext). There
13019 // is also a target-independent combine here in DAGCombiner in the other
13020 // direction for (select Cond, -1, 0) when the condition is not i1.
13021 assert(CondVT == MVT::i1 && !LegalOperations);
13022
13023 // select Cond, 1, 0 --> zext (Cond)
13024 if (C1->isOne() && C2->isZero())
13025 return DAG.getZExtOrTrunc(Cond, DL, VT);
13026
13027 // select Cond, -1, 0 --> sext (Cond)
13028 if (C1->isAllOnes() && C2->isZero())
13029 return DAG.getSExtOrTrunc(Cond, DL, VT);
13030
13031 // select Cond, 0, 1 --> zext (!Cond)
13032 if (C1->isZero() && C2->isOne()) {
13033 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
13034 NotCond = DAG.getZExtOrTrunc(NotCond, DL, VT);
13035 return NotCond;
13036 }
13037
13038 // select Cond, 0, -1 --> sext (!Cond)
13039 if (C1->isZero() && C2->isAllOnes()) {
13040 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
13041 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
13042 return NotCond;
13043 }
13044
13045 // Use a target hook because some targets may prefer to transform in the
13046 // other direction.
13048 return SDValue();
13049
13050 // For any constants that differ by 1, we can transform the select into
13051 // an extend and add.
13052 const APInt &C1Val = C1->getAPIntValue();
13053 const APInt &C2Val = C2->getAPIntValue();
13054
13055 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
13056 if (C1Val - 1 == C2Val) {
13057 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
13058 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
13059 }
13060
13061 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
13062 if (C1Val + 1 == C2Val) {
13063 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
13064 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
13065 }
13066
13067 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
13068 if (C1Val.isPowerOf2() && C2Val.isZero()) {
13069 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
13070 SDValue ShAmtC =
13071 DAG.getShiftAmountConstant(C1Val.exactLogBase2(), VT, DL);
13072 return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
13073 }
13074
13075 // select Cond, -1, C --> or (sext Cond), C
13076 if (C1->isAllOnes()) {
13077 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
13078 return DAG.getNode(ISD::OR, DL, VT, Cond, N2);
13079 }
13080
13081 // select Cond, C, -1 --> or (sext (not Cond)), C
13082 if (C2->isAllOnes()) {
13083 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
13084 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
13085 return DAG.getNode(ISD::OR, DL, VT, NotCond, N1);
13086 }
13087
13089 return V;
13090
13091 return SDValue();
13092}
13093
13095 SelectionDAG &DAG) {
13096 assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) &&
13097 "Expected a (v)select");
13098 SDValue Cond = N->getOperand(0);
13099 SDValue T = N->getOperand(1), F = N->getOperand(2);
13100 EVT VT = N->getValueType(0);
13101
13102 if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1)
13103 return SDValue();
13104
13105 // select Cond, Cond, F --> or Cond, freeze(F)
13106 // select Cond, 1, F --> or Cond, freeze(F)
13107 if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true))
13108 return DAG.getNode(ISD::OR, DL, VT, Cond, DAG.getFreeze(F));
13109
13110 // select Cond, T, Cond --> and Cond, freeze(T)
13111 // select Cond, T, 0 --> and Cond, freeze(T)
13112 if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true))
13113 return DAG.getNode(ISD::AND, DL, VT, Cond, DAG.getFreeze(T));
13114
13115 // select Cond, T, 1 --> or (not Cond), freeze(T)
13116 if (isOneOrOneSplat(F, /* AllowUndefs */ true)) {
13117 SDValue NotCond =
13118 DAG.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
13119 return DAG.getNode(ISD::OR, DL, VT, NotCond, DAG.getFreeze(T));
13120 }
13121
13122 // select Cond, 0, F --> and (not Cond), freeze(F)
13123 if (isNullOrNullSplat(T, /* AllowUndefs */ true)) {
13124 SDValue NotCond =
13125 DAG.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
13126 return DAG.getNode(ISD::AND, DL, VT, NotCond, DAG.getFreeze(F));
13127 }
13128
13129 return SDValue();
13130}
13131
13133 SDValue N0 = N->getOperand(0);
13134 SDValue N1 = N->getOperand(1);
13135 SDValue N2 = N->getOperand(2);
13136 EVT VT = N->getValueType(0);
13137 unsigned EltSizeInBits = VT.getScalarSizeInBits();
13138
13139 SDValue Cond0, Cond1;
13140 ISD::CondCode CC;
13141 if (!sd_match(N0, m_OneUse(m_SetCC(m_Value(Cond0), m_Value(Cond1),
13142 m_CondCode(CC)))) ||
13143 VT != Cond0.getValueType())
13144 return SDValue();
13145
13146 // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the
13147 // compare is inverted from that pattern ("Cond0 s> -1").
13148 if (CC == ISD::SETLT && isNullOrNullSplat(Cond1))
13149 ; // This is the pattern we are looking for.
13150 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1))
13151 std::swap(N1, N2);
13152 else
13153 return SDValue();
13154
13155 // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & freeze(N1)
13156 if (isNullOrNullSplat(N2)) {
13157 SDLoc DL(N);
13158 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
13159 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
13160 return DAG.getNode(ISD::AND, DL, VT, Sra, DAG.getFreeze(N1));
13161 }
13162
13163 // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | freeze(N2)
13164 if (isAllOnesOrAllOnesSplat(N1)) {
13165 SDLoc DL(N);
13166 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
13167 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
13168 return DAG.getNode(ISD::OR, DL, VT, Sra, DAG.getFreeze(N2));
13169 }
13170
13171 // If we have to invert the sign bit mask, only do that transform if the
13172 // target has a bitwise 'and not' instruction (the invert is free).
13173 // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & freeze(N2)
13174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13175 if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) {
13176 SDLoc DL(N);
13177 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
13178 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
13179 SDValue Not = DAG.getNOT(DL, Sra, VT);
13180 return DAG.getNode(ISD::AND, DL, VT, Not, DAG.getFreeze(N2));
13181 }
13182
13183 // TODO: There's another pattern in this family, but it may require
13184 // implementing hasOrNot() to check for profitability:
13185 // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | freeze(N2)
13186
13187 return SDValue();
13188}
13189
13190// Match SELECTs with absolute difference patterns.
13191// (select (setcc a, b, set?gt), (sub a, b), (sub b, a)) --> (abd? a, b)
13192// (select (setcc a, b, set?ge), (sub a, b), (sub b, a)) --> (abd? a, b)
13193// (select (setcc a, b, set?lt), (sub b, a), (sub a, b)) --> (abd? a, b)
13194// (select (setcc a, b, set?le), (sub b, a), (sub a, b)) --> (abd? a, b)
13195SDValue DAGCombiner::foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
13196 SDValue False, ISD::CondCode CC,
13197 const SDLoc &DL) {
13198 bool IsSigned = isSignedIntSetCC(CC);
13199 unsigned ABDOpc = IsSigned ? ISD::ABDS : ISD::ABDU;
13200 EVT VT = LHS.getValueType();
13201
13202 if (LegalOperations && !hasOperation(ABDOpc, VT))
13203 return SDValue();
13204
13205 // (setcc 0, b set???) --> (setcc b, 0, set???)
13206 if (isZeroOrZeroSplat(LHS)) {
13207 std::swap(LHS, RHS);
13209 }
13210
13211 // (setcc (add nsw A, Const), 0, sets??) --> (setcc A, -Const, sets??)
13212 SDValue A, B;
13213 if (ISD::isSignedIntSetCC(CC) && LHS->getFlags().hasNoSignedWrap() &&
13216 RHS = DAG.getNegative(B, LHS, B.getValueType());
13217 LHS = A;
13218 }
13219
13220 bool IsTypeLegalOrPromote =
13221 TLI.isTypeLegal(VT) || TLI.getTypeAction(*DAG.getContext(), VT) ==
13223
13224 switch (CC) {
13225 case ISD::SETGT:
13226 case ISD::SETGE:
13227 case ISD::SETUGT:
13228 case ISD::SETUGE:
13233 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
13238 IsTypeLegalOrPromote)
13239 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
13240 break;
13241 case ISD::SETLT:
13242 case ISD::SETLE:
13243 case ISD::SETULT:
13244 case ISD::SETULE:
13249 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
13254 IsTypeLegalOrPromote)
13255 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
13256 break;
13257 default:
13258 break;
13259 }
13260
13261 return SDValue();
13262}
13263
13264// ([v]select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
13265// ([v]select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
13266SDValue DAGCombiner::foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
13267 SDValue False, ISD::CondCode CC,
13268 const SDLoc &DL) {
13269 APInt C;
13270 EVT VT = True.getValueType();
13271 if (sd_match(RHS, m_ConstInt(C)) && hasUMin(VT)) {
13272 if (CC == ISD::SETUGT && LHS == False &&
13273 sd_match(True, m_Add(m_Specific(False), m_SpecificInt(~C)))) {
13274 SDValue AddC = DAG.getConstant(~C, DL, VT);
13275 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, False, AddC);
13276 return DAG.getNode(ISD::UMIN, DL, VT, Add, False);
13277 }
13278 if (CC == ISD::SETULT && LHS == True &&
13279 sd_match(False, m_Add(m_Specific(True), m_SpecificInt(-C)))) {
13280 SDValue AddC = DAG.getConstant(-C, DL, VT);
13281 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, True, AddC);
13282 return DAG.getNode(ISD::UMIN, DL, VT, True, Add);
13283 }
13284 }
13285 return SDValue();
13286}
13287
13288// Combine x olt y ? x : y to pseudo_fmin and x ogt y ? x : y to pseudo_fmax.
13289// Op0/Op1 are the setcc operands, LHS/RHS are the select operands, Flags are
13290// from the select.
13291// The return value is the opcode and its operands.
13292static std::tuple<unsigned, SDValue, SDValue> combineSelectCCToPseudoMinMax(
13293 SelectionDAG &DAG, const SDLoc &DL, ISD::CondCode CC, SDValue Op0,
13294 SDValue Op1, SDValue LHS, SDValue RHS, SDNodeFlags Flags, bool IsStrict) {
13295 std::tuple<unsigned, SDValue, SDValue> Invalid(0, {}, {});
13296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13297 EVT VT = LHS.getValueType();
13298 if (!VT.isFloatingPoint())
13299 return Invalid;
13300
13301 // Check for x CC y ? x : y.
13302 if (!DAG.isEqualTo(LHS, Op0) || !DAG.isEqualTo(RHS, Op1)) {
13303 if (!DAG.isEqualTo(LHS, Op1) || !DAG.isEqualTo(RHS, Op0))
13304 return Invalid;
13305
13306 // Convert x CC y ? y : x to x inv(CC) y ? x : y.
13307 CC = ISD::getSetCCInverse(CC, VT);
13308 std::swap(LHS, RHS);
13309 }
13310
13311 // Convert x CC y ? x : y to y swap(inv(CC)) x ? y : x
13312 // to convert an unordered into an ordered comparison.
13313 if (ISD::getUnorderedFlavor(CC) == 1) {
13315 std::swap(LHS, RHS);
13316 }
13317
13318 unsigned Opcode = 0;
13319 switch (CC) {
13320 default:
13321 break;
13322 case ISD::SETOLE:
13323 // Converting this to a min would handle comparisons between positive
13324 // and negative zero incorrectly.
13325 if (!Flags.hasNoSignedZeros() && !DAG.isKnownNeverLogicalZero(LHS) &&
13327 break;
13328 Opcode = ISD::PSEUDO_FMIN;
13329 break;
13330 case ISD::SETLE:
13331 // Convert setle to setlt via inv+swap.
13332 std::swap(LHS, RHS);
13333 [[fallthrough]];
13334 case ISD::SETOLT:
13335 case ISD::SETLT:
13336 Opcode = ISD::PSEUDO_FMIN;
13337 break;
13338
13339 case ISD::SETOGE:
13340 // Converting this to a max would handle comparisons between positive
13341 // and negative zero incorrectly.
13342 if (!Flags.hasNoSignedZeros() && !DAG.isKnownNeverLogicalZero(LHS) &&
13344 break;
13345 Opcode = ISD::PSEUDO_FMAX;
13346 break;
13347 case ISD::SETGE:
13348 // Convert setge to setgt via inv+swap.
13349 std::swap(LHS, RHS);
13350 [[fallthrough]];
13351 case ISD::SETOGT:
13352 case ISD::SETGT:
13353 Opcode = ISD::PSEUDO_FMAX;
13354 break;
13355 }
13356
13357 if (!Opcode)
13358 return Invalid;
13359
13360 if (IsStrict)
13361 Opcode = Opcode == ISD::PSEUDO_FMIN ? ISD::STRICT_PSEUDO_FMIN
13363 if (!TLI.isOperationLegalOrCustom(Opcode, VT))
13364 return Invalid;
13365
13366 return {Opcode, LHS, RHS};
13367}
13368
13370 SDLoc DL(N);
13371 SDValue Cond = N->getOperand(0);
13372 SDValue LHS = N->getOperand(1);
13373 SDValue RHS = N->getOperand(2);
13374 EVT VT = LHS.getValueType();
13375 if ((Cond.getOpcode() != ISD::SETCC &&
13376 Cond.getOpcode() != ISD::STRICT_FSETCCS))
13377 return SDValue();
13378
13379 bool IsStrict = Cond->isStrictFPOpcode();
13380 ISD::CondCode CC =
13381 cast<CondCodeSDNode>(Cond.getOperand(IsStrict ? 3 : 2))->get();
13382 SDValue Op0 = Cond.getOperand(IsStrict ? 1 : 0);
13383 SDValue Op1 = Cond.getOperand(IsStrict ? 2 : 1);
13384 auto [Opcode, NewLHS, NewRHS] = combineSelectCCToPseudoMinMax(
13385 DAG, DL, CC, Op0, Op1, LHS, RHS, N->getFlags(), IsStrict);
13386 if (!Opcode)
13387 return SDValue();
13388
13389 // Propagate fast-math-flags.
13390 SelectionDAG::FlagInserter FlagsInserter(DAG, N->getFlags());
13391 if (IsStrict) {
13392 SDValue Ret = DAG.getNode(Opcode, DL, {VT, MVT::Other},
13393 {Cond.getOperand(0), NewLHS, NewRHS});
13394 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Ret.getValue(1));
13395 return Ret;
13396 }
13397 return DAG.getNode(Opcode, DL, VT, NewLHS, NewRHS);
13398}
13399
13400/// Fold:
13401/// select_cc (select C, TV, FV), CmpC, TrueV, FalseV, seteq
13402/// -> select C, TrueV, FalseV
13403/// select_cc (select C, TV, FV), CmpC, TrueV, FalseV, setne
13404/// -> select C, FalseV, TrueV
13405/// and the same with CmpC on the LHS of the comparison. TV and FV must be
13406/// distinct integer constants. Also used for select (setcc ...).
13408 SDValue TrueV, SDValue FalseV,
13409 const SDLoc &DL, EVT VT, SelectionDAG &DAG,
13410 SDNodeFlags Flags) {
13411 if (CC != ISD::SETEQ && CC != ISD::SETNE)
13412 return SDValue();
13413
13414 SDValue InnerSel;
13415 SDValue CmpC;
13416 if (LHS.getOpcode() == ISD::SELECT) {
13417 InnerSel = LHS;
13418 CmpC = RHS;
13419 } else if (RHS.getOpcode() == ISD::SELECT) {
13420 InnerSel = RHS;
13421 CmpC = LHS;
13422 } else
13423 return SDValue();
13424
13425 SDValue Cond = InnerSel.getOperand(0);
13426 SDValue InnerTV = InnerSel.getOperand(1);
13427 SDValue InnerFV = InnerSel.getOperand(2);
13428
13429 auto *CTV = dyn_cast<ConstantSDNode>(InnerTV);
13430 auto *CFV = dyn_cast<ConstantSDNode>(InnerFV);
13431 auto *CCnst = dyn_cast<ConstantSDNode>(CmpC);
13432 if (!CTV || !CFV || !CCnst)
13433 return SDValue();
13434
13435 // If one of the constants is opaque, the SDNodes may differ while the values
13436 // are the same. Check APInt to avoid miscompiles.
13437 if (CTV->getAPIntValue() == CFV->getAPIntValue())
13438 return SDValue();
13439
13440 const APInt &CmpVal = CCnst->getAPIntValue();
13441 bool MatchesTV = CmpVal == CTV->getAPIntValue();
13442 bool MatchesFV = CmpVal == CFV->getAPIntValue();
13443 if (!MatchesTV && !MatchesFV)
13444 return SDValue();
13445
13446 SDValue SelTrueV = TrueV;
13447 SDValue SelFalseV = FalseV;
13448 if (CC == ISD::SETEQ) {
13449 if (MatchesFV)
13450 std::swap(SelTrueV, SelFalseV);
13451 } else {
13452 if (MatchesTV)
13453 std::swap(SelTrueV, SelFalseV);
13454 }
13455
13456 return DAG.getSelect(DL, VT, Cond, SelTrueV, SelFalseV, Flags);
13457}
13458
13460 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
13461 return foldSelectOfSelectCmp(N->getOperand(0), N->getOperand(1), CC,
13462 N->getOperand(2), N->getOperand(3), SDLoc(N),
13463 N->getValueType(0), DAG, N->getFlags());
13464}
13465
13466SDValue DAGCombiner::visitSELECT(SDNode *N) {
13467 SDValue N0 = N->getOperand(0);
13468 SDValue N1 = N->getOperand(1);
13469 SDValue N2 = N->getOperand(2);
13470 EVT VT = N->getValueType(0);
13471 EVT VT0 = N0.getValueType();
13472 SDLoc DL(N);
13473 SDNodeFlags Flags = N->getFlags();
13474
13475 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
13476 return V;
13477
13478 if (SDValue V = foldBoolSelectToLogic(N, DL, DAG))
13479 return V;
13480
13481 // select (not Cond), N1, N2 -> select Cond, N2, N1
13482 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
13483 return DAG.getSelect(DL, VT, F, N2, N1, Flags);
13484
13485 if (SDValue V = foldSelectOfConstants(N))
13486 return V;
13487
13488 // select (setcc (select C, TV, FV), CmpC, cc), TrueV, FalseV
13489 // -> select C, TrueV, FalseV (or swapped FalseV/TrueV)
13490 if (N0.getOpcode() == ISD::SETCC) {
13493 CC, N1, N2, DL, VT, DAG, Flags))
13494 return R;
13495 }
13496
13497 // If we can fold this based on the true/false value, do so.
13498 if (SimplifySelectOps(N, N1, N2))
13499 return SDValue(N, 0); // Don't revisit N.
13500
13501 if (VT0 == MVT::i1) {
13502 // The code in this block deals with the following 2 equivalences:
13503 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
13504 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
13505 // The target can specify its preferred form with the
13506 // shouldNormalizeToSelectSequence() callback. However we always transform
13507 // to the right anyway if we find the inner select exists in the DAG anyway
13508 // and we always transform to the left side if we know that we can further
13509 // optimize the combination of the conditions.
13510 bool normalizeToSequence =
13511 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT, VT0);
13512 // select (and Cond0, Cond1), X, Y
13513 // -> select Cond0, (select Cond1, X, Y), Y
13514 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
13515 SDValue Cond0 = N0->getOperand(0);
13516 SDValue Cond1 = N0->getOperand(1);
13517 SDValue InnerSelect =
13518 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
13519 if (normalizeToSequence || !InnerSelect.use_empty())
13520 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
13521 InnerSelect, N2, Flags);
13522 // Cleanup on failure.
13523 if (InnerSelect.use_empty())
13524 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13525 }
13526 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
13527 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
13528 SDValue Cond0 = N0->getOperand(0);
13529 SDValue Cond1 = N0->getOperand(1);
13530 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
13531 Cond1, N1, N2, Flags);
13532 if (normalizeToSequence || !InnerSelect.use_empty())
13533 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
13534 InnerSelect, Flags);
13535 // Cleanup on failure.
13536 if (InnerSelect.use_empty())
13537 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13538 }
13539
13540 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
13541 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
13542 SDValue N1_0 = N1->getOperand(0);
13543 SDValue N1_1 = N1->getOperand(1);
13544 SDValue N1_2 = N1->getOperand(2);
13545 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
13546 // Create the actual and node if we can generate good code for it.
13547 if (!normalizeToSequence) {
13548 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
13549 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
13550 N2, Flags);
13551 }
13552 // Otherwise see if we can optimize the "and" to a better pattern.
13553 if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
13554 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
13555 N2, Flags);
13556 }
13557 }
13558 }
13559 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
13560 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
13561 SDValue N2_0 = N2->getOperand(0);
13562 SDValue N2_1 = N2->getOperand(1);
13563 SDValue N2_2 = N2->getOperand(2);
13564 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
13565 // Create the actual or node if we can generate good code for it.
13566 if (!normalizeToSequence) {
13567 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
13568 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
13569 N2_2, Flags);
13570 }
13571 // Otherwise see if we can optimize to a better pattern.
13572 if (SDValue Combined = visitORLike(N0, N2_0, DL))
13573 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
13574 N2_2, Flags);
13575 }
13576 }
13577
13578 // select usubo(x, y).overflow, (sub y, x), (usubo x, y) -> abdu(x, y)
13579 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13580 N2.getNode() == N0.getNode() && N2.getResNo() == 0 &&
13581 N1.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13582 N2.getOperand(1) == N1.getOperand(0) &&
13583 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13584 return DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1));
13585
13586 // select usubo(x, y).overflow, (usubo x, y), (sub y, x) -> neg (abdu x, y)
13587 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13588 N1.getNode() == N0.getNode() && N1.getResNo() == 0 &&
13589 N2.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13590 N2.getOperand(1) == N1.getOperand(0) &&
13591 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13592 return DAG.getNegative(
13593 DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1)),
13594 DL, VT);
13595 }
13596
13597 // Fold selects based on a setcc into other things, such as min/max/abs.
13598 if (N0.getOpcode() == ISD::SETCC) {
13599 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
13601
13602 // select (fcmp lt x, y), x, y -> fminnum x, y
13603 // select (fcmp gt x, y), x, y -> fmaxnum x, y
13604 //
13605 // This is OK if we don't care what happens if either operand is a NaN.
13606 if (N0.hasOneUse() &&
13607 isLegalToCombineMinNumMaxNum(DAG, N1, N2, Flags, N0->getFlags(), TLI))
13608 if (SDValue FMinMax =
13609 combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, CC))
13610 return FMinMax;
13611
13612 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
13613 // This is conservatively limited to pre-legal-operations to give targets
13614 // a chance to reverse the transform if they want to do that. Also, it is
13615 // unlikely that the pattern would be formed late, so it's probably not
13616 // worth going through the other checks.
13617 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
13618 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
13619 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
13620 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
13621 auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
13622 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
13623 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
13624 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
13625 //
13626 // The IR equivalent of this transform would have this form:
13627 // %a = add %x, C
13628 // %c = icmp ugt %x, ~C
13629 // %r = select %c, -1, %a
13630 // =>
13631 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
13632 // %u0 = extractvalue %u, 0
13633 // %u1 = extractvalue %u, 1
13634 // %r = select %u1, -1, %u0
13635 SDVTList VTs = DAG.getVTList(VT, VT0);
13636 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
13637 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
13638 }
13639 }
13640
13642 return S;
13643
13644 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
13645 (!LegalOperations &&
13647 // Any flags available in a select/setcc fold will be on the setcc as they
13648 // migrated from fcmp
13649 return DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, N2,
13650 N0.getOperand(2), N0->getFlags());
13651 }
13652
13653 if (SDValue ABD = foldSelectToABD(Cond0, Cond1, N1, N2, CC, DL))
13654 return ABD;
13655
13656 if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
13657 return NewSel;
13658
13659 // (select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
13660 // (select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
13661 if (SDValue UMin = foldSelectToUMin(Cond0, Cond1, N1, N2, CC, DL))
13662 return UMin;
13663 }
13664
13665 if (!VT.isVector())
13666 if (SDValue BinOp = foldSelectOfBinops(N))
13667 return BinOp;
13668
13669 if (SDValue R = combineSelectAsExtAnd(N0, N1, N2, DL, DAG))
13670 return R;
13671
13673 return R;
13674
13675 return SDValue();
13676}
13677
13678// This function assumes all the vselect's arguments are CONCAT_VECTOR
13679// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
13681 SDLoc DL(N);
13682 SDValue Cond = N->getOperand(0);
13683 SDValue LHS = N->getOperand(1);
13684 SDValue RHS = N->getOperand(2);
13685 EVT VT = N->getValueType(0);
13686 int NumElems = VT.getVectorNumElements();
13687 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
13688 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
13689 Cond.getOpcode() == ISD::BUILD_VECTOR);
13690
13691 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
13692 // binary ones here.
13693 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
13694 return SDValue();
13695
13696 // We're sure we have an even number of elements due to the
13697 // concat_vectors we have as arguments to vselect.
13698 // Skip BV elements until we find one that's not an UNDEF
13699 // After we find an UNDEF element, keep looping until we get to half the
13700 // length of the BV and see if all the non-undef nodes are the same.
13701 ConstantSDNode *BottomHalf = nullptr;
13702 for (int i = 0; i < NumElems / 2; ++i) {
13703 if (Cond->getOperand(i)->isUndef())
13704 continue;
13705
13706 if (BottomHalf == nullptr)
13707 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13708 else if (Cond->getOperand(i).getNode() != BottomHalf)
13709 return SDValue();
13710 }
13711
13712 // Do the same for the second half of the BuildVector
13713 ConstantSDNode *TopHalf = nullptr;
13714 for (int i = NumElems / 2; i < NumElems; ++i) {
13715 if (Cond->getOperand(i)->isUndef())
13716 continue;
13717
13718 if (TopHalf == nullptr)
13719 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13720 else if (Cond->getOperand(i).getNode() != TopHalf)
13721 return SDValue();
13722 }
13723
13724 assert(TopHalf && BottomHalf &&
13725 "One half of the selector was all UNDEFs and the other was all the "
13726 "same value. This should have been addressed before this function.");
13727 return DAG.getNode(
13729 BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0),
13730 TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1));
13731}
13732
13733bool refineUniformBase(SDValue &BasePtr, SDValue &Index, bool IndexIsScaled,
13734 SelectionDAG &DAG, const SDLoc &DL) {
13735
13736 // Only perform the transformation when existing operands can be reused.
13737 if (IndexIsScaled)
13738 return false;
13739
13740 if (!isNullConstant(BasePtr) && !Index.hasOneUse())
13741 return false;
13742
13743 EVT VT = BasePtr.getValueType();
13744
13745 if (SDValue SplatVal = DAG.getSplatValue(Index);
13746 SplatVal && !isNullConstant(SplatVal) &&
13747 SplatVal.getValueType() == VT) {
13748 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13749 Index = DAG.getSplat(Index.getValueType(), DL, DAG.getConstant(0, DL, VT));
13750 return true;
13751 }
13752
13753 if (Index.getOpcode() != ISD::ADD)
13754 return false;
13755
13756 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(0));
13757 SplatVal && SplatVal.getValueType() == VT) {
13758 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13759 Index = Index.getOperand(1);
13760 return true;
13761 }
13762 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(1));
13763 SplatVal && SplatVal.getValueType() == VT) {
13764 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13765 Index = Index.getOperand(0);
13766 return true;
13767 }
13768 return false;
13769}
13770
13771// Fold sext/zext of index into index type.
13772bool refineIndexType(SDValue &Index, ISD::MemIndexType &IndexType, EVT DataVT,
13773 SelectionDAG &DAG) {
13774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13775
13776 // It's always safe to look through zero extends.
13777 if (Index.getOpcode() == ISD::ZERO_EXTEND) {
13778 if (TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13779 IndexType = ISD::UNSIGNED_SCALED;
13780 Index = Index.getOperand(0);
13781 return true;
13782 }
13783 if (ISD::isIndexTypeSigned(IndexType)) {
13784 IndexType = ISD::UNSIGNED_SCALED;
13785 return true;
13786 }
13787 }
13788
13789 // It's only safe to look through sign extends when Index is signed.
13790 if (Index.getOpcode() == ISD::SIGN_EXTEND &&
13791 ISD::isIndexTypeSigned(IndexType) &&
13792 TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13793 Index = Index.getOperand(0);
13794 return true;
13795 }
13796
13797 return false;
13798}
13799
13800SDValue DAGCombiner::visitVPSCATTER(SDNode *N) {
13801 VPScatterSDNode *MSC = cast<VPScatterSDNode>(N);
13802 SDValue Mask = MSC->getMask();
13803 SDValue Chain = MSC->getChain();
13804 SDValue Index = MSC->getIndex();
13805 SDValue Scale = MSC->getScale();
13806 SDValue StoreVal = MSC->getValue();
13807 SDValue BasePtr = MSC->getBasePtr();
13808 SDValue VL = MSC->getVectorLength();
13809 ISD::MemIndexType IndexType = MSC->getIndexType();
13810 SDLoc DL(N);
13811
13812 // Zap scatters with a zero mask.
13814 return Chain;
13815
13816 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13817 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13818 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13819 DL, Ops, MSC->getMemOperand(), IndexType);
13820 }
13821
13822 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13823 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13824 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13825 DL, Ops, MSC->getMemOperand(), IndexType);
13826 }
13827
13828 return SDValue();
13829}
13830
13831SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
13832 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
13833 SDValue Mask = MSC->getMask();
13834 SDValue Chain = MSC->getChain();
13835 SDValue Index = MSC->getIndex();
13836 SDValue Scale = MSC->getScale();
13837 SDValue StoreVal = MSC->getValue();
13838 SDValue BasePtr = MSC->getBasePtr();
13839 ISD::MemIndexType IndexType = MSC->getIndexType();
13840 SDLoc DL(N);
13841
13842 // Zap scatters with a zero mask.
13844 return Chain;
13845
13846 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13847 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13848 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13849 DL, Ops, MSC->getMemOperand(), IndexType,
13850 MSC->isTruncatingStore());
13851 }
13852
13853 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13854 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13855 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13856 DL, Ops, MSC->getMemOperand(), IndexType,
13857 MSC->isTruncatingStore());
13858 }
13859
13860 return SDValue();
13861}
13862
13863SDValue DAGCombiner::visitMSTORE(SDNode *N) {
13864 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
13865 SDValue Mask = MST->getMask();
13866 SDValue Chain = MST->getChain();
13867 SDValue Value = MST->getValue();
13868 SDValue Ptr = MST->getBasePtr();
13869
13870 // Zap masked stores with a zero mask.
13872 return Chain;
13873
13874 // Remove a masked store if base pointers and masks are equal.
13875 if (MaskedStoreSDNode *MST1 = dyn_cast<MaskedStoreSDNode>(Chain)) {
13876 if (MST->isUnindexed() && MST->isSimple() && MST1->isUnindexed() &&
13877 MST1->isSimple() && MST1->getBasePtr() == Ptr &&
13878 !MST->getBasePtr().isUndef() &&
13879 ((Mask == MST1->getMask() && MST->getMemoryVT().getStoreSize() ==
13880 MST1->getMemoryVT().getStoreSize()) ||
13882 TypeSize::isKnownLE(MST1->getMemoryVT().getStoreSize(),
13883 MST->getMemoryVT().getStoreSize())) {
13884 CombineTo(MST1, MST1->getChain());
13885 if (N->getOpcode() != ISD::DELETED_NODE)
13886 AddToWorklist(N);
13887 return SDValue(N, 0);
13888 }
13889 }
13890
13891 // If this is a masked load with an all ones mask, we can use a unmasked load.
13892 // FIXME: Can we do this for indexed, compressing, or truncating stores?
13893 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MST->isUnindexed() &&
13894 !MST->isCompressingStore() && !MST->isTruncatingStore())
13895 return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(),
13896 MST->getBasePtr(), MST->getPointerInfo(),
13897 MST->getBaseAlign(), MST->getMemOperand()->getFlags(),
13898 MST->getAAInfo());
13899
13900 // Try transforming N to an indexed store.
13901 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13902 return SDValue(N, 0);
13903
13904 if (MST->isTruncatingStore() && MST->isUnindexed() &&
13905 Value.getValueType().isInteger() &&
13907 !cast<ConstantSDNode>(Value)->isOpaque())) {
13908 APInt TruncDemandedBits =
13909 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13911
13912 // See if we can simplify the operation with
13913 // SimplifyDemandedBits, which only works if the value has a single use.
13914 if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
13915 // Re-visit the store if anything changed and the store hasn't been merged
13916 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13917 // node back to the worklist if necessary, but we also need to re-visit
13918 // the Store node itself.
13919 if (N->getOpcode() != ISD::DELETED_NODE)
13920 AddToWorklist(N);
13921 return SDValue(N, 0);
13922 }
13923 }
13924
13925 // If this is a TRUNC followed by a masked store, fold this into a masked
13926 // truncating store. We can do this even if this is already a masked
13927 // truncstore.
13928 // TODO: Try combine to masked compress store if possiable.
13929 if ((Value.getOpcode() == ISD::TRUNCATE) && Value->hasOneUse() &&
13930 MST->isUnindexed() && !MST->isCompressingStore() &&
13931 TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
13932 MST->getMemoryVT(), MST->getAlign(),
13933 MST->getAddressSpace(), LegalOperations)) {
13934 auto Mask = TLI.promoteTargetBoolean(DAG, MST->getMask(),
13935 Value.getOperand(0).getValueType());
13936 return DAG.getMaskedStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13937 MST->getOffset(), Mask, MST->getMemoryVT(),
13938 MST->getMemOperand(), MST->getAddressingMode(),
13939 /*IsTruncating=*/true);
13940 }
13941
13942 return SDValue();
13943}
13944
13945SDValue DAGCombiner::visitVP_STRIDED_STORE(SDNode *N) {
13946 auto *SST = cast<VPStridedStoreSDNode>(N);
13947 EVT EltVT = SST->getValue().getValueType().getVectorElementType();
13948 // Combine strided stores with unit-stride to a regular VP store.
13949 if (auto *CStride = dyn_cast<ConstantSDNode>(SST->getStride());
13950 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
13951 return DAG.getStoreVP(SST->getChain(), SDLoc(N), SST->getValue(),
13952 SST->getBasePtr(), SST->getOffset(), SST->getMask(),
13953 SST->getVectorLength(), SST->getMemoryVT(),
13954 SST->getMemOperand(), SST->getAddressingMode(),
13955 SST->isTruncatingStore(), SST->isCompressingStore());
13956 }
13957 return SDValue();
13958}
13959
13960SDValue DAGCombiner::visitVECTOR_COMPRESS(SDNode *N) {
13961 SDLoc DL(N);
13962 SDValue Vec = N->getOperand(0);
13963 SDValue Mask = N->getOperand(1);
13964 SDValue Passthru = N->getOperand(2);
13965 EVT VecVT = Vec.getValueType();
13966
13967 bool HasPassthru = !Passthru.isUndef();
13968
13969 APInt SplatVal;
13970 if (ISD::isConstantSplatVector(Mask.getNode(), SplatVal))
13971 return TLI.isConstTrueVal(Mask) ? Vec : Passthru;
13972
13973 if (Vec.isUndef() || Mask.isUndef())
13974 return Passthru;
13975
13976 // No need for potentially expensive compress if the mask is constant.
13979 EVT ScalarVT = VecVT.getVectorElementType();
13980 unsigned NumSelected = 0;
13981 unsigned NumElmts = VecVT.getVectorNumElements();
13982 for (unsigned I = 0; I < NumElmts; ++I) {
13983 SDValue MaskI = Mask.getOperand(I);
13984 // We treat undef mask entries as "false".
13985 if (MaskI.isUndef())
13986 continue;
13987
13988 if (TLI.isConstTrueVal(MaskI)) {
13989 SDValue VecI = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Vec,
13990 DAG.getVectorIdxConstant(I, DL));
13991 Ops.push_back(VecI);
13992 NumSelected++;
13993 }
13994 }
13995 for (unsigned Rest = NumSelected; Rest < NumElmts; ++Rest) {
13996 SDValue Val =
13997 HasPassthru
13998 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Passthru,
13999 DAG.getVectorIdxConstant(Rest, DL))
14000 : DAG.getUNDEF(ScalarVT);
14001 Ops.push_back(Val);
14002 }
14003 return DAG.getBuildVector(VecVT, DL, Ops);
14004 }
14005
14006 return SDValue();
14007}
14008
14009SDValue DAGCombiner::visitVPGATHER(SDNode *N) {
14010 VPGatherSDNode *MGT = cast<VPGatherSDNode>(N);
14011 SDValue Mask = MGT->getMask();
14012 SDValue Chain = MGT->getChain();
14013 SDValue Index = MGT->getIndex();
14014 SDValue Scale = MGT->getScale();
14015 SDValue BasePtr = MGT->getBasePtr();
14016 SDValue VL = MGT->getVectorLength();
14017 ISD::MemIndexType IndexType = MGT->getIndexType();
14018 SDLoc DL(N);
14019
14020 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
14021 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
14022 return DAG.getGatherVP(
14023 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
14024 Ops, MGT->getMemOperand(), IndexType);
14025 }
14026
14027 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
14028 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
14029 return DAG.getGatherVP(
14030 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
14031 Ops, MGT->getMemOperand(), IndexType);
14032 }
14033
14034 return SDValue();
14035}
14036
14037SDValue DAGCombiner::visitMGATHER(SDNode *N) {
14038 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
14039 SDValue Mask = MGT->getMask();
14040 SDValue Chain = MGT->getChain();
14041 SDValue Index = MGT->getIndex();
14042 SDValue Scale = MGT->getScale();
14043 SDValue PassThru = MGT->getPassThru();
14044 SDValue BasePtr = MGT->getBasePtr();
14045 ISD::MemIndexType IndexType = MGT->getIndexType();
14046 SDLoc DL(N);
14047
14048 // Zap gathers with a zero mask.
14050 return CombineTo(N, PassThru, MGT->getChain());
14051
14052 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
14053 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
14054 return DAG.getMaskedGather(
14055 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
14056 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
14057 }
14058
14059 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
14060 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
14061 return DAG.getMaskedGather(
14062 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
14063 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
14064 }
14065
14066 return SDValue();
14067}
14068
14069SDValue DAGCombiner::visitMLOAD(SDNode *N) {
14070 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
14071 SDValue Mask = MLD->getMask();
14072
14073 // Zap masked loads with a zero mask.
14075 return CombineTo(N, MLD->getPassThru(), MLD->getChain());
14076
14077 // If this is a masked load with an all ones mask, we can use a unmasked load.
14078 // FIXME: Can we do this for indexed, expanding, or extending loads?
14079 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MLD->isUnindexed() &&
14080 !MLD->isExpandingLoad() && MLD->getExtensionType() == ISD::NON_EXTLOAD) {
14081 SDValue NewLd =
14082 DAG.getLoad(N->getValueType(0), SDLoc(N), MLD->getChain(),
14083 MLD->getBasePtr(), MLD->getPointerInfo(),
14084 MLD->getBaseAlign(), MLD->getMemOperand()->getFlags(),
14085 MMOMetadata(MLD->getAAInfo(), MLD->getRanges()));
14086 return CombineTo(N, NewLd, NewLd.getValue(1));
14087 }
14088
14089 // Try transforming N to an indexed load.
14090 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14091 return SDValue(N, 0);
14092
14093 return SDValue();
14094}
14095
14096SDValue DAGCombiner::visitMHISTOGRAM(SDNode *N) {
14097 MaskedHistogramSDNode *HG = cast<MaskedHistogramSDNode>(N);
14098 SDValue Chain = HG->getChain();
14099 SDValue Inc = HG->getInc();
14100 SDValue Mask = HG->getMask();
14101 SDValue BasePtr = HG->getBasePtr();
14102 SDValue Index = HG->getIndex();
14103 SDLoc DL(HG);
14104
14105 EVT MemVT = HG->getMemoryVT();
14106 EVT DataVT = Index.getValueType();
14107 MachineMemOperand *MMO = HG->getMemOperand();
14108 ISD::MemIndexType IndexType = HG->getIndexType();
14109
14111 return Chain;
14112
14113 if (refineUniformBase(BasePtr, Index, HG->isIndexScaled(), DAG, DL) ||
14114 refineIndexType(Index, IndexType, DataVT, DAG)) {
14115 SDValue Ops[] = {Chain, Inc, Mask, BasePtr, Index,
14116 HG->getScale(), HG->getIntID()};
14117 return DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), MemVT, DL, Ops,
14118 MMO, IndexType);
14119 }
14120
14121 return SDValue();
14122}
14123
14124SDValue DAGCombiner::visitPARTIAL_REDUCE_MLA(SDNode *N) {
14125 if (SDValue Res = foldPartialReduceMLAMulOp(N))
14126 return Res;
14127 if (SDValue Res = foldPartialReduceAdd(N))
14128 return Res;
14129 return SDValue();
14130}
14131
14132// partial_reduce_*mla(acc, mul(*ext(a), *ext(b)), splat(1))
14133// -> partial_reduce_*mla(acc, a, b)
14134//
14135// partial_reduce_*mla(acc, mul(*ext(x), splat(C)), splat(1))
14136// -> partial_reduce_*mla(acc, x, splat(C))
14137//
14138// partial_reduce_*mla(acc, sel(p, mul(*ext(a), *ext(b)), splat(0)), splat(1))
14139// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), b)
14140//
14141// partial_reduce_*mla(acc, sel(p, mul(*ext(a), splat(C)), splat(0)), splat(1))
14142// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), splat(C))
14143//
14144// `sel` could either be VSELECT or VP_MERGE.
14145SDValue DAGCombiner::foldPartialReduceMLAMulOp(SDNode *N) {
14146 SDLoc DL(N);
14147 auto *Context = DAG.getContext();
14148 SDValue Tmp;
14149 SDValue Acc = N->getOperand(0);
14150 SDValue Op1 = N->getOperand(1);
14151 SDValue OrigOp1 = Op1;
14152 SDValue Op2 = N->getOperand(2);
14153 unsigned Opc = Op1->getOpcode();
14154
14155 // Handle predication by moving the VSELECT / VP_MERGE into the operand of the
14156 // MUL.
14157 SDValue Pred;
14158 if ((Opc == ISD::VSELECT || Opc == ISD::VP_MERGE) &&
14159 (isZeroOrZeroSplat(Op1->getOperand(2)) ||
14160 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
14161 Pred = Op1->getOperand(0);
14162 Op1 = Op1->getOperand(1);
14163 Opc = Op1->getOpcode();
14164 }
14165
14166 // Handle negation (sub-reduction).
14167 bool IsMLS = false;
14168 if (sd_match(Op1, m_Neg(m_Value(Tmp)))) {
14169 Op1 = Tmp;
14170 Opc = Op1->getOpcode();
14171 IsMLS = true;
14172 }
14173
14174 if (Opc != ISD::MUL && Opc != ISD::FMUL && Opc != ISD::SHL)
14175 return SDValue();
14176
14177 SDValue LHS = Op1->getOperand(0);
14178 SDValue RHS = Op1->getOperand(1);
14179
14180 // After instcombine, negation for FP operations is on the RHS, so implement:
14181 // fmul(fpext(a), fneg(fpext(b)))
14182 //-> fmul(fpext(a), fpext(fneg(b)))
14183 if (sd_match(RHS, m_FNeg(m_Value(Tmp)))) {
14184 RHS = Tmp;
14185 IsMLS = true;
14186 }
14187
14188 // Try to treat (shl %a, %c) as (mul %a, (1 << %c)) for constant %c.
14189 if (Opc == ISD::SHL) {
14190 APInt C;
14191 if (!ISD::isConstantSplatVector(RHS.getNode(), C))
14192 return SDValue();
14193
14194 RHS =
14195 DAG.getSplatVector(RHS.getValueType(), DL,
14196 DAG.getConstant(APInt(C.getBitWidth(), 1).shl(C), DL,
14197 RHS.getValueType().getScalarType()));
14198 Opc = ISD::MUL;
14199 }
14200
14201 if (!(Opc == ISD::MUL && llvm::isOneOrOneSplat(Op2)) &&
14203 return SDValue();
14204
14205 auto IsIntOrFPExtOpcode = [](unsigned int Opcode) {
14206 return (ISD::isExtOpcode(Opcode) || Opcode == ISD::FP_EXTEND);
14207 };
14208
14209 unsigned LHSOpcode = LHS->getOpcode();
14210 if (!IsIntOrFPExtOpcode(LHSOpcode))
14211 return SDValue();
14212
14213 SDValue LHSExtOp = LHS->getOperand(0);
14214 EVT LHSExtOpVT = LHSExtOp.getValueType();
14215
14216 // When Pred is non-zero, set Op = select(Pred, Op, splat(0)) and freeze
14217 // OtherOp to keep the same semantics when moving the selects into the MUL
14218 // operands.
14219 auto ApplyPredicate = [&](SDValue &Op, SDValue &OtherOp) {
14220 if (Pred) {
14221 EVT OpVT = Op.getValueType();
14222 SDValue Zero = OpVT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, OpVT)
14223 : DAG.getConstant(0, DL, OpVT);
14224 if (OrigOp1.getOpcode() == ISD::VP_MERGE)
14225 Op = DAG.getNode(ISD::VP_MERGE, DL, OpVT, Pred, Op, Zero,
14226 OrigOp1.getOperand(3));
14227 else
14228 Op = DAG.getSelect(DL, OpVT, Pred, Op, Zero);
14229 OtherOp = DAG.getFreeze(OtherOp);
14230 }
14231 };
14232
14233 // Generate an MLA or MLS.
14234 auto GetMLA = [&](unsigned Opc, SDValue Acc, SDValue LHS,
14235 SDValue RHS) -> SDValue {
14236 EVT AccVT = Acc.getValueType();
14237 return IsMLS ? DAG.getPartialReduceMLS(Opc, DL, Acc, LHS, RHS)
14238 : DAG.getNode(Opc, DL, AccVT, Acc, LHS, RHS);
14239 };
14240
14241 // partial_reduce_*mla(acc, mul(ext(x), splat(C)), splat(1))
14242 // -> partial_reduce_*mla(acc, x, C)
14243 APInt C;
14244 if (ISD::isConstantSplatVector(RHS.getNode(), C)) {
14245 // TODO: Make use of partial_reduce_sumla here
14246 APInt CTrunc = C.trunc(LHSExtOpVT.getScalarSizeInBits());
14247 unsigned LHSBits = LHS.getValueType().getScalarSizeInBits();
14248 if ((LHSOpcode != ISD::ZERO_EXTEND || CTrunc.zext(LHSBits) != C) &&
14249 (LHSOpcode != ISD::SIGN_EXTEND || CTrunc.sext(LHSBits) != C))
14250 return SDValue();
14251
14252 unsigned NewOpcode = LHSOpcode == ISD::SIGN_EXTEND
14255
14256 // Only perform these combines if the target supports folding
14257 // the extends into the operation.
14259 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14260 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
14261 return SDValue();
14262
14263 SDValue C = DAG.getConstant(CTrunc, DL, LHSExtOpVT);
14264 ApplyPredicate(C, LHSExtOp);
14265 return GetMLA(NewOpcode, Acc, LHSExtOp, C);
14266 }
14267
14268 unsigned RHSOpcode = RHS->getOpcode();
14269 if (!IsIntOrFPExtOpcode(RHSOpcode))
14270 return SDValue();
14271
14272 SDValue RHSExtOp = RHS->getOperand(0);
14273 if (LHSExtOpVT != RHSExtOp.getValueType())
14274 return SDValue();
14275
14276 unsigned NewOpc;
14277 if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::SIGN_EXTEND)
14278 NewOpc = ISD::PARTIAL_REDUCE_SMLA;
14279 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
14280 NewOpc = ISD::PARTIAL_REDUCE_UMLA;
14281 else if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
14283 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::SIGN_EXTEND) {
14285 std::swap(LHSExtOp, RHSExtOp);
14286 } else if (LHSOpcode == ISD::FP_EXTEND && RHSOpcode == ISD::FP_EXTEND) {
14287 NewOpc = ISD::PARTIAL_REDUCE_FMLA;
14288 } else
14289 return SDValue();
14290 // For a 2-stage extend the signedness of both of the extends must match
14291 // If the mul has the same type, there is no outer extend, and thus we
14292 // can simply use the inner extends to pick the result node.
14293 // TODO: extend to handle nonneg zext as sext
14294 EVT AccElemVT = Acc.getValueType().getVectorElementType();
14295 if (Op1.getValueType().getVectorElementType() != AccElemVT &&
14296 NewOpc != N->getOpcode())
14297 return SDValue();
14298
14299 // Only perform these combines if the target supports folding
14300 // the extends into the operation.
14302 NewOpc, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14303 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
14304 return SDValue();
14305
14306 ApplyPredicate(RHSExtOp, LHSExtOp);
14307 return GetMLA(NewOpc, Acc, LHSExtOp, RHSExtOp);
14308}
14309
14310// partial.reduce.*mla(acc, *ext(op), splat(1))
14311// -> partial.reduce.*mla(acc, op, splat(trunc(1)))
14312// partial.reduce.sumla(acc, sext(op), splat(1))
14313// -> partial.reduce.smla(acc, op, splat(trunc(1)))
14314//
14315// partial.reduce.*mla(acc, sel(p, *ext(op), splat(0)), splat(1))
14316// -> partial.reduce.*mla(acc, sel(p, op, splat(0)), splat(trunc(1)))
14317SDValue DAGCombiner::foldPartialReduceAdd(SDNode *N) {
14318 SDLoc DL(N);
14319 SDValue Tmp;
14320 SDValue Acc = N->getOperand(0);
14321 SDValue Op1 = N->getOperand(1);
14322 SDValue Op2 = N->getOperand(2);
14323
14325 return SDValue();
14326
14327 SDValue Pred;
14328 unsigned Op1Opcode = Op1.getOpcode();
14329 if (Op1Opcode == ISD::VSELECT && (isZeroOrZeroSplat(Op1->getOperand(2)) ||
14330 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
14331 Pred = Op1->getOperand(0);
14332 Op1 = Op1->getOperand(1);
14333 Op1Opcode = Op1->getOpcode();
14334 }
14335
14336 // Handle negation (sub-reduction).
14337 bool IsMLS = false;
14338 if (sd_match(Op1, m_AnyOf(m_Neg(m_Value(Tmp)), m_FNeg(m_Value(Tmp))))) {
14339 Op1 = Tmp;
14340 Op1Opcode = Op1.getOpcode();
14341 IsMLS = true;
14342 }
14343
14344 if (!ISD::isExtOpcode(Op1Opcode) && Op1Opcode != ISD::FP_EXTEND)
14345 return SDValue();
14346
14347 bool Op1IsSigned =
14348 Op1Opcode == ISD::SIGN_EXTEND || Op1Opcode == ISD::FP_EXTEND;
14349 bool NodeIsSigned = N->getOpcode() != ISD::PARTIAL_REDUCE_UMLA;
14350 EVT AccElemVT = Acc.getValueType().getVectorElementType();
14351 if (Op1IsSigned != NodeIsSigned &&
14352 Op1.getValueType().getVectorElementType() != AccElemVT)
14353 return SDValue();
14354
14355 unsigned NewOpcode = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14357 : Op1IsSigned ? ISD::PARTIAL_REDUCE_SMLA
14359
14360 SDValue UnextOp1 = Op1.getOperand(0);
14361 EVT UnextOp1VT = UnextOp1.getValueType();
14362 auto *Context = DAG.getContext();
14363 EVT PromOp1VT = TLI.getTypeToTransformTo(*Context, UnextOp1VT);
14365 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14366 PromOp1VT))
14367 return SDValue();
14368
14369 // The multiplier below is built at the operand type, where a splat of 1 in i1
14370 // sign extends to -1. Extend i1 masks to the promoted type first.
14371 if (Op1IsSigned && UnextOp1VT.getVectorElementType() == MVT::i1) {
14372 if (PromOp1VT == UnextOp1VT)
14373 return SDValue();
14374 UnextOp1VT = PromOp1VT;
14375 UnextOp1 = DAG.getNode(ISD::SIGN_EXTEND, DL, UnextOp1VT, UnextOp1);
14376 }
14377
14378 SDValue Constant = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14379 ? DAG.getConstantFP(1, DL, UnextOp1VT)
14380 : DAG.getConstant(1, DL, UnextOp1VT);
14381
14382 if (Pred) {
14383 SDValue Zero = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14384 ? DAG.getConstantFP(0, DL, UnextOp1VT)
14385 : DAG.getConstant(0, DL, UnextOp1VT);
14386 Constant = DAG.getSelect(DL, UnextOp1VT, Pred, Constant, Zero);
14387 }
14388 EVT AccVT = Acc.getValueType();
14389 return IsMLS ? DAG.getPartialReduceMLS(NewOpcode, DL, Acc, UnextOp1, Constant)
14390 : DAG.getNode(NewOpcode, DL, AccVT, Acc, UnextOp1, Constant);
14391}
14392
14393SDValue DAGCombiner::visitLOOP_DEPENDENCE_MASK(SDNode *N) {
14394 SDLoc DL(N);
14395 EVT VT = N->getValueType(0);
14396 unsigned LaneOffset = N->getConstantOperandVal(3);
14397
14398 // The first lane is always active, so v1i1 => true.
14399 if (LaneOffset == 0 &&
14401 return DAG.getBoolConstant(true, DL, VT, VT);
14402
14403 return SDValue();
14404}
14405
14406SDValue DAGCombiner::visitVP_STRIDED_LOAD(SDNode *N) {
14407 auto *SLD = cast<VPStridedLoadSDNode>(N);
14408 EVT EltVT = SLD->getValueType(0).getVectorElementType();
14409 // Combine strided loads with unit-stride to a regular VP load.
14410 if (auto *CStride = dyn_cast<ConstantSDNode>(SLD->getStride());
14411 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
14412 SDValue NewLd = DAG.getLoadVP(
14413 SLD->getAddressingMode(), SLD->getExtensionType(), SLD->getValueType(0),
14414 SDLoc(N), SLD->getChain(), SLD->getBasePtr(), SLD->getOffset(),
14415 SLD->getMask(), SLD->getVectorLength(), SLD->getMemoryVT(),
14416 SLD->getMemOperand(), SLD->isExpandingLoad());
14417 return CombineTo(N, NewLd, NewLd.getValue(1));
14418 }
14419 return SDValue();
14420}
14421
14422/// A vector select of 2 constant vectors can be simplified to math/logic to
14423/// avoid a variable select instruction and possibly avoid constant loads.
14424SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
14425 SDValue Cond = N->getOperand(0);
14426 SDValue N1 = N->getOperand(1);
14427 SDValue N2 = N->getOperand(2);
14428 EVT VT = N->getValueType(0);
14429 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
14433 return SDValue();
14434
14435 // Check if we can use the condition value to increment/decrement a single
14436 // constant value. This simplifies a select to an add and removes a constant
14437 // load/materialization from the general case.
14438 bool AllAddOne = true;
14439 bool AllSubOne = true;
14440 unsigned Elts = VT.getVectorNumElements();
14441 for (unsigned i = 0; i != Elts; ++i) {
14442 SDValue N1Elt = N1.getOperand(i);
14443 SDValue N2Elt = N2.getOperand(i);
14444 if (N1Elt.isUndef())
14445 continue;
14446 // N2 should not contain undef values since it will be reused in the fold.
14447 if (N2Elt.isUndef() || N1Elt.getValueType() != N2Elt.getValueType()) {
14448 AllAddOne = false;
14449 AllSubOne = false;
14450 break;
14451 }
14452
14453 const APInt &C1 = N1Elt->getAsAPIntVal();
14454 const APInt &C2 = N2Elt->getAsAPIntVal();
14455 if (C1 != C2 + 1)
14456 AllAddOne = false;
14457 if (C1 != C2 - 1)
14458 AllSubOne = false;
14459 }
14460
14461 // Further simplifications for the extra-special cases where the constants are
14462 // all 0 or all -1 should be implemented as folds of these patterns.
14463 SDLoc DL(N);
14464 if (AllAddOne || AllSubOne) {
14465 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
14466 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
14467 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14468 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
14469 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
14470 }
14471
14472 // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
14473 APInt Pow2C;
14474 if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
14475 isNullOrNullSplat(N2)) {
14476 SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
14477 SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
14478 return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
14479 }
14480
14482 return V;
14483
14484 // The general case for select-of-constants:
14485 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
14486 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
14487 // leave that to a machine-specific pass.
14488 return SDValue();
14489}
14490
14492 SDValue FVal,
14493 const TargetLowering &TLI,
14494 SelectionDAG &DAG,
14495 const SDLoc &DL) {
14496 EVT VT = TVal.getValueType();
14497 if (!TLI.isTypeLegal(VT))
14498 return SDValue();
14499
14500 EVT CondVT = Cond.getValueType();
14501 assert(CondVT.isVector() && "Vector select expects a vector selector!");
14502
14503 bool IsTAllZero = ISD::isConstantSplatVectorAllZeros(TVal.getNode());
14504 bool IsTAllOne = ISD::isConstantSplatVectorAllOnes(TVal.getNode());
14505 bool IsFAllZero = ISD::isConstantSplatVectorAllZeros(FVal.getNode());
14506 bool IsFAllOne = ISD::isConstantSplatVectorAllOnes(FVal.getNode());
14507
14508 // no vselect(cond, 0/-1, X) or vselect(cond, X, 0/-1), return
14509 if (!IsTAllZero && !IsTAllOne && !IsFAllZero && !IsFAllOne)
14510 return SDValue();
14511
14512 // select Cond, 0, 0 → 0
14513 if (IsTAllZero && IsFAllZero) {
14514 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, VT)
14515 : DAG.getConstant(0, DL, VT);
14516 }
14517
14518 // check select(setgt lhs, -1), 1, -1 --> or (sra lhs, bitwidth - 1), 1
14519 APInt TValAPInt;
14520 if (Cond.getOpcode() == ISD::SETCC &&
14521 Cond.getOperand(2) == DAG.getCondCode(ISD::SETGT) &&
14522 Cond.getOperand(0).getValueType() == VT && VT.isSimple() &&
14523 ISD::isConstantSplatVector(TVal.getNode(), TValAPInt) &&
14524 TValAPInt.isOne() &&
14525 ISD::isConstantSplatVectorAllOnes(Cond.getOperand(1).getNode()) &&
14528 SDValue LHS = Cond.getOperand(0);
14529 SDValue ShiftC =
14531 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, ShiftC);
14532 return DAG.getNode(ISD::OR, DL, VT, Shift, TVal);
14533 }
14534
14535 // To use the condition operand as a bitwise mask, it must have elements that
14536 // are the same size as the select elements. i.e, the condition operand must
14537 // have already been promoted from the IR select condition type <N x i1>.
14538 // Don't check if the types themselves are equal because that excludes
14539 // vector floating-point selects.
14540 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
14541 return SDValue();
14542
14543 // Cond value must be 'sign splat' to be converted to a logical op.
14544 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
14545 return SDValue();
14546
14547 // Try inverting Cond and swapping T/F if it gives all-ones/all-zeros form
14548 if (!IsTAllOne && !IsFAllZero && Cond.hasOneUse() &&
14549 Cond.getOpcode() == ISD::SETCC &&
14550 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
14551 CondVT) {
14552 if (IsTAllZero || IsFAllOne) {
14553 SDValue CC = Cond.getOperand(2);
14555 cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
14556 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
14557 InverseCC);
14558 std::swap(TVal, FVal);
14559 std::swap(IsTAllOne, IsFAllOne);
14560 std::swap(IsTAllZero, IsFAllZero);
14561 }
14562 }
14563
14565 "Select condition no longer all-sign bits");
14566
14567 // select Cond, -1, 0 → bitcast Cond
14568 if (IsTAllOne && IsFAllZero)
14569 return DAG.getBitcast(VT, Cond);
14570
14571 // select Cond, -1, x → or Cond, x
14572 if (IsTAllOne) {
14573 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14574 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, X);
14575 return DAG.getBitcast(VT, Or);
14576 }
14577
14578 // select Cond, x, 0 → and Cond, x
14579 if (IsFAllZero) {
14580 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(TVal));
14581 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, X);
14582 return DAG.getBitcast(VT, And);
14583 }
14584
14585 // select Cond, 0, x -> and not(Cond), x
14586 if (IsTAllZero &&
14588 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14589 SDValue And =
14590 DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT), X);
14591 return DAG.getBitcast(VT, And);
14592 }
14593
14594 return SDValue();
14595}
14596
14597SDValue DAGCombiner::visitVSELECT(SDNode *N) {
14598 SDValue N0 = N->getOperand(0);
14599 SDValue N1 = N->getOperand(1);
14600 SDValue N2 = N->getOperand(2);
14601 EVT VT = N->getValueType(0);
14602 SDLoc DL(N);
14603
14604 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
14605 return V;
14606
14607 if (SDValue V = foldBoolSelectToLogic(N, DL, DAG))
14608 return V;
14609
14610 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
14611 if (!TLI.isTargetCanonicalSelect(N))
14612 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
14613 return DAG.getSelect(DL, VT, F, N2, N1, N->getFlags());
14614
14615 // select (sext m), (add X, C), X --> (add X, (and C, (sext m))))
14616 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N2 && N1->hasOneUse() &&
14619 TLI.getBooleanContents(N0.getValueType()) ==
14621 return DAG.getNode(
14622 ISD::ADD, DL, N1.getValueType(), N2,
14623 DAG.getNode(ISD::AND, DL, N0.getValueType(), N1.getOperand(1), N0));
14624 }
14625
14626 // Canonicalize integer abs.
14627 // vselect (setg[te] X, 0), X, -X ->
14628 // vselect (setgt X, -1), X, -X ->
14629 // vselect (setl[te] X, 0), -X, X ->
14630 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14631 if (N0.getOpcode() == ISD::SETCC) {
14632 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
14634 bool isAbs = false;
14635 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
14636
14637 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14638 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
14639 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
14641 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
14642 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
14644
14645 if (isAbs) {
14647 return DAG.getNode(ISD::ABS, DL, VT, LHS);
14648
14649 SDValue Shift = DAG.getNode(
14650 ISD::SRA, DL, VT, LHS,
14651 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, DL));
14652 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
14653 AddToWorklist(Shift.getNode());
14654 AddToWorklist(Add.getNode());
14655 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
14656 }
14657
14658 // vselect x, y (fcmp lt x, y) -> fminnum x, y
14659 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
14660 //
14661 // This is OK if we don't care about what happens if either operand is a
14662 // NaN.
14663 //
14664 if (N0.hasOneUse() &&
14665 isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, N->getFlags(),
14666 N0->getFlags(), TLI)) {
14667 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC))
14668 return FMinMax;
14669 }
14670
14671 if (SDValue S = PerformMinMaxFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14672 return S;
14673 if (SDValue S = PerformUMinFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14674 return S;
14676 return S;
14677
14678 // If this select has a condition (setcc) with narrower operands than the
14679 // select, try to widen the compare to match the select width.
14680 // TODO: This should be extended to handle any constant.
14681 // TODO: This could be extended to handle non-loading patterns, but that
14682 // requires thorough testing to avoid regressions.
14683 if (isNullOrNullSplat(RHS)) {
14684 EVT NarrowVT = LHS.getValueType();
14686 EVT SetCCVT = getSetCCResultType(LHS.getValueType());
14687 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
14688 unsigned WideWidth = WideVT.getScalarSizeInBits();
14689 bool IsSigned = isSignedIntSetCC(CC);
14690 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14691 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && SetCCWidth != 1 &&
14692 SetCCWidth < WideWidth &&
14693 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
14694 LoadSDNode *Ld = cast<LoadSDNode>(LHS);
14695
14696 if (TLI.isLoadLegalOrCustom(WideVT, NarrowVT, Ld->getAlign(),
14697 Ld->getAddressSpace(), LoadExtOpcode,
14698 false)) {
14699 // Both compare operands can be widened for free. The LHS can use an
14700 // extended load, and the RHS is a constant:
14701 // vselect (ext (setcc load(X), C)), N1, N2 -->
14702 // vselect (setcc extload(X), C'), N1, N2
14703 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14704 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
14705 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
14706 EVT WideSetCCVT = getSetCCResultType(WideVT);
14707 SDValue WideSetCC =
14708 DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
14709 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
14710 }
14711 }
14712 }
14713
14714 if (SDValue ABD = foldSelectToABD(LHS, RHS, N1, N2, CC, DL))
14715 return ABD;
14716
14717 // Match VSELECTs into add with unsigned saturation.
14718 if (hasOperation(ISD::UADDSAT, VT)) {
14719 // Check if one of the arms of the VSELECT is vector with all bits set.
14720 // If it's on the left side invert the predicate to simplify logic below.
14721 SDValue Other;
14722 ISD::CondCode SatCC = CC;
14724 Other = N2;
14725 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14726 } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) {
14727 Other = N1;
14728 }
14729
14730 if (Other && Other.getOpcode() == ISD::ADD) {
14731 SDValue CondLHS = LHS, CondRHS = RHS;
14732 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14733
14734 // Canonicalize condition operands.
14735 if (SatCC == ISD::SETUGE) {
14736 std::swap(CondLHS, CondRHS);
14737 SatCC = ISD::SETULE;
14738 }
14739
14740 // We can test against either of the addition operands.
14741 // x <= x+y ? x+y : ~0 --> uaddsat x, y
14742 // x+y >= x ? x+y : ~0 --> uaddsat x, y
14743 if (SatCC == ISD::SETULE && Other == CondRHS &&
14744 (OpLHS == CondLHS || OpRHS == CondLHS))
14745 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14746
14747 if (OpRHS.getOpcode() == CondRHS.getOpcode() &&
14748 (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14749 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) &&
14750 CondLHS == OpLHS) {
14751 // If the RHS is a constant we have to reverse the const
14752 // canonicalization.
14753 // x >= ~C ? x+C : ~0 --> uaddsat x, C
14754 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14755 return Cond->getAPIntValue() == ~Op->getAPIntValue();
14756 };
14757 if (SatCC == ISD::SETULE &&
14758 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
14759 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14760 }
14761 }
14762 }
14763
14764 // Match VSELECTs into sub with unsigned saturation.
14765 if (hasOperation(ISD::USUBSAT, VT)) {
14766 // Check if one of the arms of the VSELECT is a zero vector. If it's on
14767 // the left side invert the predicate to simplify logic below.
14768 SDValue Other;
14769 ISD::CondCode SatCC = CC;
14771 Other = N2;
14772 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14774 Other = N1;
14775 }
14776
14777 // zext(x) >= y ? trunc(zext(x) - y) : 0
14778 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14779 // zext(x) > y ? trunc(zext(x) - y) : 0
14780 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14781 if (Other && Other.getOpcode() == ISD::TRUNCATE &&
14782 Other.getOperand(0).getOpcode() == ISD::SUB &&
14783 (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT)) {
14784 SDValue OpLHS = Other.getOperand(0).getOperand(0);
14785 SDValue OpRHS = Other.getOperand(0).getOperand(1);
14786 if (LHS == OpLHS && RHS == OpRHS && LHS.getOpcode() == ISD::ZERO_EXTEND)
14787 if (SDValue R = getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS,
14788 DAG, DL))
14789 return R;
14790 }
14791
14792 if (Other && Other.getNumOperands() == 2) {
14793 SDValue CondRHS = RHS;
14794 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14795
14796 if (OpLHS == LHS) {
14797 // Look for a general sub with unsigned saturation first.
14798 // x >= y ? x-y : 0 --> usubsat x, y
14799 // x > y ? x-y : 0 --> usubsat x, y
14800 if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) &&
14801 Other.getOpcode() == ISD::SUB && OpRHS == CondRHS)
14802 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14803
14804 if (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14805 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14806 if (CondRHS.getOpcode() == ISD::BUILD_VECTOR ||
14807 CondRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14808 // If the RHS is a constant we have to reverse the const
14809 // canonicalization.
14810 // x > C-1 ? x+-C : 0 --> usubsat x, C
14811 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14812 return (!Op && !Cond) ||
14813 (Op && Cond &&
14814 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
14815 };
14816 if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD &&
14817 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
14818 /*AllowUndefs*/ true)) {
14819 OpRHS = DAG.getNegative(OpRHS, DL, VT);
14820 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14821 }
14822
14823 // Another special case: If C was a sign bit, the sub has been
14824 // canonicalized into a xor.
14825 // FIXME: Would it be better to use computeKnownBits to
14826 // determine whether it's safe to decanonicalize the xor?
14827 // x s< 0 ? x^C : 0 --> usubsat x, C
14828 APInt SplatValue;
14829 if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
14830 ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) &&
14832 SplatValue.isSignMask()) {
14833 // Note that we have to rebuild the RHS constant here to
14834 // ensure we don't rely on particular values of undef lanes.
14835 OpRHS = DAG.getConstant(SplatValue, DL, VT);
14836 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14837 }
14838 }
14839 }
14840 }
14841 }
14842 }
14843
14844 // (vselect (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
14845 // (vselect (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
14846 if (SDValue UMin = foldSelectToUMin(LHS, RHS, N1, N2, CC, DL))
14847 return UMin;
14848 }
14849
14850 if (SimplifySelectOps(N, N1, N2))
14851 return SDValue(N, 0); // Don't revisit N.
14852
14853 // Fold (vselect all_ones, N1, N2) -> N1
14855 return N1;
14856 // Fold (vselect all_zeros, N1, N2) -> N2
14858 return N2;
14859
14860 // The ConvertSelectToConcatVector function is assuming both the above
14861 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
14862 // and addressed.
14863 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14866 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
14867 return CV;
14868 }
14869
14870 if (SDValue V = foldVSelectOfConstants(N))
14871 return V;
14872
14873 if (hasOperation(ISD::SRA, VT))
14875 return V;
14876
14878 return SDValue(N, 0);
14879
14880 if (SDValue V = combineVSelectWithAllOnesOrZeros(N0, N1, N2, TLI, DAG, DL))
14881 return V;
14882
14884 return R;
14885
14886 return SDValue();
14887}
14888
14889SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
14890 SDValue N0 = N->getOperand(0);
14891 SDValue N1 = N->getOperand(1);
14892 SDValue N2 = N->getOperand(2);
14893 SDValue N3 = N->getOperand(3);
14894 SDValue N4 = N->getOperand(4);
14895 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
14896 SDLoc DL(N);
14897
14898 // fold select_cc lhs, rhs, x, x, cc -> x
14899 if (N2 == N3)
14900 return N2;
14901
14902 if (SDValue R = foldSelectCCOfSelect(N, DAG))
14903 return R;
14904
14905 // select_cc bool, 0, x, y, seteq -> select bool, y, x
14906 if (CC == ISD::SETEQ && !LegalTypes && N0.getValueType() == MVT::i1 &&
14907 isNullConstant(N1))
14908 return DAG.getSelect(DL, N2.getValueType(), N0, N3, N2);
14909
14910 // Determine if the condition we're dealing with is constant
14911 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
14912 CC, DL, false)) {
14913 AddToWorklist(SCC.getNode());
14914
14915 // cond always true -> true val
14916 // cond always false -> false val
14917 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode()))
14918 return SCCC->isZero() ? N3 : N2;
14919
14920 // When the condition is UNDEF, just return the first operand. This is
14921 // coherent the DAG creation, no setcc node is created in this case
14922 if (SCC->isUndef())
14923 return N2;
14924
14925 // Fold to a simpler select_cc
14926 if (SCC.getOpcode() == ISD::SETCC) {
14927 return DAG.getNode(ISD::SELECT_CC, DL, N2.getValueType(),
14928 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
14929 SCC.getOperand(2), SCC->getFlags());
14930 }
14931 }
14932
14933 // If we can fold this based on the true/false value, do so.
14934 if (SimplifySelectOps(N, N2, N3))
14935 return SDValue(N, 0); // Don't revisit N.
14936
14937 auto [Opcode, NewLHS, NewRHS] = combineSelectCCToPseudoMinMax(
14938 DAG, DL, CC, N0, N1, N2, N3, N->getFlags(), /*IsStrict=*/false);
14939 if (Opcode)
14940 return DAG.getNode(Opcode, DL, N->getValueType(0), NewLHS, NewRHS,
14941 N->getFlags());
14942
14943 // fold select_cc into other things, such as min/max/abs
14944 return SimplifySelectCC(DL, N0, N1, N2, N3, CC);
14945}
14946
14947SDValue DAGCombiner::visitSETCC(SDNode *N) {
14948 // setcc is very commonly used as an argument to brcond or cond_loop. This
14949 // pattern also lend itself to numerous combines and, as a result, it is
14950 // desired we keep the argument to a brcond as a setcc as much as possible.
14951 bool PreferSetCC =
14952 N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::BRCOND ||
14953 N->user_begin()->getOpcode() == ISD::COND_LOOP);
14954
14955 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
14956 EVT VT = N->getValueType(0);
14957 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
14958 SDLoc DL(N);
14959
14960 if (SDValue Combined = SimplifySetCC(VT, N0, N1, Cond, DL, !PreferSetCC)) {
14961 // If we prefer to have a setcc, and we don't, we'll try our best to
14962 // recreate one using rebuildSetCC.
14963 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
14964 SDValue NewSetCC = rebuildSetCC(Combined);
14965
14966 // We don't have anything interesting to combine to.
14967 if (NewSetCC.getNode() == N)
14968 return SDValue();
14969
14970 if (NewSetCC)
14971 return NewSetCC;
14972 }
14973 return Combined;
14974 }
14975
14976 // Optimize
14977 // 1) (icmp eq/ne (and X, C0), (shift X, C1))
14978 // or
14979 // 2) (icmp eq/ne X, (rotate X, C1))
14980 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
14981 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
14982 // Then:
14983 // If C1 is a power of 2, then the rotate and shift+and versions are
14984 // equivilent, so we can interchange them depending on target preference.
14985 // Otherwise, if we have the shift+and version we can interchange srl/shl
14986 // which inturn affects the constant C0. We can use this to get better
14987 // constants again determined by target preference.
14988 if (Cond == ISD::SETNE || Cond == ISD::SETEQ) {
14989 auto IsAndWithShift = [](SDValue A, SDValue B) {
14990 return A.getOpcode() == ISD::AND &&
14991 (B.getOpcode() == ISD::SRL || B.getOpcode() == ISD::SHL) &&
14992 A.getOperand(0) == B.getOperand(0);
14993 };
14994 auto IsRotateWithOp = [](SDValue A, SDValue B) {
14995 return (B.getOpcode() == ISD::ROTL || B.getOpcode() == ISD::ROTR) &&
14996 B.getOperand(0) == A;
14997 };
14998 SDValue AndOrOp = SDValue(), ShiftOrRotate = SDValue();
14999 bool IsRotate = false;
15000
15001 // Find either shift+and or rotate pattern.
15002 if (IsAndWithShift(N0, N1)) {
15003 AndOrOp = N0;
15004 ShiftOrRotate = N1;
15005 } else if (IsAndWithShift(N1, N0)) {
15006 AndOrOp = N1;
15007 ShiftOrRotate = N0;
15008 } else if (IsRotateWithOp(N0, N1)) {
15009 IsRotate = true;
15010 AndOrOp = N0;
15011 ShiftOrRotate = N1;
15012 } else if (IsRotateWithOp(N1, N0)) {
15013 IsRotate = true;
15014 AndOrOp = N1;
15015 ShiftOrRotate = N0;
15016 }
15017
15018 if (AndOrOp && ShiftOrRotate && ShiftOrRotate.hasOneUse() &&
15019 (IsRotate || AndOrOp.hasOneUse())) {
15020 EVT OpVT = N0.getValueType();
15021 // Get constant shift/rotate amount and possibly mask (if its shift+and
15022 // variant).
15023 auto GetAPIntValue = [](SDValue Op) -> std::optional<APInt> {
15024 ConstantSDNode *CNode = isConstOrConstSplat(Op, /*AllowUndefs*/ false,
15025 /*AllowTrunc*/ false);
15026 if (CNode == nullptr)
15027 return std::nullopt;
15028 return CNode->getAPIntValue();
15029 };
15030 std::optional<APInt> AndCMask =
15031 IsRotate ? std::nullopt : GetAPIntValue(AndOrOp.getOperand(1));
15032 std::optional<APInt> ShiftCAmt =
15033 GetAPIntValue(ShiftOrRotate.getOperand(1));
15034 unsigned NumBits = OpVT.getScalarSizeInBits();
15035
15036 // We found constants.
15037 if (ShiftCAmt && (IsRotate || AndCMask) && ShiftCAmt->ult(NumBits)) {
15038 unsigned ShiftOpc = ShiftOrRotate.getOpcode();
15039 // Check that the constants meet the constraints.
15040 bool CanTransform = IsRotate;
15041 if (!CanTransform) {
15042 // Check that mask and shift compliment eachother
15043 CanTransform = *ShiftCAmt == (~*AndCMask).popcount();
15044 // Check that we are comparing all bits
15045 CanTransform &= (*ShiftCAmt + AndCMask->popcount()) == NumBits;
15046 // Check that the and mask is correct for the shift
15047 CanTransform &=
15048 ShiftOpc == ISD::SHL ? (~*AndCMask).isMask() : AndCMask->isMask();
15049 }
15050
15051 // See if target prefers another shift/rotate opcode.
15052 unsigned NewShiftOpc = TLI.preferedOpcodeForCmpEqPiecesOfOperand(
15053 OpVT, ShiftOpc, ShiftCAmt->isPowerOf2(), *ShiftCAmt, AndCMask);
15054 // Transform is valid and we have a new preference.
15055 if (CanTransform && NewShiftOpc != ShiftOpc) {
15056 SDValue NewShiftOrRotate =
15057 DAG.getNode(NewShiftOpc, DL, OpVT, ShiftOrRotate.getOperand(0),
15058 ShiftOrRotate.getOperand(1));
15059 SDValue NewAndOrOp = SDValue();
15060
15061 if (NewShiftOpc == ISD::SHL || NewShiftOpc == ISD::SRL) {
15062 APInt NewMask =
15063 NewShiftOpc == ISD::SHL
15064 ? APInt::getHighBitsSet(NumBits,
15065 NumBits - ShiftCAmt->getZExtValue())
15066 : APInt::getLowBitsSet(NumBits,
15067 NumBits - ShiftCAmt->getZExtValue());
15068 NewAndOrOp =
15069 DAG.getNode(ISD::AND, DL, OpVT, ShiftOrRotate.getOperand(0),
15070 DAG.getConstant(NewMask, DL, OpVT));
15071 } else {
15072 NewAndOrOp = ShiftOrRotate.getOperand(0);
15073 }
15074
15075 return DAG.getSetCC(DL, VT, NewAndOrOp, NewShiftOrRotate, Cond);
15076 }
15077 }
15078 }
15079 }
15080 return SDValue();
15081}
15082
15083SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
15084 SDValue LHS = N->getOperand(0);
15085 SDValue RHS = N->getOperand(1);
15086 SDValue Carry = N->getOperand(2);
15087 SDValue Cond = N->getOperand(3);
15088
15089 // If Carry is false, fold to a regular SETCC.
15090 if (isNullConstant(Carry))
15091 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
15092
15093 return SDValue();
15094}
15095
15096/// Check if N satisfies:
15097/// N is used once.
15098/// N is a Load.
15099/// The load is compatible with ExtOpcode. It means
15100/// If load has explicit zero/sign extension, ExpOpcode must have the same
15101/// extension.
15102/// Otherwise returns true.
15103static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) {
15104 if (!N.hasOneUse())
15105 return false;
15106
15107 if (!isa<LoadSDNode>(N))
15108 return false;
15109
15111 ISD::LoadExtType LoadExt = Load->getExtensionType();
15112 if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD)
15113 return true;
15114
15115 // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same
15116 // extension.
15117 if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) ||
15118 (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND))
15119 return false;
15120
15121 return true;
15122}
15123
15124/// Fold
15125/// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y)
15126/// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y)
15127/// (aext (select c, load x, load y)) -> (select c, extload x, extload y)
15128/// This function is called by the DAGCombiner when visiting sext/zext/aext
15129/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
15131 SelectionDAG &DAG, const SDLoc &DL,
15132 CombineLevel Level) {
15133 unsigned Opcode = N->getOpcode();
15134 SDValue N0 = N->getOperand(0);
15135 EVT VT = N->getValueType(0);
15136 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
15137 Opcode == ISD::ANY_EXTEND) &&
15138 "Expected EXTEND dag node in input!");
15139
15140 SDValue Cond, Op1, Op2;
15142 m_Value(Op2)))))
15143 return SDValue();
15144
15145 if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode))
15146 return SDValue();
15147
15148 auto ExtLoadOpcode = ISD::EXTLOAD;
15149 if (Opcode == ISD::SIGN_EXTEND)
15150 ExtLoadOpcode = ISD::SEXTLOAD;
15151 else if (Opcode == ISD::ZERO_EXTEND)
15152 ExtLoadOpcode = ISD::ZEXTLOAD;
15153
15154 // Illegal VSELECT may ISel fail if happen after legalization (DAG
15155 // Combine2), so we should conservatively check the OperationAction.
15156 LoadSDNode *Load1 = cast<LoadSDNode>(Op1);
15157 LoadSDNode *Load2 = cast<LoadSDNode>(Op2);
15158 if (!TLI.isLoadLegal(VT, Load1->getMemoryVT(), Load1->getAlign(),
15159 Load1->getAddressSpace(), ExtLoadOpcode, false) ||
15160 !TLI.isLoadLegal(VT, Load2->getMemoryVT(), Load2->getAlign(),
15161 Load2->getAddressSpace(), ExtLoadOpcode, false) ||
15162 (N0->getOpcode() == ISD::VSELECT && Level >= AfterLegalizeTypes &&
15164 return SDValue();
15165
15166 SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1);
15167 SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2);
15168 return DAG.getSelect(DL, VT, Cond, Ext1, Ext2);
15169}
15170
15171/// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
15172/// a build_vector of constants.
15173/// This function is called by the DAGCombiner when visiting sext/zext/aext
15174/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
15175/// Vector extends are not folded if operations are legal; this is to
15176/// avoid introducing illegal build_vector dag nodes.
15178 const TargetLowering &TLI,
15179 SelectionDAG &DAG, bool LegalTypes) {
15180 unsigned Opcode = N->getOpcode();
15181 SDValue N0 = N->getOperand(0);
15182 EVT VT = N->getValueType(0);
15183
15184 assert((ISD::isExtOpcode(Opcode) || ISD::isExtVecInRegOpcode(Opcode)) &&
15185 "Expected EXTEND dag node in input!");
15186
15187 // fold (sext c1) -> c1
15188 // fold (zext c1) -> c1
15189 // fold (aext c1) -> c1
15190 if (isa<ConstantSDNode>(N0))
15191 return DAG.getNode(Opcode, DL, VT, N0);
15192
15193 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
15194 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
15195 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
15196 if (N0->getOpcode() == ISD::SELECT) {
15197 SDValue Op1 = N0->getOperand(1);
15198 SDValue Op2 = N0->getOperand(2);
15199 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
15200 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
15201 // For any_extend, choose sign extension of the constants to allow a
15202 // possible further transform to sign_extend_inreg.i.e.
15203 //
15204 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
15205 // t2: i64 = any_extend t1
15206 // -->
15207 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
15208 // -->
15209 // t4: i64 = sign_extend_inreg t3
15210 unsigned FoldOpc = Opcode;
15211 if (FoldOpc == ISD::ANY_EXTEND)
15212 FoldOpc = ISD::SIGN_EXTEND;
15213 return DAG.getSelect(DL, VT, N0->getOperand(0),
15214 DAG.getNode(FoldOpc, DL, VT, Op1),
15215 DAG.getNode(FoldOpc, DL, VT, Op2));
15216 }
15217 }
15218
15219 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
15220 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
15221 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
15222 EVT SVT = VT.getScalarType();
15223 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
15225 return SDValue();
15226
15227 // We can fold this node into a build_vector.
15228 unsigned VTBits = SVT.getSizeInBits();
15229 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
15231 unsigned NumElts = VT.getVectorNumElements();
15232
15233 for (unsigned i = 0; i != NumElts; ++i) {
15234 SDValue Op = N0.getOperand(i);
15235 if (Op.isUndef()) {
15236 if (Opcode == ISD::ANY_EXTEND || Opcode == ISD::ANY_EXTEND_VECTOR_INREG)
15237 Elts.push_back(DAG.getUNDEF(SVT));
15238 else
15239 Elts.push_back(DAG.getConstant(0, DL, SVT));
15240 continue;
15241 }
15242
15243 SDLoc DL(Op);
15244 // Get the constant value and if needed trunc it to the size of the type.
15245 // Nodes like build_vector might have constants wider than the scalar type.
15246 APInt C = Op->getAsAPIntVal().zextOrTrunc(EVTBits);
15247 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
15248 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
15249 else
15250 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
15251 }
15252
15253 return DAG.getBuildVector(VT, DL, Elts);
15254}
15255
15256// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
15257// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
15258// transformation. Returns true if extension are possible and the above
15259// mentioned transformation is profitable.
15261 unsigned ExtOpc,
15262 SmallVectorImpl<SDNode *> &ExtendNodes,
15263 const TargetLowering &TLI) {
15264 bool HasCopyToRegUses = false;
15265 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
15266 for (SDUse &Use : N0->uses()) {
15267 SDNode *User = Use.getUser();
15268 if (User == N)
15269 continue;
15270 if (Use.getResNo() != N0.getResNo())
15271 continue;
15272 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
15273 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
15275 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
15276 // Sign bits will be lost after a zext.
15277 return false;
15278 bool Add = false;
15279 for (unsigned i = 0; i != 2; ++i) {
15280 SDValue UseOp = User->getOperand(i);
15281 if (UseOp == N0)
15282 continue;
15283 if (!isa<ConstantSDNode>(UseOp))
15284 return false;
15285 Add = true;
15286 }
15287 if (Add)
15288 ExtendNodes.push_back(User);
15289 continue;
15290 }
15291 // If truncates aren't free and there are users we can't
15292 // extend, it isn't worthwhile.
15293 if (!isTruncFree)
15294 return false;
15295 // Remember if this value is live-out.
15296 if (User->getOpcode() == ISD::CopyToReg)
15297 HasCopyToRegUses = true;
15298 }
15299
15300 if (HasCopyToRegUses) {
15301 bool BothLiveOut = false;
15302 for (SDUse &Use : N->uses()) {
15303 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
15304 BothLiveOut = true;
15305 break;
15306 }
15307 }
15308 if (BothLiveOut)
15309 // Both unextended and extended values are live out. There had better be
15310 // a good reason for the transformation.
15311 return !ExtendNodes.empty();
15312 }
15313 return true;
15314}
15315
15316void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
15317 SDValue OrigLoad, SDValue ExtLoad,
15318 ISD::NodeType ExtType) {
15319 // Extend SetCC uses if necessary.
15320 SDLoc DL(ExtLoad);
15321 for (SDNode *SetCC : SetCCs) {
15323
15324 for (unsigned j = 0; j != 2; ++j) {
15325 SDValue SOp = SetCC->getOperand(j);
15326 if (SOp == OrigLoad)
15327 Ops.push_back(ExtLoad);
15328 else
15329 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
15330 }
15331
15332 Ops.push_back(SetCC->getOperand(2));
15333 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
15334 }
15335}
15336
15337// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
15338SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
15339 SDValue N0 = N->getOperand(0);
15340 EVT DstVT = N->getValueType(0);
15341 EVT SrcVT = N0.getValueType();
15342
15343 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
15344 N->getOpcode() == ISD::ZERO_EXTEND) &&
15345 "Unexpected node type (not an extend)!");
15346
15347 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
15348 // For example, on a target with legal v4i32, but illegal v8i32, turn:
15349 // (v8i32 (sext (v8i16 (load x))))
15350 // into:
15351 // (v8i32 (concat_vectors (v4i32 (sextload x)),
15352 // (v4i32 (sextload (x + 16)))))
15353 // Where uses of the original load, i.e.:
15354 // (v8i16 (load x))
15355 // are replaced with:
15356 // (v8i16 (truncate
15357 // (v8i32 (concat_vectors (v4i32 (sextload x)),
15358 // (v4i32 (sextload (x + 16)))))))
15359 //
15360 // This combine is only applicable to illegal, but splittable, vectors.
15361 // All legal types, and illegal non-vector types, are handled elsewhere.
15362 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
15363 //
15364 if (N0->getOpcode() != ISD::LOAD)
15365 return SDValue();
15366
15367 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15368
15369 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
15370 !N0.hasOneUse() || !LN0->isSimple() ||
15371 !DstVT.isVector() || !DstVT.isPow2VectorType() ||
15373 return SDValue();
15374
15376 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
15377 return SDValue();
15378
15379 ISD::LoadExtType ExtType =
15380 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15381
15382 // Try to split the vector types to get down to legal types.
15383 EVT SplitSrcVT = SrcVT;
15384 EVT SplitDstVT = DstVT;
15385 while (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
15386 LN0->getAddressSpace(), ExtType, false) &&
15387 SplitSrcVT.getVectorNumElements() > 1) {
15388 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
15389 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
15390 }
15391
15392 if (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
15393 LN0->getAddressSpace(), ExtType, false))
15394 return SDValue();
15395
15396 assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
15397
15398 SDLoc DL(N);
15399 const unsigned NumSplits =
15400 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
15401 const unsigned Stride = SplitSrcVT.getStoreSize();
15404
15405 SDValue BasePtr = LN0->getBasePtr();
15406 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
15407 const unsigned Offset = Idx * Stride;
15408
15410 DAG.getExtLoad(ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(),
15411 BasePtr, LN0->getPointerInfo().getWithOffset(Offset),
15412 SplitSrcVT, LN0->getBaseAlign(),
15413 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
15414
15415 BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::getFixed(Stride), DL);
15416
15417 Loads.push_back(SplitLoad.getValue(0));
15418 Chains.push_back(SplitLoad.getValue(1));
15419 }
15420
15421 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15422 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
15423
15424 // Simplify TF.
15425 AddToWorklist(NewChain.getNode());
15426
15427 CombineTo(N, NewValue);
15428
15429 // Replace uses of the original load (before extension)
15430 // with a truncate of the concatenated sextloaded vectors.
15431 SDValue Trunc =
15432 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
15433 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
15434 CombineTo(N0.getNode(), Trunc, NewChain);
15435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15436}
15437
15438// fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
15439// (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
15440SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
15441 assert(N->getOpcode() == ISD::ZERO_EXTEND);
15442 EVT VT = N->getValueType(0);
15443 EVT OrigVT = N->getOperand(0).getValueType();
15444 if (TLI.isZExtFree(OrigVT, VT))
15445 return SDValue();
15446
15447 // and/or/xor
15448 SDValue N0 = N->getOperand(0);
15449 if (!ISD::isBitwiseLogicOp(N0.getOpcode()) ||
15450 N0.getOperand(1).getOpcode() != ISD::Constant ||
15451 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
15452 return SDValue();
15453
15454 // shl/shr
15455 SDValue N1 = N0->getOperand(0);
15456 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
15457 N1.getOperand(1).getOpcode() != ISD::Constant ||
15458 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
15459 return SDValue();
15460
15461 // load
15462 if (!isa<LoadSDNode>(N1.getOperand(0)))
15463 return SDValue();
15464 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
15465 EVT MemVT = Load->getMemoryVT();
15466 if (!TLI.isLoadLegal(VT, MemVT, Load->getAlign(), Load->getAddressSpace(),
15467 ISD::ZEXTLOAD, false) ||
15468 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
15469 return SDValue();
15470
15471
15472 // If the shift op is SHL, the logic op must be AND, otherwise the result
15473 // will be wrong.
15474 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
15475 return SDValue();
15476
15477 if (!N0.hasOneUse() || !N1.hasOneUse())
15478 return SDValue();
15479
15481 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
15482 ISD::ZERO_EXTEND, SetCCs, TLI))
15483 return SDValue();
15484
15485 // Actually do the transformation.
15486 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
15487 Load->getChain(), Load->getBasePtr(),
15488 Load->getMemoryVT(), Load->getMemOperand());
15489
15490 SDLoc DL1(N1);
15491 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
15492 N1.getOperand(1));
15493
15494 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
15495 SDLoc DL0(N0);
15496 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
15497 DAG.getConstant(Mask, DL0, VT));
15498
15499 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
15500 CombineTo(N, And);
15501 if (SDValue(Load, 0).hasOneUse()) {
15502 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15503 } else {
15504 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
15505 Load->getValueType(0), ExtLoad);
15506 CombineTo(Load, Trunc, ExtLoad.getValue(1));
15507 }
15508
15509 // N0 is dead at this point.
15510 recursivelyDeleteUnusedNodes(N0.getNode());
15511
15512 return SDValue(N,0); // Return N so it doesn't get rechecked!
15513}
15514
15515/// If we're narrowing or widening the result of a vector select and the final
15516/// size is the same size as a setcc (compare) feeding the select, then try to
15517/// apply the cast operation to the select's operands because matching vector
15518/// sizes for a select condition and other operands should be more efficient.
15519SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
15520 unsigned CastOpcode = Cast->getOpcode();
15521 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
15522 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
15523 CastOpcode == ISD::FP_ROUND) &&
15524 "Unexpected opcode for vector select narrowing/widening");
15525
15526 // We only do this transform before legal ops because the pattern may be
15527 // obfuscated by target-specific operations after legalization. Do not create
15528 // an illegal select op, however, because that may be difficult to lower.
15529 EVT VT = Cast->getValueType(0);
15530 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
15531 return SDValue();
15532
15533 SDValue VSel = Cast->getOperand(0);
15534 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
15535 VSel.getOperand(0).getOpcode() != ISD::SETCC)
15536 return SDValue();
15537
15538 // Does the setcc have the same vector size as the casted select?
15539 SDValue SetCC = VSel.getOperand(0);
15540 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
15541 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
15542 return SDValue();
15543
15544 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
15545 SDValue A = VSel.getOperand(1);
15546 SDValue B = VSel.getOperand(2);
15547 SDValue CastA, CastB;
15548 SDLoc DL(Cast);
15549 if (CastOpcode == ISD::FP_ROUND) {
15550 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
15551 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
15552 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
15553 } else {
15554 CastA = DAG.getNode(CastOpcode, DL, VT, A);
15555 CastB = DAG.getNode(CastOpcode, DL, VT, B);
15556 }
15557 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
15558}
15559
15560// fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15561// fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15563 const TargetLowering &TLI, EVT VT,
15564 bool LegalOperations, SDNode *N,
15565 SDValue N0, ISD::LoadExtType ExtLoadType) {
15566 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15567 auto *OldExtLoad = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15568 if (!OldExtLoad)
15569 return SDValue();
15570
15571 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD)
15572 ? ISD::isSEXTLoad(OldExtLoad)
15573 : ISD::isZEXTLoad(OldExtLoad);
15574 if ((!isAExtLoad && !ISD::isEXTLoad(OldExtLoad)) ||
15575 !ISD::isUNINDEXEDLoad(OldExtLoad) || !OldExtLoad->hasNUsesOfValue(1, 0))
15576 return SDValue();
15577
15578 EVT MemVT = OldExtLoad->getMemoryVT();
15579 if ((LegalOperations || !OldExtLoad->isSimple() || VT.isVector()) &&
15580 !TLI.isLoadLegal(VT, MemVT, OldExtLoad->getAlign(),
15581 OldExtLoad->getAddressSpace(), ExtLoadType, false))
15582 return SDValue();
15583
15584 SDLoc DL(OldExtLoad);
15585 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, DL, VT, OldExtLoad->getChain(),
15586 OldExtLoad->getBasePtr(), MemVT,
15587 OldExtLoad->getMemOperand());
15588 SDValue Res = ExtLoad;
15589 if (Frozen) {
15590 Res = DAG.getFreeze(ExtLoad);
15591 Res = DAG.getNode(
15592 ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext : ISD::AssertZext, DL,
15593 Res.getValueType(), Res,
15594 DAG.getValueType(OldExtLoad->getValueType(0).getScalarType()));
15595 }
15596 Combiner.CombineTo(N, Res);
15597 DAG.ReplaceAllUsesOfValueWith(SDValue(OldExtLoad, 1), ExtLoad.getValue(1));
15598 if (N0->use_empty())
15599 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15601}
15602
15603// fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15604// Only generate vector extloads when 1) they're legal, and 2) they are
15605// deemed desirable by the target. NonNegZExt can be set to true if a zero
15606// extend has the nonneg flag to allow use of sextload if profitable.
15608 const TargetLowering &TLI, EVT VT,
15609 bool LegalOperations, SDNode *N, SDValue N0,
15610 ISD::LoadExtType ExtLoadType,
15611 ISD::NodeType ExtOpc,
15612 bool NonNegZExt = false) {
15613
15614 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15615 SDValue Freeze = Frozen ? N0 : SDValue();
15616 auto *Load = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15617 // TODO: Support multiple uses of the load when frozen.
15619 (Frozen && !Load->hasNUsesOfValue(1, 0)))
15620 return {};
15621
15622 // If this is zext nneg, see if it would make sense to treat it as a sext.
15623 if (NonNegZExt) {
15624 assert(ExtLoadType == ISD::ZEXTLOAD && ExtOpc == ISD::ZERO_EXTEND &&
15625 "Unexpected load type or opcode");
15626 for (SDNode *User : Load->users()) {
15627 if (User->getOpcode() == ISD::SETCC) {
15629 if (ISD::isSignedIntSetCC(CC)) {
15630 ExtLoadType = ISD::SEXTLOAD;
15631 ExtOpc = ISD::SIGN_EXTEND;
15632 break;
15633 }
15634 }
15635 }
15636 }
15637
15638 // TODO: isFixedLengthVector() should be removed and any negative effects on
15639 // code generation being the result of that target's implementation of
15640 // isVectorLoadExtDesirable().
15641 if ((LegalOperations || VT.isFixedLengthVector() || !Load->isSimple()) &&
15642 !TLI.isLoadLegal(VT, Load->getValueType(0), Load->getAlign(),
15643 Load->getAddressSpace(), ExtLoadType, false))
15644 return {};
15645
15646 bool DoXform = true;
15648 if (!N0->hasOneUse())
15649 DoXform = ExtendUsesToFormExtLoad(VT, N, Frozen ? Freeze : SDValue(Load, 0),
15650 ExtOpc, SetCCs, TLI);
15651 if (VT.isVector())
15652 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
15653 if (!DoXform)
15654 return {};
15655
15656 SDLoc DL(Load);
15657
15658 auto SalvageDbgValue = [&](SDDbgValue *Dbg, SDValue Old, SDValue New,
15659 unsigned OldBits, unsigned NewBits,
15660 bool IsSigned) {
15661 SmallVector<SDDbgOperand> Locs = Dbg->copyLocationOps();
15662 bool Changed = false;
15663
15664 bool IsVariadic = Dbg->isVariadic();
15665 SmallVector<unsigned, 2> AffectedArgs;
15666
15667 for (unsigned I = 0, E = Locs.size(); I != E; ++I) {
15668 SDDbgOperand &Op = Locs[I];
15669 if (Op.getKind() != SDDbgOperand::SDNODE)
15670 continue;
15671
15672 if (Op.getSDNode() == Old.getNode() && Op.getResNo() == Old.getResNo()) {
15673 Op = SDDbgOperand::fromNode(New.getNode(), New.getResNo());
15674 Changed = true;
15675
15676 if (IsVariadic)
15677 AffectedArgs.push_back(I);
15678 }
15679 }
15680
15681 if (!Changed)
15682 return;
15683
15684 const DIExpression *OldExpr = Dbg->getExpression();
15685 const DIExpression *NewExpr = nullptr;
15686
15687 if (!IsVariadic) {
15688 // Do not introduce DW_OP_LLVM_arg into ordinary single-location
15689 // DBG_VALUEs.
15690 NewExpr = DIExpression::appendExt(OldExpr, NewBits, OldBits, IsSigned);
15691 } else {
15692 auto ExtOps = DIExpression::getExtOps(NewBits, OldBits, IsSigned);
15693
15695
15696 for (unsigned ArgNo : AffectedArgs)
15698 /*StackValue=*/false);
15699 }
15700
15701 SDDbgValue *NewDV = DAG.getDbgValueList(
15702 Dbg->getVariable(), const_cast<DIExpression *>(NewExpr), Locs,
15703 Dbg->getAdditionalDependencies(), Dbg->isIndirect(), Dbg->getDebugLoc(),
15704 Dbg->getOrder(), Dbg->isVariadic());
15705
15706 Dbg->setIsInvalidated();
15707 Dbg->setIsEmitted();
15708 DAG.AddDbgValue(NewDV, /*isParameter=*/false);
15709 };
15710
15711 // Because we are replacing a load and a s|z ext with a load-s|z ext
15712 // instruction, the dbg_value attached to the load will be of a smaller bit
15713 // width, and we have to add a DW_OP_LLVM_convert expression to get the
15714 // correct size.
15715 auto SalvageToOldLoadSize = [&](SDValue Old, SDValue New, bool IsSigned) {
15717 DAG.GetDbgValues(Old.getNode()).begin(),
15718 DAG.GetDbgValues(Old.getNode()).end());
15719
15720 unsigned VarBitsOld = Old.getValueSizeInBits();
15721 unsigned VarBitsNew = New.getValueSizeInBits();
15722
15723 for (SDDbgValue *Dbg : DbgVals) {
15724 if (Dbg->isInvalidated())
15725 continue;
15726
15727 SalvageDbgValue(Dbg, Old, New, VarBitsOld, VarBitsNew, IsSigned);
15728 }
15729 };
15730
15731 SDValue ExtLoad =
15732 DAG.getExtLoad(ExtLoadType, DL, VT, Load->getChain(), Load->getBasePtr(),
15733 Load->getValueType(0), Load->getMemOperand());
15734 SDValue Res = ExtLoad;
15735 if (Frozen) {
15736 Res = DAG.getFreeze(ExtLoad);
15737 Res = DAG.getNode(ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext
15739 DL, Res.getValueType(), Res,
15740 DAG.getValueType(Load->getValueType(0).getScalarType()));
15741 }
15742 Combiner.ExtendSetCCUses(SetCCs, N0, Res, ExtOpc);
15743 // If the load value is used only by N, replace it via CombineTo N.
15744 bool NoReplaceTrunc = N0.hasOneUse();
15745 if (N->getHasDebugValue()) {
15746 SDValue OldExtValue(N, 0);
15747 DAG.transferDbgValues(OldExtValue, ExtLoad);
15748 }
15749 if (NoReplaceTrunc) {
15750 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
15751 if (Load->getHasDebugValue()) {
15752 SDValue OldLoadVal(Load, 0);
15753 SalvageToOldLoadSize(OldLoadVal, ExtLoad, IsSigned);
15754 }
15755 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15756 Combiner.CombineTo(N, Res);
15757 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15758 } else {
15759 Combiner.CombineTo(N, Res);
15760 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Load->getValueType(0), Res);
15761 if (Frozen) {
15762 Combiner.CombineTo(Freeze.getNode(), Trunc);
15763 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15764 } else {
15765 Combiner.CombineTo(Load, Trunc, ExtLoad.getValue(1));
15766 }
15767 }
15768 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15769}
15770
15771static SDValue
15773 bool LegalOperations, SDNode *N, SDValue N0,
15774 ISD::LoadExtType ExtLoadType, ISD::NodeType ExtOpc) {
15775 if (!N0.hasOneUse())
15776 return SDValue();
15777
15779 if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
15780 return SDValue();
15781
15782 if ((LegalOperations || !cast<MaskedLoadSDNode>(N0)->isSimple()) &&
15783 !TLI.isLoadLegalOrCustom(VT, Ld->getValueType(0), Ld->getAlign(),
15784 Ld->getAddressSpace(), ExtLoadType, false))
15785 return SDValue();
15786
15787 if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
15788 return SDValue();
15789
15790 SDLoc dl(Ld);
15791 SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
15792 SDValue NewLoad = DAG.getMaskedLoad(
15793 VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
15794 PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
15795 ExtLoadType, Ld->isExpandingLoad());
15796 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
15797 return NewLoad;
15798}
15799
15800// fold ([s|z]ext (atomic_load)) -> ([s|z]ext (truncate ([s|z]ext atomic_load)))
15802 const TargetLowering &TLI, EVT VT,
15803 SDValue N0,
15804 ISD::LoadExtType ExtLoadType) {
15805 auto *ALoad = dyn_cast<AtomicSDNode>(N0);
15806 if (!ALoad || ALoad->getOpcode() != ISD::ATOMIC_LOAD)
15807 return {};
15808 EVT MemoryVT = ALoad->getMemoryVT();
15809 if (!TLI.isLoadLegal(VT, MemoryVT, ALoad->getAlign(),
15810 ALoad->getAddressSpace(), ExtLoadType, true))
15811 return {};
15812 // Can't fold into ALoad if it is already extending differently.
15813 ISD::LoadExtType ALoadExtTy = ALoad->getExtensionType();
15814 if ((ALoadExtTy == ISD::ZEXTLOAD && ExtLoadType == ISD::SEXTLOAD) ||
15815 (ALoadExtTy == ISD::SEXTLOAD && ExtLoadType == ISD::ZEXTLOAD))
15816 return {};
15817
15818 EVT OrigVT = ALoad->getValueType(0);
15819 assert(OrigVT.getSizeInBits() < VT.getSizeInBits() && "VT should be wider.");
15820 auto *NewALoad = cast<AtomicSDNode>(DAG.getAtomicLoad(
15821 ExtLoadType, SDLoc(ALoad), MemoryVT, VT, ALoad->getChain(),
15822 ALoad->getBasePtr(), ALoad->getMemOperand()));
15824 SDValue(ALoad, 0),
15825 DAG.getNode(ISD::TRUNCATE, SDLoc(ALoad), OrigVT, SDValue(NewALoad, 0)));
15826 // Update the chain uses.
15827 DAG.ReplaceAllUsesOfValueWith(SDValue(ALoad, 1), SDValue(NewALoad, 1));
15828 return SDValue(NewALoad, 0);
15829}
15830
15832 bool LegalOperations) {
15833 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
15834 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
15835
15836 SDValue SetCC = N->getOperand(0);
15837 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
15838 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
15839 return SDValue();
15840
15841 SDValue X = SetCC.getOperand(0);
15842 SDValue Ones = SetCC.getOperand(1);
15843 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
15844 EVT VT = N->getValueType(0);
15845 EVT XVT = X.getValueType();
15846 // setge X, C is canonicalized to setgt, so we do not need to match that
15847 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
15848 // not require the 'not' op.
15849 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
15850 // Invert and smear/shift the sign bit:
15851 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
15852 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
15853 SDLoc DL(N);
15854 unsigned ShCt = VT.getSizeInBits() - 1;
15855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15856 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
15857 SDValue NotX = DAG.getNOT(DL, X, VT);
15858 SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
15859 auto ShiftOpcode =
15860 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
15861 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
15862 }
15863 }
15864 return SDValue();
15865}
15866
15867SDValue DAGCombiner::foldSextSetcc(SDNode *N) {
15868 SDValue N0 = N->getOperand(0);
15869 if (N0.getOpcode() != ISD::SETCC)
15870 return SDValue();
15871
15872 SDValue N00 = N0.getOperand(0);
15873 SDValue N01 = N0.getOperand(1);
15875 EVT VT = N->getValueType(0);
15876 EVT N00VT = N00.getValueType();
15877 SDLoc DL(N);
15878
15879 // Propagate fast-math-flags.
15880 SDNodeFlags Flags = N0->getFlags();
15881
15882 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
15883 // the same size as the compared operands. Try to optimize sext(setcc())
15884 // if this is the case.
15885 if (VT.isVector() && !LegalOperations &&
15886 TLI.getBooleanContents(N00VT) ==
15888 EVT SVT = getSetCCResultType(N00VT);
15889
15890 // If we already have the desired type, don't change it.
15891 if (SVT != N0.getValueType()) {
15892 // We know that the # elements of the results is the same as the
15893 // # elements of the compare (and the # elements of the compare result
15894 // for that matter). Check to see that they are the same size. If so,
15895 // we know that the element size of the sext'd result matches the
15896 // element size of the compare operands.
15897 if (VT.getSizeInBits() == SVT.getSizeInBits())
15898 return DAG.getSetCC(DL, VT, N00, N01, CC, /*Chain=*/{},
15899 /*Signaling=*/false, Flags);
15900
15901 // If the desired elements are smaller or larger than the source
15902 // elements, we can use a matching integer vector type and then
15903 // truncate/sign extend.
15904 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
15905 if (SVT == MatchingVecType) {
15906 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC,
15907 /*Chain=*/{}, /*Signaling=*/false, Flags);
15908 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
15909 }
15910 }
15911
15912 // Try to eliminate the sext of a setcc by zexting the compare operands.
15913 if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) &&
15915 bool IsSignedCmp = ISD::isSignedIntSetCC(CC);
15916 unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15917 unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15918
15919 // We have an unsupported narrow vector compare op that would be legal
15920 // if extended to the destination type. See if the compare operands
15921 // can be freely extended to the destination type.
15922 auto IsFreeToExtend = [&](SDValue V) {
15923 if (isConstantOrConstantVector(V, /*NoOpaques*/ true))
15924 return true;
15925 // Match a simple, non-extended load that can be converted to a
15926 // legal {z/s}ext-load.
15927 // TODO: Allow widening of an existing {z/s}ext-load?
15928 if (!(ISD::isNON_EXTLoad(V.getNode()) &&
15929 ISD::isUNINDEXEDLoad(V.getNode())))
15930 return false;
15931
15932 LoadSDNode *Ld = cast<LoadSDNode>(V.getNode());
15933
15934 if (!Ld->isSimple() ||
15935 !TLI.isLoadLegal(VT, V.getValueType(), Ld->getAlign(),
15936 Ld->getAddressSpace(), LoadOpcode, false))
15937 return false;
15938
15939 // Non-chain users of this value must either be the setcc in this
15940 // sequence or extends that can be folded into the new {z/s}ext-load.
15941 for (SDUse &Use : V->uses()) {
15942 // Skip uses of the chain and the setcc.
15943 SDNode *User = Use.getUser();
15944 if (Use.getResNo() != 0 || User == N0.getNode())
15945 continue;
15946 // Extra users must have exactly the same cast we are about to create.
15947 // TODO: This restriction could be eased if ExtendUsesToFormExtLoad()
15948 // is enhanced similarly.
15949 if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT)
15950 return false;
15951 }
15952 return true;
15953 };
15954
15955 if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) {
15956 SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00);
15957 SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01);
15958 return DAG.getSetCC(DL, VT, Ext0, Ext1, CC, /*Chain=*/{},
15959 /*Signaling=*/false, Flags);
15960 }
15961 }
15962 }
15963
15964 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
15965 // Here, T can be 1 or -1, depending on the type of the setcc and
15966 // getBooleanContents().
15967 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
15968
15969 // To determine the "true" side of the select, we need to know the high bit
15970 // of the value returned by the setcc if it evaluates to true.
15971 // If the type of the setcc is i1, then the true case of the select is just
15972 // sext(i1 1), that is, -1.
15973 // If the type of the setcc is larger (say, i8) then the value of the high
15974 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
15975 // of the appropriate width.
15976 SDValue ExtTrueVal = (SetCCWidth == 1)
15977 ? DAG.getAllOnesConstant(DL, VT)
15978 : DAG.getBoolConstant(true, DL, VT, N00VT);
15979 SDValue Zero = DAG.getConstant(0, DL, VT);
15980 if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
15981 return SCC;
15982
15983 if (!VT.isVector() && !shouldConvertSelectOfConstantsToMath(N0, VT, TLI)) {
15984 EVT SetCCVT = getSetCCResultType(N00VT);
15985 // Don't do this transform for i1 because there's a select transform
15986 // that would reverse it.
15987 // TODO: We should not do this transform at all without a target hook
15988 // because a sext is likely cheaper than a select?
15989 if (SetCCVT.getScalarSizeInBits() != 1 &&
15990 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
15991 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC, /*Chain=*/{},
15992 /*Signaling=*/false, Flags);
15993 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero, Flags);
15994 }
15995 }
15996
15997 return SDValue();
15998}
15999
16000SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
16001 SDValue N0 = N->getOperand(0);
16002 EVT VT = N->getValueType(0);
16003 SDLoc DL(N);
16004
16005 if (VT.isVector())
16006 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
16007 return FoldedVOp;
16008
16009 // sext(undef) = 0 because the top bit will all be the same.
16010 if (N0.isUndef())
16011 return DAG.getConstant(0, DL, VT);
16012
16013 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16014 return Res;
16015
16016 // fold (sext (sext x)) -> (sext x)
16017 // fold (sext (aext x)) -> (sext x)
16018 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
16019 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
16020
16021 // fold (sext (aext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
16022 // fold (sext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
16025 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT,
16026 N0.getOperand(0));
16027
16028 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
16029 SDValue N00 = N0.getOperand(0);
16030 EVT ExtVT = cast<VTSDNode>(N0->getOperand(1))->getVT();
16031 if (N00.getOpcode() == ISD::TRUNCATE || TLI.isTruncateFree(N00, ExtVT)) {
16032 // fold (sext (sext_inreg x)) -> (sext (trunc x))
16033 if ((!LegalTypes || TLI.isTypeLegal(ExtVT))) {
16034 SDValue T = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N00);
16035 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, T);
16036 }
16037
16038 // If the trunc wasn't legal, try to fold to (sext_inreg (anyext x))
16039 if (!LegalTypes || TLI.isTypeLegal(VT)) {
16040 SDValue ExtSrc = DAG.getAnyExtOrTrunc(N00, DL, VT);
16041 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ExtSrc,
16042 N0->getOperand(1));
16043 }
16044 }
16045 }
16046
16047 if (N0.getOpcode() == ISD::TRUNCATE) {
16048 // fold (sext (truncate (load x))) -> (sext (smaller load x))
16049 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
16050 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16051 SDNode *oye = N0.getOperand(0).getNode();
16052 if (NarrowLoad.getNode() != N0.getNode()) {
16053 CombineTo(N0.getNode(), NarrowLoad);
16054 // CombineTo deleted the truncate, if needed, but not what's under it.
16055 AddToWorklist(oye);
16056 }
16057 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16058 }
16059
16060 // See if the value being truncated is already sign extended. If so, just
16061 // eliminate the trunc/sext pair.
16062 SDValue Op = N0.getOperand(0);
16063 unsigned OpBits = Op.getScalarValueSizeInBits();
16064 unsigned MidBits = N0.getScalarValueSizeInBits();
16065 unsigned DestBits = VT.getScalarSizeInBits();
16066
16067 if (N0->getFlags().hasNoSignedWrap() ||
16068 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
16069 if (OpBits == DestBits) {
16070 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
16071 // bits, it is already ready.
16072 return Op;
16073 }
16074
16075 if (OpBits < DestBits) {
16076 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
16077 // bits, just sext from i32.
16078 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
16079 }
16080
16081 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
16082 // bits, just truncate to i32.
16083 SDNodeFlags Flags;
16084 Flags.setNoSignedWrap(true);
16085 Flags.setNoUnsignedWrap(N0->getFlags().hasNoUnsignedWrap());
16086 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
16087 }
16088
16089 // fold (sext (truncate x)) -> (sextinreg x).
16090 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
16091 N0.getValueType())) {
16092 if (OpBits < DestBits)
16093 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
16094 else if (OpBits > DestBits)
16095 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
16096 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
16097 DAG.getValueType(N0.getValueType()));
16098 }
16099 }
16100
16101 // Try to simplify (sext (load x)).
16102 if (SDValue foldedExt =
16103 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
16105 return foldedExt;
16106
16107 if (SDValue foldedExt =
16108 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
16110 return foldedExt;
16111
16112 // fold (sext (load x)) to multiple smaller sextloads.
16113 // Only on illegal but splittable vectors.
16114 if (SDValue ExtLoad = CombineExtLoad(N))
16115 return ExtLoad;
16116
16117 // Try to simplify (sext (sextload x)).
16118 if (SDValue foldedExt = tryToFoldExtOfExtload(
16119 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
16120 return foldedExt;
16121
16122 // Try to simplify (sext (atomic_load x)).
16123 if (SDValue foldedExt =
16124 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::SEXTLOAD))
16125 return foldedExt;
16126
16127 // fold (sext (and/or/xor (load x), cst)) ->
16128 // (and/or/xor (sextload x), (sext cst))
16129 if (ISD::isBitwiseLogicOp(N0.getOpcode()) &&
16130 isa<LoadSDNode>(N0.getOperand(0)) &&
16131 N0.getOperand(1).getOpcode() == ISD::Constant &&
16132 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
16133 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
16134 EVT MemVT = LN00->getMemoryVT();
16135 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
16136 ISD::SEXTLOAD, false) &&
16137 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
16139 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
16140 ISD::SIGN_EXTEND, SetCCs, TLI);
16141 if (DoXform) {
16142 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
16143 LN00->getChain(), LN00->getBasePtr(),
16144 LN00->getMemoryVT(),
16145 LN00->getMemOperand());
16146 APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
16147 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
16148 ExtLoad, DAG.getConstant(Mask, DL, VT));
16149 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
16150 bool NoReplaceTruncAnd = !N0.hasOneUse();
16151 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
16152 CombineTo(N, And);
16153 // If N0 has multiple uses, change other uses as well.
16154 if (NoReplaceTruncAnd) {
16155 SDValue TruncAnd =
16157 CombineTo(N0.getNode(), TruncAnd);
16158 }
16159 if (NoReplaceTrunc) {
16160 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
16161 } else {
16162 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
16163 LN00->getValueType(0), ExtLoad);
16164 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
16165 }
16166 return SDValue(N,0); // Return N so it doesn't get rechecked!
16167 }
16168 }
16169 }
16170
16171 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
16172 return V;
16173
16174 if (SDValue V = foldSextSetcc(N))
16175 return V;
16176
16177 // fold (sext x) -> (zext x) if the sign bit is known zero.
16178 if (!TLI.isSExtCheaperThanZExt(N0.getValueType(), VT) &&
16179 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
16180 DAG.SignBitIsZero(N0))
16181 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0, SDNodeFlags::NonNeg);
16182
16183 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
16184 return NewVSel;
16185
16186 // Eliminate this sign extend by doing a negation in the destination type:
16187 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
16188 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
16192 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
16193 return DAG.getNegative(Zext, DL, VT);
16194 }
16195 // Eliminate this sign extend by doing a decrement in the destination type:
16196 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
16197 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
16201 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
16202 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
16203 }
16204
16205 // fold sext (not i1 X) -> add (zext i1 X), -1
16206 // TODO: This could be extended to handle bool vectors.
16207 if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() &&
16208 (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) &&
16209 TLI.isOperationLegal(ISD::ADD, VT)))) {
16210 // If we can eliminate the 'not', the sext form should be better
16211 if (SDValue NewXor = visitXOR(N0.getNode())) {
16212 // Returning N0 is a form of in-visit replacement that may have
16213 // invalidated N0.
16214 if (NewXor.getNode() == N0.getNode()) {
16215 // Return SDValue here as the xor should have already been replaced in
16216 // this sext.
16217 return SDValue();
16218 }
16219
16220 // Return a new sext with the new xor.
16221 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor);
16222 }
16223
16224 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
16225 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
16226 }
16227
16228 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16229 return Res;
16230
16231 return SDValue();
16232}
16233
16234/// Given an extending node with a pop-count operand, if the target does not
16235/// support a pop-count in the narrow source type but does support it in the
16236/// destination type, widen the pop-count to the destination type.
16237static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG, const SDLoc &DL) {
16238 assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
16239 Extend->getOpcode() == ISD::ANY_EXTEND) &&
16240 "Expected extend op");
16241
16242 SDValue CtPop = Extend->getOperand(0);
16243 if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
16244 return SDValue();
16245
16246 EVT VT = Extend->getValueType(0);
16247 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16250 return SDValue();
16251
16252 // zext (ctpop X) --> ctpop (zext X)
16253 SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
16254 return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
16255}
16256
16257// If we have (zext (abs X)) where X is a type that will be promoted by type
16258// legalization, convert to (abs_min_poison (sext X)). But do not extend
16259// past a legal type.
16260static SDValue widenAbs(SDNode *Extend, SelectionDAG &DAG) {
16261 assert(Extend->getOpcode() == ISD::ZERO_EXTEND && "Expected zero extend.");
16262
16263 EVT VT = Extend->getValueType(0);
16264 if (VT.isVector())
16265 return SDValue();
16266
16267 SDValue Abs = Extend->getOperand(0);
16268 if (!ISD::isAbsOpcode(Abs.getOpcode()) || !Abs.hasOneUse())
16269 return SDValue();
16270
16271 EVT AbsVT = Abs.getValueType();
16272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16273 if (TLI.getTypeAction(*DAG.getContext(), AbsVT) !=
16275 return SDValue();
16276
16277 EVT LegalVT = TLI.getTypeToTransformTo(*DAG.getContext(), AbsVT);
16278
16279 SDValue SExt =
16280 DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Abs), LegalVT, Abs.getOperand(0));
16281 SDValue NewAbs = DAG.getNode(ISD::ABS_MIN_POISON, SDLoc(Abs), LegalVT, SExt);
16282 return DAG.getZExtOrTrunc(NewAbs, SDLoc(Extend), VT);
16283}
16284
16285SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
16286 SDValue N0 = N->getOperand(0);
16287 EVT VT = N->getValueType(0);
16288 SDLoc DL(N);
16289
16290 if (VT.isVector())
16291 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
16292 return FoldedVOp;
16293
16294 // zext(undef) = 0
16295 if (N0.isUndef())
16296 return DAG.getConstant(0, DL, VT);
16297
16298 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16299 return Res;
16300
16301 // fold (zext (zext x)) -> (zext x)
16302 // fold (zext (aext x)) -> (zext x)
16303 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
16304 SDNodeFlags Flags;
16305 if (N0.getOpcode() == ISD::ZERO_EXTEND)
16306 Flags.setNonNeg(N0->getFlags().hasNonNeg());
16307 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0), Flags);
16308 }
16309
16310 // fold (zext (aext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16311 // fold (zext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16314 return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, N0.getOperand(0));
16315
16316 // fold (zext (truncate x)) -> (zext x) or
16317 // (zext (truncate x)) -> (truncate x)
16318 // This is valid when the truncated bits of x are already zero.
16319 SDValue Op;
16320 KnownBits Known;
16321 if (isTruncateOf(DAG, N0, Op, Known)) {
16322 APInt TruncatedBits =
16323 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
16324 APInt(Op.getScalarValueSizeInBits(), 0) :
16325 APInt::getBitsSet(Op.getScalarValueSizeInBits(),
16326 N0.getScalarValueSizeInBits(),
16327 std::min(Op.getScalarValueSizeInBits(),
16328 VT.getScalarSizeInBits()));
16329 if (TruncatedBits.isSubsetOf(Known.Zero)) {
16330 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
16331 DAG.salvageDebugInfo(*N0.getNode());
16332
16333 return ZExtOrTrunc;
16334 }
16335 }
16336
16337 // fold (zext (truncate x)) -> (and x, mask)
16338 if (N0.getOpcode() == ISD::TRUNCATE) {
16339 // fold (zext (truncate (load x))) -> (zext (smaller load x))
16340 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
16341 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16342 SDNode *oye = N0.getOperand(0).getNode();
16343 if (NarrowLoad.getNode() != N0.getNode()) {
16344 CombineTo(N0.getNode(), NarrowLoad);
16345 // CombineTo deleted the truncate, if needed, but not what's under it.
16346 AddToWorklist(oye);
16347 }
16348 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16349 }
16350
16351 EVT SrcVT = N0.getOperand(0).getValueType();
16352 EVT MinVT = N0.getValueType();
16353
16354 if (N->getFlags().hasNonNeg()) {
16355 SDValue Op = N0.getOperand(0);
16356 unsigned OpBits = SrcVT.getScalarSizeInBits();
16357 unsigned MidBits = MinVT.getScalarSizeInBits();
16358 unsigned DestBits = VT.getScalarSizeInBits();
16359
16360 if (N0->getFlags().hasNoSignedWrap() ||
16361 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
16362 if (OpBits == DestBits) {
16363 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
16364 // bits, it is already ready.
16365 return Op;
16366 }
16367
16368 if (OpBits < DestBits) {
16369 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
16370 // bits, just sext from i32.
16371 // FIXME: This can probably be ZERO_EXTEND nneg?
16372 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
16373 }
16374
16375 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
16376 // bits, just truncate to i32.
16377 SDNodeFlags Flags;
16378 Flags.setNoSignedWrap(true);
16379 Flags.setNoUnsignedWrap(true);
16380 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
16381 }
16382 }
16383
16384 // Try to mask before the extension to avoid having to generate a larger mask,
16385 // possibly over several sub-vectors.
16386 if (SrcVT.bitsLT(VT) && VT.isVector()) {
16387 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
16389 SDValue Op = N0.getOperand(0);
16390 Op = DAG.getZeroExtendInReg(Op, DL, MinVT);
16391 AddToWorklist(Op.getNode());
16392 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
16393 // Transfer the debug info; the new node is equivalent to N0.
16394 DAG.transferDbgValues(N0, ZExtOrTrunc);
16395 return ZExtOrTrunc;
16396 }
16397 }
16398
16399 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
16400 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
16401 AddToWorklist(Op.getNode());
16402 SDValue And = DAG.getZeroExtendInReg(Op, DL, MinVT);
16403 // We may safely transfer the debug info describing the truncate node over
16404 // to the equivalent and operation.
16405 DAG.transferDbgValues(N0, And);
16406 return And;
16407 }
16408 }
16409
16410 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
16411 // if either of the casts is not free.
16412 // Also handles (zext (and (bitcast (extract_subvector vNi1, 0)) cst))
16413 // by treating the bitcast+extract as equivalent to a truncate of the
16414 // wider bitcast, e.g. on AVX512DQ where v8i1 extract replaces truncate.
16415 if (N0.getOpcode() == ISD::AND &&
16416 N0.getOperand(1).getOpcode() == ISD::Constant) {
16417 SDValue AndSrc = N0.getOperand(0);
16418 SDValue X;
16419 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
16420 X = AndSrc.getOperand(0);
16421 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
16423 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
16424 // (bitcast (extract_subvector vNi1, 0) -> iK) is equivalent to
16425 // (truncate (bitcast vNi1 -> iN) -> iK); use the wider vNi1 as X.
16426 SDValue Src = AndSrc.getOperand(0).getOperand(0);
16427 EVT SrcVT = Src.getValueType();
16428 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
16429 EVT WideIntVT =
16431 if (TLI.isTypeLegal(WideIntVT))
16432 X = DAG.getBitcast(WideIntVT, Src);
16433 }
16434 }
16435 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
16436 !TLI.isZExtFree(N0.getValueType(), VT))) {
16437 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
16438 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16439 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
16440 }
16441 }
16442
16443 // Try to simplify (zext (load x)).
16444 if (SDValue foldedExt = tryToFoldExtOfLoad(
16445 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD,
16446 ISD::ZERO_EXTEND, N->getFlags().hasNonNeg()))
16447 return foldedExt;
16448
16449 if (SDValue foldedExt =
16450 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
16452 return foldedExt;
16453
16454 // fold (zext (load x)) to multiple smaller zextloads.
16455 // Only on illegal but splittable vectors.
16456 if (SDValue ExtLoad = CombineExtLoad(N))
16457 return ExtLoad;
16458
16459 // Try to simplify (zext (atomic_load x)).
16460 if (SDValue foldedExt =
16461 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::ZEXTLOAD))
16462 return foldedExt;
16463
16464 // fold (zext (and/or/xor (load x), cst)) ->
16465 // (and/or/xor (zextload x), (zext cst))
16466 // Unless (and (load x) cst) will match as a zextload already and has
16467 // additional users, or the zext is already free.
16468 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && !TLI.isZExtFree(N0, VT) &&
16469 isa<LoadSDNode>(N0.getOperand(0)) &&
16470 N0.getOperand(1).getOpcode() == ISD::Constant &&
16471 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
16472 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
16473 EVT MemVT = LN00->getMemoryVT();
16474 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
16475 ISD::ZEXTLOAD, false) &&
16476 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
16477 bool DoXform = true;
16479 if (!N0.hasOneUse()) {
16480 if (N0.getOpcode() == ISD::AND) {
16481 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
16482 EVT LoadResultTy = AndC->getValueType(0);
16483 EVT ExtVT;
16484 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
16485 DoXform = false;
16486 }
16487 }
16488 if (DoXform)
16489 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
16490 ISD::ZERO_EXTEND, SetCCs, TLI);
16491 if (DoXform) {
16492 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
16493 LN00->getChain(), LN00->getBasePtr(),
16494 LN00->getMemoryVT(),
16495 LN00->getMemOperand());
16496 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16497 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
16498 ExtLoad, DAG.getConstant(Mask, DL, VT));
16499 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
16500 bool NoReplaceTruncAnd = !N0.hasOneUse();
16501 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
16502 CombineTo(N, And);
16503 // If N0 has multiple uses, change other uses as well.
16504 if (NoReplaceTruncAnd) {
16505 SDValue TruncAnd =
16507 CombineTo(N0.getNode(), TruncAnd);
16508 }
16509 if (NoReplaceTrunc) {
16510 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
16511 } else {
16512 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
16513 LN00->getValueType(0), ExtLoad);
16514 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
16515 }
16516 return SDValue(N,0); // Return N so it doesn't get rechecked!
16517 }
16518 }
16519 }
16520
16521 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
16522 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
16523 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
16524 return ZExtLoad;
16525
16526 // Try to simplify (zext (zextload x)).
16527 if (SDValue foldedExt = tryToFoldExtOfExtload(
16528 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
16529 return foldedExt;
16530
16531 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
16532 return V;
16533
16534 if (N0.getOpcode() == ISD::SETCC) {
16535 // Propagate fast-math-flags.
16536 SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
16537
16538 // Only do this before legalize for now.
16539 if (!LegalOperations && VT.isVector() &&
16540 N0.getValueType().getVectorElementType() == MVT::i1) {
16541 EVT N00VT = N0.getOperand(0).getValueType();
16542 if (getSetCCResultType(N00VT) == N0.getValueType())
16543 return SDValue();
16544
16545 // We know that the # elements of the results is the same as the #
16546 // elements of the compare (and the # elements of the compare result for
16547 // that matter). Check to see that they are the same size. If so, we know
16548 // that the element size of the sext'd result matches the element size of
16549 // the compare operands.
16550 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
16551 // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
16552 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
16553 N0.getOperand(1), N0.getOperand(2));
16554 return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
16555 }
16556
16557 // If the desired elements are smaller or larger than the source
16558 // elements we can use a matching integer vector type and then
16559 // truncate/any extend followed by zext_in_reg.
16560 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16561 SDValue VsetCC =
16562 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
16563 N0.getOperand(1), N0.getOperand(2));
16564 return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
16565 N0.getValueType());
16566 }
16567
16568 // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc)
16569 EVT N0VT = N0.getValueType();
16570 EVT N00VT = N0.getOperand(0).getValueType();
16571 if (SDValue SCC = SimplifySelectCC(
16572 DL, N0.getOperand(0), N0.getOperand(1),
16573 DAG.getBoolConstant(true, DL, N0VT, N00VT),
16574 DAG.getBoolConstant(false, DL, N0VT, N00VT),
16575 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16576 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC);
16577 }
16578
16579 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
16580 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
16581 !TLI.isZExtFree(N0, VT)) {
16582 SDValue ShVal = N0.getOperand(0);
16583 SDValue ShAmt = N0.getOperand(1);
16584 if (auto *ShAmtC = dyn_cast<ConstantSDNode>(ShAmt)) {
16585 if (ShVal.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse()) {
16586 if (N0.getOpcode() == ISD::SHL) {
16587 // If the original shl may be shifting out bits, do not perform this
16588 // transformation.
16589 unsigned KnownZeroBits = ShVal.getValueSizeInBits() -
16590 ShVal.getOperand(0).getValueSizeInBits();
16591 if (ShAmtC->getAPIntValue().ugt(KnownZeroBits)) {
16592 // If the shift is too large, then see if we can deduce that the
16593 // shift is safe anyway.
16594
16595 // Check if the bits being shifted out are known to be zero.
16596 KnownBits KnownShVal = DAG.computeKnownBits(ShVal);
16597 if (ShAmtC->getAPIntValue().ugt(KnownShVal.countMinLeadingZeros()))
16598 return SDValue();
16599 }
16600 }
16601
16602 // Ensure that the shift amount is wide enough for the shifted value.
16603 if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
16604 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
16605
16606 return DAG.getNode(N0.getOpcode(), DL, VT,
16607 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ShVal), ShAmt);
16608 }
16609 }
16610 }
16611
16612 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
16613 return NewVSel;
16614
16615 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16616 return NewCtPop;
16617
16618 if (SDValue V = widenAbs(N, DAG))
16619 return V;
16620
16621 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16622 return Res;
16623
16624 // CSE zext nneg with sext if the zext is not free.
16625 if (N->getFlags().hasNonNeg() && !TLI.isZExtFree(N0.getValueType(), VT)) {
16626 SDNode *CSENode = DAG.getNodeIfExists(ISD::SIGN_EXTEND, N->getVTList(), N0);
16627 if (CSENode)
16628 return SDValue(CSENode, 0);
16629 }
16630
16631 return SDValue();
16632}
16633
16634SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
16635 SDValue N0 = N->getOperand(0);
16636 EVT VT = N->getValueType(0);
16637 SDLoc DL(N);
16638
16639 // aext(undef) = undef
16640 if (N0.isUndef())
16641 return DAG.getUNDEF(VT);
16642
16643 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16644 return Res;
16645
16646 // fold (aext (aext x)) -> (aext x)
16647 // fold (aext (zext x)) -> (zext x)
16648 // fold (aext (sext x)) -> (sext x)
16649 if (N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::ZERO_EXTEND ||
16650 N0.getOpcode() == ISD::SIGN_EXTEND) {
16651 SDNodeFlags Flags;
16652 if (N0.getOpcode() == ISD::ZERO_EXTEND)
16653 Flags.setNonNeg(N0->getFlags().hasNonNeg());
16654 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
16655 }
16656
16657 // fold (aext (aext_extend_vector_inreg x)) -> (aext_extend_vector_inreg x)
16658 // fold (aext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16659 // fold (aext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
16663 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
16664
16665 // fold (aext (truncate (load x))) -> (aext (smaller load x))
16666 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
16667 if (N0.getOpcode() == ISD::TRUNCATE) {
16668 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16669 SDNode *oye = N0.getOperand(0).getNode();
16670 if (NarrowLoad.getNode() != N0.getNode()) {
16671 CombineTo(N0.getNode(), NarrowLoad);
16672 // CombineTo deleted the truncate, if needed, but not what's under it.
16673 AddToWorklist(oye);
16674 }
16675 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16676 }
16677 }
16678
16679 // fold (aext (truncate x))
16680 if (N0.getOpcode() == ISD::TRUNCATE)
16681 return DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
16682
16683 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
16684 // if either of the casts is not free, and sign-extending the narrow type is
16685 // not cheaper than zero-extending it (which would indicate the target prefers
16686 // to keep operations at the narrower width).
16687 // Also handles (aext (and (bitcast (extract_subvector vNi1, 0)) cst))
16688 // which arises on AVX512DQ where v8i1 extract replaces truncate.
16689 if (N0.getOpcode() == ISD::AND &&
16690 N0.getOperand(1).getOpcode() == ISD::Constant) {
16691 SDValue AndSrc = N0.getOperand(0);
16692 SDValue X;
16693 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
16694 X = AndSrc.getOperand(0);
16695 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
16697 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
16698 SDValue Src = AndSrc.getOperand(0).getOperand(0);
16699 EVT SrcVT = Src.getValueType();
16700 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
16701 EVT WideIntVT =
16703 if (TLI.isTypeLegal(WideIntVT))
16704 X = DAG.getBitcast(WideIntVT, Src);
16705 }
16706 }
16707 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
16708 (!TLI.isZExtFree(N0.getValueType(), VT) &&
16709 !TLI.isSExtCheaperThanZExt(N0.getValueType(), VT)))) {
16710 X = DAG.getAnyExtOrTrunc(X, DL, VT);
16711 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16712 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
16713 }
16714 }
16715
16716 // fold (aext (load x)) -> (aext (truncate (extload x)))
16717 // None of the supported targets knows how to perform load and any_ext
16718 // on vectors in one instruction, so attempt to fold to zext instead.
16719 if (VT.isVector()) {
16720 // Try to simplify (zext (load x)).
16721 if (SDValue foldedExt =
16722 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
16724 return foldedExt;
16725 } else if (ISD::isNON_EXTLoad(N0.getNode()) &&
16727 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16728 if (TLI.isLoadLegalOrCustom(VT, N0.getValueType(), LN0->getAlign(),
16729 LN0->getAddressSpace(), ISD::EXTLOAD, false)) {
16730 bool DoXform = true;
16732 if (!N0.hasOneUse())
16733 DoXform =
16734 ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
16735 if (DoXform) {
16736 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, DL, VT, LN0->getChain(),
16737 LN0->getBasePtr(), N0.getValueType(),
16738 LN0->getMemOperand());
16739 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
16740 // If the load value is used only by N, replace it via CombineTo N.
16741 bool NoReplaceTrunc = N0.hasOneUse();
16742 CombineTo(N, ExtLoad);
16743 if (NoReplaceTrunc) {
16744 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16745 recursivelyDeleteUnusedNodes(LN0);
16746 } else {
16747 SDValue Trunc =
16748 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
16749 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
16750 }
16751 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16752 }
16753 }
16754 }
16755
16756 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
16757 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
16758 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
16759 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
16760 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
16761 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16762 ISD::LoadExtType ExtType = LN0->getExtensionType();
16763 EVT MemVT = LN0->getMemoryVT();
16764 if (!LegalOperations ||
16765 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
16766 ExtType, false)) {
16767 SDValue ExtLoad =
16768 DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), LN0->getBasePtr(),
16769 MemVT, LN0->getMemOperand());
16770 CombineTo(N, ExtLoad);
16771 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16772 recursivelyDeleteUnusedNodes(LN0);
16773 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16774 }
16775 }
16776
16777 if (N0.getOpcode() == ISD::SETCC) {
16778 // Propagate fast-math-flags.
16779 SDNodeFlags Flags = N0->getFlags();
16780 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
16781
16782 // For vectors:
16783 // aext(setcc) -> vsetcc
16784 // aext(setcc) -> truncate(vsetcc)
16785 // aext(setcc) -> aext(vsetcc)
16786 // Only do this before legalize for now.
16787 if (VT.isVector() && !LegalOperations) {
16788 EVT N00VT = N0.getOperand(0).getValueType();
16789 if (getSetCCResultType(N00VT) == N0.getValueType())
16790 return SDValue();
16791
16792 // We know that the # elements of the results is the same as the
16793 // # elements of the compare (and the # elements of the compare result
16794 // for that matter). Check to see that they are the same size. If so,
16795 // we know that the element size of the sext'd result matches the
16796 // element size of the compare operands.
16797 if (VT.getSizeInBits() == N00VT.getSizeInBits())
16798 return DAG.getSetCC(DL, VT, N0.getOperand(0), N0.getOperand(1),
16799 cast<CondCodeSDNode>(N0.getOperand(2))->get(),
16800 /*Chain=*/{}, /*Signaling=*/false, Flags);
16801
16802 // If the desired elements are smaller or larger than the source
16803 // elements we can use a matching integer vector type and then
16804 // truncate/any extend
16805 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16806 SDValue VsetCC = DAG.getSetCC(
16807 DL, MatchingVectorType, N0.getOperand(0), N0.getOperand(1),
16808 cast<CondCodeSDNode>(N0.getOperand(2))->get(), /*Chain=*/{},
16809 /*Signaling=*/false, Flags);
16810 return DAG.getAnyExtOrTrunc(VsetCC, DL, VT);
16811 }
16812
16813 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
16814 if (SDValue SCC = SimplifySelectCC(
16815 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
16816 DAG.getConstant(0, DL, VT),
16817 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16818 return SCC;
16819 }
16820
16821 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16822 return NewCtPop;
16823
16824 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16825 return Res;
16826
16827 return SDValue();
16828}
16829
16830SDValue DAGCombiner::visitAssertExt(SDNode *N) {
16831 unsigned Opcode = N->getOpcode();
16832 SDValue N0 = N->getOperand(0);
16833 SDValue N1 = N->getOperand(1);
16834 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
16835
16836 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
16837 if (N0.getOpcode() == Opcode &&
16838 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
16839 return N0;
16840
16841 // fold (assert?ext c, vt) -> c
16842 if (isa<ConstantSDNode>(N0))
16843 return N0;
16844
16845 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16846 N0.getOperand(0).getOpcode() == Opcode) {
16847 // We have an assert, truncate, assert sandwich. Make one stronger assert
16848 // by asserting on the smallest asserted type to the larger source type.
16849 // This eliminates the later assert:
16850 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
16851 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
16852 SDLoc DL(N);
16853 SDValue BigA = N0.getOperand(0);
16854 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16855 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
16856 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
16857 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16858 BigA.getOperand(0), MinAssertVTVal);
16859 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16860 }
16861
16862 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
16863 // than X. Just move the AssertZext in front of the truncate and drop the
16864 // AssertSExt.
16865 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16867 Opcode == ISD::AssertZext) {
16868 SDValue BigA = N0.getOperand(0);
16869 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16870 if (AssertVT.bitsLT(BigA_AssertVT)) {
16871 SDLoc DL(N);
16872 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16873 BigA.getOperand(0), N1);
16874 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16875 }
16876 }
16877
16878 if (Opcode == ISD::AssertZext && N0.getOpcode() == ISD::AND &&
16880 const APInt &Mask = N0.getConstantOperandAPInt(1);
16881
16882 // If we have (AssertZext (and (AssertSext X, iX), M), iY) and Y is smaller
16883 // than X, and the And doesn't change the lower iX bits, we can move the
16884 // AssertZext in front of the And and drop the AssertSext.
16885 if (N0.getOperand(0).getOpcode() == ISD::AssertSext && N0.hasOneUse()) {
16886 SDValue BigA = N0.getOperand(0);
16887 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16888 if (AssertVT.bitsLT(BigA_AssertVT) &&
16889 Mask.countr_one() >= BigA_AssertVT.getScalarSizeInBits()) {
16890 SDLoc DL(N);
16891 SDValue NewAssert =
16892 DAG.getNode(Opcode, DL, N->getValueType(0), BigA.getOperand(0), N1);
16893 return DAG.getNode(ISD::AND, DL, N->getValueType(0), NewAssert,
16894 N0.getOperand(1));
16895 }
16896 }
16897
16898 // Remove AssertZext entirely if the mask guarantees the assertion cannot
16899 // fail.
16900 // TODO: Use KB countMinLeadingZeros to handle non-constant masks?
16901 if (Mask.isIntN(AssertVT.getScalarSizeInBits()))
16902 return N0;
16903 }
16904
16905 return SDValue();
16906}
16907
16908SDValue DAGCombiner::visitAssertAlign(SDNode *N) {
16909 SDLoc DL(N);
16910
16911 Align AL = cast<AssertAlignSDNode>(N)->getAlign();
16912 SDValue N0 = N->getOperand(0);
16913
16914 // Fold (assertalign (assertalign x, AL0), AL1) ->
16915 // (assertalign x, max(AL0, AL1))
16916 if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0))
16917 return DAG.getAssertAlign(DL, N0.getOperand(0),
16918 std::max(AL, AAN->getAlign()));
16919
16920 // In rare cases, there are trivial arithmetic ops in source operands. Sink
16921 // this assert down to source operands so that those arithmetic ops could be
16922 // exposed to the DAG combining.
16923 switch (N0.getOpcode()) {
16924 default:
16925 break;
16926 case ISD::ADD:
16927 case ISD::PTRADD:
16928 case ISD::SUB: {
16929 unsigned AlignShift = Log2(AL);
16930 SDValue LHS = N0.getOperand(0);
16931 SDValue RHS = N0.getOperand(1);
16932 unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros();
16933 unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros();
16934 if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) {
16935 if (LHSAlignShift < AlignShift)
16936 LHS = DAG.getAssertAlign(DL, LHS, AL);
16937 if (RHSAlignShift < AlignShift)
16938 RHS = DAG.getAssertAlign(DL, RHS, AL);
16939 return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS);
16940 }
16941 break;
16942 }
16943 }
16944
16945 return SDValue();
16946}
16947
16948SDValue DAGCombiner::visitIS_FPCLASS(SDNode *N) {
16949 SDValue Src = N->getOperand(0);
16950 FPClassTest Mask = static_cast<FPClassTest>(N->getConstantOperandVal(1));
16951 EVT VT = N->getValueType(0);
16952 SDLoc DL(N);
16953
16954 // is.fpclass(poison, mask) -> poison
16955 if (Src.getOpcode() == ISD::POISON)
16956 return DAG.getPOISON(VT);
16957
16958 KnownFPClass Known = DAG.computeKnownFPClass(Src, Mask);
16959
16960 // All possible classes are within the mask: result is always true.
16961 if ((~Mask & Known.KnownFPClasses) == fcNone)
16962 return DAG.getBoolConstant(true, DL, VT, Src.getValueType());
16963
16964 // Clear test bits we know must be false from the source value.
16965 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
16966 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
16967 if ((Mask & Known.KnownFPClasses) != Mask) {
16968 return DAG.getNode(
16969 ISD::IS_FPCLASS, DL, VT, Src,
16970 DAG.getTargetConstant(Mask & Known.KnownFPClasses, DL, MVT::i32),
16971 N->getFlags());
16972 }
16973
16974 return SDValue();
16975}
16976
16977/// If the result of a load is shifted/masked/truncated to an effectively
16978/// narrower type, try to transform the load to a narrower type and/or
16979/// use an extending load.
16980SDValue DAGCombiner::reduceLoadWidth(SDNode *N) {
16981 unsigned Opc = N->getOpcode();
16982
16984 SDValue N0 = N->getOperand(0);
16985 EVT VT = N->getValueType(0);
16986 EVT ExtVT = VT;
16987
16988 // This transformation isn't valid for vector loads.
16989 if (VT.isVector())
16990 return SDValue();
16991
16992 // The ShAmt variable is used to indicate that we've consumed a right
16993 // shift. I.e. we want to narrow the width of the load by skipping to load the
16994 // ShAmt least significant bits.
16995 unsigned ShAmt = 0;
16996 // A special case is when the least significant bits from the load are masked
16997 // away, but using an AND rather than a right shift. HasShiftedOffset is used
16998 // to indicate that the narrowed load should be left-shifted ShAmt bits to get
16999 // the result.
17000 unsigned ShiftedOffset = 0;
17001 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
17002 // extended to VT.
17003 if (Opc == ISD::SIGN_EXTEND_INREG) {
17004 ExtType = ISD::SEXTLOAD;
17005 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
17006 } else if (Opc == ISD::SRL || Opc == ISD::SRA) {
17007 // Another special-case: SRL/SRA is basically zero/sign-extending a narrower
17008 // value, or it may be shifting a higher subword, half or byte into the
17009 // lowest bits.
17010
17011 // Only handle shift with constant shift amount, and the shiftee must be a
17012 // load.
17013 auto *LN = dyn_cast<LoadSDNode>(N0);
17014 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17015 if (!N1C || !LN)
17016 return SDValue();
17017 // If the shift amount is larger than the memory type then we're not
17018 // accessing any of the loaded bytes.
17019 ShAmt = N1C->getZExtValue();
17020 uint64_t MemoryWidth = LN->getMemoryVT().getScalarSizeInBits();
17021 if (MemoryWidth <= ShAmt)
17022 return SDValue();
17023 // Attempt to fold away the SRL by using ZEXTLOAD and SRA by using SEXTLOAD.
17024 ExtType = Opc == ISD::SRL ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
17025 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
17026 // If original load is a SEXTLOAD then we can't simply replace it by a
17027 // ZEXTLOAD (we could potentially replace it by a more narrow SEXTLOAD
17028 // followed by a ZEXT, but that is not handled at the moment). Similarly if
17029 // the original load is a ZEXTLOAD and we want to use a SEXTLOAD.
17030 if ((LN->getExtensionType() == ISD::SEXTLOAD ||
17031 LN->getExtensionType() == ISD::ZEXTLOAD) &&
17032 LN->getExtensionType() != ExtType)
17033 return SDValue();
17034 } else if (Opc == ISD::AND) {
17035 // An AND with a constant mask is the same as a truncate + zero-extend.
17036 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
17037 if (!AndC)
17038 return SDValue();
17039
17040 const APInt &Mask = AndC->getAPIntValue();
17041 unsigned ActiveBits = 0;
17042 if (Mask.isMask()) {
17043 ActiveBits = Mask.countr_one();
17044 } else if (Mask.isShiftedMask(ShAmt, ActiveBits)) {
17045 ShiftedOffset = ShAmt;
17046 } else {
17047 return SDValue();
17048 }
17049
17050 ExtType = ISD::ZEXTLOAD;
17051 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
17052 }
17053
17054 // In case Opc==SRL we've already prepared ExtVT/ExtType/ShAmt based on doing
17055 // a right shift. Here we redo some of those checks, to possibly adjust the
17056 // ExtVT even further based on "a masking AND". We could also end up here for
17057 // other reasons (e.g. based on Opc==TRUNCATE) and that is why some checks
17058 // need to be done here as well.
17059 if (Opc == ISD::SRL || N0.getOpcode() == ISD::SRL) {
17060 SDValue SRL = Opc == ISD::SRL ? SDValue(N, 0) : N0;
17061 // Bail out when the SRL has more than one use. This is done for historical
17062 // (undocumented) reasons. Maybe intent was to guard the AND-masking below
17063 // check below? And maybe it could be non-profitable to do the transform in
17064 // case the SRL has multiple uses and we get here with Opc!=ISD::SRL?
17065 // FIXME: Can't we just skip this check for the Opc==ISD::SRL case.
17066 if (!SRL.hasOneUse())
17067 return SDValue();
17068
17069 // Only handle shift with constant shift amount, and the shiftee must be a
17070 // load.
17071 auto *LN = dyn_cast<LoadSDNode>(SRL.getOperand(0));
17072 auto *SRL1C = dyn_cast<ConstantSDNode>(SRL.getOperand(1));
17073 if (!SRL1C || !LN)
17074 return SDValue();
17075
17076 // If the shift amount is larger than the input type then we're not
17077 // accessing any of the loaded bytes. If the load was a zextload/extload
17078 // then the result of the shift+trunc is zero/undef (handled elsewhere).
17079 ShAmt = SRL1C->getZExtValue();
17080 uint64_t MemoryWidth = LN->getMemoryVT().getSizeInBits();
17081 if (ShAmt >= MemoryWidth)
17082 return SDValue();
17083
17084 // Because a SRL must be assumed to *need* to zero-extend the high bits
17085 // (as opposed to anyext the high bits), we can't combine the zextload
17086 // lowering of SRL and an sextload.
17087 if (LN->getExtensionType() == ISD::SEXTLOAD)
17088 return SDValue();
17089
17090 // Avoid reading outside the memory accessed by the original load (could
17091 // happened if we only adjust the load base pointer by ShAmt). Instead we
17092 // try to narrow the load even further. The typical scenario here is:
17093 // (i64 (truncate (i96 (srl (load x), 64)))) ->
17094 // (i64 (truncate (i96 (zextload (load i32 + offset) from i32))))
17095 if (ExtVT.getScalarSizeInBits() > MemoryWidth - ShAmt) {
17096 // Don't replace sextload by zextload.
17097 if (ExtType == ISD::SEXTLOAD)
17098 return SDValue();
17099 // Narrow the load.
17100 ExtType = ISD::ZEXTLOAD;
17101 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
17102 }
17103
17104 // If the SRL is only used by a masking AND, we may be able to adjust
17105 // the ExtVT to make the AND redundant.
17106 SDNode *Mask = *(SRL->user_begin());
17107 if (SRL.hasOneUse() && Mask->getOpcode() == ISD::AND &&
17108 isa<ConstantSDNode>(Mask->getOperand(1))) {
17109 unsigned Offset, ActiveBits;
17110 const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
17111 if (ShiftMask.isMask()) {
17112 EVT MaskedVT =
17113 EVT::getIntegerVT(*DAG.getContext(), ShiftMask.countr_one());
17114 // If the mask is smaller, recompute the type.
17115 if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) &&
17116 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
17117 LN->getAddressSpace(), ExtType, false))
17118 ExtVT = MaskedVT;
17119 } else if (ExtType == ISD::ZEXTLOAD &&
17120 ShiftMask.isShiftedMask(Offset, ActiveBits) &&
17121 (Offset + ShAmt) < VT.getScalarSizeInBits()) {
17122 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
17123 // If the mask is shifted we can use a narrower load and a shl to insert
17124 // the trailing zeros.
17125 if (((Offset + ActiveBits) <= ExtVT.getScalarSizeInBits()) &&
17126 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
17127 LN->getAddressSpace(), ExtType, false)) {
17128 ExtVT = MaskedVT;
17129 ShAmt = Offset + ShAmt;
17130 ShiftedOffset = Offset;
17131 }
17132 }
17133 }
17134
17135 N0 = SRL.getOperand(0);
17136 }
17137
17138 // If the load is shifted left (and the result isn't shifted back right), we
17139 // can fold a truncate through the shift. The typical scenario is that N
17140 // points at a TRUNCATE here so the attempted fold is:
17141 // (truncate (shl (load x), c))) -> (shl (narrow load x), c)
17142 // ShLeftAmt will indicate how much a narrowed load should be shifted left.
17143 unsigned ShLeftAmt = 0;
17144 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
17145 ExtVT == VT && TLI.isNarrowingProfitable(N, N0.getValueType(), VT)) {
17146 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
17147 ShLeftAmt = N01->getZExtValue();
17148 N0 = N0.getOperand(0);
17149 }
17150 }
17151
17152 // Look through a freeze if present between the operation and the load.
17153 // The freeze will be preserved on the narrowed result.
17154 SDValue FreezeNode;
17155 if (N0.getOpcode() == ISD::FREEZE) {
17156 FreezeNode = N0;
17157 N0 = N0.getOperand(0);
17158 }
17159
17160 // If we haven't found a load, we can't narrow it.
17161 if (!isa<LoadSDNode>(N0))
17162 return SDValue();
17163
17164 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
17165 // Reducing the width of a volatile load is illegal. For atomics, we may be
17166 // able to reduce the width provided we never widen again. (see D66309)
17167 if (!LN0->isSimple() ||
17168 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
17169 return SDValue();
17170
17171 // Bail early when looking through a multi-use freeze, since other users of
17172 // the freeze can depend on the full load value. But its still safe to change
17173 // the extension type from anyext to zext.
17174 if (FreezeNode && !FreezeNode.hasOneUse() &&
17175 (LN0->getMemoryVT().bitsGT(ExtVT) || ExtType != ISD::ZEXTLOAD ||
17176 (LN0->getExtensionType() != ISD::EXTLOAD &&
17177 LN0->getExtensionType() != ISD::ZEXTLOAD)))
17178 return SDValue();
17179
17180 auto AdjustBigEndianShift = [&](unsigned ShAmt) {
17181 unsigned LVTStoreBits =
17183 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedValue();
17184 return LVTStoreBits - EVTStoreBits - ShAmt;
17185 };
17186
17187 // We need to adjust the pointer to the load by ShAmt bits in order to load
17188 // the correct bytes.
17189 unsigned PtrAdjustmentInBits =
17190 DAG.getDataLayout().isBigEndian() ? AdjustBigEndianShift(ShAmt) : ShAmt;
17191
17192 uint64_t PtrOff = PtrAdjustmentInBits / 8;
17193 SDLoc DL(LN0);
17194 // The original load itself didn't wrap, so an offset within it doesn't.
17195 SDValue NewPtr =
17198 AddToWorklist(NewPtr.getNode());
17199
17200 SDValue Load;
17201 if (ExtType == ISD::NON_EXTLOAD) {
17202 const MDNode *OldRanges = LN0->getRanges();
17203 const MDNode *NewRanges = nullptr;
17204 // If LSBs are loaded and the truncated ConstantRange for the OldRanges
17205 // metadata is not the full-set for the new width then create a NewRanges
17206 // metadata for the truncated load
17207 if (ShAmt == 0 && OldRanges) {
17208 ConstantRange CR = getConstantRangeFromMetadata(*OldRanges);
17209 unsigned BitSize = VT.getScalarSizeInBits();
17210
17211 // It is possible for an 8-bit extending load with 8-bit range
17212 // metadata to be narrowed to an 8-bit load. This guard is necessary to
17213 // ensure that truncation is strictly smaller.
17214 if (CR.getBitWidth() > BitSize) {
17215 ConstantRange TruncatedCR = CR.truncate(BitSize);
17216 if (!TruncatedCR.isFullSet()) {
17217 Metadata *Bounds[2] = {
17219 ConstantInt::get(*DAG.getContext(), TruncatedCR.getLower())),
17221 ConstantInt::get(*DAG.getContext(), TruncatedCR.getUpper()))};
17222 NewRanges = MDNode::get(*DAG.getContext(), Bounds);
17223 }
17224 } else if (CR.getBitWidth() == BitSize)
17225 NewRanges = OldRanges;
17226 }
17227 Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
17228 LN0->getPointerInfo().getWithOffset(PtrOff),
17229 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
17230 MMOMetadata(LN0->getAAInfo(), NewRanges));
17231 } else
17232 Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
17233 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
17234 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
17235 LN0->getAAInfo());
17236
17237 // Replace the old load's chain with the new load's chain.
17238 WorklistRemover DeadNodes(*this);
17240
17241 // Replace old load value for multi-use freeze so all users benefit.
17242 if (FreezeNode && !FreezeNode.hasOneUse())
17244
17245 // If we looked through a freeze, rewrap the narrowed result and add an
17246 // Assert node so downstream analyses can see the range.
17248 if (FreezeNode) {
17249 Result = DAG.getNode(ISD::FREEZE, DL, VT, Result);
17250 if (ExtType == ISD::ZEXTLOAD)
17251 Result =
17252 DAG.getNode(ISD::AssertZext, DL, VT, Result, DAG.getValueType(ExtVT));
17253 else if (ExtType == ISD::SEXTLOAD)
17254 Result =
17255 DAG.getNode(ISD::AssertSext, DL, VT, Result, DAG.getValueType(ExtVT));
17256 }
17257
17258 // Shift the result left, if we've swallowed a left shift.
17259 if (ShLeftAmt != 0) {
17260 // If the shift amount is as large as the result size (but, presumably,
17261 // no larger than the source) then the useful bits of the result are
17262 // zero; we can't simply return the shortened shift, because the result
17263 // of that operation is undefined.
17264 if (ShLeftAmt >= VT.getScalarSizeInBits())
17265 Result = DAG.getConstant(0, DL, VT);
17266 else
17267 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
17268 DAG.getShiftAmountConstant(ShLeftAmt, VT, DL));
17269 }
17270
17271 if (ShiftedOffset != 0) {
17272 // We're using a shifted mask, so the load now has an offset. This means
17273 // that data has been loaded into the lower bytes than it would have been
17274 // before, so we need to shl the loaded data into the correct position in the
17275 // register.
17276 SDValue ShiftC = DAG.getConstant(ShiftedOffset, DL, VT);
17277 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
17278 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
17279 }
17280
17281 // Return the new loaded value.
17282 return Result;
17283}
17284
17285SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
17286 SDValue N0 = N->getOperand(0);
17287 SDValue N1 = N->getOperand(1);
17288 EVT VT = N->getValueType(0);
17289 EVT ExtVT = cast<VTSDNode>(N1)->getVT();
17290 unsigned VTBits = VT.getScalarSizeInBits();
17291 unsigned ExtVTBits = ExtVT.getScalarSizeInBits();
17292 SDLoc DL(N);
17293
17294 // sext_vector_inreg(undef) = 0 because the top bit will all be the same.
17295 if (N0.isUndef())
17296 return DAG.getConstant(0, DL, VT);
17297
17298 // fold (sext_in_reg c1) -> c1
17299 if (SDValue C =
17301 return C;
17302
17303 // If the input is already sign extended, just drop the extension.
17304 if (ExtVTBits >= DAG.ComputeMaxSignificantBits(N0))
17305 return N0;
17306
17307 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
17308 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
17309 ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
17310 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N0.getOperand(0), N1);
17311
17312 // fold (sext_in_reg (sext x)) -> (sext x)
17313 // fold (sext_in_reg (aext x)) -> (sext x)
17314 // if x is small enough or if we know that x has more than 1 sign bit and the
17315 // sign_extend_inreg is extending from one of them.
17316 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
17317 SDValue N00 = N0.getOperand(0);
17318 unsigned N00Bits = N00.getScalarValueSizeInBits();
17319 if ((N00Bits <= ExtVTBits ||
17320 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits) &&
17321 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
17322 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
17323 }
17324
17325 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
17326 // if x is small enough or if we know that x has more than 1 sign bit and the
17327 // sign_extend_inreg is extending from one of them.
17329 SDValue N00 = N0.getOperand(0);
17330 unsigned N00Bits = N00.getScalarValueSizeInBits();
17331 bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
17332 if ((N00Bits == ExtVTBits ||
17333 (!IsZext && (N00Bits < ExtVTBits ||
17334 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits))) &&
17335 (!LegalOperations ||
17337 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, N00);
17338 }
17339
17340 // fold (sext_in_reg (zext x)) -> (sext x)
17341 // iff we are extending the source sign bit.
17342 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
17343 SDValue N00 = N0.getOperand(0);
17344 if (N00.getScalarValueSizeInBits() == ExtVTBits &&
17345 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
17346 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
17347 }
17348
17349 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
17350 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1)))
17351 return DAG.getZeroExtendInReg(N0, DL, ExtVT);
17352
17353 // fold operands of sext_in_reg based on knowledge that the top bits are not
17354 // demanded.
17356 return SDValue(N, 0);
17357
17358 // fold (sext_in_reg (load x)) -> (smaller sextload x)
17359 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
17360 if (SDValue NarrowLoad = reduceLoadWidth(N))
17361 return NarrowLoad;
17362
17363 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
17364 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
17365 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
17366 if (N0.getOpcode() == ISD::SRL) {
17367 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
17368 if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) {
17369 // We can turn this into an SRA iff the input to the SRL is already sign
17370 // extended enough.
17371 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
17372 if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits)
17373 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
17374 N0.getOperand(1));
17375 }
17376 }
17377
17378 // fold (sext_inreg (extload x)) -> (sextload x)
17379 // If sextload is not supported by target, we can only do the combine when
17380 // load has one use. Doing otherwise can block folding the extload with other
17381 // extends that the target does support.
17383 auto *LN0 = cast<LoadSDNode>(N0);
17384 if (ExtVT == LN0->getMemoryVT() &&
17385 ((!LegalOperations && LN0->isSimple() && N0.hasOneUse()) ||
17386 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
17387 ISD::SEXTLOAD, false))) {
17388 SDValue ExtLoad =
17389 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
17390 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
17391 CombineTo(N, ExtLoad);
17392 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17393 AddToWorklist(ExtLoad.getNode());
17394 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17395 }
17396 }
17397
17398 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
17400 auto *LN0 = cast<LoadSDNode>(N0);
17401
17402 if (N0.hasOneUse() && ExtVT == LN0->getMemoryVT() &&
17403 ((!LegalOperations && LN0->isSimple()) &&
17404 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
17405 ISD::SEXTLOAD, false))) {
17406 SDValue ExtLoad =
17407 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
17408 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
17409 CombineTo(N, ExtLoad);
17410 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17411 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17412 }
17413 }
17414
17415 // fold (sext_inreg (masked_load x)) -> (sext_masked_load x)
17416 // ignore it if the masked load is already sign extended
17417 bool Frozen = N0.getOpcode() == ISD::FREEZE && N0.hasOneUse();
17418 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0)) {
17419 if (ExtVT == Ld->getMemoryVT() && Ld->hasNUsesOfValue(1, 0) &&
17420 Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD &&
17421 TLI.isLoadLegal(VT, ExtVT, Ld->getAlign(), Ld->getAddressSpace(),
17422 ISD::SEXTLOAD, false)) {
17423 SDValue ExtMaskedLoad = DAG.getMaskedLoad(
17424 VT, DL, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(),
17425 Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(),
17426 Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad());
17427 CombineTo(N, Frozen ? N0 : ExtMaskedLoad);
17428 CombineTo(Ld, ExtMaskedLoad, ExtMaskedLoad.getValue(1));
17429 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17430 }
17431 }
17432
17433 // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x)
17434 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
17435 if (SDValue(GN0, 0).hasOneUse() && ExtVT == GN0->getMemoryVT() &&
17437 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
17438 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
17439
17440 SDValue ExtLoad = DAG.getMaskedGather(
17441 DAG.getVTList(VT, MVT::Other), ExtVT, DL, Ops, GN0->getMemOperand(),
17442 GN0->getIndexType(), ISD::SEXTLOAD);
17443
17444 CombineTo(N, ExtLoad);
17445 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17446 AddToWorklist(ExtLoad.getNode());
17447 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17448 }
17449 }
17450
17451 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
17452 if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) {
17453 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
17454 N0.getOperand(1), false))
17455 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, BSwap, N1);
17456 }
17457
17458 // Fold (iM_signext_inreg
17459 // (extract_subvector (zext|anyext|sext iN_v to _) _)
17460 // from iN)
17461 // -> (extract_subvector (signext iN_v to iM))
17462 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() &&
17464 SDValue InnerExt = N0.getOperand(0);
17465 EVT InnerExtVT = InnerExt->getValueType(0);
17466 SDValue Extendee = InnerExt->getOperand(0);
17467
17468 if (ExtVTBits == Extendee.getValueType().getScalarSizeInBits() &&
17469 (!LegalOperations ||
17470 TLI.isOperationLegal(ISD::SIGN_EXTEND, InnerExtVT))) {
17471 SDValue SignExtExtendee =
17472 DAG.getNode(ISD::SIGN_EXTEND, DL, InnerExtVT, Extendee);
17473 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SignExtExtendee,
17474 N0.getOperand(1));
17475 }
17476 }
17477
17478 return SDValue();
17479}
17480
17482 SDNode *N, const SDLoc &DL, const TargetLowering &TLI, SelectionDAG &DAG,
17483 bool LegalOperations) {
17484 unsigned InregOpcode = N->getOpcode();
17485 unsigned Opcode = DAG.getOpcode_EXTEND(InregOpcode);
17486
17487 SDValue Src = N->getOperand(0);
17488 EVT VT = N->getValueType(0);
17489 EVT SrcVT = VT.changeVectorElementType(
17490 *DAG.getContext(), Src.getValueType().getVectorElementType());
17491
17492 assert(ISD::isExtVecInRegOpcode(InregOpcode) &&
17493 "Expected EXTEND_VECTOR_INREG dag node in input!");
17494
17495 // Profitability check: our operand must be an one-use CONCAT_VECTORS.
17496 // FIXME: one-use check may be overly restrictive
17497 if (!Src.hasOneUse() || Src.getOpcode() != ISD::CONCAT_VECTORS)
17498 return SDValue();
17499
17500 // Profitability check: we must be extending exactly one of it's operands.
17501 // FIXME: this is probably overly restrictive.
17502 Src = Src.getOperand(0);
17503 if (Src.getValueType() != SrcVT)
17504 return SDValue();
17505
17506 if (LegalOperations && !TLI.isOperationLegal(Opcode, VT))
17507 return SDValue();
17508
17509 return DAG.getNode(Opcode, DL, VT, Src);
17510}
17511
17512SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) {
17513 SDValue N0 = N->getOperand(0);
17514 EVT VT = N->getValueType(0);
17515 SDLoc DL(N);
17516
17517 if (N0.isUndef()) {
17518 // aext_vector_inreg(undef) = undef because the top bits are undefined.
17519 // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same.
17520 return N->getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
17521 ? DAG.getUNDEF(VT)
17522 : DAG.getConstant(0, DL, VT);
17523 }
17524
17525 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
17526 return Res;
17527
17529 return SDValue(N, 0);
17530
17532 LegalOperations))
17533 return R;
17534
17535 return SDValue();
17536}
17537
17538SDValue DAGCombiner::visitTRUNCATE_USAT_U(SDNode *N) {
17539 EVT VT = N->getValueType(0);
17540 SDValue N0 = N->getOperand(0);
17541
17542 SDValue FPVal;
17543 if (sd_match(N0, m_FPToUI(m_Value(FPVal))) &&
17545 ISD::FP_TO_UINT_SAT, FPVal.getValueType(), VT))
17546 return DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), VT, FPVal,
17547 DAG.getValueType(VT.getScalarType()));
17548
17549 return SDValue();
17550}
17551
17552/// Detect patterns of truncation with unsigned saturation:
17553///
17554/// (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
17555/// Return the source value x to be truncated or SDValue() if the pattern was
17556/// not matched.
17557///
17559 unsigned NumDstBits = VT.getScalarSizeInBits();
17560 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17561 // Saturation with truncation. We truncate from InVT to VT.
17562 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17563
17564 SDValue Min;
17565 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17566 if (sd_match(In, m_UMin(m_Value(Min), m_SpecificInt(UnsignedMax))))
17567 return Min;
17568
17569 return SDValue();
17570}
17571
17572/// Detect patterns of truncation with signed saturation:
17573/// (truncate (smin (smax (x, signed_min_of_dest_type),
17574/// signed_max_of_dest_type)) to dest_type)
17575/// or:
17576/// (truncate (smax (smin (x, signed_max_of_dest_type),
17577/// signed_min_of_dest_type)) to dest_type).
17578///
17579/// Return the source value to be truncated or SDValue() if the pattern was not
17580/// matched.
17582 unsigned NumDstBits = VT.getScalarSizeInBits();
17583 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17584 // Saturation with truncation. We truncate from InVT to VT.
17585 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17586
17587 SDValue Val;
17588 APInt SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
17589 APInt SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
17590
17591 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_SpecificInt(SignedMin)),
17592 m_SpecificInt(SignedMax))))
17593 return Val;
17594
17595 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(SignedMax)),
17596 m_SpecificInt(SignedMin))))
17597 return Val;
17598
17599 return SDValue();
17600}
17601
17602/// Detect patterns of truncation with unsigned saturation:
17604 const SDLoc &DL) {
17605 unsigned NumDstBits = VT.getScalarSizeInBits();
17606 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17607 // Saturation with truncation. We truncate from InVT to VT.
17608 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17609
17610 SDValue Val;
17611 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17612 // Min == 0, Max is unsigned max of destination type.
17613 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(UnsignedMax)),
17614 m_Zero())))
17615 return Val;
17616
17617 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_Zero()),
17618 m_SpecificInt(UnsignedMax))))
17619 return Val;
17620
17621 if (sd_match(In, m_UMin(m_SMax(m_Value(Val), m_Zero()),
17622 m_SpecificInt(UnsignedMax))))
17623 return Val;
17624
17625 return SDValue();
17626}
17627
17628static SDValue foldToSaturated(SDNode *N, EVT &VT, SDValue &Src, EVT &SrcVT,
17629 SDLoc &DL, const TargetLowering &TLI,
17630 SelectionDAG &DAG) {
17631 auto AllowedTruncateSat = [&](unsigned Opc, EVT SrcVT, EVT VT) -> bool {
17632 return (TLI.isOperationLegalOrCustom(Opc, SrcVT) &&
17633 TLI.isTypeDesirableForOp(Opc, VT));
17634 };
17635
17636 if (Src.getOpcode() == ISD::SMIN || Src.getOpcode() == ISD::SMAX) {
17637 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_S, SrcVT, VT))
17638 if (SDValue SSatVal = detectSSatSPattern(Src, VT))
17639 return DAG.getNode(ISD::TRUNCATE_SSAT_S, DL, VT, SSatVal);
17640 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17641 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17642 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17643 } else if (Src.getOpcode() == ISD::UMIN) {
17644 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17645 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17646 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17647 if (AllowedTruncateSat(ISD::TRUNCATE_USAT_U, SrcVT, VT))
17648 if (SDValue USatVal = detectUSatUPattern(Src, VT))
17649 return DAG.getNode(ISD::TRUNCATE_USAT_U, DL, VT, USatVal);
17650 }
17651
17652 return SDValue();
17653}
17654
17655SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
17656 SDValue N0 = N->getOperand(0);
17657 EVT VT = N->getValueType(0);
17658 EVT SrcVT = N0.getValueType();
17659 bool isLE = DAG.getDataLayout().isLittleEndian();
17660 SDLoc DL(N);
17661
17662 // trunc(undef) = undef
17663 if (N0.isUndef())
17664 return DAG.getUNDEF(VT);
17665
17666 // fold (truncate (truncate x)) -> (truncate x)
17667 if (N0.getOpcode() == ISD::TRUNCATE)
17668 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17669
17670 // fold saturated truncate
17671 if (SDValue SaturatedTR = foldToSaturated(N, VT, N0, SrcVT, DL, TLI, DAG))
17672 return SaturatedTR;
17673
17674 // fold (truncate c1) -> c1
17675 if (SDValue C = DAG.FoldConstantArithmetic(ISD::TRUNCATE, DL, VT, {N0}))
17676 return C;
17677
17678 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
17679 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
17680 N0.getOpcode() == ISD::SIGN_EXTEND ||
17681 N0.getOpcode() == ISD::ANY_EXTEND) {
17682 // if the source is smaller than the dest, we still need an extend.
17683 if (N0.getOperand(0).getValueType().bitsLT(VT)) {
17684 SDNodeFlags Flags;
17685 if (N0.getOpcode() == ISD::ZERO_EXTEND)
17686 Flags.setNonNeg(N0->getFlags().hasNonNeg());
17687 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
17688 }
17689 // if the source is larger than the dest, than we just need the truncate.
17690 if (N0.getOperand(0).getValueType().bitsGT(VT))
17691 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17692 // if the source and dest are the same type, we can drop both the extend
17693 // and the truncate.
17694 return N0.getOperand(0);
17695 }
17696
17697 // Try to narrow a truncate-of-sext_in_reg to the destination type:
17698 // trunc (sign_ext_inreg X, iM) to iN --> sign_ext_inreg (trunc X to iN), iM
17699 if (!LegalTypes && N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
17700 N0.hasOneUse()) {
17701 SDValue X = N0.getOperand(0);
17702 SDValue ExtVal = N0.getOperand(1);
17703 EVT ExtVT = cast<VTSDNode>(ExtVal)->getVT();
17704 if (ExtVT.bitsLT(VT) && TLI.preferSextInRegOfTruncate(VT, SrcVT, ExtVT)) {
17705 SDValue TrX = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
17706 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, TrX, ExtVal);
17707 }
17708 }
17709
17710 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
17711 if (N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::ANY_EXTEND))
17712 return SDValue();
17713
17714 // Fold extract-and-trunc into a narrow extract. For example:
17715 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
17716 // i32 y = TRUNCATE(i64 x)
17717 // -- becomes --
17718 // v16i8 b = BITCAST (v2i64 val)
17719 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
17720 //
17721 // Note: We only run this optimization after type legalization (which often
17722 // creates this pattern) and before operation legalization after which
17723 // we need to be more careful about the vector instructions that we generate.
17724 if (LegalTypes && !LegalOperations && VT.isScalarInteger() && VT != MVT::i1 &&
17725 N0->hasOneUse()) {
17726 EVT TrTy = N->getValueType(0);
17727 SDValue Src = N0;
17728
17729 // Check for cases where we shift down an upper element before truncation.
17730 int EltOffset = 0;
17731 if (Src.getOpcode() == ISD::SRL && Src.getOperand(0)->hasOneUse()) {
17732 if (auto ShAmt = DAG.getValidShiftAmount(Src)) {
17733 if ((*ShAmt % TrTy.getSizeInBits()) == 0) {
17734 Src = Src.getOperand(0);
17735 EltOffset = *ShAmt / TrTy.getSizeInBits();
17736 }
17737 }
17738 }
17739
17740 if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17741 EVT VecTy = Src.getOperand(0).getValueType();
17742 EVT ExTy = Src.getValueType();
17743
17744 auto EltCnt = VecTy.getVectorElementCount();
17745 unsigned SizeRatio = ExTy.getSizeInBits() / TrTy.getSizeInBits();
17746 auto NewEltCnt = EltCnt * SizeRatio;
17747
17748 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt);
17749 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
17750
17751 SDValue EltNo = Src->getOperand(1);
17752 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
17753 int Elt = EltNo->getAsZExtVal();
17754 int Index = isLE ? (Elt * SizeRatio + EltOffset)
17755 : (Elt * SizeRatio + (SizeRatio - 1) - EltOffset);
17756 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
17757 DAG.getBitcast(NVT, Src.getOperand(0)),
17758 DAG.getVectorIdxConstant(Index, DL));
17759 }
17760 }
17761 }
17762
17763 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
17764 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse() &&
17765 TLI.isTruncateFree(SrcVT, VT)) {
17766 if (!LegalOperations ||
17767 (TLI.isOperationLegal(ISD::SELECT, SrcVT) &&
17768 TLI.isNarrowingProfitable(N0.getNode(), SrcVT, VT))) {
17769 SDLoc SL(N0);
17770 SDValue Cond = N0.getOperand(0);
17771 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
17772 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
17773 return DAG.getNode(ISD::SELECT, DL, VT, Cond, TruncOp0, TruncOp1);
17774 }
17775 }
17776
17777 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
17778 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
17779 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
17780 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
17781 SDValue Amt = N0.getOperand(1);
17782 KnownBits Known = DAG.computeKnownBits(Amt);
17783 unsigned Size = VT.getScalarSizeInBits();
17784 if (Known.countMaxActiveBits() <= Log2_32(Size)) {
17785 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
17786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17787 if (AmtVT != Amt.getValueType()) {
17788 Amt = DAG.getZExtOrTrunc(Amt, DL, AmtVT);
17789 AddToWorklist(Amt.getNode());
17790 }
17791 return DAG.getNode(ISD::SHL, DL, VT, Trunc, Amt);
17792 }
17793 }
17794
17795 if (SDValue V = foldSubToUSubSat(VT, N0.getNode(), DL))
17796 return V;
17797
17798 if (SDValue ABD = foldABSToABD(N, DL))
17799 return ABD;
17800
17801 // Attempt to pre-truncate BUILD_VECTOR sources.
17802 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
17803 N0.hasOneUse() &&
17804 // Avoid creating illegal types if running after type legalizer.
17805 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
17806 if (TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()))
17807 return DAG.UnrollVectorOp(N);
17808
17809 // trunc(build_vector(ext(x), ext(x)) -> build_vector(x,x)
17810 if (SDValue SplatVal = DAG.getSplatValue(N0)) {
17811 if (ISD::isExtOpcode(SplatVal.getOpcode()) &&
17812 SrcVT.getScalarType() == SplatVal.getValueType())
17813 return DAG.UnrollVectorOp(N);
17814 }
17815 }
17816
17817 // trunc (splat_vector x) -> splat_vector (trunc x)
17818 if (N0.getOpcode() == ISD::SPLAT_VECTOR &&
17819 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType())) &&
17820 (!LegalOperations || TLI.isOperationLegal(ISD::SPLAT_VECTOR, VT))) {
17821 EVT SVT = VT.getScalarType();
17822 return DAG.getSplatVector(
17823 VT, DL, DAG.getNode(ISD::TRUNCATE, DL, SVT, N0->getOperand(0)));
17824 }
17825
17826 // Fold a series of buildvector, bitcast, and truncate if possible.
17827 // For example fold
17828 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
17829 // (2xi32 (buildvector x, y)).
17830 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
17831 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
17833 N0.getOperand(0).hasOneUse()) {
17834 SDValue BuildVect = N0.getOperand(0);
17835 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
17836 EVT TruncVecEltTy = VT.getVectorElementType();
17837
17838 // Check that the element types match.
17839 if (BuildVectEltTy == TruncVecEltTy) {
17840 // Now we only need to compute the offset of the truncated elements.
17841 unsigned BuildVecNumElts = BuildVect.getNumOperands();
17842 unsigned TruncVecNumElts = VT.getVectorNumElements();
17843 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
17844 unsigned FirstElt = isLE ? 0 : (TruncEltOffset - 1);
17845
17846 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
17847 "Invalid number of elements");
17848
17850 for (unsigned i = FirstElt, e = BuildVecNumElts; i < e;
17851 i += TruncEltOffset)
17852 Opnds.push_back(BuildVect.getOperand(i));
17853
17854 return DAG.getBuildVector(VT, DL, Opnds);
17855 }
17856 }
17857
17858 // fold (truncate (load x)) -> (smaller load x)
17859 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
17860 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
17861 if (SDValue Reduced = reduceLoadWidth(N))
17862 return Reduced;
17863
17864 // Handle the case where the truncated result is at least as wide as the
17865 // loaded type.
17866 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
17867 auto *LN0 = cast<LoadSDNode>(N0);
17868 if (LN0->isSimple() && LN0->getMemoryVT().bitsLE(VT)) {
17869 SDValue NewLoad = DAG.getExtLoad(
17870 LN0->getExtensionType(), SDLoc(LN0), VT, LN0->getChain(),
17871 LN0->getBasePtr(), LN0->getMemoryVT(), LN0->getMemOperand());
17872 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
17873 return NewLoad;
17874 }
17875 }
17876 }
17877
17878 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
17879 // where ... are all 'undef'.
17880 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
17882 SDValue V;
17883 unsigned Idx = 0;
17884 unsigned NumDefs = 0;
17885
17886 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
17887 SDValue X = N0.getOperand(i);
17888 if (!X.isUndef()) {
17889 V = X;
17890 Idx = i;
17891 NumDefs++;
17892 }
17893 // Stop if more than one members are non-undef.
17894 if (NumDefs > 1)
17895 break;
17896
17899 X.getValueType().getVectorElementCount()));
17900 }
17901
17902 if (NumDefs == 0)
17903 return DAG.getUNDEF(VT);
17904
17905 if (NumDefs == 1) {
17906 assert(V.getNode() && "The single defined operand is empty!");
17908 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
17909 if (i != Idx) {
17910 Opnds.push_back(DAG.getUNDEF(VTs[i]));
17911 continue;
17912 }
17913 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
17914 AddToWorklist(NV.getNode());
17915 Opnds.push_back(NV);
17916 }
17917 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
17918 }
17919 }
17920
17921 // Fold truncate of a bitcast of a vector to an extract of the low vector
17922 // element.
17923 //
17924 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
17925 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
17926 SDValue VecSrc = N0.getOperand(0);
17927 EVT VecSrcVT = VecSrc.getValueType();
17928 if (VecSrcVT.isVectorOf(VT) &&
17929 (!LegalOperations ||
17930 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
17931 unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
17932 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VecSrc,
17933 DAG.getVectorIdxConstant(Idx, DL));
17934 }
17935 }
17936
17937 // Simplify the operands using demanded-bits information.
17939 return SDValue(N, 0);
17940
17941 // fold (truncate (extract_subvector(ext x))) ->
17942 // (extract_subvector x)
17943 // TODO: This can be generalized to cover cases where the truncate and extract
17944 // do not fully cancel each other out.
17945 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
17946 SDValue N00 = N0.getOperand(0);
17947 if (N00.getOpcode() == ISD::SIGN_EXTEND ||
17948 N00.getOpcode() == ISD::ZERO_EXTEND ||
17949 N00.getOpcode() == ISD::ANY_EXTEND) {
17950 if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
17952 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
17953 N00.getOperand(0), N0.getOperand(1));
17954 }
17955 }
17956
17957 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
17958 return NewVSel;
17959
17960 // Narrow a suitable binary operation with a non-opaque constant operand by
17961 // moving it ahead of the truncate. This is limited to pre-legalization
17962 // because targets may prefer a wider type during later combines and invert
17963 // this transform.
17964 switch (N0.getOpcode()) {
17965 case ISD::ADD:
17966 case ISD::SUB:
17967 case ISD::MUL:
17968 case ISD::AND:
17969 case ISD::OR:
17970 case ISD::XOR:
17971 if (!LegalOperations && N0.hasOneUse() &&
17972 (N0.getOperand(0) == N0.getOperand(1) ||
17974 isConstantOrConstantVector(N0.getOperand(1), true))) {
17975 // TODO: We already restricted this to pre-legalization, but for vectors
17976 // we are extra cautious to not create an unsupported operation.
17977 // Target-specific changes are likely needed to avoid regressions here.
17978 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
17979 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17980 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
17981 SDNodeFlags Flags;
17982 // Propagate nuw for sub.
17983 if (N0->getOpcode() == ISD::SUB && N0->getFlags().hasNoUnsignedWrap() &&
17985 N0->getOperand(0),
17987 VT.getScalarSizeInBits())))
17988 Flags.setNoUnsignedWrap(true);
17989 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR, Flags);
17990 }
17991 }
17992 break;
17993 case ISD::ADDE:
17994 case ISD::UADDO_CARRY:
17995 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
17996 // (trunc uaddo_carry(X, Y, Carry)) ->
17997 // (uaddo_carry trunc(X), trunc(Y), Carry)
17998 // When the adde's carry is not used.
17999 // We only do for uaddo_carry before legalize operation
18000 if (((!LegalOperations && N0.getOpcode() == ISD::UADDO_CARRY) ||
18001 TLI.isOperationLegal(N0.getOpcode(), VT)) &&
18002 N0.hasOneUse() && !N0->hasAnyUseOfValue(1)) {
18003 SDValue X = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
18004 SDValue Y = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
18005 SDVTList VTs = DAG.getVTList(VT, N0->getValueType(1));
18006 return DAG.getNode(N0.getOpcode(), DL, VTs, X, Y, N0.getOperand(2));
18007 }
18008 break;
18009 case ISD::USUBSAT:
18010 // Truncate the USUBSAT only if LHS is a known zero-extension, its not
18011 // enough to know that the upper bits are zero we must ensure that we don't
18012 // introduce an extra truncate.
18013 if (!LegalOperations && N0.hasOneUse() &&
18016 VT.getScalarSizeInBits() &&
18017 hasOperation(N0.getOpcode(), VT)) {
18018 return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1),
18019 DAG, DL);
18020 }
18021 break;
18022 case ISD::AVGCEILS:
18023 case ISD::AVGCEILU:
18024 // trunc (avgceilu (sext (x), sext (y))) -> avgceils(x, y)
18025 // trunc (avgceils (zext (x), zext (y))) -> avgceilu(x, y)
18026 if (N0.hasOneUse()) {
18027 SDValue Op0 = N0.getOperand(0);
18028 SDValue Op1 = N0.getOperand(1);
18029 if (N0.getOpcode() == ISD::AVGCEILU) {
18031 Op0.getOpcode() == ISD::SIGN_EXTEND &&
18032 Op1.getOpcode() == ISD::SIGN_EXTEND &&
18033 Op0.getOperand(0).getValueType() == VT &&
18034 Op1.getOperand(0).getValueType() == VT)
18035 return DAG.getNode(ISD::AVGCEILS, DL, VT, Op0.getOperand(0),
18036 Op1.getOperand(0));
18037 } else {
18039 Op0.getOpcode() == ISD::ZERO_EXTEND &&
18040 Op1.getOpcode() == ISD::ZERO_EXTEND &&
18041 Op0.getOperand(0).getValueType() == VT &&
18042 Op1.getOperand(0).getValueType() == VT)
18043 return DAG.getNode(ISD::AVGCEILU, DL, VT, Op0.getOperand(0),
18044 Op1.getOperand(0));
18045 }
18046 }
18047 [[fallthrough]];
18048 case ISD::AVGFLOORS:
18049 case ISD::AVGFLOORU:
18050 case ISD::ABDS:
18051 case ISD::ABDU:
18052 // (trunc (avg a, b)) -> (avg (trunc a), (trunc b))
18053 // (trunc (abdu/abds a, b)) -> (abdu/abds (trunc a), (trunc b))
18054 if (!LegalOperations && N0.hasOneUse() &&
18055 TLI.isOperationLegal(N0.getOpcode(), VT)) {
18056 EVT TruncVT = VT;
18057 unsigned SrcBits = SrcVT.getScalarSizeInBits();
18058 unsigned TruncBits = TruncVT.getScalarSizeInBits();
18059
18060 SDValue A = N0.getOperand(0);
18061 SDValue B = N0.getOperand(1);
18062 bool CanFold = false;
18063
18064 if (N0.getOpcode() == ISD::AVGFLOORU || N0.getOpcode() == ISD::AVGCEILU ||
18065 N0.getOpcode() == ISD::ABDU) {
18066 APInt UpperBits = APInt::getBitsSetFrom(SrcBits, TruncBits);
18067 CanFold = DAG.MaskedValueIsZero(B, UpperBits) &&
18068 DAG.MaskedValueIsZero(A, UpperBits);
18069 } else {
18070 unsigned NeededBits = SrcBits - TruncBits;
18071 CanFold = DAG.ComputeNumSignBits(B) > NeededBits &&
18072 DAG.ComputeNumSignBits(A) > NeededBits;
18073 }
18074
18075 if (CanFold) {
18076 SDValue NewA = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, A);
18077 SDValue NewB = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, B);
18078 return DAG.getNode(N0.getOpcode(), DL, TruncVT, NewA, NewB);
18079 }
18080 }
18081 break;
18082 }
18083
18084 return SDValue();
18085}
18086
18087static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
18088 SDValue Elt = N->getOperand(i);
18089 if (Elt.getOpcode() != ISD::MERGE_VALUES)
18090 return Elt.getNode();
18091 return Elt.getOperand(Elt.getResNo()).getNode();
18092}
18093
18094/// build_pair (load, load) -> load
18095/// if load locations are consecutive.
18096SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
18097 assert(N->getOpcode() == ISD::BUILD_PAIR);
18098
18099 auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
18100 auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
18101
18102 // A BUILD_PAIR is always having the least significant part in elt 0 and the
18103 // most significant part in elt 1. So when combining into one large load, we
18104 // need to consider the endianness.
18105 if (DAG.getDataLayout().isBigEndian())
18106 std::swap(LD1, LD2);
18107
18108 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) ||
18109 !LD1->hasOneUse() || !LD2->hasOneUse() ||
18110 LD1->getAddressSpace() != LD2->getAddressSpace())
18111 return SDValue();
18112
18113 unsigned LD1Fast = 0;
18114 EVT LD1VT = LD1->getValueType(0);
18115 unsigned LD1Bytes = LD1VT.getStoreSize();
18116 if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
18117 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) &&
18118 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
18119 *LD1->getMemOperand(), &LD1Fast) && LD1Fast)
18120 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
18121 LD1->getPointerInfo(), LD1->getAlign());
18122
18123 return SDValue();
18124}
18125
18126static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
18127 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
18128 // and Lo parts; on big-endian machines it doesn't.
18129 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
18130}
18131
18132SDValue DAGCombiner::foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
18133 const TargetLowering &TLI) {
18134 // If this is not a bitcast to an FP type or if the target doesn't have
18135 // IEEE754-compliant FP logic, we're done.
18136 EVT VT = N->getValueType(0);
18137 SDValue N0 = N->getOperand(0);
18138 EVT SourceVT = N0.getValueType();
18139
18140 if (!VT.isFloatingPoint())
18141 return SDValue();
18142
18143 // TODO: Handle cases where the integer constant is a different scalar
18144 // bitwidth to the FP.
18145 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
18146 return SDValue();
18147
18148 unsigned FPOpcode;
18149 APInt SignMask;
18150 switch (N0.getOpcode()) {
18151 case ISD::AND:
18152 FPOpcode = ISD::FABS;
18153 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
18154 break;
18155 case ISD::XOR:
18156 FPOpcode = ISD::FNEG;
18157 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
18158 break;
18159 case ISD::OR:
18160 FPOpcode = ISD::FABS;
18161 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
18162 break;
18163 default:
18164 return SDValue();
18165 }
18166
18167 if (LegalOperations && !TLI.isOperationLegal(FPOpcode, VT))
18168 return SDValue();
18169
18170 // This needs to be the inverse of logic in foldSignChangeInBitcast.
18171 // FIXME: I don't think looking for bitcast intrinsically makes sense, but
18172 // removing this would require more changes.
18173 auto IsBitCastOrFree = [&TLI, FPOpcode](SDValue Op, EVT VT) {
18174 if (sd_match(Op, m_BitCast(m_SpecificVT(VT))))
18175 return true;
18176
18177 return FPOpcode == ISD::FABS ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT);
18178 };
18179
18180 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
18181 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
18182 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
18183 // fneg (fabs X)
18184 SDValue LogicOp0 = N0.getOperand(0);
18185 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
18186 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
18187 IsBitCastOrFree(LogicOp0, VT)) {
18188 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, LogicOp0);
18189 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, CastOp0);
18190 NumFPLogicOpsConv++;
18191 if (N0.getOpcode() == ISD::OR)
18192 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
18193 return FPOp;
18194 }
18195
18196 return SDValue();
18197}
18198
18199SDValue DAGCombiner::visitBITCAST(SDNode *N) {
18200 SDValue N0 = N->getOperand(0);
18201 EVT VT = N->getValueType(0);
18202
18203 if (N0.isUndef())
18204 return DAG.getUNDEF(VT);
18205
18206 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
18207 // Only do this before legalize types, unless both types are integer and the
18208 // scalar type is legal. Only do this before legalize ops, since the target
18209 // maybe depending on the bitcast.
18210 // First check to see if this is all constant.
18211 // TODO: Support FP bitcasts after legalize types.
18212 if (VT.isVector() &&
18213 (!LegalTypes ||
18214 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
18215 TLI.isTypeLegal(VT.getVectorElementType()))) &&
18216 N0.getOpcode() == ISD::BUILD_VECTOR && N0->hasOneUse() &&
18217 cast<BuildVectorSDNode>(N0)->isConstant())
18218 return DAG.FoldConstantBuildVector(cast<BuildVectorSDNode>(N0), SDLoc(N),
18220
18221 // If the input is a constant, let getNode fold it.
18222 if (isIntOrFPConstant(N0)) {
18223 // If we can't allow illegal operations, we need to check that this is just
18224 // a fp -> int or int -> conversion and that the resulting operation will
18225 // be legal.
18226 if (!LegalOperations ||
18227 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
18229 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
18230 TLI.isOperationLegal(ISD::Constant, VT))) {
18231 SDValue C = DAG.getBitcast(VT, N0);
18232 if (C.getNode() != N)
18233 return C;
18234 }
18235 }
18236
18237 // (conv (conv x, t1), t2) -> (conv x, t2)
18238 if (N0.getOpcode() == ISD::BITCAST)
18239 return DAG.getBitcast(VT, N0.getOperand(0));
18240
18241 // fold (conv (logicop (conv x), (c))) -> (logicop x, (conv c))
18242 // iff the current bitwise logicop type isn't legal
18243 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && VT.isInteger() &&
18244 !TLI.isTypeLegal(N0.getOperand(0).getValueType())) {
18245 auto IsFreeBitcast = [VT](SDValue V) {
18246 return (V.getOpcode() == ISD::BITCAST &&
18247 V.getOperand(0).getValueType() == VT) ||
18249 V->hasOneUse());
18250 };
18251 if (IsFreeBitcast(N0.getOperand(0)) && IsFreeBitcast(N0.getOperand(1)))
18252 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
18253 DAG.getBitcast(VT, N0.getOperand(0)),
18254 DAG.getBitcast(VT, N0.getOperand(1)));
18255 }
18256
18257 // fold (conv (load x)) -> (load (conv*)x)
18258 // fold (conv (freeze (load x))) -> (freeze (load (conv*)x))
18259 // If the resultant load doesn't need a higher alignment than the original!
18260 auto CastLoad = [this, &VT](SDValue N0, const SDLoc &DL) {
18261 // Peek through scalar_to_vector if the scalar is same size as VT - often a
18262 // leftover from legalization.
18263 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && N0.hasOneUse() &&
18265 N0 = N0.getOperand(0);
18266 if (N0.getOpcode() == ISD::AssertNoFPClass)
18267 N0 = N0.getOperand(0);
18268 if (!ISD::isNormalLoad(N0.getNode()) || !N0.hasOneUse())
18269 return SDValue();
18270
18271 // Do not remove the cast if the types differ in endian layout.
18274 return SDValue();
18275
18276 // If the load is volatile, we only want to change the load type if the
18277 // resulting load is legal. Otherwise we might increase the number of
18278 // memory accesses. We don't care if the original type was legal or not
18279 // as we assume software couldn't rely on the number of accesses of an
18280 // illegal type.
18281 auto *LN0 = cast<LoadSDNode>(N0);
18282 if ((LegalOperations || !LN0->isSimple()) &&
18283 !TLI.isOperationLegal(ISD::LOAD, VT))
18284 return SDValue();
18285
18286 if (!TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
18287 *LN0->getMemOperand()))
18288 return SDValue();
18289
18290 // If the range metadata type does not match the new memory
18291 // operation type, remove the range metadata.
18292 if (const MDNode *MD = LN0->getRanges()) {
18293 ConstantInt *Lower = mdconst::extract<ConstantInt>(MD->getOperand(0));
18294 if (Lower->getBitWidth() != VT.getScalarSizeInBits() || !VT.isInteger()) {
18295 LN0->getMemOperand()->clearRanges();
18296 }
18297 }
18298 SDValue Load = DAG.getLoad(VT, DL, LN0->getChain(), LN0->getBasePtr(),
18299 LN0->getMemOperand());
18301 return Load;
18302 };
18303
18304 if (SDValue NewLd = CastLoad(N0, SDLoc(N)))
18305 return NewLd;
18306
18307 if (N0.getOpcode() == ISD::FREEZE && N0.hasOneUse())
18308 if (SDValue NewLd = CastLoad(N0.getOperand(0), SDLoc(N)))
18309 return DAG.getFreeze(NewLd);
18310
18311 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
18312 return V;
18313
18314 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
18315 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
18316 //
18317 // For ppc_fp128:
18318 // fold (bitcast (fneg x)) ->
18319 // flipbit = signbit
18320 // (xor (bitcast x) (build_pair flipbit, flipbit))
18321 //
18322 // fold (bitcast (fabs x)) ->
18323 // flipbit = (and (extract_element (bitcast x), 0), signbit)
18324 // (xor (bitcast x) (build_pair flipbit, flipbit))
18325 // This often reduces constant pool loads.
18326 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
18327 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
18328 N0->hasOneUse() && VT.isInteger() && !VT.isVector() &&
18329 !N0.getValueType().isVector()) {
18330 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
18331 AddToWorklist(NewConv.getNode());
18332
18333 SDLoc DL(N);
18334 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
18335 assert(VT.getSizeInBits() == 128);
18336 SDValue SignBit = DAG.getConstant(
18337 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
18338 SDValue FlipBit;
18339 if (N0.getOpcode() == ISD::FNEG) {
18340 FlipBit = SignBit;
18341 AddToWorklist(FlipBit.getNode());
18342 } else {
18343 assert(N0.getOpcode() == ISD::FABS);
18344 SDValue Hi =
18345 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
18347 SDLoc(NewConv)));
18348 AddToWorklist(Hi.getNode());
18349 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
18350 AddToWorklist(FlipBit.getNode());
18351 }
18352 SDValue FlipBits =
18353 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
18354 AddToWorklist(FlipBits.getNode());
18355 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
18356 }
18357 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
18358 if (N0.getOpcode() == ISD::FNEG)
18359 return DAG.getNode(ISD::XOR, DL, VT,
18360 NewConv, DAG.getConstant(SignBit, DL, VT));
18361 assert(N0.getOpcode() == ISD::FABS);
18362 return DAG.getNode(ISD::AND, DL, VT,
18363 NewConv, DAG.getConstant(~SignBit, DL, VT));
18364 }
18365
18366 // fold (bitconvert (fcopysign cst, x)) ->
18367 // (or (and (bitconvert x), sign), (and cst, (not sign)))
18368 // Note that we don't handle (copysign x, cst) because this can always be
18369 // folded to an fneg or fabs.
18370 //
18371 // For ppc_fp128:
18372 // fold (bitcast (fcopysign cst, x)) ->
18373 // flipbit = (and (extract_element
18374 // (xor (bitcast cst), (bitcast x)), 0),
18375 // signbit)
18376 // (xor (bitcast cst) (build_pair flipbit, flipbit))
18377 if (N0.getOpcode() == ISD::FCOPYSIGN && N0->hasOneUse() &&
18379 !VT.isVector()) {
18380 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
18381 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
18382 if (isTypeLegal(IntXVT)) {
18383 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
18384 AddToWorklist(X.getNode());
18385
18386 // If X has a different width than the result/lhs, sext it or truncate it.
18387 unsigned VTWidth = VT.getSizeInBits();
18388 if (OrigXWidth < VTWidth) {
18389 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
18390 AddToWorklist(X.getNode());
18391 } else if (OrigXWidth > VTWidth) {
18392 // To get the sign bit in the right place, we have to shift it right
18393 // before truncating.
18394 SDLoc DL(X);
18395 X = DAG.getNode(ISD::SRL, DL,
18396 X.getValueType(), X,
18397 DAG.getConstant(OrigXWidth-VTWidth, DL,
18398 X.getValueType()));
18399 AddToWorklist(X.getNode());
18400 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
18401 AddToWorklist(X.getNode());
18402 }
18403
18404 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
18405 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
18406 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
18407 AddToWorklist(Cst.getNode());
18408 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
18409 AddToWorklist(X.getNode());
18410 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
18411 AddToWorklist(XorResult.getNode());
18412 SDValue XorResult64 = DAG.getNode(
18413 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
18415 SDLoc(XorResult)));
18416 AddToWorklist(XorResult64.getNode());
18417 SDValue FlipBit =
18418 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
18419 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
18420 AddToWorklist(FlipBit.getNode());
18421 SDValue FlipBits =
18422 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
18423 AddToWorklist(FlipBits.getNode());
18424 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
18425 }
18426 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
18427 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
18428 X, DAG.getConstant(SignBit, SDLoc(X), VT));
18429 AddToWorklist(X.getNode());
18430
18431 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
18432 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
18433 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
18434 AddToWorklist(Cst.getNode());
18435
18436 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
18437 }
18438 }
18439
18440 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
18441 if (N0.getOpcode() == ISD::BUILD_PAIR)
18442 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
18443 return CombineLD;
18444
18445 // int_vt (bitcast (vec_vt (scalar_to_vector elt_vt:x)))
18446 // => int_vt (any_extend elt_vt:x)
18447 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isScalarInteger()) {
18448 SDValue SrcScalar = N0.getOperand(0);
18449 EVT SrcVT = SrcScalar.getValueType();
18450 if (SrcVT.isScalarInteger() && VT.bitsGT(SrcVT))
18451 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SrcScalar);
18452 }
18453
18454 // Remove double bitcasts from shuffles - this is often a legacy of
18455 // XformToShuffleWithZero being used to combine bitmaskings (of
18456 // float vectors bitcast to integer vectors) into shuffles.
18457 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
18458 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
18459 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
18462 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
18463
18464 // If operands are a bitcast, peek through if it casts the original VT.
18465 // If operands are a constant, just bitcast back to original VT.
18466 auto PeekThroughBitcast = [&](SDValue Op) {
18467 if (Op.getOpcode() == ISD::BITCAST &&
18468 Op.getOperand(0).getValueType() == VT)
18469 return SDValue(Op.getOperand(0));
18470 if (Op.isUndef() || isAnyConstantBuildVector(Op))
18471 return DAG.getBitcast(VT, Op);
18472 return SDValue();
18473 };
18474
18475 // FIXME: If either input vector is bitcast, try to convert the shuffle to
18476 // the result type of this bitcast. This would eliminate at least one
18477 // bitcast. See the transform in InstCombine.
18478 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
18479 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
18480 if (!(SV0 && SV1))
18481 return SDValue();
18482
18483 int MaskScale =
18485 SmallVector<int, 8> NewMask;
18486 for (int M : SVN->getMask())
18487 for (int i = 0; i != MaskScale; ++i)
18488 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
18489
18490 SDValue LegalShuffle =
18491 TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
18492 if (LegalShuffle)
18493 return LegalShuffle;
18494 }
18495
18496 return SDValue();
18497}
18498
18499SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
18500 EVT VT = N->getValueType(0);
18501 return CombineConsecutiveLoads(N, VT);
18502}
18503
18504SDValue DAGCombiner::visitFREEZE(SDNode *N) {
18505 SDValue N0 = N->getOperand(0);
18506
18508 return N0;
18509
18510 // If we have frozen and unfrozen users of N0, update so everything uses N.
18511 if (!N0.isUndef() && !N0.hasOneUse()) {
18512 SDValue FrozenN0(N, 0);
18513 // Unfreeze all (possibly nested) uses of N to avoid double deleting N from
18514 // the CSE map.
18515 while (!N->use_empty())
18516 DAG.ReplaceAllUsesOfValueWith(FrozenN0, N0);
18517 DAG.ReplaceAllUsesOfValueWith(N0, FrozenN0);
18518 // ReplaceAllUsesOfValueWith will have also updated the use in N, thus
18519 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18520 assert(N->getOperand(0) == FrozenN0 && "Expected cycle in DAG");
18521 DAG.UpdateNodeOperands(N, N0);
18522 // Revisit the node.
18523 AddToWorklist(N);
18524 return FrozenN0;
18525 }
18526
18527 // We currently avoid folding freeze over SRL, due to the problems seen
18528 // with (freeze (assert ext)) blocking simplifications of SRL. See for
18529 // example https://reviews.llvm.org/D136529#4120959.
18530 if (N0.getOpcode() == ISD::SRL)
18531 return SDValue();
18532
18533 // Fold freeze(op(x, ...)) -> op(freeze(x), ...).
18534 // Try to push freeze through instructions that propagate but don't produce
18535 // poison as far as possible. If an operand of freeze follows three
18536 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
18537 // guaranteed-non-poison operands (or is a BUILD_VECTOR or similar) then push
18538 // the freeze through to the operands that are not guaranteed non-poison.
18539 // NOTE: we will strip poison-generating flags, so ignore them here.
18541 /*ConsiderFlags*/ false) ||
18542 N0->getNumValues() != 1 || !N0->hasOneUse())
18543 return SDValue();
18544
18545 // TOOD: we should always allow multiple operands, however this increases the
18546 // likelihood of infinite loops due to the ReplaceAllUsesOfValueWith call
18547 // below causing later nodes that share frozen operands to fold again and no
18548 // longer being able to confirm other operands are not poison due to recursion
18549 // depth limits on isGuaranteedNotToBeUndefOrPoison.
18550 bool AllowMultipleMaybePoisonOperands =
18551 N0.getOpcode() == ISD::SELECT_CC || N0.getOpcode() == ISD::SETCC ||
18552 N0.getOpcode() == ISD::BUILD_VECTOR ||
18554 N0.getOpcode() == ISD::BUILD_PAIR ||
18557
18558 // Avoid turning a BUILD_VECTOR that can be recognized as "all zeros", "all
18559 // ones" or "constant" into something that depends on FrozenUndef. We can
18560 // instead pick undef values to keep those properties, while at the same time
18561 // folding away the freeze.
18562 // If we implement a more general solution for folding away freeze(undef) in
18563 // the future, then this special handling can be removed.
18564 if (N0.getOpcode() == ISD::BUILD_VECTOR) {
18565 SDLoc DL(N0);
18566 EVT VT = N0.getValueType();
18568 return DAG.getAllOnesConstant(DL, VT);
18571 for (const SDValue &Op : N0->op_values())
18572 NewVecC.push_back(
18573 Op.isUndef() ? DAG.getConstant(0, DL, Op.getValueType()) : Op);
18574 return DAG.getBuildVector(VT, DL, NewVecC);
18575 }
18576 }
18577
18578 SmallSet<SDValue, 8> MaybePoisonOperands;
18579 SmallVector<unsigned, 8> MaybePoisonOperandNumbers;
18580 for (auto [OpNo, Op] : enumerate(N0->ops())) {
18583 continue;
18584 bool HadMaybePoisonOperands = !MaybePoisonOperands.empty();
18585 bool IsNewMaybePoisonOperand = MaybePoisonOperands.insert(Op).second;
18586 if (IsNewMaybePoisonOperand)
18587 MaybePoisonOperandNumbers.push_back(OpNo);
18588 if (!HadMaybePoisonOperands)
18589 continue;
18590 if (IsNewMaybePoisonOperand && !AllowMultipleMaybePoisonOperands) {
18591 // Multiple maybe-poison ops when not allowed - bail out.
18592 return SDValue();
18593 }
18594 }
18595 // NOTE: the whole op may be not guaranteed to not be undef or poison because
18596 // it could create undef or poison due to it's poison-generating flags.
18597 // So not finding any maybe-poison operands is fine.
18598
18599 for (unsigned OpNo : MaybePoisonOperandNumbers) {
18600 // N0 can mutate during iteration, so make sure to refetch the maybe poison
18601 // operands via the operand numbers. The typical scenario is that we have
18602 // something like this
18603 // t262: i32 = freeze t181
18604 // t150: i32 = ctlz_zero_poison t262
18605 // t184: i32 = ctlz_zero_poison t181
18606 // t268: i32 = select_cc t181, Constant:i32<0>, t184, t186, setne:ch
18607 // When freezing the t181 operand we get t262 back, and then the
18608 // ReplaceAllUsesOfValueWith call will not only replace t181 by t262, but
18609 // also recursively replace t184 by t150.
18610 SDValue MaybePoisonOperand = N->getOperand(0).getOperand(OpNo);
18611 // Don't replace every single UNDEF everywhere with frozen UNDEF, though.
18612 if (MaybePoisonOperand.isUndef())
18613 continue;
18614 // First, freeze each offending operand.
18615 SDValue FrozenMaybePoisonOperand = DAG.getFreeze(MaybePoisonOperand);
18616 // Then, change all other uses of unfrozen operand to use frozen operand.
18617 DAG.ReplaceAllUsesOfValueWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
18618 if (FrozenMaybePoisonOperand.getOpcode() == ISD::FREEZE &&
18619 FrozenMaybePoisonOperand.getOperand(0) == FrozenMaybePoisonOperand) {
18620 // But, that also updated the use in the freeze we just created, thus
18621 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18622 DAG.UpdateNodeOperands(FrozenMaybePoisonOperand.getNode(),
18623 MaybePoisonOperand);
18624 }
18625
18626 // This node has been merged with another.
18627 if (N->getOpcode() == ISD::DELETED_NODE)
18628 return SDValue(N, 0);
18629 }
18630
18631 assert(N->getOpcode() != ISD::DELETED_NODE && "Node was deleted!");
18632
18633 // The whole node may have been updated, so the value we were holding
18634 // may no longer be valid. Re-fetch the operand we're `freeze`ing.
18635 N0 = N->getOperand(0);
18636
18637 // Finally, recreate the node, it's operands were updated to use
18638 // frozen operands, so we just need to use it's "original" operands.
18640 // TODO: ISD::UNDEF and ISD::POISON should get separate handling, but best
18641 // leave for a future patch.
18642 for (SDValue &Op : Ops) {
18643 if (Op.isUndef())
18644 Op = DAG.getFreeze(Op);
18645 }
18646
18647 SDLoc DL(N0);
18648
18649 // Special case handling for ShuffleVectorSDNode nodes.
18650 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N0))
18651 return DAG.getVectorShuffle(N0.getValueType(), DL, Ops[0], Ops[1],
18652 SVN->getMask());
18653
18654 // NOTE: this strips poison generating flags.
18655 // Folding freeze(op(x, ...)) -> op(freeze(x), ...) does not require nnan,
18656 // ninf, nsz, or fast.
18657 // However, contract, reassoc, afn, and arcp should be preserved,
18658 // as these fast-math flags do not introduce poison values.
18659 SDNodeFlags SrcFlags = N0->getFlags();
18660 SDNodeFlags SafeFlags;
18661 SafeFlags.setAllowContract(SrcFlags.hasAllowContract());
18662 SafeFlags.setAllowReassociation(SrcFlags.hasAllowReassociation());
18663 SafeFlags.setApproximateFuncs(SrcFlags.hasApproximateFuncs());
18664 SafeFlags.setAllowReciprocal(SrcFlags.hasAllowReciprocal());
18665 return DAG.getNode(N0.getOpcode(), DL, N0->getVTList(), Ops, SafeFlags);
18666}
18667
18668// Returns true if floating point contraction is allowed on the FMUL-SDValue
18669// `N`
18671 assert(N.getOpcode() == ISD::FMUL);
18672
18673 return N->getFlags().hasAllowContract();
18674}
18675
18676/// Try to perform FMA combining on a given FADD node.
18677SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
18678 SDValue N0 = N->getOperand(0);
18679 SDValue N1 = N->getOperand(1);
18680 EVT VT = N->getValueType(0);
18681 SDLoc SL(N);
18682
18683 // Floating-point multiply-add with intermediate rounding.
18684 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18685
18686 // Floating-point multiply-add without intermediate rounding.
18687 bool HasFMA =
18688 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18690
18691 // No valid opcode, do not combine.
18692 if (!HasFMAD && !HasFMA)
18693 return SDValue();
18694
18695 // FMAD (with intermediate rounding) is always safe to form; FMA requires the
18696 // contract fast-math flag.
18697 bool AllowFusionGlobally = HasFMAD;
18698 // If the addition is not contractable, do not combine.
18699 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18700 return SDValue();
18701
18702 // Folding fadd (fmul x, y), (fmul x, y) -> fma x, y, (fmul x, y) is never
18703 // beneficial. It does not reduce latency. It increases register pressure. It
18704 // replaces an fadd with an fma which is a more complex instruction, so is
18705 // likely to have a larger encoding, use more functional units, etc.
18706 if (N0 == N1)
18707 return SDValue();
18708
18709 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18710 return SDValue();
18711
18712 // Always prefer FMAD to FMA for precision.
18713 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18715
18716 auto isFusedOp = [&](SDValue N) {
18717 unsigned Opcode = N.getOpcode();
18718 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
18719 };
18720
18721 // Is the node an FMUL and contractable either due to global flags or
18722 // SDNodeFlags.
18723 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18724 if (N.getOpcode() != ISD::FMUL)
18725 return false;
18726 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18727 };
18728 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
18729 // prefer to fold the multiply with fewer uses.
18731 if (N0->use_size() > N1->use_size())
18732 std::swap(N0, N1);
18733 }
18734
18735 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
18736 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
18737 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
18738 N0.getOperand(1), N1);
18739 }
18740
18741 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
18742 // Note: Commutes FADD operands.
18743 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
18744 return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0),
18745 N1.getOperand(1), N0);
18746 }
18747
18748 // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E)
18749 // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E)
18750 // This also works with nested fma instructions:
18751 // fadd (fma A, B, (fma (C, D, (fmul (E, F))))), G -->
18752 // fma A, B, (fma C, D, fma (E, F, G))
18753 // fadd (G, (fma A, B, (fma (C, D, (fmul (E, F)))))) -->
18754 // fma A, B, (fma C, D, fma (E, F, G)).
18755 // This requires reassociation because it changes the order of operations.
18756 bool CanReassociate = N->getFlags().hasAllowReassociation();
18757 if (CanReassociate) {
18758 SDValue FMA, E;
18759 if (isFusedOp(N0) && N0.hasOneUse()) {
18760 FMA = N0;
18761 E = N1;
18762 } else if (isFusedOp(N1) && N1.hasOneUse()) {
18763 FMA = N1;
18764 E = N0;
18765 }
18766
18767 SDValue TmpFMA = FMA;
18768 while (E && isFusedOp(TmpFMA) && TmpFMA.hasOneUse()) {
18769 SDValue FMul = TmpFMA->getOperand(2);
18770 if (FMul.getOpcode() == ISD::FMUL && FMul.hasOneUse()) {
18771 SDValue C = FMul.getOperand(0);
18772 SDValue D = FMul.getOperand(1);
18773 SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E);
18775 // Replacing the inner FMul could cause the outer FMA to be simplified
18776 // away.
18777 return FMA.getOpcode() == ISD::DELETED_NODE ? SDValue(N, 0) : FMA;
18778 }
18779
18780 TmpFMA = TmpFMA->getOperand(2);
18781 }
18782 }
18783
18784 // Look through FP_EXTEND nodes to do more combining.
18785
18786 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
18787 if (N0.getOpcode() == ISD::FP_EXTEND) {
18788 SDValue N00 = N0.getOperand(0);
18789 if (isContractableFMUL(N00) &&
18790 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18791 N00.getValueType())) {
18792 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18793 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18794 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18795 N1);
18796 }
18797 }
18798
18799 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
18800 // Note: Commutes FADD operands.
18801 if (N1.getOpcode() == ISD::FP_EXTEND) {
18802 SDValue N10 = N1.getOperand(0);
18803 if (isContractableFMUL(N10) &&
18804 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18805 N10.getValueType())) {
18806 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18807 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)),
18808 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)),
18809 N0);
18810 }
18811 }
18812
18813 // More folding opportunities when target permits.
18814 if (Aggressive) {
18815 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
18816 // -> (fma x, y, (fma (fpext u), (fpext v), z))
18817 auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18818 SDValue Z) {
18819 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
18820 DAG.getNode(PreferredFusedOpcode, SL, VT,
18821 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18822 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
18823 Z));
18824 };
18825 if (isFusedOp(N0)) {
18826 SDValue N02 = N0.getOperand(2);
18827 if (N02.getOpcode() == ISD::FP_EXTEND) {
18828 SDValue N020 = N02.getOperand(0);
18829 if (isContractableFMUL(N020) &&
18830 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18831 N020.getValueType())) {
18832 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
18833 N020.getOperand(0), N020.getOperand(1),
18834 N1);
18835 }
18836 }
18837 }
18838
18839 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
18840 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
18841 // FIXME: This turns two single-precision and one double-precision
18842 // operation into two double-precision operations, which might not be
18843 // interesting for all targets, especially GPUs.
18844 auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18845 SDValue Z) {
18846 return DAG.getNode(
18847 PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
18848 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
18849 DAG.getNode(PreferredFusedOpcode, SL, VT,
18850 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18851 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z));
18852 };
18853 if (N0.getOpcode() == ISD::FP_EXTEND) {
18854 SDValue N00 = N0.getOperand(0);
18855 if (isFusedOp(N00)) {
18856 SDValue N002 = N00.getOperand(2);
18857 if (isContractableFMUL(N002) &&
18858 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18859 N00.getValueType())) {
18860 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
18861 N002.getOperand(0), N002.getOperand(1),
18862 N1);
18863 }
18864 }
18865 }
18866
18867 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
18868 // -> (fma y, z, (fma (fpext u), (fpext v), x))
18869 if (isFusedOp(N1)) {
18870 SDValue N12 = N1.getOperand(2);
18871 if (N12.getOpcode() == ISD::FP_EXTEND) {
18872 SDValue N120 = N12.getOperand(0);
18873 if (isContractableFMUL(N120) &&
18874 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18875 N120.getValueType())) {
18876 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
18877 N120.getOperand(0), N120.getOperand(1),
18878 N0);
18879 }
18880 }
18881 }
18882
18883 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
18884 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
18885 // FIXME: This turns two single-precision and one double-precision
18886 // operation into two double-precision operations, which might not be
18887 // interesting for all targets, especially GPUs.
18888 if (N1.getOpcode() == ISD::FP_EXTEND) {
18889 SDValue N10 = N1.getOperand(0);
18890 if (isFusedOp(N10)) {
18891 SDValue N102 = N10.getOperand(2);
18892 if (isContractableFMUL(N102) &&
18893 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18894 N10.getValueType())) {
18895 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
18896 N102.getOperand(0), N102.getOperand(1),
18897 N0);
18898 }
18899 }
18900 }
18901 }
18902
18903 return SDValue();
18904}
18905
18906/// Try to perform FMA combining on a given FSUB node.
18907SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
18908 SDValue N0 = N->getOperand(0);
18909 SDValue N1 = N->getOperand(1);
18910 EVT VT = N->getValueType(0);
18911 SDLoc SL(N);
18912
18913 // Floating-point multiply-add with intermediate rounding.
18914 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18915
18916 // Floating-point multiply-add without intermediate rounding.
18917 bool HasFMA =
18918 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18920
18921 // No valid opcode, do not combine.
18922 if (!HasFMAD && !HasFMA)
18923 return SDValue();
18924
18925 const SDNodeFlags Flags = N->getFlags();
18926 // FMAD (with intermediate rounding) is always safe to form; FMA requires the
18927 // contract fast-math flag.
18928 bool AllowFusionGlobally = HasFMAD;
18929
18930 // If the subtraction is not contractable, do not combine.
18931 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18932 return SDValue();
18933
18934 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18935 return SDValue();
18936
18937 // Always prefer FMAD to FMA for precision.
18938 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18940 bool NoSignedZero = Flags.hasNoSignedZeros();
18941
18942 // Is the node an FMUL and contractable either due to global flags or
18943 // SDNodeFlags.
18944 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18945 if (N.getOpcode() != ISD::FMUL)
18946 return false;
18947 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18948 };
18949
18950 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18951 auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
18952 if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
18953 return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
18954 XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z));
18955 }
18956 return SDValue();
18957 };
18958
18959 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18960 // Note: Commutes FSUB operands.
18961 auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
18962 if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
18963 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18964 DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
18965 YZ.getOperand(1), X);
18966 }
18967 return SDValue();
18968 };
18969
18970 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
18971 // prefer to fold the multiply with fewer uses.
18972 if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
18973 (N0->use_size() > N1->use_size())) {
18974 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
18975 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18976 return V;
18977 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
18978 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18979 return V;
18980 } else {
18981 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18982 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18983 return V;
18984 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18985 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18986 return V;
18987 }
18988
18989 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
18990 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
18991 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
18992 SDValue N00 = N0.getOperand(0).getOperand(0);
18993 SDValue N01 = N0.getOperand(0).getOperand(1);
18994 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18995 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
18996 DAG.getNode(ISD::FNEG, SL, VT, N1));
18997 }
18998
18999 // Look through FP_EXTEND nodes to do more combining.
19000
19001 // fold (fsub (fpext (fmul x, y)), z)
19002 // -> (fma (fpext x), (fpext y), (fneg z))
19003 if (N0.getOpcode() == ISD::FP_EXTEND) {
19004 SDValue N00 = N0.getOperand(0);
19005 if (isContractableFMUL(N00) &&
19006 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19007 N00.getValueType())) {
19008 return DAG.getNode(PreferredFusedOpcode, SL, VT,
19009 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
19010 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
19011 DAG.getNode(ISD::FNEG, SL, VT, N1));
19012 }
19013 }
19014
19015 // fold (fsub x, (fpext (fmul y, z)))
19016 // -> (fma (fneg (fpext y)), (fpext z), x)
19017 // Note: Commutes FSUB operands.
19018 if (N1.getOpcode() == ISD::FP_EXTEND) {
19019 SDValue N10 = N1.getOperand(0);
19020 if (isContractableFMUL(N10) &&
19021 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19022 N10.getValueType())) {
19023 return DAG.getNode(
19024 PreferredFusedOpcode, SL, VT,
19025 DAG.getNode(ISD::FNEG, SL, VT,
19026 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))),
19027 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0);
19028 }
19029 }
19030
19031 // fold (fsub (fpext (fneg (fmul, x, y))), z)
19032 // -> (fneg (fma (fpext x), (fpext y), z))
19033 // Note: This could be removed with appropriate canonicalization of the
19034 // input expression into (fneg (fadd (fpext (fmul, x, y)), z)). However, the
19035 // command line flag -fp-contract=fast and fast-math flag contract prevent
19036 // from implementing the canonicalization in visitFSUB.
19037 if (N0.getOpcode() == ISD::FP_EXTEND) {
19038 SDValue N00 = N0.getOperand(0);
19039 if (N00.getOpcode() == ISD::FNEG) {
19040 SDValue N000 = N00.getOperand(0);
19041 if (isContractableFMUL(N000) &&
19042 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19043 N00.getValueType())) {
19044 return DAG.getNode(
19045 ISD::FNEG, SL, VT,
19046 DAG.getNode(PreferredFusedOpcode, SL, VT,
19047 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
19048 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
19049 N1));
19050 }
19051 }
19052 }
19053
19054 // fold (fsub (fneg (fpext (fmul, x, y))), z)
19055 // -> (fneg (fma (fpext x)), (fpext y), z)
19056 // Note: This could be removed with appropriate canonicalization of the
19057 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
19058 // command line flag -fp-contract=fast and fast-math flag contract prevent
19059 // from implementing the canonicalization in visitFSUB.
19060 if (N0.getOpcode() == ISD::FNEG) {
19061 SDValue N00 = N0.getOperand(0);
19062 if (N00.getOpcode() == ISD::FP_EXTEND) {
19063 SDValue N000 = N00.getOperand(0);
19064 if (isContractableFMUL(N000) &&
19065 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19066 N000.getValueType())) {
19067 return DAG.getNode(
19068 ISD::FNEG, SL, VT,
19069 DAG.getNode(PreferredFusedOpcode, SL, VT,
19070 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
19071 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
19072 N1));
19073 }
19074 }
19075 }
19076
19077 auto isContractableAndReassociableFMUL = [&isContractableFMUL](SDValue N) {
19078 return isContractableFMUL(N) && N->getFlags().hasAllowReassociation();
19079 };
19080
19081 auto isFusedOp = [&](SDValue N) {
19082 unsigned Opcode = N.getOpcode();
19083 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
19084 };
19085
19086 // More folding opportunities when target permits.
19087 if (Aggressive && N->getFlags().hasAllowReassociation()) {
19088 bool CanFuse = N->getFlags().hasAllowContract();
19089 // fold (fsub (fma x, y, (fmul u, v)), z)
19090 // -> (fma x, y (fma u, v, (fneg z)))
19091 if (CanFuse && isFusedOp(N0) &&
19092 isContractableAndReassociableFMUL(N0.getOperand(2)) &&
19093 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
19094 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
19095 N0.getOperand(1),
19096 DAG.getNode(PreferredFusedOpcode, SL, VT,
19097 N0.getOperand(2).getOperand(0),
19098 N0.getOperand(2).getOperand(1),
19099 DAG.getNode(ISD::FNEG, SL, VT, N1)));
19100 }
19101
19102 // fold (fsub x, (fma y, z, (fmul u, v)))
19103 // -> (fma (fneg y), z, (fma (fneg u), v, x))
19104 if (CanFuse && isFusedOp(N1) &&
19105 isContractableAndReassociableFMUL(N1.getOperand(2)) &&
19106 N1->hasOneUse() && NoSignedZero) {
19107 SDValue N20 = N1.getOperand(2).getOperand(0);
19108 SDValue N21 = N1.getOperand(2).getOperand(1);
19109 return DAG.getNode(
19110 PreferredFusedOpcode, SL, VT,
19111 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
19112 DAG.getNode(PreferredFusedOpcode, SL, VT,
19113 DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0));
19114 }
19115
19116 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
19117 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
19118 if (isFusedOp(N0) && N0->hasOneUse()) {
19119 SDValue N02 = N0.getOperand(2);
19120 if (N02.getOpcode() == ISD::FP_EXTEND) {
19121 SDValue N020 = N02.getOperand(0);
19122 if (isContractableAndReassociableFMUL(N020) &&
19123 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19124 N020.getValueType())) {
19125 return DAG.getNode(
19126 PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1),
19127 DAG.getNode(
19128 PreferredFusedOpcode, SL, VT,
19129 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)),
19130 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)),
19131 DAG.getNode(ISD::FNEG, SL, VT, N1)));
19132 }
19133 }
19134 }
19135
19136 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
19137 // -> (fma (fpext x), (fpext y),
19138 // (fma (fpext u), (fpext v), (fneg z)))
19139 // FIXME: This turns two single-precision and one double-precision
19140 // operation into two double-precision operations, which might not be
19141 // interesting for all targets, especially GPUs.
19142 if (N0.getOpcode() == ISD::FP_EXTEND) {
19143 SDValue N00 = N0.getOperand(0);
19144 if (isFusedOp(N00)) {
19145 SDValue N002 = N00.getOperand(2);
19146 if (isContractableAndReassociableFMUL(N002) &&
19147 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19148 N00.getValueType())) {
19149 return DAG.getNode(
19150 PreferredFusedOpcode, SL, VT,
19151 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
19152 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
19153 DAG.getNode(
19154 PreferredFusedOpcode, SL, VT,
19155 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)),
19156 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)),
19157 DAG.getNode(ISD::FNEG, SL, VT, N1)));
19158 }
19159 }
19160 }
19161
19162 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
19163 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
19164 if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
19165 N1->hasOneUse()) {
19166 SDValue N120 = N1.getOperand(2).getOperand(0);
19167 if (isContractableAndReassociableFMUL(N120) &&
19168 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19169 N120.getValueType())) {
19170 SDValue N1200 = N120.getOperand(0);
19171 SDValue N1201 = N120.getOperand(1);
19172 return DAG.getNode(
19173 PreferredFusedOpcode, SL, VT,
19174 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
19175 DAG.getNode(PreferredFusedOpcode, SL, VT,
19176 DAG.getNode(ISD::FNEG, SL, VT,
19177 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)),
19178 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0));
19179 }
19180 }
19181
19182 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
19183 // -> (fma (fneg (fpext y)), (fpext z),
19184 // (fma (fneg (fpext u)), (fpext v), x))
19185 // FIXME: This turns two single-precision and one double-precision
19186 // operation into two double-precision operations, which might not be
19187 // interesting for all targets, especially GPUs.
19188 if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) {
19189 SDValue CvtSrc = N1.getOperand(0);
19190 SDValue N100 = CvtSrc.getOperand(0);
19191 SDValue N101 = CvtSrc.getOperand(1);
19192 SDValue N102 = CvtSrc.getOperand(2);
19193 if (isContractableAndReassociableFMUL(N102) &&
19194 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
19195 CvtSrc.getValueType())) {
19196 SDValue N1020 = N102.getOperand(0);
19197 SDValue N1021 = N102.getOperand(1);
19198 return DAG.getNode(
19199 PreferredFusedOpcode, SL, VT,
19200 DAG.getNode(ISD::FNEG, SL, VT,
19201 DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)),
19202 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
19203 DAG.getNode(PreferredFusedOpcode, SL, VT,
19204 DAG.getNode(ISD::FNEG, SL, VT,
19205 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)),
19206 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0));
19207 }
19208 }
19209 }
19210
19211 return SDValue();
19212}
19213
19214/// Try to perform FMA combining on a given FMUL node based on the distributive
19215/// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
19216/// subtraction instead of addition).
19217SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
19218 SDValue N0 = N->getOperand(0);
19219 SDValue N1 = N->getOperand(1);
19220 EVT VT = N->getValueType(0);
19221 SDLoc SL(N);
19222
19223 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
19224
19225 // The transforms below are incorrect when x == 0 and y == inf, because the
19226 // intermediate multiplication produces a nan.
19227 SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1;
19228 if (!FAdd->getFlags().hasNoInfs())
19229 return SDValue();
19230
19231 // Floating-point multiply-add without intermediate rounding.
19232 bool HasFMA =
19234 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
19236
19237 // Floating-point multiply-add with intermediate rounding. This can result
19238 // in a less precise result due to the changed rounding order.
19239 bool HasFMAD = LegalOperations && TLI.isFMADLegal(DAG, N);
19240
19241 // No valid opcode, do not combine.
19242 if (!HasFMAD && !HasFMA)
19243 return SDValue();
19244
19245 // Always prefer FMAD to FMA for precision.
19246 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
19248
19249 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
19250 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
19251 auto FuseFADD = [&](SDValue X, SDValue Y) {
19252 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
19253 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
19254 if (C->isOne())
19255 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19256 Y);
19257 if (C->isMinusOne())
19258 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19259 DAG.getNode(ISD::FNEG, SL, VT, Y));
19260 }
19261 }
19262 return SDValue();
19263 };
19264
19265 if (SDValue FMA = FuseFADD(N0, N1))
19266 return FMA;
19267 if (SDValue FMA = FuseFADD(N1, N0))
19268 return FMA;
19269
19270 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
19271 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
19272 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
19273 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
19274 auto FuseFSUB = [&](SDValue X, SDValue Y) {
19275 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
19276 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
19277 if (C0->isOne())
19278 return DAG.getNode(PreferredFusedOpcode, SL, VT,
19279 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
19280 Y);
19281 if (C0->isMinusOne())
19282 return DAG.getNode(PreferredFusedOpcode, SL, VT,
19283 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
19284 DAG.getNode(ISD::FNEG, SL, VT, Y));
19285 }
19286 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
19287 if (C1->isOne())
19288 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19289 DAG.getNode(ISD::FNEG, SL, VT, Y));
19290 if (C1->isMinusOne())
19291 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19292 Y);
19293 }
19294 }
19295 return SDValue();
19296 };
19297
19298 if (SDValue FMA = FuseFSUB(N0, N1))
19299 return FMA;
19300 if (SDValue FMA = FuseFSUB(N1, N0))
19301 return FMA;
19302
19303 return SDValue();
19304}
19305
19306SDValue DAGCombiner::visitFADD(SDNode *N) {
19307 SDValue N0 = N->getOperand(0);
19308 SDValue N1 = N->getOperand(1);
19309 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0);
19310 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1);
19311 EVT VT = N->getValueType(0);
19312 SDLoc DL(N);
19313 SDNodeFlags Flags = N->getFlags();
19314 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19315
19316 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19317 return R;
19318
19319 // fold (fadd c1, c2) -> c1 + c2
19320 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FADD, DL, VT, {N0, N1}))
19321 return C;
19322
19323 // canonicalize constant to RHS
19324 if (N0CFP && !N1CFP)
19325 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
19326
19327 // fold vector ops
19328 if (VT.isVector())
19329 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19330 return FoldedVOp;
19331
19332 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
19333 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
19334 if (N1C && N1C->isZero())
19335 if (N1C->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0)))
19336 return N0;
19337
19338 if (SDValue NewSel = foldBinOpIntoSelect(N))
19339 return NewSel;
19340
19341 // fold (fadd A, (fneg B)) -> (fsub A, B)
19342 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
19343 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
19344 N1, DAG, LegalOperations, ForCodeSize))
19345 return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1);
19346
19347 // fold (fadd (fneg A), B) -> (fsub B, A)
19348 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
19349 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
19350 N0, DAG, LegalOperations, ForCodeSize))
19351 return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0);
19352
19353 auto isFMulNegTwo = [](SDValue FMul) {
19354 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
19355 return false;
19356 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
19357 return C && C->isExactlyValue(-2.0);
19358 };
19359
19360 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
19361 if (isFMulNegTwo(N0)) {
19362 SDValue B = N0.getOperand(0);
19363 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
19364 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add);
19365 }
19366 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
19367 if (isFMulNegTwo(N1)) {
19368 SDValue B = N1.getOperand(0);
19369 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
19370 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add);
19371 }
19372
19373 // No FP constant should be created after legalization as Instruction
19374 // Selection pass has a hard time dealing with FP constants.
19375 bool AllowNewConst = (Level < AfterLegalizeDAG);
19376
19377 // If nnan is enabled, fold lots of things.
19378 if (Flags.hasNoNaNs() && AllowNewConst) {
19379 // If allowed, fold (fadd (fneg x), x) -> 0.0
19380 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
19381 return DAG.getConstantFP(0.0, DL, VT);
19382
19383 // If allowed, fold (fadd x, (fneg x)) -> 0.0
19384 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
19385 return DAG.getConstantFP(0.0, DL, VT);
19386 }
19387
19388 // If reassoc and nsz, fold lots of things.
19389 // TODO: break out portions of the transformations below for which Unsafe is
19390 // considered and which do not require both nsz and reassoc
19391 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
19392 AllowNewConst) {
19393 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
19394 if (N1CFP && N0.getOpcode() == ISD::FADD &&
19396 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1);
19397 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC);
19398 }
19399
19400 // We can fold chains of FADD's of the same value into multiplications.
19401 // This transform is not safe in general because we are reducing the number
19402 // of rounding steps.
19403 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
19404 if (N0.getOpcode() == ISD::FMUL) {
19405 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
19406 bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
19407
19408 // (fadd (fmul x, c), x) -> (fmul x, c+1)
19409 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
19410 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
19411 DAG.getConstantFP(1.0, DL, VT));
19412 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
19413 }
19414
19415 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
19416 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
19417 N1.getOperand(0) == N1.getOperand(1) &&
19418 N0.getOperand(0) == N1.getOperand(0)) {
19419 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
19420 DAG.getConstantFP(2.0, DL, VT));
19421 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
19422 }
19423 }
19424
19425 if (N1.getOpcode() == ISD::FMUL) {
19426 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
19427 bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
19428
19429 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
19430 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
19431 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
19432 DAG.getConstantFP(1.0, DL, VT));
19433 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
19434 }
19435
19436 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
19437 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
19438 N0.getOperand(0) == N0.getOperand(1) &&
19439 N1.getOperand(0) == N0.getOperand(0)) {
19440 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
19441 DAG.getConstantFP(2.0, DL, VT));
19442 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
19443 }
19444 }
19445
19446 if (N0.getOpcode() == ISD::FADD) {
19447 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
19448 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
19449 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
19450 (N0.getOperand(0) == N1)) {
19451 return DAG.getNode(ISD::FMUL, DL, VT, N1,
19452 DAG.getConstantFP(3.0, DL, VT));
19453 }
19454 }
19455
19456 if (N1.getOpcode() == ISD::FADD) {
19457 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
19458 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
19459 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
19460 N1.getOperand(0) == N0) {
19461 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19462 DAG.getConstantFP(3.0, DL, VT));
19463 }
19464 }
19465
19466 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
19467 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
19468 N0.getOperand(0) == N0.getOperand(1) &&
19469 N1.getOperand(0) == N1.getOperand(1) &&
19470 N0.getOperand(0) == N1.getOperand(0)) {
19471 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
19472 DAG.getConstantFP(4.0, DL, VT));
19473 }
19474 }
19475 } // reassoc && nsz && AllowNewConst
19476
19477 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros()) {
19478 // Fold fadd(vecreduce(x), vecreduce(y)) -> vecreduce(fadd(x, y))
19479 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FADD, ISD::FADD, DL,
19480 VT, N0, N1, Flags))
19481 return SD;
19482 }
19483
19484 // FADD -> FMA combines:
19485 if (SDValue Fused = visitFADDForFMACombine(N)) {
19486 if (Fused.getOpcode() != ISD::DELETED_NODE)
19487 AddToWorklist(Fused.getNode());
19488 return Fused;
19489 }
19490 return SDValue();
19491}
19492
19493SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) {
19494 SDValue Chain = N->getOperand(0);
19495 SDValue N0 = N->getOperand(1);
19496 SDValue N1 = N->getOperand(2);
19497 EVT VT = N->getValueType(0);
19498 EVT ChainVT = N->getValueType(1);
19499 SDLoc DL(N);
19500 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19501
19502 // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B)
19503 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
19504 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
19505 N1, DAG, LegalOperations, ForCodeSize)) {
19506 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
19507 {Chain, N0, NegN1});
19508 }
19509
19510 // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A)
19511 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
19512 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
19513 N0, DAG, LegalOperations, ForCodeSize)) {
19514 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
19515 {Chain, N1, NegN0});
19516 }
19517 return SDValue();
19518}
19519
19520SDValue DAGCombiner::visitFSUB(SDNode *N) {
19521 SDValue N0 = N->getOperand(0);
19522 SDValue N1 = N->getOperand(1);
19523 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
19524 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19525 EVT VT = N->getValueType(0);
19526 SDLoc DL(N);
19527 const SDNodeFlags Flags = N->getFlags();
19528 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19529
19530 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19531 return R;
19532
19533 // fold (fsub c1, c2) -> c1-c2
19534 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FSUB, DL, VT, {N0, N1}))
19535 return C;
19536
19537 // fold vector ops
19538 if (VT.isVector())
19539 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19540 return FoldedVOp;
19541
19542 if (SDValue NewSel = foldBinOpIntoSelect(N))
19543 return NewSel;
19544
19545 // (fsub A, 0) -> A
19546 if (N1CFP && N1CFP->isZero()) {
19547 if (!N1CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19548 return N0;
19549 }
19550 }
19551
19552 if (N0 == N1) {
19553 // (fsub x, x) -> 0.0
19554 if (Flags.hasNoNaNs())
19555 return DAG.getConstantFP(0.0f, DL, VT);
19556 }
19557
19558 // (fsub -0.0, N1) -> -N1
19559 if (N0CFP && N0CFP->isZero()) {
19560 if (N0CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19561 // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are
19562 // flushed to zero, unless all users treat denorms as zero (DAZ).
19563 // FIXME: This transform will change the sign of a NaN and the behavior
19564 // of a signaling NaN. It is only valid when a NoNaN flag is present.
19565 DenormalMode DenormMode = DAG.getDenormalMode(VT);
19566 if (DenormMode == DenormalMode::getIEEE()) {
19567 if (SDValue NegN1 =
19568 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19569 return NegN1;
19570 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
19571 return DAG.getNode(ISD::FNEG, DL, VT, N1);
19572 }
19573 }
19574 }
19575
19576 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
19577 N1.getOpcode() == ISD::FADD) {
19578 // X - (X + Y) -> -Y
19579 if (N0 == N1->getOperand(0))
19580 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1));
19581 // X - (Y + X) -> -Y
19582 if (N0 == N1->getOperand(1))
19583 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0));
19584 }
19585
19586 // fold (fsub A, (fneg B)) -> (fadd A, B)
19587 if (SDValue NegN1 =
19588 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19589 return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1);
19590
19591 // FSUB -> FMA combines:
19592 if (SDValue Fused = visitFSUBForFMACombine(N)) {
19593 AddToWorklist(Fused.getNode());
19594 return Fused;
19595 }
19596
19597 return SDValue();
19598}
19599
19600// Transform IEEE Floats:
19601// (fmul C, (uitofp Pow2))
19602// -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
19603// (fdiv C, (uitofp Pow2))
19604// -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
19605//
19606// The rationale is fmul/fdiv by a power of 2 is just change the exponent, so
19607// there is no need for more than an add/sub.
19608//
19609// This is valid under the following circumstances:
19610// 1) We are dealing with IEEE floats
19611// 2) C is normal
19612// 3) The fmul/fdiv add/sub will not go outside of min/max exponent bounds.
19613// TODO: Much of this could also be used for generating `ldexp` on targets the
19614// prefer it.
19615SDValue DAGCombiner::combineFMulOrFDivWithIntPow2(SDNode *N) {
19616 EVT VT = N->getValueType(0);
19618 return SDValue();
19619
19620 SDValue ConstOp, Pow2Op;
19621
19622 std::optional<int> Mantissa;
19623 auto GetConstAndPow2Ops = [&](unsigned ConstOpIdx) {
19624 if (ConstOpIdx == 1 && N->getOpcode() == ISD::FDIV)
19625 return false;
19626
19627 ConstOp = peekThroughBitcasts(N->getOperand(ConstOpIdx));
19628 Pow2Op = N->getOperand(1 - ConstOpIdx);
19629 unsigned Pow2Opc = Pow2Op.getOpcode();
19630 if (Pow2Opc != ISD::UINT_TO_FP && Pow2Opc != ISD::SINT_TO_FP)
19631 return false;
19632
19633 Pow2Op = Pow2Op.getOperand(0);
19634
19635 KnownBits Pow2OpKnownBits = DAG.computeKnownBits(Pow2Op);
19636 if (Pow2Opc == ISD::SINT_TO_FP && !Pow2OpKnownBits.isNonNegative())
19637 return false;
19638
19639 int MaxExpChange = Pow2OpKnownBits.countMaxActiveBits();
19640
19641 auto IsFPConstValid = [N, MaxExpChange, &Mantissa](ConstantFPSDNode *CFP) {
19642 if (CFP == nullptr)
19643 return false;
19644
19645 const APFloat &APF = CFP->getValueAPF();
19646
19647 // Make sure we have normal constant.
19648 if (!APF.isNormal())
19649 return false;
19650
19651 // Make sure the floats exponent is within the bounds that this transform
19652 // produces bitwise equals value.
19653 int CurExp = ilogb(APF);
19654 // FMul by pow2 will only increase exponent.
19655 int MinExp =
19656 N->getOpcode() == ISD::FMUL ? CurExp : (CurExp - MaxExpChange);
19657 // FDiv by pow2 will only decrease exponent.
19658 int MaxExp =
19659 N->getOpcode() == ISD::FDIV ? CurExp : (CurExp + MaxExpChange);
19660 if (MinExp <= APFloat::semanticsMinExponent(APF.getSemantics()) ||
19662 return false;
19663
19664 // Finally make sure we actually know the mantissa for the float type.
19665 int ThisMantissa = APFloat::semanticsPrecision(APF.getSemantics()) - 1;
19666 if (!Mantissa)
19667 Mantissa = ThisMantissa;
19668
19669 return *Mantissa == ThisMantissa && ThisMantissa > 0;
19670 };
19671
19672 // TODO: We may be able to include undefs.
19673 return ISD::matchUnaryFpPredicate(ConstOp, IsFPConstValid);
19674 };
19675
19676 if (!GetConstAndPow2Ops(0) && !GetConstAndPow2Ops(1))
19677 return SDValue();
19678
19679 if (!TLI.optimizeFMulOrFDivAsShiftAddBitcast(N, ConstOp, Pow2Op))
19680 return SDValue();
19681
19682 // Get log2 after all other checks have taken place. This is because
19683 // BuildLogBase2 may create a new node.
19684 SDLoc DL(N);
19685 // Get Log2 type with same bitwidth as the float type (VT).
19686 EVT NewIntVT = VT.changeElementType(
19687 *DAG.getContext(),
19689
19690 SDValue Log2 = BuildLogBase2(Pow2Op, DL, DAG.isKnownNeverZero(Pow2Op),
19691 /*InexpensiveOnly*/ true, NewIntVT);
19692 if (!Log2)
19693 return SDValue();
19694
19695 // Perform actual transform.
19696 SDValue MantissaShiftCnt =
19697 DAG.getShiftAmountConstant(*Mantissa, NewIntVT, DL);
19698 // TODO: Sometimes Log2 is of form `(X + C)`. `(X + C) << C1` should fold to
19699 // `(X << C1) + (C << C1)`, but that isn't always the case because of the
19700 // cast. We could implement that by handle here to handle the casts.
19701 SDValue Shift = DAG.getNode(ISD::SHL, DL, NewIntVT, Log2, MantissaShiftCnt);
19702 SDValue ResAsInt =
19703 DAG.getNode(N->getOpcode() == ISD::FMUL ? ISD::ADD : ISD::SUB, DL,
19704 NewIntVT, DAG.getBitcast(NewIntVT, ConstOp), Shift);
19705 SDValue ResAsFP = DAG.getBitcast(VT, ResAsInt);
19706 return ResAsFP;
19707}
19708
19709SDValue DAGCombiner::visitFMUL(SDNode *N) {
19710 SDValue N0 = N->getOperand(0);
19711 SDValue N1 = N->getOperand(1);
19712 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19713 EVT VT = N->getValueType(0);
19714 SDLoc DL(N);
19715 const SDNodeFlags Flags = N->getFlags();
19716 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19717
19718 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19719 return R;
19720
19721 // fold (fmul c1, c2) -> c1*c2
19722 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMUL, DL, VT, {N0, N1}))
19723 return C;
19724
19725 // canonicalize constant to RHS
19728 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
19729
19730 // fold vector ops
19731 if (VT.isVector())
19732 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19733 return FoldedVOp;
19734
19735 if (SDValue NewSel = foldBinOpIntoSelect(N))
19736 return NewSel;
19737
19738 if (Flags.hasAllowReassociation()) {
19739 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
19741 N0.getOpcode() == ISD::FMUL) {
19742 SDValue N00 = N0.getOperand(0);
19743 SDValue N01 = N0.getOperand(1);
19744 // Avoid an infinite loop by making sure that N00 is not a constant
19745 // (the inner multiply has not been constant folded yet).
19748 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
19749 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
19750 }
19751 }
19752
19753 // Match a special-case: we convert X * 2.0 into fadd.
19754 // fmul (fadd X, X), C -> fmul X, 2.0 * C
19755 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
19756 N0.getOperand(0) == N0.getOperand(1)) {
19757 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
19758 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
19759 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
19760 }
19761
19762 // Fold fmul(vecreduce(x), vecreduce(y)) -> vecreduce(fmul(x, y))
19763 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FMUL, ISD::FMUL, DL,
19764 VT, N0, N1, Flags))
19765 return SD;
19766 }
19767
19768 // fold (fmul X, 2.0) -> (fadd X, X)
19769 if (N1CFP && N1CFP->isExactlyValue(+2.0))
19770 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
19771
19772 // fold (fmul X, -1.0) -> (fsub -0.0, X)
19773 if (N1CFP && N1CFP->isMinusOne()) {
19774 if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) {
19775 return DAG.getNode(ISD::FSUB, DL, VT,
19776 DAG.getConstantFP(-0.0, DL, VT), N0, Flags);
19777 }
19778 }
19779
19780 // -N0 * -N1 --> N0 * N1
19785 SDValue NegN0 =
19786 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19787 if (NegN0) {
19788 HandleSDNode NegN0Handle(NegN0);
19789 SDValue NegN1 =
19790 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19791 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19793 return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1);
19794 }
19795
19796 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
19797 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
19798 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
19799 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
19800 TLI.isOperationLegal(ISD::FABS, VT)) {
19801 SDValue Select = N0, X = N1;
19802 if (Select.getOpcode() != ISD::SELECT)
19803 std::swap(Select, X);
19804
19805 SDValue Cond = Select.getOperand(0);
19806 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
19807 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
19808
19809 if (TrueOpnd && FalseOpnd && Cond.getOpcode() == ISD::SETCC &&
19810 Cond.getOperand(0) == X && isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
19811 cast<ConstantFPSDNode>(Cond.getOperand(1))->isPosZero()) {
19812 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19813 switch (CC) {
19814 default: break;
19815 case ISD::SETOLT:
19816 case ISD::SETULT:
19817 case ISD::SETOLE:
19818 case ISD::SETULE:
19819 case ISD::SETLT:
19820 case ISD::SETLE:
19821 std::swap(TrueOpnd, FalseOpnd);
19822 [[fallthrough]];
19823 case ISD::SETOGT:
19824 case ISD::SETUGT:
19825 case ISD::SETOGE:
19826 case ISD::SETUGE:
19827 case ISD::SETGT:
19828 case ISD::SETGE:
19829 if (TrueOpnd->isMinusOne() && FalseOpnd->isOne() &&
19830 TLI.isOperationLegal(ISD::FNEG, VT))
19831 return DAG.getNode(ISD::FNEG, DL, VT,
19832 DAG.getNode(ISD::FABS, DL, VT, X));
19833 if (TrueOpnd->isOne() && FalseOpnd->isMinusOne())
19834 return DAG.getNode(ISD::FABS, DL, VT, X);
19835
19836 break;
19837 }
19838 }
19839 }
19840
19841 // FMUL -> FMA combines:
19842 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
19843 AddToWorklist(Fused.getNode());
19844 return Fused;
19845 }
19846
19847 // Don't do `combineFMulOrFDivWithIntPow2` until after FMUL -> FMA has been
19848 // able to run.
19849 if (SDValue R = combineFMulOrFDivWithIntPow2(N))
19850 return R;
19851
19852 return SDValue();
19853}
19854
19855SDValue DAGCombiner::visitFMA(SDNode *N) {
19856 SDValue N0 = N->getOperand(0);
19857 SDValue N1 = N->getOperand(1);
19858 SDValue N2 = N->getOperand(2);
19859 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
19860 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
19861 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
19862 EVT VT = N->getValueType(0);
19863 SDLoc DL(N);
19864 // FMA nodes have flags that propagate to the created nodes.
19865 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19866
19867 // Constant fold FMA.
19868 if (SDValue C =
19869 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
19870 return C;
19871
19872 // (-N0 * -N1) + N2 --> (N0 * N1) + N2
19877 SDValue NegN0 =
19878 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19879 if (NegN0) {
19880 HandleSDNode NegN0Handle(NegN0);
19881 SDValue NegN1 =
19882 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19883 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19885 return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2);
19886 }
19887
19888 if (N->getFlags().hasNoNaNs() && N->getFlags().hasNoInfs()) {
19889 if (N->getFlags().hasNoSignedZeros() || (N2CFP && !N2CFP->isNegZero())) {
19890 if (N0CFP && N0CFP->isZero())
19891 return N2;
19892 if (N1CFP && N1CFP->isZero())
19893 return N2;
19894 }
19895 }
19896
19897 if (N0CFP && N0CFP->isOne())
19898 return DAG.getNode(ISD::FADD, DL, VT, N1, N2);
19899 if (N1CFP && N1CFP->isOne())
19900 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19901
19902 // Canonicalize (fma c, x, y) -> (fma x, c, y)
19905 return DAG.getNode(ISD::FMA, DL, VT, N1, N0, N2);
19906
19907 bool CanReassociate = N->getFlags().hasAllowReassociation();
19908 if (CanReassociate) {
19909 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
19910 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
19913 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19914 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1)));
19915 }
19916
19917 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
19918 if (N0.getOpcode() == ISD::FMUL &&
19921 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19922 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)),
19923 N2);
19924 }
19925 }
19926
19927 // (fma x, -1, y) -> (fadd (fneg x), y)
19928 if (N1CFP) {
19929 if (N1CFP->isOne())
19930 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19931
19932 if (N1CFP->isMinusOne() &&
19933 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
19934 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
19935 AddToWorklist(RHSNeg.getNode());
19936 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
19937 }
19938
19939 // fma (fneg x), K, y -> fma x -K, y
19940 if (N0.getOpcode() == ISD::FNEG &&
19942 (N1.hasOneUse() &&
19943 !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, ForCodeSize)))) {
19944 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19945 DAG.getNode(ISD::FNEG, DL, VT, N1), N2);
19946 }
19947 }
19948
19949 if (CanReassociate) {
19950 // (fma x, c, x) -> (fmul x, (c+1))
19951 if (N1CFP && N0 == N2) {
19952 return DAG.getNode(
19953 ISD::FMUL, DL, VT, N0,
19954 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT)));
19955 }
19956
19957