LLVM  9.0.0svn
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/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constant.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/KnownBits.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <functional>
71 #include <iterator>
72 #include <string>
73 #include <tuple>
74 #include <utility>
75 
76 using namespace llvm;
77 
78 #define DEBUG_TYPE "dagcombine"
79 
80 STATISTIC(NodesCombined , "Number of dag nodes combined");
81 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
82 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
83 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
84 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
85 STATISTIC(SlicedLoads, "Number of load sliced");
86 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
87 
88 static cl::opt<bool>
89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
90  cl::desc("Enable DAG combiner's use of IR alias analysis"));
91 
92 static cl::opt<bool>
93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
94  cl::desc("Enable DAG combiner's use of TBAA"));
95 
96 #ifndef NDEBUG
98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
99  cl::desc("Only use DAG-combiner alias analysis in this"
100  " function"));
101 #endif
102 
103 /// Hidden option to stress test load slicing, i.e., when this option
104 /// is enabled, load slicing bypasses most of its profitability guards.
105 static cl::opt<bool>
106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
107  cl::desc("Bypass the profitability model of load slicing"),
108  cl::init(false));
109 
110 static cl::opt<bool>
111  MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
112  cl::desc("DAG combiner may split indexing from loads"));
113 
114 namespace {
115 
116  class DAGCombiner {
117  SelectionDAG &DAG;
118  const TargetLowering &TLI;
120  CodeGenOpt::Level OptLevel;
121  bool LegalOperations = false;
122  bool LegalTypes = false;
123  bool ForCodeSize;
124 
125  /// Worklist of all of the nodes that need to be simplified.
126  ///
127  /// This must behave as a stack -- new nodes to process are pushed onto the
128  /// back and when processing we pop off of the back.
129  ///
130  /// The worklist will not contain duplicates but may contain null entries
131  /// due to nodes being deleted from the underlying DAG.
132  SmallVector<SDNode *, 64> Worklist;
133 
134  /// Mapping from an SDNode to its position on the worklist.
135  ///
136  /// This is used to find and remove nodes from the worklist (by nulling
137  /// them) when they are deleted from the underlying DAG. It relies on
138  /// stable indices of nodes within the worklist.
139  DenseMap<SDNode *, unsigned> WorklistMap;
140 
141  /// Set of nodes which have been combined (at least once).
142  ///
143  /// This is used to allow us to reliably add any operands of a DAG node
144  /// which have not yet been combined to the worklist.
145  SmallPtrSet<SDNode *, 32> CombinedNodes;
146 
147  // AA - Used for DAG load/store alias analysis.
148  AliasAnalysis *AA;
149 
150  /// When an instruction is simplified, add all users of the instruction to
151  /// the work lists because they might get more simplified now.
152  void AddUsersToWorklist(SDNode *N) {
153  for (SDNode *Node : N->uses())
154  AddToWorklist(Node);
155  }
156 
157  /// Call the node-specific routine that folds each particular type of node.
158  SDValue visit(SDNode *N);
159 
160  public:
161  DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
162  : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
163  OptLevel(OL), AA(AA) {
164  ForCodeSize = DAG.getMachineFunction().getFunction().optForSize();
165 
166  MaximumLegalStoreInBits = 0;
167  for (MVT VT : MVT::all_valuetypes())
168  if (EVT(VT).isSimple() && VT != MVT::Other &&
169  TLI.isTypeLegal(EVT(VT)) &&
170  VT.getSizeInBits() >= MaximumLegalStoreInBits)
171  MaximumLegalStoreInBits = VT.getSizeInBits();
172  }
173 
174  /// Add to the worklist making sure its instance is at the back (next to be
175  /// processed.)
176  void AddToWorklist(SDNode *N) {
178  "Deleted Node added to Worklist");
179 
180  // Skip handle nodes as they can't usefully be combined and confuse the
181  // zero-use deletion strategy.
182  if (N->getOpcode() == ISD::HANDLENODE)
183  return;
184 
185  if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
186  Worklist.push_back(N);
187  }
188 
189  /// Remove all instances of N from the worklist.
190  void removeFromWorklist(SDNode *N) {
191  CombinedNodes.erase(N);
192 
193  auto It = WorklistMap.find(N);
194  if (It == WorklistMap.end())
195  return; // Not in the worklist.
196 
197  // Null out the entry rather than erasing it to avoid a linear operation.
198  Worklist[It->second] = nullptr;
199  WorklistMap.erase(It);
200  }
201 
202  void deleteAndRecombine(SDNode *N);
203  bool recursivelyDeleteUnusedNodes(SDNode *N);
204 
205  /// Replaces all uses of the results of one DAG node with new values.
206  SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
207  bool AddTo = true);
208 
209  /// Replaces all uses of the results of one DAG node with new values.
210  SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
211  return CombineTo(N, &Res, 1, AddTo);
212  }
213 
214  /// Replaces all uses of the results of one DAG node with new values.
215  SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
216  bool AddTo = true) {
217  SDValue To[] = { Res0, Res1 };
218  return CombineTo(N, To, 2, AddTo);
219  }
220 
221  void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
222 
223  private:
224  unsigned MaximumLegalStoreInBits;
225 
226  /// Check the specified integer node value to see if it can be simplified or
227  /// if things it uses can be simplified by bit propagation.
228  /// If so, return true.
229  bool SimplifyDemandedBits(SDValue Op) {
230  unsigned BitWidth = Op.getScalarValueSizeInBits();
231  APInt Demanded = APInt::getAllOnesValue(BitWidth);
232  return SimplifyDemandedBits(Op, Demanded);
233  }
234 
235  /// Check the specified vector node value to see if it can be simplified or
236  /// if things it uses can be simplified as it only uses some of the
237  /// elements. If so, return true.
238  bool SimplifyDemandedVectorElts(SDValue Op) {
239  unsigned NumElts = Op.getValueType().getVectorNumElements();
240  APInt Demanded = APInt::getAllOnesValue(NumElts);
241  return SimplifyDemandedVectorElts(Op, Demanded);
242  }
243 
244  bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
245  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded,
246  bool AssumeSingleUse = false);
247 
248  bool CombineToPreIndexedLoadStore(SDNode *N);
249  bool CombineToPostIndexedLoadStore(SDNode *N);
250  SDValue SplitIndexingFromLoad(LoadSDNode *LD);
251  bool SliceUpLoad(SDNode *N);
252 
253  // Scalars have size 0 to distinguish from singleton vectors.
254  SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
255  bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
256  bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
257 
258  /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
259  /// load.
260  ///
261  /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
262  /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
263  /// \param EltNo index of the vector element to load.
264  /// \param OriginalLoad load that EVE came from to be replaced.
265  /// \returns EVE on success SDValue() on failure.
266  SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
267  SDValue EltNo,
268  LoadSDNode *OriginalLoad);
269  void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
270  SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
271  SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
272  SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
273  SDValue PromoteIntBinOp(SDValue Op);
274  SDValue PromoteIntShiftOp(SDValue Op);
275  SDValue PromoteExtend(SDValue Op);
276  bool PromoteLoad(SDValue Op);
277 
278  /// Call the node-specific routine that knows how to fold each
279  /// particular type of node. If that doesn't do anything, try the
280  /// target-specific DAG combines.
281  SDValue combine(SDNode *N);
282 
283  // Visitation implementation - Implement dag node combining for different
284  // node types. The semantics are as follows:
285  // Return Value:
286  // SDValue.getNode() == 0 - No change was made
287  // SDValue.getNode() == N - N was replaced, is dead and has been handled.
288  // otherwise - N should be replaced by the returned Operand.
289  //
290  SDValue visitTokenFactor(SDNode *N);
291  SDValue visitMERGE_VALUES(SDNode *N);
292  SDValue visitADD(SDNode *N);
293  SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
294  SDValue visitSUB(SDNode *N);
295  SDValue visitADDSAT(SDNode *N);
296  SDValue visitSUBSAT(SDNode *N);
297  SDValue visitADDC(SDNode *N);
298  SDValue visitADDO(SDNode *N);
299  SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
300  SDValue visitSUBC(SDNode *N);
301  SDValue visitSUBO(SDNode *N);
302  SDValue visitADDE(SDNode *N);
303  SDValue visitADDCARRY(SDNode *N);
304  SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
305  SDValue visitSUBE(SDNode *N);
306  SDValue visitSUBCARRY(SDNode *N);
307  SDValue visitMUL(SDNode *N);
308  SDValue useDivRem(SDNode *N);
309  SDValue visitSDIV(SDNode *N);
310  SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
311  SDValue visitUDIV(SDNode *N);
312  SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
313  SDValue visitREM(SDNode *N);
314  SDValue visitMULHU(SDNode *N);
315  SDValue visitMULHS(SDNode *N);
316  SDValue visitSMUL_LOHI(SDNode *N);
317  SDValue visitUMUL_LOHI(SDNode *N);
318  SDValue visitMULO(SDNode *N);
319  SDValue visitIMINMAX(SDNode *N);
320  SDValue visitAND(SDNode *N);
321  SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
322  SDValue visitOR(SDNode *N);
323  SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
324  SDValue visitXOR(SDNode *N);
325  SDValue SimplifyVBinOp(SDNode *N);
326  SDValue visitSHL(SDNode *N);
327  SDValue visitSRA(SDNode *N);
328  SDValue visitSRL(SDNode *N);
329  SDValue visitFunnelShift(SDNode *N);
330  SDValue visitRotate(SDNode *N);
331  SDValue visitABS(SDNode *N);
332  SDValue visitBSWAP(SDNode *N);
333  SDValue visitBITREVERSE(SDNode *N);
334  SDValue visitCTLZ(SDNode *N);
335  SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
336  SDValue visitCTTZ(SDNode *N);
337  SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
338  SDValue visitCTPOP(SDNode *N);
339  SDValue visitSELECT(SDNode *N);
340  SDValue visitVSELECT(SDNode *N);
341  SDValue visitSELECT_CC(SDNode *N);
342  SDValue visitSETCC(SDNode *N);
343  SDValue visitSETCCCARRY(SDNode *N);
344  SDValue visitSIGN_EXTEND(SDNode *N);
345  SDValue visitZERO_EXTEND(SDNode *N);
346  SDValue visitANY_EXTEND(SDNode *N);
347  SDValue visitAssertExt(SDNode *N);
348  SDValue visitSIGN_EXTEND_INREG(SDNode *N);
349  SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
350  SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
351  SDValue visitTRUNCATE(SDNode *N);
352  SDValue visitBITCAST(SDNode *N);
353  SDValue visitBUILD_PAIR(SDNode *N);
354  SDValue visitFADD(SDNode *N);
355  SDValue visitFSUB(SDNode *N);
356  SDValue visitFMUL(SDNode *N);
357  SDValue visitFMA(SDNode *N);
358  SDValue visitFDIV(SDNode *N);
359  SDValue visitFREM(SDNode *N);
360  SDValue visitFSQRT(SDNode *N);
361  SDValue visitFCOPYSIGN(SDNode *N);
362  SDValue visitFPOW(SDNode *N);
363  SDValue visitSINT_TO_FP(SDNode *N);
364  SDValue visitUINT_TO_FP(SDNode *N);
365  SDValue visitFP_TO_SINT(SDNode *N);
366  SDValue visitFP_TO_UINT(SDNode *N);
367  SDValue visitFP_ROUND(SDNode *N);
368  SDValue visitFP_ROUND_INREG(SDNode *N);
369  SDValue visitFP_EXTEND(SDNode *N);
370  SDValue visitFNEG(SDNode *N);
371  SDValue visitFABS(SDNode *N);
372  SDValue visitFCEIL(SDNode *N);
373  SDValue visitFTRUNC(SDNode *N);
374  SDValue visitFFLOOR(SDNode *N);
375  SDValue visitFMINNUM(SDNode *N);
376  SDValue visitFMAXNUM(SDNode *N);
377  SDValue visitFMINIMUM(SDNode *N);
378  SDValue visitFMAXIMUM(SDNode *N);
379  SDValue visitBRCOND(SDNode *N);
380  SDValue visitBR_CC(SDNode *N);
381  SDValue visitLOAD(SDNode *N);
382 
383  SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
384  SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
385 
386  SDValue visitSTORE(SDNode *N);
387  SDValue visitLIFETIME_END(SDNode *N);
388  SDValue visitINSERT_VECTOR_ELT(SDNode *N);
389  SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
390  SDValue visitBUILD_VECTOR(SDNode *N);
391  SDValue visitCONCAT_VECTORS(SDNode *N);
392  SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
393  SDValue visitVECTOR_SHUFFLE(SDNode *N);
394  SDValue visitSCALAR_TO_VECTOR(SDNode *N);
395  SDValue visitINSERT_SUBVECTOR(SDNode *N);
396  SDValue visitMLOAD(SDNode *N);
397  SDValue visitMSTORE(SDNode *N);
398  SDValue visitMGATHER(SDNode *N);
399  SDValue visitMSCATTER(SDNode *N);
400  SDValue visitFP_TO_FP16(SDNode *N);
401  SDValue visitFP16_TO_FP(SDNode *N);
402  SDValue visitVECREDUCE(SDNode *N);
403 
404  SDValue visitFADDForFMACombine(SDNode *N);
405  SDValue visitFSUBForFMACombine(SDNode *N);
406  SDValue visitFMULForFMADistributiveCombine(SDNode *N);
407 
408  SDValue XformToShuffleWithZero(SDNode *N);
409  SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
410  SDValue N1, SDNodeFlags Flags);
411 
412  SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
413 
414  SDValue foldSelectOfConstants(SDNode *N);
415  SDValue foldVSelectOfConstants(SDNode *N);
416  SDValue foldBinOpIntoSelect(SDNode *BO);
417  bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
418  SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
419  SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
420  SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
421  SDValue N2, SDValue N3, ISD::CondCode CC,
422  bool NotExtCompare = false);
423  SDValue convertSelectOfFPConstantsToLoadOffset(
424  const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
425  ISD::CondCode CC);
426  SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
427  SDValue N2, SDValue N3, ISD::CondCode CC);
428  SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
429  const SDLoc &DL);
430  SDValue unfoldMaskedMerge(SDNode *N);
431  SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
432  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
433  const SDLoc &DL, bool foldBooleans);
434  SDValue rebuildSetCC(SDValue N);
435 
436  bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
437  SDValue &CC) const;
438  bool isOneUseSetCC(SDValue N) const;
439 
440  SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
441  unsigned HiOp);
442  SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
443  SDValue CombineExtLoad(SDNode *N);
444  SDValue CombineZExtLogicopShiftLoad(SDNode *N);
445  SDValue combineRepeatedFPDivisors(SDNode *N);
446  SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
447  SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
448  SDValue BuildSDIV(SDNode *N);
449  SDValue BuildSDIVPow2(SDNode *N);
450  SDValue BuildUDIV(SDNode *N);
451  SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
452  SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
453  SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
454  SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
455  SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
456  SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
457  SDNodeFlags Flags, bool Reciprocal);
458  SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
459  SDNodeFlags Flags, bool Reciprocal);
460  SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
461  bool DemandHighBits = true);
462  SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
463  SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
464  SDValue InnerPos, SDValue InnerNeg,
465  unsigned PosOpcode, unsigned NegOpcode,
466  const SDLoc &DL);
467  SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
468  SDValue MatchLoadCombine(SDNode *N);
469  SDValue ReduceLoadWidth(SDNode *N);
470  SDValue ReduceLoadOpStoreWidth(SDNode *N);
472  SDValue TransformFPLoadStorePair(SDNode *N);
473  SDValue convertBuildVecZextToZext(SDNode *N);
474  SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
475  SDValue reduceBuildVecToShuffle(SDNode *N);
476  SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
477  ArrayRef<int> VectorMask, SDValue VecIn1,
478  SDValue VecIn2, unsigned LeftIdx);
479  SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
480 
481  /// Walk up chain skipping non-aliasing memory nodes,
482  /// looking for aliasing nodes and adding them to the Aliases vector.
483  void GatherAllAliases(LSBaseSDNode *N, SDValue OriginalChain,
484  SmallVectorImpl<SDValue> &Aliases);
485 
486  /// Return true if there is any possibility that the two addresses overlap.
487  bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
488 
489  /// Walk up chain skipping non-aliasing memory nodes, looking for a better
490  /// chain (aliasing node.)
491  SDValue FindBetterChain(LSBaseSDNode *N, SDValue Chain);
492 
493  /// Try to replace a store and any possibly adjacent stores on
494  /// consecutive chains with better chains. Return true only if St is
495  /// replaced.
496  ///
497  /// Notice that other chains may still be replaced even if the function
498  /// returns false.
499  bool findBetterNeighborChains(StoreSDNode *St);
500 
501  // Helper for findBetterNeighborChains. Walk up store chain add additional
502  // chained stores that do not overlap and can be parallelized.
503  bool parallelizeChainedStores(StoreSDNode *St);
504 
505  /// Holds a pointer to an LSBaseSDNode as well as information on where it
506  /// is located in a sequence of memory operations connected by a chain.
507  struct MemOpLink {
508  // Ptr to the mem node.
509  LSBaseSDNode *MemNode;
510 
511  // Offset from the base ptr.
512  int64_t OffsetFromBase;
513 
514  MemOpLink(LSBaseSDNode *N, int64_t Offset)
515  : MemNode(N), OffsetFromBase(Offset) {}
516  };
517 
518  /// This is a helper function for visitMUL to check the profitability
519  /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
520  /// MulNode is the original multiply, AddNode is (add x, c1),
521  /// and ConstNode is c2.
522  bool isMulAddWithConstProfitable(SDNode *MulNode,
523  SDValue &AddNode,
524  SDValue &ConstNode);
525 
526  /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
527  /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
528  /// the type of the loaded value to be extended.
529  bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
530  EVT LoadResultTy, EVT &ExtVT);
531 
532  /// Helper function to calculate whether the given Load/Store can have its
533  /// width reduced to ExtVT.
534  bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
535  EVT &MemVT, unsigned ShAmt = 0);
536 
537  /// Used by BackwardsPropagateMask to find suitable loads.
538  bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
539  SmallPtrSetImpl<SDNode*> &NodesWithConsts,
540  ConstantSDNode *Mask, SDNode *&NodeToMask);
541  /// Attempt to propagate a given AND node back to load leaves so that they
542  /// can be combined into narrow loads.
543  bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
544 
545  /// Helper function for MergeConsecutiveStores which merges the
546  /// component store chains.
547  SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
548  unsigned NumStores);
549 
550  /// This is a helper function for MergeConsecutiveStores. When the
551  /// source elements of the consecutive stores are all constants or
552  /// all extracted vector elements, try to merge them into one
553  /// larger store introducing bitcasts if necessary. \return True
554  /// if a merged store was created.
555  bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
556  EVT MemVT, unsigned NumStores,
557  bool IsConstantSrc, bool UseVector,
558  bool UseTrunc);
559 
560  /// This is a helper function for MergeConsecutiveStores. Stores
561  /// that potentially may be merged with St are placed in
562  /// StoreNodes. RootNode is a chain predecessor to all store
563  /// candidates.
564  void getStoreMergeCandidates(StoreSDNode *St,
565  SmallVectorImpl<MemOpLink> &StoreNodes,
566  SDNode *&Root);
567 
568  /// Helper function for MergeConsecutiveStores. Checks if
569  /// candidate stores have indirect dependency through their
570  /// operands. RootNode is the predecessor to all stores calculated
571  /// by getStoreMergeCandidates and is used to prune the dependency check.
572  /// \return True if safe to merge.
573  bool checkMergeStoreCandidatesForDependencies(
574  SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
575  SDNode *RootNode);
576 
577  /// Merge consecutive store operations into a wide store.
578  /// This optimization uses wide integers or vectors when possible.
579  /// \return number of stores that were merged into a merged store (the
580  /// affected nodes are stored as a prefix in \p StoreNodes).
581  bool MergeConsecutiveStores(StoreSDNode *St);
582 
583  /// Try to transform a truncation where C is a constant:
584  /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
585  ///
586  /// \p N needs to be a truncation and its first operand an AND. Other
587  /// requirements are checked by the function (e.g. that trunc is
588  /// single-use) and if missed an empty SDValue is returned.
589  SDValue distributeTruncateThroughAnd(SDNode *N);
590 
591  /// Helper function to determine whether the target supports operation
592  /// given by \p Opcode for type \p VT, that is, whether the operation
593  /// is legal or custom before legalizing operations, and whether is
594  /// legal (but not custom) after legalization.
595  bool hasOperation(unsigned Opcode, EVT VT) {
596  if (LegalOperations)
597  return TLI.isOperationLegal(Opcode, VT);
598  return TLI.isOperationLegalOrCustom(Opcode, VT);
599  }
600 
601  public:
602  /// Runs the dag combiner on all nodes in the work list
603  void Run(CombineLevel AtLevel);
604 
605  SelectionDAG &getDAG() const { return DAG; }
606 
607  /// Returns a type large enough to hold any valid shift amount - before type
608  /// legalization these can be huge.
609  EVT getShiftAmountTy(EVT LHSTy) {
610  assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
611  return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
612  }
613 
614  /// This method returns true if we are running before type legalization or
615  /// if the specified VT is legal.
616  bool isTypeLegal(const EVT &VT) {
617  if (!LegalTypes) return true;
618  return TLI.isTypeLegal(VT);
619  }
620 
621  /// Convenience wrapper around TargetLowering::getSetCCResultType
622  EVT getSetCCResultType(EVT VT) const {
623  return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
624  }
625 
626  void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
627  SDValue OrigLoad, SDValue ExtLoad,
629  };
630 
631 /// This class is a DAGUpdateListener that removes any deleted
632 /// nodes from the worklist.
633 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
634  DAGCombiner &DC;
635 
636 public:
637  explicit WorklistRemover(DAGCombiner &dc)
638  : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
639 
640  void NodeDeleted(SDNode *N, SDNode *E) override {
641  DC.removeFromWorklist(N);
642  }
643 };
644 
645 } // end anonymous namespace
646 
647 //===----------------------------------------------------------------------===//
648 // TargetLowering::DAGCombinerInfo implementation
649 //===----------------------------------------------------------------------===//
650 
652  ((DAGCombiner*)DC)->AddToWorklist(N);
653 }
654 
656 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
657  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
658 }
659 
661 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
662  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
663 }
664 
666 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
667  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
668 }
669 
672  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
673 }
674 
675 //===----------------------------------------------------------------------===//
676 // Helper Functions
677 //===----------------------------------------------------------------------===//
678 
679 void DAGCombiner::deleteAndRecombine(SDNode *N) {
680  removeFromWorklist(N);
681 
682  // If the operands of this node are only used by the node, they will now be
683  // dead. Make sure to re-visit them and recursively delete dead nodes.
684  for (const SDValue &Op : N->ops())
685  // For an operand generating multiple values, one of the values may
686  // become dead allowing further simplification (e.g. split index
687  // arithmetic from an indexed load).
688  if (Op->hasOneUse() || Op->getNumValues() > 1)
689  AddToWorklist(Op.getNode());
690 
691  DAG.DeleteNode(N);
692 }
693 
694 /// Return 1 if we can compute the negated form of the specified expression for
695 /// the same cost as the expression itself, or 2 if we can compute the negated
696 /// form more cheaply than the expression itself.
697 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
698  const TargetLowering &TLI,
699  const TargetOptions *Options,
700  unsigned Depth = 0) {
701  // fneg is removable even if it has multiple uses.
702  if (Op.getOpcode() == ISD::FNEG) return 2;
703 
704  // Don't allow anything with multiple uses unless we know it is free.
705  EVT VT = Op.getValueType();
706  const SDNodeFlags Flags = Op->getFlags();
707  if (!Op.hasOneUse())
708  if (!(Op.getOpcode() == ISD::FP_EXTEND &&
709  TLI.isFPExtFree(VT, Op.getOperand(0).getValueType())))
710  return 0;
711 
712  // Don't recurse exponentially.
713  if (Depth > 6) return 0;
714 
715  switch (Op.getOpcode()) {
716  default: return false;
717  case ISD::ConstantFP: {
718  if (!LegalOperations)
719  return 1;
720 
721  // Don't invert constant FP values after legalization unless the target says
722  // the negated constant is legal.
723  return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
724  TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
725  }
726  case ISD::FADD:
727  if (!Options->UnsafeFPMath && !Flags.hasNoSignedZeros())
728  return 0;
729 
730  // After operation legalization, it might not be legal to create new FSUBs.
731  if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
732  return 0;
733 
734  // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
735  if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
736  Options, Depth + 1))
737  return V;
738  // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
739  return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
740  Depth + 1);
741  case ISD::FSUB:
742  // We can't turn -(A-B) into B-A when we honor signed zeros.
743  if (!Options->NoSignedZerosFPMath &&
744  !Flags.hasNoSignedZeros())
745  return 0;
746 
747  // fold (fneg (fsub A, B)) -> (fsub B, A)
748  return 1;
749 
750  case ISD::FMUL:
751  case ISD::FDIV:
752  // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
753  if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
754  Options, Depth + 1))
755  return V;
756 
757  return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
758  Depth + 1);
759 
760  case ISD::FP_EXTEND:
761  case ISD::FP_ROUND:
762  case ISD::FSIN:
763  return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
764  Depth + 1);
765  }
766 }
767 
768 /// If isNegatibleForFree returns true, return the newly negated expression.
770  bool LegalOperations, unsigned Depth = 0) {
771  const TargetOptions &Options = DAG.getTarget().Options;
772  // fneg is removable even if it has multiple uses.
773  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
774 
775  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
776 
777  const SDNodeFlags Flags = Op.getNode()->getFlags();
778 
779  switch (Op.getOpcode()) {
780  default: llvm_unreachable("Unknown code");
781  case ISD::ConstantFP: {
782  APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
783  V.changeSign();
784  return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
785  }
786  case ISD::FADD:
787  assert(Options.UnsafeFPMath || Flags.hasNoSignedZeros());
788 
789  // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
790  if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
791  DAG.getTargetLoweringInfo(), &Options, Depth+1))
792  return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
793  GetNegatedExpression(Op.getOperand(0), DAG,
794  LegalOperations, Depth+1),
795  Op.getOperand(1), Flags);
796  // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
797  return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
798  GetNegatedExpression(Op.getOperand(1), DAG,
799  LegalOperations, Depth+1),
800  Op.getOperand(0), Flags);
801  case ISD::FSUB:
802  // fold (fneg (fsub 0, B)) -> B
803  if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
804  if (N0CFP->isZero())
805  return Op.getOperand(1);
806 
807  // fold (fneg (fsub A, B)) -> (fsub B, A)
808  return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
809  Op.getOperand(1), Op.getOperand(0), Flags);
810 
811  case ISD::FMUL:
812  case ISD::FDIV:
813  // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
814  if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
815  DAG.getTargetLoweringInfo(), &Options, Depth+1))
816  return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
817  GetNegatedExpression(Op.getOperand(0), DAG,
818  LegalOperations, Depth+1),
819  Op.getOperand(1), Flags);
820 
821  // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
822  return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
823  Op.getOperand(0),
824  GetNegatedExpression(Op.getOperand(1), DAG,
825  LegalOperations, Depth+1), Flags);
826 
827  case ISD::FP_EXTEND:
828  case ISD::FSIN:
829  return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
830  GetNegatedExpression(Op.getOperand(0), DAG,
831  LegalOperations, Depth+1));
832  case ISD::FP_ROUND:
833  return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
834  GetNegatedExpression(Op.getOperand(0), DAG,
835  LegalOperations, Depth+1),
836  Op.getOperand(1));
837  }
838 }
839 
840 // APInts must be the same size for most operations, this helper
841 // function zero extends the shorter of the pair so that they match.
842 // We provide an Offset so that we can create bitwidths that won't overflow.
843 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
844  unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
845  LHS = LHS.zextOrSelf(Bits);
846  RHS = RHS.zextOrSelf(Bits);
847 }
848 
849 // Return true if this node is a setcc, or is a select_cc
850 // that selects between the target values used for true and false, making it
851 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
852 // the appropriate nodes based on the type of node we are checking. This
853 // simplifies life a bit for the callers.
854 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
855  SDValue &CC) const {
856  if (N.getOpcode() == ISD::SETCC) {
857  LHS = N.getOperand(0);
858  RHS = N.getOperand(1);
859  CC = N.getOperand(2);
860  return true;
861  }
862 
863  if (N.getOpcode() != ISD::SELECT_CC ||
864  !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
865  !TLI.isConstFalseVal(N.getOperand(3).getNode()))
866  return false;
867 
868  if (TLI.getBooleanContents(N.getValueType()) ==
870  return false;
871 
872  LHS = N.getOperand(0);
873  RHS = N.getOperand(1);
874  CC = N.getOperand(4);
875  return true;
876 }
877 
878 /// Return true if this is a SetCC-equivalent operation with only one use.
879 /// If this is true, it allows the users to invert the operation for free when
880 /// it is profitable to do so.
881 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
882  SDValue N0, N1, N2;
883  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
884  return true;
885  return false;
886 }
887 
888 // Returns the SDNode if it is a constant float BuildVector
889 // or constant float.
891  if (isa<ConstantFPSDNode>(N))
892  return N.getNode();
894  return N.getNode();
895  return nullptr;
896 }
897 
898 // Determines if it is a constant integer or a build vector of constant
899 // integers (and undefs).
900 // Do not permit build vector implicit truncation.
901 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
902  if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
903  return !(Const->isOpaque() && NoOpaques);
904  if (N.getOpcode() != ISD::BUILD_VECTOR)
905  return false;
906  unsigned BitWidth = N.getScalarValueSizeInBits();
907  for (const SDValue &Op : N->op_values()) {
908  if (Op.isUndef())
909  continue;
911  if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
912  (Const->isOpaque() && NoOpaques))
913  return false;
914  }
915  return true;
916 }
917 
918 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
919 // undef's.
920 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
921  if (V.getOpcode() != ISD::BUILD_VECTOR)
922  return false;
923  return isConstantOrConstantVector(V, NoOpaques) ||
925 }
926 
927 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
928  SDValue N1, SDNodeFlags Flags) {
929  // Don't reassociate reductions.
930  if (Flags.hasVectorReduction())
931  return SDValue();
932 
933  EVT VT = N0.getValueType();
934  if (N0.getOpcode() == Opc && !N0->getFlags().hasVectorReduction()) {
937  // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
938  if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
939  return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
940  return SDValue();
941  }
942  if (N0.hasOneUse()) {
943  // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
944  // use
945  SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
946  if (!OpNode.getNode())
947  return SDValue();
948  AddToWorklist(OpNode.getNode());
949  return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
950  }
951  }
952  }
953 
954  if (N1.getOpcode() == Opc && !N1->getFlags().hasVectorReduction()) {
957  // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
958  if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
959  return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
960  return SDValue();
961  }
962  if (N1.hasOneUse()) {
963  // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
964  // use
965  SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
966  if (!OpNode.getNode())
967  return SDValue();
968  AddToWorklist(OpNode.getNode());
969  return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
970  }
971  }
972  }
973 
974  return SDValue();
975 }
976 
977 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
978  bool AddTo) {
979  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
980  ++NodesCombined;
981  LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
982  To[0].getNode()->dump(&DAG);
983  dbgs() << " and " << NumTo - 1 << " other values\n");
984  for (unsigned i = 0, e = NumTo; i != e; ++i)
985  assert((!To[i].getNode() ||
986  N->getValueType(i) == To[i].getValueType()) &&
987  "Cannot combine value to value of different type!");
988 
989  WorklistRemover DeadNodes(*this);
990  DAG.ReplaceAllUsesWith(N, To);
991  if (AddTo) {
992  // Push the new nodes and any users onto the worklist
993  for (unsigned i = 0, e = NumTo; i != e; ++i) {
994  if (To[i].getNode()) {
995  AddToWorklist(To[i].getNode());
996  AddUsersToWorklist(To[i].getNode());
997  }
998  }
999  }
1000 
1001  // Finally, if the node is now dead, remove it from the graph. The node
1002  // may not be dead if the replacement process recursively simplified to
1003  // something else needing this node.
1004  if (N->use_empty())
1005  deleteAndRecombine(N);
1006  return SDValue(N, 0);
1007 }
1008 
1009 void DAGCombiner::
1010 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1011  // Replace all uses. If any nodes become isomorphic to other nodes and
1012  // are deleted, make sure to remove them from our worklist.
1013  WorklistRemover DeadNodes(*this);
1014  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1015 
1016  // Push the new node and any (possibly new) users onto the worklist.
1017  AddToWorklist(TLO.New.getNode());
1018  AddUsersToWorklist(TLO.New.getNode());
1019 
1020  // Finally, if the node is now dead, remove it from the graph. The node
1021  // may not be dead if the replacement process recursively simplified to
1022  // something else needing this node.
1023  if (TLO.Old.getNode()->use_empty())
1024  deleteAndRecombine(TLO.Old.getNode());
1025 }
1026 
1027 /// Check the specified integer node value to see if it can be simplified or if
1028 /// things it uses can be simplified by bit propagation. If so, return true.
1029 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1030  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1031  KnownBits Known;
1032  if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1033  return false;
1034 
1035  // Revisit the node.
1036  AddToWorklist(Op.getNode());
1037 
1038  // Replace the old value with the new one.
1039  ++NodesCombined;
1040  LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1041  dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1042  dbgs() << '\n');
1043 
1044  CommitTargetLoweringOpt(TLO);
1045  return true;
1046 }
1047 
1048 /// Check the specified vector node value to see if it can be simplified or
1049 /// if things it uses can be simplified as it only uses some of the elements.
1050 /// If so, return true.
1051 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded,
1052  bool AssumeSingleUse) {
1053  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1054  APInt KnownUndef, KnownZero;
1055  if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO,
1056  0, AssumeSingleUse))
1057  return false;
1058 
1059  // Revisit the node.
1060  AddToWorklist(Op.getNode());
1061 
1062  // Replace the old value with the new one.
1063  ++NodesCombined;
1064  LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1065  dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1066  dbgs() << '\n');
1067 
1068  CommitTargetLoweringOpt(TLO);
1069  return true;
1070 }
1071 
1072 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1073  SDLoc DL(Load);
1074  EVT VT = Load->getValueType(0);
1075  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1076 
1077  LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1078  Trunc.getNode()->dump(&DAG); dbgs() << '\n');
1079  WorklistRemover DeadNodes(*this);
1080  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1081  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1082  deleteAndRecombine(Load);
1083  AddToWorklist(Trunc.getNode());
1084 }
1085 
1086 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1087  Replace = false;
1088  SDLoc DL(Op);
1089  if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1090  LoadSDNode *LD = cast<LoadSDNode>(Op);
1091  EVT MemVT = LD->getMemoryVT();
1093  : LD->getExtensionType();
1094  Replace = true;
1095  return DAG.getExtLoad(ExtType, DL, PVT,
1096  LD->getChain(), LD->getBasePtr(),
1097  MemVT, LD->getMemOperand());
1098  }
1099 
1100  unsigned Opc = Op.getOpcode();
1101  switch (Opc) {
1102  default: break;
1103  case ISD::AssertSext:
1104  if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1105  return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1106  break;
1107  case ISD::AssertZext:
1108  if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1109  return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1110  break;
1111  case ISD::Constant: {
1112  unsigned ExtOpc =
1114  return DAG.getNode(ExtOpc, DL, PVT, Op);
1115  }
1116  }
1117 
1118  if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1119  return SDValue();
1120  return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1121 }
1122 
1123 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1125  return SDValue();
1126  EVT OldVT = Op.getValueType();
1127  SDLoc DL(Op);
1128  bool Replace = false;
1129  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1130  if (!NewOp.getNode())
1131  return SDValue();
1132  AddToWorklist(NewOp.getNode());
1133 
1134  if (Replace)
1135  ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1136  return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1137  DAG.getValueType(OldVT));
1138 }
1139 
1140 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1141  EVT OldVT = Op.getValueType();
1142  SDLoc DL(Op);
1143  bool Replace = false;
1144  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1145  if (!NewOp.getNode())
1146  return SDValue();
1147  AddToWorklist(NewOp.getNode());
1148 
1149  if (Replace)
1150  ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1151  return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1152 }
1153 
1154 /// Promote the specified integer binary operation if the target indicates it is
1155 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1156 /// i32 since i16 instructions are longer.
1157 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1158  if (!LegalOperations)
1159  return SDValue();
1160 
1161  EVT VT = Op.getValueType();
1162  if (VT.isVector() || !VT.isInteger())
1163  return SDValue();
1164 
1165  // If operation type is 'undesirable', e.g. i16 on x86, consider
1166  // promoting it.
1167  unsigned Opc = Op.getOpcode();
1168  if (TLI.isTypeDesirableForOp(Opc, VT))
1169  return SDValue();
1170 
1171  EVT PVT = VT;
1172  // Consult target whether it is a good idea to promote this operation and
1173  // what's the right type to promote it to.
1174  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1175  assert(PVT != VT && "Don't know what type to promote to!");
1176 
1177  LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1178 
1179  bool Replace0 = false;
1180  SDValue N0 = Op.getOperand(0);
1181  SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1182 
1183  bool Replace1 = false;
1184  SDValue N1 = Op.getOperand(1);
1185  SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1186  SDLoc DL(Op);
1187 
1188  SDValue RV =
1189  DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1190 
1191  // We are always replacing N0/N1's use in N and only need
1192  // additional replacements if there are additional uses.
1193  Replace0 &= !N0->hasOneUse();
1194  Replace1 &= (N0 != N1) && !N1->hasOneUse();
1195 
1196  // Combine Op here so it is preserved past replacements.
1197  CombineTo(Op.getNode(), RV);
1198 
1199  // If operands have a use ordering, make sure we deal with
1200  // predecessor first.
1201  if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1202  std::swap(N0, N1);
1203  std::swap(NN0, NN1);
1204  }
1205 
1206  if (Replace0) {
1207  AddToWorklist(NN0.getNode());
1208  ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1209  }
1210  if (Replace1) {
1211  AddToWorklist(NN1.getNode());
1212  ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1213  }
1214  return Op;
1215  }
1216  return SDValue();
1217 }
1218 
1219 /// Promote the specified integer shift operation if the target indicates it is
1220 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1221 /// i32 since i16 instructions are longer.
1222 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1223  if (!LegalOperations)
1224  return SDValue();
1225 
1226  EVT VT = Op.getValueType();
1227  if (VT.isVector() || !VT.isInteger())
1228  return SDValue();
1229 
1230  // If operation type is 'undesirable', e.g. i16 on x86, consider
1231  // promoting it.
1232  unsigned Opc = Op.getOpcode();
1233  if (TLI.isTypeDesirableForOp(Opc, VT))
1234  return SDValue();
1235 
1236  EVT PVT = VT;
1237  // Consult target whether it is a good idea to promote this operation and
1238  // what's the right type to promote it to.
1239  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240  assert(PVT != VT && "Don't know what type to promote to!");
1241 
1242  LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1243 
1244  bool Replace = false;
1245  SDValue N0 = Op.getOperand(0);
1246  SDValue N1 = Op.getOperand(1);
1247  if (Opc == ISD::SRA)
1248  N0 = SExtPromoteOperand(N0, PVT);
1249  else if (Opc == ISD::SRL)
1250  N0 = ZExtPromoteOperand(N0, PVT);
1251  else
1252  N0 = PromoteOperand(N0, PVT, Replace);
1253 
1254  if (!N0.getNode())
1255  return SDValue();
1256 
1257  SDLoc DL(Op);
1258  SDValue RV =
1259  DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1260 
1261  AddToWorklist(N0.getNode());
1262  if (Replace)
1263  ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1264 
1265  // Deal with Op being deleted.
1266  if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1267  return RV;
1268  }
1269  return SDValue();
1270 }
1271 
1272 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1273  if (!LegalOperations)
1274  return SDValue();
1275 
1276  EVT VT = Op.getValueType();
1277  if (VT.isVector() || !VT.isInteger())
1278  return SDValue();
1279 
1280  // If operation type is 'undesirable', e.g. i16 on x86, consider
1281  // promoting it.
1282  unsigned Opc = Op.getOpcode();
1283  if (TLI.isTypeDesirableForOp(Opc, VT))
1284  return SDValue();
1285 
1286  EVT PVT = VT;
1287  // Consult target whether it is a good idea to promote this operation and
1288  // what's the right type to promote it to.
1289  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1290  assert(PVT != VT && "Don't know what type to promote to!");
1291  // fold (aext (aext x)) -> (aext x)
1292  // fold (aext (zext x)) -> (zext x)
1293  // fold (aext (sext x)) -> (sext x)
1294  LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1295  return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1296  }
1297  return SDValue();
1298 }
1299 
1300 bool DAGCombiner::PromoteLoad(SDValue Op) {
1301  if (!LegalOperations)
1302  return false;
1303 
1304  if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1305  return false;
1306 
1307  EVT VT = Op.getValueType();
1308  if (VT.isVector() || !VT.isInteger())
1309  return false;
1310 
1311  // If operation type is 'undesirable', e.g. i16 on x86, consider
1312  // promoting it.
1313  unsigned Opc = Op.getOpcode();
1314  if (TLI.isTypeDesirableForOp(Opc, VT))
1315  return false;
1316 
1317  EVT PVT = VT;
1318  // Consult target whether it is a good idea to promote this operation and
1319  // what's the right type to promote it to.
1320  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1321  assert(PVT != VT && "Don't know what type to promote to!");
1322 
1323  SDLoc DL(Op);
1324  SDNode *N = Op.getNode();
1325  LoadSDNode *LD = cast<LoadSDNode>(N);
1326  EVT MemVT = LD->getMemoryVT();
1328  : LD->getExtensionType();
1329  SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1330  LD->getChain(), LD->getBasePtr(),
1331  MemVT, LD->getMemOperand());
1332  SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1333 
1334  LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1335  Result.getNode()->dump(&DAG); dbgs() << '\n');
1336  WorklistRemover DeadNodes(*this);
1337  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1338  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1339  deleteAndRecombine(N);
1340  AddToWorklist(Result.getNode());
1341  return true;
1342  }
1343  return false;
1344 }
1345 
1346 /// Recursively delete a node which has no uses and any operands for
1347 /// which it is the only use.
1348 ///
1349 /// Note that this both deletes the nodes and removes them from the worklist.
1350 /// It also adds any nodes who have had a user deleted to the worklist as they
1351 /// may now have only one use and subject to other combines.
1352 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1353  if (!N->use_empty())
1354  return false;
1355 
1357  Nodes.insert(N);
1358  do {
1359  N = Nodes.pop_back_val();
1360  if (!N)
1361  continue;
1362 
1363  if (N->use_empty()) {
1364  for (const SDValue &ChildN : N->op_values())
1365  Nodes.insert(ChildN.getNode());
1366 
1367  removeFromWorklist(N);
1368  DAG.DeleteNode(N);
1369  } else {
1370  AddToWorklist(N);
1371  }
1372  } while (!Nodes.empty());
1373  return true;
1374 }
1375 
1376 //===----------------------------------------------------------------------===//
1377 // Main DAG Combiner implementation
1378 //===----------------------------------------------------------------------===//
1379 
1380 void DAGCombiner::Run(CombineLevel AtLevel) {
1381  // set the instance variables, so that the various visit routines may use it.
1382  Level = AtLevel;
1383  LegalOperations = Level >= AfterLegalizeVectorOps;
1384  LegalTypes = Level >= AfterLegalizeTypes;
1385 
1386  // Add all the dag nodes to the worklist.
1387  for (SDNode &Node : DAG.allnodes())
1388  AddToWorklist(&Node);
1389 
1390  // Create a dummy node (which is not added to allnodes), that adds a reference
1391  // to the root node, preventing it from being deleted, and tracking any
1392  // changes of the root.
1393  HandleSDNode Dummy(DAG.getRoot());
1394 
1395  // While the worklist isn't empty, find a node and try to combine it.
1396  while (!WorklistMap.empty()) {
1397  SDNode *N;
1398  // The Worklist holds the SDNodes in order, but it may contain null entries.
1399  do {
1400  N = Worklist.pop_back_val();
1401  } while (!N);
1402 
1403  bool GoodWorklistEntry = WorklistMap.erase(N);
1404  (void)GoodWorklistEntry;
1405  assert(GoodWorklistEntry &&
1406  "Found a worklist entry without a corresponding map entry!");
1407 
1408  // If N has no uses, it is dead. Make sure to revisit all N's operands once
1409  // N is deleted from the DAG, since they too may now be dead or may have a
1410  // reduced number of uses, allowing other xforms.
1411  if (recursivelyDeleteUnusedNodes(N))
1412  continue;
1413 
1414  WorklistRemover DeadNodes(*this);
1415 
1416  // If this combine is running after legalizing the DAG, re-legalize any
1417  // nodes pulled off the worklist.
1418  if (Level == AfterLegalizeDAG) {
1419  SmallSetVector<SDNode *, 16> UpdatedNodes;
1420  bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1421 
1422  for (SDNode *LN : UpdatedNodes) {
1423  AddToWorklist(LN);
1424  AddUsersToWorklist(LN);
1425  }
1426  if (!NIsValid)
1427  continue;
1428  }
1429 
1430  LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1431 
1432  // Add any operands of the new node which have not yet been combined to the
1433  // worklist as well. Because the worklist uniques things already, this
1434  // won't repeatedly process the same operand.
1435  CombinedNodes.insert(N);
1436  for (const SDValue &ChildN : N->op_values())
1437  if (!CombinedNodes.count(ChildN.getNode()))
1438  AddToWorklist(ChildN.getNode());
1439 
1440  SDValue RV = combine(N);
1441 
1442  if (!RV.getNode())
1443  continue;
1444 
1445  ++NodesCombined;
1446 
1447  // If we get back the same node we passed in, rather than a new node or
1448  // zero, we know that the node must have defined multiple values and
1449  // CombineTo was used. Since CombineTo takes care of the worklist
1450  // mechanics for us, we have no work to do in this case.
1451  if (RV.getNode() == N)
1452  continue;
1453 
1455  RV.getOpcode() != ISD::DELETED_NODE &&
1456  "Node was deleted but visit returned new node!");
1457 
1458  LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
1459 
1460  if (N->getNumValues() == RV.getNode()->getNumValues())
1461  DAG.ReplaceAllUsesWith(N, RV.getNode());
1462  else {
1463  assert(N->getValueType(0) == RV.getValueType() &&
1464  N->getNumValues() == 1 && "Type mismatch");
1465  DAG.ReplaceAllUsesWith(N, &RV);
1466  }
1467 
1468  // Push the new node and any users onto the worklist
1469  AddToWorklist(RV.getNode());
1470  AddUsersToWorklist(RV.getNode());
1471 
1472  // Finally, if the node is now dead, remove it from the graph. The node
1473  // may not be dead if the replacement process recursively simplified to
1474  // something else needing this node. This will also take care of adding any
1475  // operands which have lost a user to the worklist.
1476  recursivelyDeleteUnusedNodes(N);
1477  }
1478 
1479  // If the root changed (e.g. it was a dead load, update the root).
1480  DAG.setRoot(Dummy.getValue());
1481  DAG.RemoveDeadNodes();
1482 }
1483 
1484 SDValue DAGCombiner::visit(SDNode *N) {
1485  switch (N->getOpcode()) {
1486  default: break;
1487  case ISD::TokenFactor: return visitTokenFactor(N);
1488  case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1489  case ISD::ADD: return visitADD(N);
1490  case ISD::SUB: return visitSUB(N);
1491  case ISD::SADDSAT:
1492  case ISD::UADDSAT: return visitADDSAT(N);
1493  case ISD::SSUBSAT:
1494  case ISD::USUBSAT: return visitSUBSAT(N);
1495  case ISD::ADDC: return visitADDC(N);
1496  case ISD::SADDO:
1497  case ISD::UADDO: return visitADDO(N);
1498  case ISD::SUBC: return visitSUBC(N);
1499  case ISD::SSUBO:
1500  case ISD::USUBO: return visitSUBO(N);
1501  case ISD::ADDE: return visitADDE(N);
1502  case ISD::ADDCARRY: return visitADDCARRY(N);
1503  case ISD::SUBE: return visitSUBE(N);
1504  case ISD::SUBCARRY: return visitSUBCARRY(N);
1505  case ISD::MUL: return visitMUL(N);
1506  case ISD::SDIV: return visitSDIV(N);
1507  case ISD::UDIV: return visitUDIV(N);
1508  case ISD::SREM:
1509  case ISD::UREM: return visitREM(N);
1510  case ISD::MULHU: return visitMULHU(N);
1511  case ISD::MULHS: return visitMULHS(N);
1512  case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1513  case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1514  case ISD::SMULO:
1515  case ISD::UMULO: return visitMULO(N);
1516  case ISD::SMIN:
1517  case ISD::SMAX:
1518  case ISD::UMIN:
1519  case ISD::UMAX: return visitIMINMAX(N);
1520  case ISD::AND: return visitAND(N);
1521  case ISD::OR: return visitOR(N);
1522  case ISD::XOR: return visitXOR(N);
1523  case ISD::SHL: return visitSHL(N);
1524  case ISD::SRA: return visitSRA(N);
1525  case ISD::SRL: return visitSRL(N);
1526  case ISD::ROTR:
1527  case ISD::ROTL: return visitRotate(N);
1528  case ISD::FSHL:
1529  case ISD::FSHR: return visitFunnelShift(N);
1530  case ISD::ABS: return visitABS(N);
1531  case ISD::BSWAP: return visitBSWAP(N);
1532  case ISD::BITREVERSE: return visitBITREVERSE(N);
1533  case ISD::CTLZ: return visitCTLZ(N);
1534  case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1535  case ISD::CTTZ: return visitCTTZ(N);
1536  case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1537  case ISD::CTPOP: return visitCTPOP(N);
1538  case ISD::SELECT: return visitSELECT(N);
1539  case ISD::VSELECT: return visitVSELECT(N);
1540  case ISD::SELECT_CC: return visitSELECT_CC(N);
1541  case ISD::SETCC: return visitSETCC(N);
1542  case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1543  case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1544  case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1545  case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1546  case ISD::AssertSext:
1547  case ISD::AssertZext: return visitAssertExt(N);
1548  case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1549  case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1550  case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1551  case ISD::TRUNCATE: return visitTRUNCATE(N);
1552  case ISD::BITCAST: return visitBITCAST(N);
1553  case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1554  case ISD::FADD: return visitFADD(N);
1555  case ISD::FSUB: return visitFSUB(N);
1556  case ISD::FMUL: return visitFMUL(N);
1557  case ISD::FMA: return visitFMA(N);
1558  case ISD::FDIV: return visitFDIV(N);
1559  case ISD::FREM: return visitFREM(N);
1560  case ISD::FSQRT: return visitFSQRT(N);
1561  case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1562  case ISD::FPOW: return visitFPOW(N);
1563  case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1564  case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1565  case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1566  case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1567  case ISD::FP_ROUND: return visitFP_ROUND(N);
1568  case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1569  case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1570  case ISD::FNEG: return visitFNEG(N);
1571  case ISD::FABS: return visitFABS(N);
1572  case ISD::FFLOOR: return visitFFLOOR(N);
1573  case ISD::FMINNUM: return visitFMINNUM(N);
1574  case ISD::FMAXNUM: return visitFMAXNUM(N);
1575  case ISD::FMINIMUM: return visitFMINIMUM(N);
1576  case ISD::FMAXIMUM: return visitFMAXIMUM(N);
1577  case ISD::FCEIL: return visitFCEIL(N);
1578  case ISD::FTRUNC: return visitFTRUNC(N);
1579  case ISD::BRCOND: return visitBRCOND(N);
1580  case ISD::BR_CC: return visitBR_CC(N);
1581  case ISD::LOAD: return visitLOAD(N);
1582  case ISD::STORE: return visitSTORE(N);
1583  case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1584  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1585  case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1586  case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1587  case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1588  case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1589  case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1590  case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1591  case ISD::MGATHER: return visitMGATHER(N);
1592  case ISD::MLOAD: return visitMLOAD(N);
1593  case ISD::MSCATTER: return visitMSCATTER(N);
1594  case ISD::MSTORE: return visitMSTORE(N);
1595  case ISD::LIFETIME_END: return visitLIFETIME_END(N);
1596  case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1597  case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1598  case ISD::VECREDUCE_FADD:
1599  case ISD::VECREDUCE_FMUL:
1600  case ISD::VECREDUCE_ADD:
1601  case ISD::VECREDUCE_MUL:
1602  case ISD::VECREDUCE_AND:
1603  case ISD::VECREDUCE_OR:
1604  case ISD::VECREDUCE_XOR:
1605  case ISD::VECREDUCE_SMAX:
1606  case ISD::VECREDUCE_SMIN:
1607  case ISD::VECREDUCE_UMAX:
1608  case ISD::VECREDUCE_UMIN:
1609  case ISD::VECREDUCE_FMAX:
1610  case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N);
1611  }
1612  return SDValue();
1613 }
1614 
1615 SDValue DAGCombiner::combine(SDNode *N) {
1616  SDValue RV = visit(N);
1617 
1618  // If nothing happened, try a target-specific DAG combine.
1619  if (!RV.getNode()) {
1621  "Node was deleted but visit returned NULL!");
1622 
1623  if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1625 
1626  // Expose the DAG combiner to the target combiner impls.
1628  DagCombineInfo(DAG, Level, false, this);
1629 
1630  RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1631  }
1632  }
1633 
1634  // If nothing happened still, try promoting the operation.
1635  if (!RV.getNode()) {
1636  switch (N->getOpcode()) {
1637  default: break;
1638  case ISD::ADD:
1639  case ISD::SUB:
1640  case ISD::MUL:
1641  case ISD::AND:
1642  case ISD::OR:
1643  case ISD::XOR:
1644  RV = PromoteIntBinOp(SDValue(N, 0));
1645  break;
1646  case ISD::SHL:
1647  case ISD::SRA:
1648  case ISD::SRL:
1649  RV = PromoteIntShiftOp(SDValue(N, 0));
1650  break;
1651  case ISD::SIGN_EXTEND:
1652  case ISD::ZERO_EXTEND:
1653  case ISD::ANY_EXTEND:
1654  RV = PromoteExtend(SDValue(N, 0));
1655  break;
1656  case ISD::LOAD:
1657  if (PromoteLoad(SDValue(N, 0)))
1658  RV = SDValue(N, 0);
1659  break;
1660  }
1661  }
1662 
1663  // If N is a commutative binary node, try eliminate it if the commuted
1664  // version is already present in the DAG.
1665  if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1666  N->getNumValues() == 1) {
1667  SDValue N0 = N->getOperand(0);
1668  SDValue N1 = N->getOperand(1);
1669 
1670  // Constant operands are canonicalized to RHS.
1671  if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1672  SDValue Ops[] = {N1, N0};
1673  SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1674  N->getFlags());
1675  if (CSENode)
1676  return SDValue(CSENode, 0);
1677  }
1678  }
1679 
1680  return RV;
1681 }
1682 
1683 /// Given a node, return its input chain if it has one, otherwise return a null
1684 /// sd operand.
1686  if (unsigned NumOps = N->getNumOperands()) {
1687  if (N->getOperand(0).getValueType() == MVT::Other)
1688  return N->getOperand(0);
1689  if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1690  return N->getOperand(NumOps-1);
1691  for (unsigned i = 1; i < NumOps-1; ++i)
1692  if (N->getOperand(i).getValueType() == MVT::Other)
1693  return N->getOperand(i);
1694  }
1695  return SDValue();
1696 }
1697 
1698 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1699  // If N has two operands, where one has an input chain equal to the other,
1700  // the 'other' chain is redundant.
1701  if (N->getNumOperands() == 2) {
1702  if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1703  return N->getOperand(0);
1704  if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1705  return N->getOperand(1);
1706  }
1707 
1708  // Don't simplify token factors if optnone.
1709  if (OptLevel == CodeGenOpt::None)
1710  return SDValue();
1711 
1712  // If the sole user is a token factor, we should make sure we have a
1713  // chance to merge them together. This prevents TF chains from inhibiting
1714  // optimizations.
1715  if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
1716  AddToWorklist(*(N->use_begin()));
1717 
1718  SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1719  SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1720  SmallPtrSet<SDNode*, 16> SeenOps;
1721  bool Changed = false; // If we should replace this token factor.
1722 
1723  // Start out with this token factor.
1724  TFs.push_back(N);
1725 
1726  // Iterate through token factors. The TFs grows when new token factors are
1727  // encountered.
1728  for (unsigned i = 0; i < TFs.size(); ++i) {
1729  SDNode *TF = TFs[i];
1730 
1731  // Check each of the operands.
1732  for (const SDValue &Op : TF->op_values()) {
1733  switch (Op.getOpcode()) {
1734  case ISD::EntryToken:
1735  // Entry tokens don't need to be added to the list. They are
1736  // redundant.
1737  Changed = true;
1738  break;
1739 
1740  case ISD::TokenFactor:
1741  if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1742  // Queue up for processing.
1743  TFs.push_back(Op.getNode());
1744  // Clean up in case the token factor is removed.
1745  AddToWorklist(Op.getNode());
1746  Changed = true;
1747  break;
1748  }
1750 
1751  default:
1752  // Only add if it isn't already in the list.
1753  if (SeenOps.insert(Op.getNode()).second)
1754  Ops.push_back(Op);
1755  else
1756  Changed = true;
1757  break;
1758  }
1759  }
1760  }
1761 
1762  // Remove Nodes that are chained to another node in the list. Do so
1763  // by walking up chains breath-first stopping when we've seen
1764  // another operand. In general we must climb to the EntryNode, but we can exit
1765  // early if we find all remaining work is associated with just one operand as
1766  // no further pruning is possible.
1767 
1768  // List of nodes to search through and original Ops from which they originate.
1770  SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1771  SmallPtrSet<SDNode *, 16> SeenChains;
1772  bool DidPruneOps = false;
1773 
1774  unsigned NumLeftToConsider = 0;
1775  for (const SDValue &Op : Ops) {
1776  Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1777  OpWorkCount.push_back(1);
1778  }
1779 
1780  auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1781  // If this is an Op, we can remove the op from the list. Remark any
1782  // search associated with it as from the current OpNumber.
1783  if (SeenOps.count(Op) != 0) {
1784  Changed = true;
1785  DidPruneOps = true;
1786  unsigned OrigOpNumber = 0;
1787  while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1788  OrigOpNumber++;
1789  assert((OrigOpNumber != Ops.size()) &&
1790  "expected to find TokenFactor Operand");
1791  // Re-mark worklist from OrigOpNumber to OpNumber
1792  for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1793  if (Worklist[i].second == OrigOpNumber) {
1794  Worklist[i].second = OpNumber;
1795  }
1796  }
1797  OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1798  OpWorkCount[OrigOpNumber] = 0;
1799  NumLeftToConsider--;
1800  }
1801  // Add if it's a new chain
1802  if (SeenChains.insert(Op).second) {
1803  OpWorkCount[OpNumber]++;
1804  Worklist.push_back(std::make_pair(Op, OpNumber));
1805  }
1806  };
1807 
1808  for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1809  // We need at least be consider at least 2 Ops to prune.
1810  if (NumLeftToConsider <= 1)
1811  break;
1812  auto CurNode = Worklist[i].first;
1813  auto CurOpNumber = Worklist[i].second;
1814  assert((OpWorkCount[CurOpNumber] > 0) &&
1815  "Node should not appear in worklist");
1816  switch (CurNode->getOpcode()) {
1817  case ISD::EntryToken:
1818  // Hitting EntryToken is the only way for the search to terminate without
1819  // hitting
1820  // another operand's search. Prevent us from marking this operand
1821  // considered.
1822  NumLeftToConsider++;
1823  break;
1824  case ISD::TokenFactor:
1825  for (const SDValue &Op : CurNode->op_values())
1826  AddToWorklist(i, Op.getNode(), CurOpNumber);
1827  break;
1828  case ISD::CopyFromReg:
1829  case ISD::CopyToReg:
1830  AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1831  break;
1832  default:
1833  if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1834  AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1835  break;
1836  }
1837  OpWorkCount[CurOpNumber]--;
1838  if (OpWorkCount[CurOpNumber] == 0)
1839  NumLeftToConsider--;
1840  }
1841 
1842  // If we've changed things around then replace token factor.
1843  if (Changed) {
1844  SDValue Result;
1845  if (Ops.empty()) {
1846  // The entry token is the only possible outcome.
1847  Result = DAG.getEntryNode();
1848  } else {
1849  if (DidPruneOps) {
1850  SmallVector<SDValue, 8> PrunedOps;
1851  //
1852  for (const SDValue &Op : Ops) {
1853  if (SeenChains.count(Op.getNode()) == 0)
1854  PrunedOps.push_back(Op);
1855  }
1856  Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1857  } else {
1858  Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1859  }
1860  }
1861  return Result;
1862  }
1863  return SDValue();
1864 }
1865 
1866 /// MERGE_VALUES can always be eliminated.
1867 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1868  WorklistRemover DeadNodes(*this);
1869  // Replacing results may cause a different MERGE_VALUES to suddenly
1870  // be CSE'd with N, and carry its uses with it. Iterate until no
1871  // uses remain, to ensure that the node can be safely deleted.
1872  // First add the users of this node to the work list so that they
1873  // can be tried again once they have new operands.
1874  AddUsersToWorklist(N);
1875  do {
1876  // Do as a single replacement to avoid rewalking use lists.
1878  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1879  Ops.push_back(N->getOperand(i));
1880  DAG.ReplaceAllUsesWith(N, Ops.data());
1881  } while (!N->use_empty());
1882  deleteAndRecombine(N);
1883  return SDValue(N, 0); // Return N so it doesn't get rechecked!
1884 }
1885 
1886 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1887 /// ConstantSDNode pointer else nullptr.
1890  return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1891 }
1892 
1893 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1894  assert(ISD::isBinaryOp(BO) && "Unexpected binary operator");
1895 
1896  // Don't do this unless the old select is going away. We want to eliminate the
1897  // binary operator, not replace a binop with a select.
1898  // TODO: Handle ISD::SELECT_CC.
1899  unsigned SelOpNo = 0;
1900  SDValue Sel = BO->getOperand(0);
1901  if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
1902  SelOpNo = 1;
1903  Sel = BO->getOperand(1);
1904  }
1905 
1906  if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1907  return SDValue();
1908 
1909  SDValue CT = Sel.getOperand(1);
1910  if (!isConstantOrConstantVector(CT, true) &&
1912  return SDValue();
1913 
1914  SDValue CF = Sel.getOperand(2);
1915  if (!isConstantOrConstantVector(CF, true) &&
1917  return SDValue();
1918 
1919  // Bail out if any constants are opaque because we can't constant fold those.
1920  // The exception is "and" and "or" with either 0 or -1 in which case we can
1921  // propagate non constant operands into select. I.e.:
1922  // and (select Cond, 0, -1), X --> select Cond, 0, X
1923  // or X, (select Cond, -1, 0) --> select Cond, -1, X
1924  auto BinOpcode = BO->getOpcode();
1925  bool CanFoldNonConst =
1926  (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
1929 
1930  SDValue CBO = BO->getOperand(SelOpNo ^ 1);
1931  if (!CanFoldNonConst &&
1932  !isConstantOrConstantVector(CBO, true) &&
1934  return SDValue();
1935 
1936  EVT VT = Sel.getValueType();
1937 
1938  // In case of shift value and shift amount may have different VT. For instance
1939  // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
1940  // swapped operands and value types do not match. NB: x86 is fine if operands
1941  // are not swapped with shift amount VT being not bigger than shifted value.
1942  // TODO: that is possible to check for a shift operation, correct VTs and
1943  // still perform optimization on x86 if needed.
1944  if (SelOpNo && VT != CBO.getValueType())
1945  return SDValue();
1946 
1947  // We have a select-of-constants followed by a binary operator with a
1948  // constant. Eliminate the binop by pulling the constant math into the select.
1949  // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
1950  SDLoc DL(Sel);
1951  SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
1952  : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
1953  if (!CanFoldNonConst && !NewCT.isUndef() &&
1954  !isConstantOrConstantVector(NewCT, true) &&
1956  return SDValue();
1957 
1958  SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
1959  : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
1960  if (!CanFoldNonConst && !NewCF.isUndef() &&
1961  !isConstantOrConstantVector(NewCF, true) &&
1963  return SDValue();
1964 
1965  return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1966 }
1967 
1969  assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
1970  "Expecting add or sub");
1971 
1972  // Match a constant operand and a zext operand for the math instruction:
1973  // add Z, C
1974  // sub C, Z
1975  bool IsAdd = N->getOpcode() == ISD::ADD;
1976  SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
1977  SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
1978  auto *CN = dyn_cast<ConstantSDNode>(C);
1979  if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
1980  return SDValue();
1981 
1982  // Match the zext operand as a setcc of a boolean.
1983  if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
1984  Z.getOperand(0).getValueType() != MVT::i1)
1985  return SDValue();
1986 
1987  // Match the compare as: setcc (X & 1), 0, eq.
1988  SDValue SetCC = Z.getOperand(0);
1989  ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
1990  if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
1991  SetCC.getOperand(0).getOpcode() != ISD::AND ||
1992  !isOneConstant(SetCC.getOperand(0).getOperand(1)))
1993  return SDValue();
1994 
1995  // We are adding/subtracting a constant and an inverted low bit. Turn that
1996  // into a subtract/add of the low bit with incremented/decremented constant:
1997  // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
1998  // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
1999  EVT VT = C.getValueType();
2000  SDLoc DL(N);
2001  SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
2002  SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
2003  DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2004  return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2005 }
2006 
2007 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2008 /// a shift and add with a different constant.
2010  assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2011  "Expecting add or sub");
2012 
2013  // We need a constant operand for the add/sub, and the other operand is a
2014  // logical shift right: add (srl), C or sub C, (srl).
2015  bool IsAdd = N->getOpcode() == ISD::ADD;
2016  SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2017  SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2018  ConstantSDNode *C = isConstOrConstSplat(ConstantOp);
2019  if (!C || ShiftOp.getOpcode() != ISD::SRL)
2020  return SDValue();
2021 
2022  // The shift must be of a 'not' value.
2023  SDValue Not = ShiftOp.getOperand(0);
2024  if (!Not.hasOneUse() || !isBitwiseNot(Not))
2025  return SDValue();
2026 
2027  // The shift must be moving the sign bit to the least-significant-bit.
2028  EVT VT = ShiftOp.getValueType();
2029  SDValue ShAmt = ShiftOp.getOperand(1);
2030  ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2031  if (!ShAmtC || ShAmtC->getZExtValue() != VT.getScalarSizeInBits() - 1)
2032  return SDValue();
2033 
2034  // Eliminate the 'not' by adjusting the shift and add/sub constant:
2035  // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2036  // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2037  SDLoc DL(N);
2038  auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
2039  SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
2040  APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1;
2041  return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT));
2042 }
2043 
2044 SDValue DAGCombiner::visitADD(SDNode *N) {
2045  SDValue N0 = N->getOperand(0);
2046  SDValue N1 = N->getOperand(1);
2047  EVT VT = N0.getValueType();
2048  SDLoc DL(N);
2049 
2050  // fold vector ops
2051  if (VT.isVector()) {
2052  if (SDValue FoldedVOp = SimplifyVBinOp(N))
2053  return FoldedVOp;
2054 
2055  // fold (add x, 0) -> x, vector edition
2057  return N0;
2059  return N1;
2060  }
2061 
2062  // fold (add x, undef) -> undef
2063  if (N0.isUndef())
2064  return N0;
2065 
2066  if (N1.isUndef())
2067  return N1;
2068 
2070  // canonicalize constant to RHS
2072  return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2073  // fold (add c1, c2) -> c1+c2
2074  return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
2075  N1.getNode());
2076  }
2077 
2078  // fold (add x, 0) -> x
2079  if (isNullConstant(N1))
2080  return N0;
2081 
2082  if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2083  // fold ((c1-A)+c2) -> (c1+c2)-A
2084  if (N0.getOpcode() == ISD::SUB &&
2085  isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2086  // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
2087  return DAG.getNode(ISD::SUB, DL, VT,
2088  DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
2089  N0.getOperand(1));
2090  }
2091 
2092  // add (sext i1 X), 1 -> zext (not i1 X)
2093  // We don't transform this pattern:
2094  // add (zext i1 X), -1 -> sext (not i1 X)
2095  // because most (?) targets generate better code for the zext form.
2096  if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2097  isOneOrOneSplat(N1)) {
2098  SDValue X = N0.getOperand(0);
2099  if ((!LegalOperations ||
2100  (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2101  TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2102  X.getScalarValueSizeInBits() == 1) {
2103  SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2104  return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2105  }
2106  }
2107 
2108  // Undo the add -> or combine to merge constant offsets from a frame index.
2109  if (N0.getOpcode() == ISD::OR &&
2110  isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2111  isa<ConstantSDNode>(N0.getOperand(1)) &&
2112  DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2113  SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2114  return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2115  }
2116  }
2117 
2118  if (SDValue NewSel = foldBinOpIntoSelect(N))
2119  return NewSel;
2120 
2121  // reassociate add
2122  if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2123  return RADD;
2124 
2125  // fold ((0-A) + B) -> B-A
2126  if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
2127  return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2128 
2129  // fold (A + (0-B)) -> A-B
2130  if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2131  return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2132 
2133  // fold (A+(B-A)) -> B
2134  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2135  return N1.getOperand(0);
2136 
2137  // fold ((B-A)+A) -> B
2138  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2139  return N0.getOperand(0);
2140 
2141  // fold ((A-B)+(C-A)) -> (C-B)
2142  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2143  N0.getOperand(0) == N1.getOperand(1))
2144  return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2145  N0.getOperand(1));
2146 
2147  // fold ((A-B)+(B-C)) -> (A-C)
2148  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2149  N0.getOperand(1) == N1.getOperand(0))
2150  return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2151  N1.getOperand(1));
2152 
2153  // fold (A+(B-(A+C))) to (B-C)
2154  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2155  N0 == N1.getOperand(1).getOperand(0))
2156  return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2157  N1.getOperand(1).getOperand(1));
2158 
2159  // fold (A+(B-(C+A))) to (B-C)
2160  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2161  N0 == N1.getOperand(1).getOperand(1))
2162  return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2163  N1.getOperand(1).getOperand(0));
2164 
2165  // fold (A+((B-A)+or-C)) to (B+or-C)
2166  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2167  N1.getOperand(0).getOpcode() == ISD::SUB &&
2168  N0 == N1.getOperand(0).getOperand(1))
2169  return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2170  N1.getOperand(1));
2171 
2172  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2173  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2174  SDValue N00 = N0.getOperand(0);
2175  SDValue N01 = N0.getOperand(1);
2176  SDValue N10 = N1.getOperand(0);
2177  SDValue N11 = N1.getOperand(1);
2178 
2180  return DAG.getNode(ISD::SUB, DL, VT,
2181  DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2182  DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2183  }
2184 
2185  // fold (add (umax X, C), -C) --> (usubsat X, C)
2186  if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
2187  auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
2188  return (!Max && !Op) ||
2189  (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
2190  };
2191  if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
2192  /*AllowUndefs*/ true))
2193  return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
2194  N0.getOperand(1));
2195  }
2196 
2197  if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2198  return V;
2199 
2200  if (SDValue V = foldAddSubOfSignBit(N, DAG))
2201  return V;
2202 
2203  if (SimplifyDemandedBits(SDValue(N, 0)))
2204  return SDValue(N, 0);
2205 
2206  // fold (a+b) -> (a|b) iff a and b share no bits.
2207  if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2208  DAG.haveNoCommonBitsSet(N0, N1))
2209  return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2210 
2211  if (isOneOrOneSplat(N1)) {
2212  // fold (add (xor a, -1), 1) -> (sub 0, a)
2213  if (isBitwiseNot(N0))
2214  return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2215  N0.getOperand(0));
2216 
2217  // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2218  if (N0.getOpcode() == ISD::ADD ||
2219  N0.getOpcode() == ISD::UADDO ||
2220  N0.getOpcode() == ISD::SADDO) {
2221  SDValue A, Xor;
2222 
2223  if (isBitwiseNot(N0.getOperand(0))) {
2224  A = N0.getOperand(1);
2225  Xor = N0.getOperand(0);
2226  } else if (isBitwiseNot(N0.getOperand(1))) {
2227  A = N0.getOperand(0);
2228  Xor = N0.getOperand(1);
2229  }
2230 
2231  if (Xor)
2232  return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
2233  }
2234  }
2235 
2236  if (SDValue Combined = visitADDLike(N0, N1, N))
2237  return Combined;
2238 
2239  if (SDValue Combined = visitADDLike(N1, N0, N))
2240  return Combined;
2241 
2242  return SDValue();
2243 }
2244 
2245 SDValue DAGCombiner::visitADDSAT(SDNode *N) {
2246  unsigned Opcode = N->getOpcode();
2247  SDValue N0 = N->getOperand(0);
2248  SDValue N1 = N->getOperand(1);
2249  EVT VT = N0.getValueType();
2250  SDLoc DL(N);
2251 
2252  // fold vector ops
2253  if (VT.isVector()) {
2254  // TODO SimplifyVBinOp
2255 
2256  // fold (add_sat x, 0) -> x, vector edition
2258  return N0;
2260  return N1;
2261  }
2262 
2263  // fold (add_sat x, undef) -> -1
2264  if (N0.isUndef() || N1.isUndef())
2265  return DAG.getAllOnesConstant(DL, VT);
2266 
2268  // canonicalize constant to RHS
2270  return DAG.getNode(Opcode, DL, VT, N1, N0);
2271  // fold (add_sat c1, c2) -> c3
2272  return DAG.FoldConstantArithmetic(Opcode, DL, VT, N0.getNode(),
2273  N1.getNode());
2274  }
2275 
2276  // fold (add_sat x, 0) -> x
2277  if (isNullConstant(N1))
2278  return N0;
2279 
2280  // If it cannot overflow, transform into an add.
2281  if (Opcode == ISD::UADDSAT)
2282  if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2283  return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
2284 
2285  return SDValue();
2286 }
2287 
2288 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2289  bool Masked = false;
2290 
2291  // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2292  while (true) {
2293  if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2294  V = V.getOperand(0);
2295  continue;
2296  }
2297 
2298  if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2299  Masked = true;
2300  V = V.getOperand(0);
2301  continue;
2302  }
2303 
2304  break;
2305  }
2306 
2307  // If this is not a carry, return.
2308  if (V.getResNo() != 1)
2309  return SDValue();
2310 
2311  if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2312  V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2313  return SDValue();
2314 
2315  // If the result is masked, then no matter what kind of bool it is we can
2316  // return. If it isn't, then we need to make sure the bool type is either 0 or
2317  // 1 and not other values.
2318  if (Masked ||
2319  TLI.getBooleanContents(V.getValueType()) ==
2321  return V;
2322 
2323  return SDValue();
2324 }
2325 
2326 /// Given the operands of an add/sub operation, see if the 2nd operand is a
2327 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2328 /// the opcode and bypass the mask operation.
2329 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
2330  SelectionDAG &DAG, const SDLoc &DL) {
2331  if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
2332  return SDValue();
2333 
2334  EVT VT = N0.getValueType();
2335  if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
2336  return SDValue();
2337 
2338  // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2339  // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2340  return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
2341 }
2342 
2343 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2344  EVT VT = N0.getValueType();
2345  SDLoc DL(LocReference);
2346 
2347  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2348  if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2350  return DAG.getNode(ISD::SUB, DL, VT, N0,
2351  DAG.getNode(ISD::SHL, DL, VT,
2352  N1.getOperand(0).getOperand(1),
2353  N1.getOperand(1)));
2354 
2355  if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
2356  return V;
2357 
2358  // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2359  // rather than 'add 0/-1' (the zext should get folded).
2360  // add (sext i1 Y), X --> sub X, (zext i1 Y)
2361  if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2362  N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
2364  SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2365  return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2366  }
2367 
2368  // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2369  if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2370  VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2371  if (TN->getVT() == MVT::i1) {
2372  SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2373  DAG.getConstant(1, DL, VT));
2374  return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2375  }
2376  }
2377 
2378  // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2379  if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2380  N1.getResNo() == 0)
2381  return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2382  N0, N1.getOperand(0), N1.getOperand(2));
2383 
2384  // (add X, Carry) -> (addcarry X, 0, Carry)
2386  if (SDValue Carry = getAsCarry(TLI, N1))
2387  return DAG.getNode(ISD::ADDCARRY, DL,
2388  DAG.getVTList(VT, Carry.getValueType()), N0,
2389  DAG.getConstant(0, DL, VT), Carry);
2390 
2391  return SDValue();
2392 }
2393 
2394 SDValue DAGCombiner::visitADDC(SDNode *N) {
2395  SDValue N0 = N->getOperand(0);
2396  SDValue N1 = N->getOperand(1);
2397  EVT VT = N0.getValueType();
2398  SDLoc DL(N);
2399 
2400  // If the flag result is dead, turn this into an ADD.
2401  if (!N->hasAnyUseOfValue(1))
2402  return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2403  DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2404 
2405  // canonicalize constant to RHS.
2408  if (N0C && !N1C)
2409  return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2410 
2411  // fold (addc x, 0) -> x + no carry out
2412  if (isNullConstant(N1))
2413  return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2414  DL, MVT::Glue));
2415 
2416  // If it cannot overflow, transform into an add.
2417  if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2418  return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2419  DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2420 
2421  return SDValue();
2422 }
2423 
2424 static SDValue flipBoolean(SDValue V, const SDLoc &DL,
2425  SelectionDAG &DAG, const TargetLowering &TLI) {
2426  EVT VT = V.getValueType();
2427 
2428  SDValue Cst;
2429  switch (TLI.getBooleanContents(VT)) {
2432  Cst = DAG.getConstant(1, DL, VT);
2433  break;
2435  Cst = DAG.getConstant(-1, DL, VT);
2436  break;
2437  }
2438 
2439  return DAG.getNode(ISD::XOR, DL, VT, V, Cst);
2440 }
2441 
2443  if (V.getOpcode() != ISD::XOR)
2444  return SDValue();
2445 
2446  ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
2447  if (!Const)
2448  return SDValue();
2449 
2450  EVT VT = V.getValueType();
2451 
2452  bool IsFlip = false;
2453  switch(TLI.getBooleanContents(VT)) {
2455  IsFlip = Const->isOne();
2456  break;
2458  IsFlip = Const->isAllOnesValue();
2459  break;
2461  IsFlip = (Const->getAPIntValue() & 0x01) == 1;
2462  break;
2463  }
2464 
2465  if (IsFlip)
2466  return V.getOperand(0);
2467  return SDValue();
2468 }
2469 
2470 SDValue DAGCombiner::visitADDO(SDNode *N) {
2471  SDValue N0 = N->getOperand(0);
2472  SDValue N1 = N->getOperand(1);
2473  EVT VT = N0.getValueType();
2474  bool IsSigned = (ISD::SADDO == N->getOpcode());
2475 
2476  EVT CarryVT = N->getValueType(1);
2477  SDLoc DL(N);
2478 
2479  // If the flag result is dead, turn this into an ADD.
2480  if (!N->hasAnyUseOfValue(1))
2481  return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2482  DAG.getUNDEF(CarryVT));
2483 
2484  // canonicalize constant to RHS.
2487  return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
2488 
2489  // fold (addo x, 0) -> x + no carry out
2490  if (isNullOrNullSplat(N1))
2491  return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2492 
2493  if (!IsSigned) {
2494  // If it cannot overflow, transform into an add.
2495  if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2496  return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2497  DAG.getConstant(0, DL, CarryVT));
2498 
2499  // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2500  if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
2501  SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2502  DAG.getConstant(0, DL, VT), N0.getOperand(0));
2503  return CombineTo(N, Sub,
2504  flipBoolean(Sub.getValue(1), DL, DAG, TLI));
2505  }
2506 
2507  if (SDValue Combined = visitUADDOLike(N0, N1, N))
2508  return Combined;
2509 
2510  if (SDValue Combined = visitUADDOLike(N1, N0, N))
2511  return Combined;
2512  }
2513 
2514  return SDValue();
2515 }
2516 
2517 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2518  EVT VT = N0.getValueType();
2519  if (VT.isVector())
2520  return SDValue();
2521 
2522  // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2523  // If Y + 1 cannot overflow.
2524  if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2525  SDValue Y = N1.getOperand(0);
2526  SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2527  if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2528  return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2529  N1.getOperand(2));
2530  }
2531 
2532  // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2534  if (SDValue Carry = getAsCarry(TLI, N1))
2535  return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2536  DAG.getConstant(0, SDLoc(N), VT), Carry);
2537 
2538  return SDValue();
2539 }
2540 
2541 SDValue DAGCombiner::visitADDE(SDNode *N) {
2542  SDValue N0 = N->getOperand(0);
2543  SDValue N1 = N->getOperand(1);
2544  SDValue CarryIn = N->getOperand(2);
2545 
2546  // canonicalize constant to RHS
2549  if (N0C && !N1C)
2550  return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2551  N1, N0, CarryIn);
2552 
2553  // fold (adde x, y, false) -> (addc x, y)
2554  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2555  return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2556 
2557  return SDValue();
2558 }
2559 
2560 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2561  SDValue N0 = N->getOperand(0);
2562  SDValue N1 = N->getOperand(1);
2563  SDValue CarryIn = N->getOperand(2);
2564  SDLoc DL(N);
2565 
2566  // canonicalize constant to RHS
2569  if (N0C && !N1C)
2570  return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2571 
2572  // fold (addcarry x, y, false) -> (uaddo x, y)
2573  if (isNullConstant(CarryIn)) {
2574  if (!LegalOperations ||
2576  return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2577  }
2578 
2579  EVT CarryVT = CarryIn.getValueType();
2580 
2581  // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2582  if (isNullConstant(N0) && isNullConstant(N1)) {
2583  EVT VT = N0.getValueType();
2584  SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2585  AddToWorklist(CarryExt.getNode());
2586  return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2587  DAG.getConstant(1, DL, VT)),
2588  DAG.getConstant(0, DL, CarryVT));
2589  }
2590 
2591  // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry.
2592  if (isBitwiseNot(N0) && isNullConstant(N1)) {
2593  if (SDValue B = extractBooleanFlip(CarryIn, TLI)) {
2594  SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(),
2595  DAG.getConstant(0, DL, N0.getValueType()),
2596  N0.getOperand(0), B);
2597  return CombineTo(N, Sub,
2598  flipBoolean(Sub.getValue(1), DL, DAG, TLI));
2599  }
2600  }
2601 
2602  if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2603  return Combined;
2604 
2605  if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2606  return Combined;
2607 
2608  return SDValue();
2609 }
2610 
2611 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2612  SDNode *N) {
2613  // Iff the flag result is dead:
2614  // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2615  if ((N0.getOpcode() == ISD::ADD ||
2616  (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2617  isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2618  return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2619  N0.getOperand(0), N0.getOperand(1), CarryIn);
2620 
2621  /**
2622  * When one of the addcarry argument is itself a carry, we may be facing
2623  * a diamond carry propagation. In which case we try to transform the DAG
2624  * to ensure linear carry propagation if that is possible.
2625  *
2626  * We are trying to get:
2627  * (addcarry X, 0, (addcarry A, B, Z):Carry)
2628  */
2629  if (auto Y = getAsCarry(TLI, N1)) {
2630  /**
2631  * (uaddo A, B)
2632  * / \
2633  * Carry Sum
2634  * | \
2635  * | (addcarry *, 0, Z)
2636  * | /
2637  * \ Carry
2638  * | /
2639  * (addcarry X, *, *)
2640  */
2641  if (Y.getOpcode() == ISD::UADDO &&
2642  CarryIn.getResNo() == 1 &&
2643  CarryIn.getOpcode() == ISD::ADDCARRY &&
2644  isNullConstant(CarryIn.getOperand(1)) &&
2645  CarryIn.getOperand(0) == Y.getValue(0)) {
2646  auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2647  Y.getOperand(0), Y.getOperand(1),
2648  CarryIn.getOperand(2));
2649  AddToWorklist(NewY.getNode());
2650  return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2651  DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2652  NewY.getValue(1));
2653  }
2654  }
2655 
2656  return SDValue();
2657 }
2658 
2659 // Since it may not be valid to emit a fold to zero for vector initializers
2660 // check if we can before folding.
2661 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2662  SelectionDAG &DAG, bool LegalOperations) {
2663  if (!VT.isVector())
2664  return DAG.getConstant(0, DL, VT);
2665  if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2666  return DAG.getConstant(0, DL, VT);
2667  return SDValue();
2668 }
2669 
2670 SDValue DAGCombiner::visitSUB(SDNode *N) {
2671  SDValue N0 = N->getOperand(0);
2672  SDValue N1 = N->getOperand(1);
2673  EVT VT = N0.getValueType();
2674  SDLoc DL(N);
2675 
2676  // fold vector ops
2677  if (VT.isVector()) {
2678  if (SDValue FoldedVOp = SimplifyVBinOp(N))
2679  return FoldedVOp;
2680 
2681  // fold (sub x, 0) -> x, vector edition
2683  return N0;
2684  }
2685 
2686  // fold (sub x, x) -> 0
2687  // FIXME: Refactor this and xor and other similar operations together.
2688  if (N0 == N1)
2689  return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
2692  // fold (sub c1, c2) -> c1-c2
2693  return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2694  N1.getNode());
2695  }
2696 
2697  if (SDValue NewSel = foldBinOpIntoSelect(N))
2698  return NewSel;
2699 
2701 
2702  // fold (sub x, c) -> (add x, -c)
2703  if (N1C) {
2704  return DAG.getNode(ISD::ADD, DL, VT, N0,
2705  DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2706  }
2707 
2708  if (isNullOrNullSplat(N0)) {
2709  unsigned BitWidth = VT.getScalarSizeInBits();
2710  // Right-shifting everything out but the sign bit followed by negation is
2711  // the same as flipping arithmetic/logical shift type without the negation:
2712  // -(X >>u 31) -> (X >>s 31)
2713  // -(X >>s 31) -> (X >>u 31)
2714  if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2715  ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2716  if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2717  auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2718  if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2719  return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2720  }
2721  }
2722 
2723  // 0 - X --> 0 if the sub is NUW.
2724  if (N->getFlags().hasNoUnsignedWrap())
2725  return N0;
2726 
2727  if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2728  // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2729  // N1 must be 0 because negating the minimum signed value is undefined.
2730  if (N->getFlags().hasNoSignedWrap())
2731  return N0;
2732 
2733  // 0 - X --> X if X is 0 or the minimum signed value.
2734  return N1;
2735  }
2736  }
2737 
2738  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2739  if (isAllOnesOrAllOnesSplat(N0))
2740  return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2741 
2742  // fold (A - (0-B)) -> A+B
2743  if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2744  return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
2745 
2746  // fold A-(A-B) -> B
2747  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2748  return N1.getOperand(1);
2749 
2750  // fold (A+B)-A -> B
2751  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2752  return N0.getOperand(1);
2753 
2754  // fold (A+B)-B -> A
2755  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2756  return N0.getOperand(0);
2757 
2758  // fold C2-(A+C1) -> (C2-C1)-A
2759  if (N1.getOpcode() == ISD::ADD) {
2760  SDValue N11 = N1.getOperand(1);
2761  if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2762  isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2763  SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2764  return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2765  }
2766  }
2767 
2768  // fold ((A+(B+or-C))-B) -> A+or-C
2769  if (N0.getOpcode() == ISD::ADD &&
2770  (N0.getOperand(1).getOpcode() == ISD::SUB ||
2771  N0.getOperand(1).getOpcode() == ISD::ADD) &&
2772  N0.getOperand(1).getOperand(0) == N1)
2773  return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2774  N0.getOperand(1).getOperand(1));
2775 
2776  // fold ((A+(C+B))-B) -> A+C
2777  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2778  N0.getOperand(1).getOperand(1) == N1)
2779  return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2780  N0.getOperand(1).getOperand(0));
2781 
2782  // fold ((A-(B-C))-C) -> A-B
2783  if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2784  N0.getOperand(1).getOperand(1) == N1)
2785  return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2786  N0.getOperand(1).getOperand(0));
2787 
2788  // fold (A-(B-C)) -> A+(C-B)
2789  if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
2790  return DAG.getNode(ISD::ADD, DL, VT, N0,
2791  DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
2792  N1.getOperand(0)));
2793 
2794  // fold (X - (-Y * Z)) -> (X + (Y * Z))
2795  if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
2796  if (N1.getOperand(0).getOpcode() == ISD::SUB &&
2798  SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
2799  N1.getOperand(0).getOperand(1),
2800  N1.getOperand(1));
2801  return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
2802  }
2803  if (N1.getOperand(1).getOpcode() == ISD::SUB &&
2805  SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
2806  N1.getOperand(0),
2807  N1.getOperand(1).getOperand(1));
2808  return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
2809  }
2810  }
2811 
2812  // If either operand of a sub is undef, the result is undef
2813  if (N0.isUndef())
2814  return N0;
2815  if (N1.isUndef())
2816  return N1;
2817 
2818  if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2819  return V;
2820 
2821  if (SDValue V = foldAddSubOfSignBit(N, DAG))
2822  return V;
2823 
2824  if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
2825  return V;
2826 
2827  // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
2828  // rather than 'sub 0/1' (the sext should get folded).
2829  // sub X, (zext i1 Y) --> add X, (sext i1 Y)
2830  if (N1.getOpcode() == ISD::ZERO_EXTEND &&
2831  N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
2832  TLI.getBooleanContents(VT) ==
2834  SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
2835  return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
2836  }
2837 
2838  // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
2839  if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
2840  if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
2841  SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
2842  SDValue S0 = N1.getOperand(0);
2843  if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) {
2844  unsigned OpSizeInBits = VT.getScalarSizeInBits();
2846  if (C->getAPIntValue() == (OpSizeInBits - 1))
2847  return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
2848  }
2849  }
2850  }
2851 
2852  // If the relocation model supports it, consider symbol offsets.
2853  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2854  if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2855  // fold (sub Sym, c) -> Sym-c
2856  if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2857  return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2858  GA->getOffset() -
2859  (uint64_t)N1C->getSExtValue());
2860  // fold (sub Sym+c1, Sym+c2) -> c1-c2
2861  if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2862  if (GA->getGlobal() == GB->getGlobal())
2863  return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2864  DL, VT);
2865  }
2866 
2867  // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2868  if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2869  VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2870  if (TN->getVT() == MVT::i1) {
2871  SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2872  DAG.getConstant(1, DL, VT));
2873  return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2874  }
2875  }
2876 
2877  // Prefer an add for more folding potential and possibly better codegen:
2878  // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
2879  if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
2880  SDValue ShAmt = N1.getOperand(1);
2881  ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2882  if (ShAmtC && ShAmtC->getZExtValue() == N1.getScalarValueSizeInBits() - 1) {
2883  SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
2884  return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
2885  }
2886  }
2887 
2888  return SDValue();
2889 }
2890 
2891 SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
2892  SDValue N0 = N->getOperand(0);
2893  SDValue N1 = N->getOperand(1);
2894  EVT VT = N0.getValueType();
2895  SDLoc DL(N);
2896 
2897  // fold vector ops
2898  if (VT.isVector()) {
2899  // TODO SimplifyVBinOp
2900 
2901  // fold (sub_sat x, 0) -> x, vector edition
2903  return N0;
2904  }
2905 
2906  // fold (sub_sat x, undef) -> 0
2907  if (N0.isUndef() || N1.isUndef())
2908  return DAG.getConstant(0, DL, VT);
2909 
2910  // fold (sub_sat x, x) -> 0
2911  if (N0 == N1)
2912  return DAG.getConstant(0, DL, VT);
2913 
2916  // fold (sub_sat c1, c2) -> c3
2917  return DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, N0.getNode(),
2918  N1.getNode());
2919  }
2920 
2921  // fold (sub_sat x, 0) -> x
2922  if (isNullConstant(N1))
2923  return N0;
2924 
2925  return SDValue();
2926 }
2927 
2928 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2929  SDValue N0 = N->getOperand(0);
2930  SDValue N1 = N->getOperand(1);
2931  EVT VT = N0.getValueType();
2932  SDLoc DL(N);
2933 
2934  // If the flag result is dead, turn this into an SUB.
2935  if (!N->hasAnyUseOfValue(1))
2936  return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2937  DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2938 
2939  // fold (subc x, x) -> 0 + no borrow
2940  if (N0 == N1)
2941  return CombineTo(N, DAG.getConstant(0, DL, VT),
2942  DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2943 
2944  // fold (subc x, 0) -> x + no borrow
2945  if (isNullConstant(N1))
2946  return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2947 
2948  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2949  if (isAllOnesConstant(N0))
2950  return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2951  DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2952 
2953  return SDValue();
2954 }
2955 
2956 SDValue DAGCombiner::visitSUBO(SDNode *N) {
2957  SDValue N0 = N->getOperand(0);
2958  SDValue N1 = N->getOperand(1);
2959  EVT VT = N0.getValueType();
2960  bool IsSigned = (ISD::SSUBO == N->getOpcode());
2961 
2962  EVT CarryVT = N->getValueType(1);
2963  SDLoc DL(N);
2964 
2965  // If the flag result is dead, turn this into an SUB.
2966  if (!N->hasAnyUseOfValue(1))
2967  return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2968  DAG.getUNDEF(CarryVT));
2969 
2970  // fold (subo x, x) -> 0 + no borrow
2971  if (N0 == N1)
2972  return CombineTo(N, DAG.getConstant(0, DL, VT),
2973  DAG.getConstant(0, DL, CarryVT));
2974 
2975  // fold (subo x, 0) -> x + no borrow
2976  if (isNullOrNullSplat(N1))
2977  return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2978 
2979  // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2980  if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
2981  return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2982  DAG.getConstant(0, DL, CarryVT));
2983 
2984  return SDValue();
2985 }
2986 
2987 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2988  SDValue N0 = N->getOperand(0);
2989  SDValue N1 = N->getOperand(1);
2990  SDValue CarryIn = N->getOperand(2);
2991 
2992  // fold (sube x, y, false) -> (subc x, y)
2993  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2994  return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2995 
2996  return SDValue();
2997 }
2998 
2999 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
3000  SDValue N0 = N->getOperand(0);
3001  SDValue N1 = N->getOperand(1);
3002  SDValue CarryIn = N->getOperand(2);
3003 
3004  // fold (subcarry x, y, false) -> (usubo x, y)
3005  if (isNullConstant(CarryIn)) {
3006  if (!LegalOperations ||
3008  return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
3009  }
3010 
3011  return SDValue();
3012 }
3013 
3014 SDValue DAGCombiner::visitMUL(SDNode *N) {
3015  SDValue N0 = N->getOperand(0);
3016  SDValue N1 = N->getOperand(1);
3017  EVT VT = N0.getValueType();
3018 
3019  // fold (mul x, undef) -> 0
3020  if (N0.isUndef() || N1.isUndef())
3021  return DAG.getConstant(0, SDLoc(N), VT);
3022 
3023  bool N0IsConst = false;
3024  bool N1IsConst = false;
3025  bool N1IsOpaqueConst = false;
3026  bool N0IsOpaqueConst = false;
3027  APInt ConstValue0, ConstValue1;
3028  // fold vector ops
3029  if (VT.isVector()) {
3030  if (SDValue FoldedVOp = SimplifyVBinOp(N))
3031  return FoldedVOp;
3032 
3033  N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
3034  N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
3035  assert((!N0IsConst ||
3036  ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
3037  "Splat APInt should be element width");
3038  assert((!N1IsConst ||
3039  ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
3040  "Splat APInt should be element width");
3041  } else {
3042  N0IsConst = isa<ConstantSDNode>(N0);
3043  if (N0IsConst) {
3044  ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
3045  N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
3046  }
3047  N1IsConst = isa<ConstantSDNode>(N1);
3048  if (N1IsConst) {
3049  ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3050  N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3051  }
3052  }
3053 
3054  // fold (mul c1, c2) -> c1*c2
3055  if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
3056  return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
3057  N0.getNode(), N1.getNode());
3058 
3059  // canonicalize constant to RHS (vector doesn't have to splat)
3062  return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
3063  // fold (mul x, 0) -> 0
3064  if (N1IsConst && ConstValue1.isNullValue())
3065  return N1;
3066  // fold (mul x, 1) -> x
3067  if (N1IsConst && ConstValue1.isOneValue())
3068  return N0;
3069 
3070  if (SDValue NewSel = foldBinOpIntoSelect(N))
3071  return NewSel;
3072 
3073  // fold (mul x, -1) -> 0-x
3074  if (N1IsConst && ConstValue1.isAllOnesValue()) {
3075  SDLoc DL(N);
3076  return DAG.getNode(ISD::SUB, DL, VT,
3077  DAG.getConstant(0, DL, VT), N0);
3078  }
3079  // fold (mul x, (1 << c)) -> x << c
3080  if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3081  DAG.isKnownToBeAPowerOfTwo(N1) &&
3082  (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
3083  SDLoc DL(N);
3084  SDValue LogBase2 = BuildLogBase2(N1, DL);
3085  EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3086  SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3087  return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
3088  }
3089  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3090  if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
3091  unsigned Log2Val = (-ConstValue1).logBase2();
3092  SDLoc DL(N);
3093  // FIXME: If the input is something that is easily negated (e.g. a
3094  // single-use add), we should put the negate there.
3095  return DAG.getNode(ISD::SUB, DL, VT,
3096  DAG.getConstant(0, DL, VT),
3097  DAG.getNode(ISD::SHL, DL, VT, N0,
3098  DAG.getConstant(Log2Val, DL,
3099  getShiftAmountTy(N0.getValueType()))));
3100  }
3101 
3102  // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3103  // mul x, (2^N + 1) --> add (shl x, N), x
3104  // mul x, (2^N - 1) --> sub (shl x, N), x
3105  // Examples: x * 33 --> (x << 5) + x
3106  // x * 15 --> (x << 4) - x
3107  // x * -33 --> -((x << 5) + x)
3108  // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3109  if (N1IsConst && TLI.decomposeMulByConstant(VT, N1)) {
3110  // TODO: We could handle more general decomposition of any constant by
3111  // having the target set a limit on number of ops and making a
3112  // callback to determine that sequence (similar to sqrt expansion).
3113  unsigned MathOp = ISD::DELETED_NODE;
3114  APInt MulC = ConstValue1.abs();
3115  if ((MulC - 1).isPowerOf2())
3116  MathOp = ISD::ADD;
3117  else if ((MulC + 1).isPowerOf2())
3118  MathOp = ISD::SUB;
3119 
3120  if (MathOp != ISD::DELETED_NODE) {
3121  unsigned ShAmt = MathOp == ISD::ADD ? (MulC - 1).logBase2()
3122  : (MulC + 1).logBase2();
3123  assert(ShAmt > 0 && ShAmt < VT.getScalarSizeInBits() &&
3124  "Not expecting multiply-by-constant that could have simplified");
3125  SDLoc DL(N);
3126  SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, N0,
3127  DAG.getConstant(ShAmt, DL, VT));
3128  SDValue R = DAG.getNode(MathOp, DL, VT, Shl, N0);
3129  if (ConstValue1.isNegative())
3130  R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
3131  return R;
3132  }
3133  }
3134 
3135  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3136  if (N0.getOpcode() == ISD::SHL &&
3137  isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3138  isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3139  SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
3141  return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
3142  }
3143 
3144  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3145  // use.
3146  {
3147  SDValue Sh(nullptr, 0), Y(nullptr, 0);
3148 
3149  // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3150  if (N0.getOpcode() == ISD::SHL &&
3152  N0.getNode()->hasOneUse()) {
3153  Sh = N0; Y = N1;
3154  } else if (N1.getOpcode() == ISD::SHL &&
3156  N1.getNode()->hasOneUse()) {
3157  Sh = N1; Y = N0;
3158  }
3159 
3160  if (Sh.getNode()) {
3161  SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
3162  return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
3163  }
3164  }
3165 
3166  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3168  N0.getOpcode() == ISD::ADD &&
3170  isMulAddWithConstProfitable(N, N0, N1))
3171  return DAG.getNode(ISD::ADD, SDLoc(N), VT,
3172  DAG.getNode(ISD::MUL, SDLoc(N0), VT,
3173  N0.getOperand(0), N1),
3174  DAG.getNode(ISD::MUL, SDLoc(N1), VT,
3175  N0.getOperand(1), N1));
3176 
3177  // reassociate mul
3178  if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
3179  return RMUL;
3180 
3181  return SDValue();
3182 }
3183 
3184 /// Return true if divmod libcall is available.
3185 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
3186  const TargetLowering &TLI) {
3187  RTLIB::Libcall LC;
3188  EVT NodeType = Node->getValueType(0);
3189  if (!NodeType.isSimple())
3190  return false;
3191  switch (NodeType.getSimpleVT().SimpleTy) {
3192  default: return false; // No libcall for vector types.
3193  case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
3194  case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
3195  case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
3196  case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
3197  case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
3198  }
3199 
3200  return TLI.getLibcallName(LC) != nullptr;
3201 }
3202 
3203 /// Issue divrem if both quotient and remainder are needed.
3204 SDValue DAGCombiner::useDivRem(SDNode *Node) {
3205  if (Node->use_empty())
3206  return SDValue(); // This is a dead node, leave it alone.
3207 
3208  unsigned Opcode = Node->getOpcode();
3209  bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
3210  unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3211 
3212  // DivMod lib calls can still work on non-legal types if using lib-calls.
3213  EVT VT = Node->getValueType(0);
3214  if (VT.isVector() || !VT.isInteger())
3215  return SDValue();
3216 
3217  if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
3218  return SDValue();
3219 
3220  // If DIVREM is going to get expanded into a libcall,
3221  // but there is no libcall available, then don't combine.
3222  if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
3223  !isDivRemLibcallAvailable(Node, isSigned, TLI))
3224  return SDValue();
3225 
3226  // If div is legal, it's better to do the normal expansion
3227  unsigned OtherOpcode = 0;
3228  if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
3229  OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
3230  if (TLI.isOperationLegalOrCustom(Opcode, VT))
3231  return SDValue();
3232  } else {
3233  OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3234  if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
3235  return SDValue();
3236  }
3237 
3238  SDValue Op0 = Node->getOperand(0);
3239  SDValue Op1 = Node->getOperand(1);
3240  SDValue combined;
3241  for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
3242  UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
3243  SDNode *User = *UI;
3244  if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
3245  User->use_empty())
3246  continue;
3247  // Convert the other matching node(s), too;
3248  // otherwise, the DIVREM may get target-legalized into something
3249  // target-specific that we won't be able to recognize.
3250  unsigned UserOpc = User->getOpcode();
3251  if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
3252  User->getOperand(0) == Op0 &&
3253  User->getOperand(1) == Op1) {
3254  if (!combined) {
3255  if (UserOpc == OtherOpcode) {
3256  SDVTList VTs = DAG.getVTList(VT, VT);
3257  combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
3258  } else if (UserOpc == DivRemOpc) {
3259  combined = SDValue(User, 0);
3260  } else {
3261  assert(UserOpc == Opcode);
3262  continue;
3263  }
3264  }
3265  if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
3266  CombineTo(User, combined);
3267  else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
3268  CombineTo(User, combined.getValue(1));
3269  }
3270  }
3271  return combined;
3272 }
3273 
3275  SDValue N0 = N->getOperand(0);
3276  SDValue N1 = N->getOperand(1);
3277  EVT VT = N->getValueType(0);
3278  SDLoc DL(N);
3279 
3280  unsigned Opc = N->getOpcode();
3281  bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
3283 
3284  // X / undef -> undef
3285  // X % undef -> undef
3286  // X / 0 -> undef
3287  // X % 0 -> undef
3288  // NOTE: This includes vectors where any divisor element is zero/undef.
3289  if (DAG.isUndef(Opc, {N0, N1}))
3290  return DAG.getUNDEF(VT);
3291 
3292  // undef / X -> 0
3293  // undef % X -> 0
3294  if (N0.isUndef())
3295  return DAG.getConstant(0, DL, VT);
3296 
3297  // 0 / X -> 0
3298  // 0 % X -> 0
3300  if (N0C && N0C->isNullValue())
3301  return N0;
3302 
3303  // X / X -> 1
3304  // X % X -> 0
3305  if (N0 == N1)
3306  return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
3307 
3308  // X / 1 -> X
3309  // X % 1 -> 0
3310  // If this is a boolean op (single-bit element type), we can't have
3311  // division-by-zero or remainder-by-zero, so assume the divisor is 1.
3312  // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
3313  // it's a 1.
3314  if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
3315  return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
3316 
3317  return SDValue();
3318 }
3319 
3320 SDValue DAGCombiner::visitSDIV(SDNode *N) {
3321  SDValue N0 = N->getOperand(0);
3322  SDValue N1 = N->getOperand(1);
3323  EVT VT = N->getValueType(0);
3324  EVT CCVT = getSetCCResultType(VT);
3325 
3326  // fold vector ops
3327  if (VT.isVector())
3328  if (SDValue FoldedVOp = SimplifyVBinOp(N))
3329  return FoldedVOp;
3330 
3331  SDLoc DL(N);
3332 
3333  // fold (sdiv c1, c2) -> c1/c2
3336  if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
3337  return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
3338  // fold (sdiv X, -1) -> 0-X
3339  if (N1C && N1C->isAllOnesValue())
3340  return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
3341  // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3342  if (N1C && N1C->getAPIntValue().isMinSignedValue())
3343  return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3344  DAG.getConstant(1, DL, VT),
3345  DAG.getConstant(0, DL, VT));
3346 
3347  if (SDValue V = simplifyDivRem(N, DAG))
3348  return V;
3349 
3350  if (SDValue NewSel = foldBinOpIntoSelect(N))
3351  return NewSel;
3352 
3353  // If we know the sign bits of both operands are zero, strength reduce to a
3354  // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
3355  if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3356  return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
3357 
3358  if (SDValue V = visitSDIVLike(N0, N1, N)) {
3359  // If the corresponding remainder node exists, update its users with
3360  // (Dividend - (Quotient * Divisor).
3361  if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
3362  { N0, N1 })) {
3363  SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3364  SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3365  AddToWorklist(Mul.getNode());
3366  AddToWorklist(Sub.getNode());
3367  CombineTo(RemNode, Sub);
3368  }
3369  return V;
3370  }
3371 
3372  // sdiv, srem -> sdivrem
3373  // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3374  // true. Otherwise, we break the simplification logic in visitREM().
3376  if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3377  if (SDValue DivRem = useDivRem(N))
3378  return DivRem;
3379 
3380  return SDValue();
3381 }
3382 
3383 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3384  SDLoc DL(N);
3385  EVT VT = N->getValueType(0);
3386  EVT CCVT = getSetCCResultType(VT);
3387  unsigned BitWidth = VT.getScalarSizeInBits();
3388 
3389  // Helper for determining whether a value is a power-2 constant scalar or a
3390  // vector of such elements.
3391  auto IsPowerOfTwo = [](ConstantSDNode *C) {
3392  if (C->isNullValue() || C->isOpaque())
3393  return false;
3394  if (C->getAPIntValue().isPowerOf2())
3395  return true;
3396  if ((-C->getAPIntValue()).isPowerOf2())
3397  return true;
3398  return false;
3399  };
3400 
3401  // fold (sdiv X, pow2) -> simple ops after legalize
3402  // FIXME: We check for the exact bit here because the generic lowering gives
3403  // better results in that case. The target-specific lowering should learn how
3404  // to handle exact sdivs efficiently.
3405  if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
3406  // Target-specific implementation of sdiv x, pow2.
3407  if (SDValue Res = BuildSDIVPow2(N))
3408  return Res;
3409 
3410  // Create constants that are functions of the shift amount value.
3411  EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
3412  SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
3413  SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
3414  C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
3415  SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
3416  if (!isConstantOrConstantVector(Inexact))
3417  return SDValue();
3418 
3419  // Splat the sign bit into the register
3420  SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
3421  DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
3422  AddToWorklist(Sign.getNode());
3423 
3424  // Add (N0 < 0) ? abs2 - 1 : 0;
3425  SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
3426  AddToWorklist(Srl.getNode());
3427  SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
3428  AddToWorklist(Add.getNode());
3429  SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
3430  AddToWorklist(Sra.getNode());
3431 
3432  // Special case: (sdiv X, 1) -> X
3433  // Special Case: (sdiv X, -1) -> 0-X
3434  SDValue One = DAG.getConstant(1, DL, VT);
3435  SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
3436  SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
3437  SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
3438  SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
3439  Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
3440 
3441  // If dividing by a positive value, we're done. Otherwise, the result must
3442  // be negated.
3443  SDValue Zero = DAG.getConstant(0, DL, VT);
3444  SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
3445 
3446  // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3447  SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
3448  SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
3449  return Res;
3450  }
3451 
3452  // If integer divide is expensive and we satisfy the requirements, emit an
3453  // alternate sequence. Targets may check function attributes for size/speed
3454  // trade-offs.
3456  if (isConstantOrConstantVector(N1) &&
3457  !TLI.isIntDivCheap(N->getValueType(0), Attr))
3458  if (SDValue Op = BuildSDIV(N))
3459  return Op;
3460 
3461  return SDValue();
3462 }
3463 
3464 SDValue DAGCombiner::visitUDIV(SDNode *N) {
3465  SDValue N0 = N->getOperand(0);
3466  SDValue N1 = N->getOperand(1);
3467  EVT VT = N->getValueType(0);
3468  EVT CCVT = getSetCCResultType(VT);
3469 
3470  // fold vector ops
3471  if (VT.isVector())
3472  if (SDValue FoldedVOp = SimplifyVBinOp(N))
3473  return FoldedVOp;
3474 
3475  SDLoc DL(N);
3476 
3477  // fold (udiv c1, c2) -> c1/c2
3480  if (N0C && N1C)
3481  if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
3482  N0C, N1C))
3483  return Folded;
3484  // fold (udiv X, -1) -> select(X == -1, 1, 0)
3485  if (N1C && N1C->getAPIntValue().isAllOnesValue())
3486  return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3487  DAG.getConstant(1, DL, VT),
3488  DAG.getConstant(0, DL, VT));
3489 
3490  if (SDValue V = simplifyDivRem(N, DAG))
3491  return V;
3492 
3493  if (SDValue NewSel = foldBinOpIntoSelect(N))
3494  return NewSel;
3495 
3496  if (SDValue V = visitUDIVLike(N0, N1, N)) {
3497  // If the corresponding remainder node exists, update its users with
3498  // (Dividend - (Quotient * Divisor).
3499  if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
3500  { N0, N1 })) {
3501  SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3502  SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3503  AddToWorklist(Mul.getNode());
3504  AddToWorklist(Sub.getNode());
3505  CombineTo(RemNode, Sub);
3506  }
3507  return V;
3508  }
3509 
3510  // sdiv, srem -> sdivrem
3511  // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3512  // true. Otherwise, we break the simplification logic in visitREM().
3514  if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3515  if (SDValue DivRem = useDivRem(N))
3516  return DivRem;
3517 
3518  return SDValue();
3519 }
3520 
3521 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3522  SDLoc DL(N);
3523  EVT VT = N->getValueType(0);
3524 
3525  // fold (udiv x, (1 << c)) -> x >>u c
3526  if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3527  DAG.isKnownToBeAPowerOfTwo(N1)) {
3528  SDValue LogBase2 = BuildLogBase2(N1, DL);
3529  AddToWorklist(LogBase2.getNode());
3530 
3531  EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3532  SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3533  AddToWorklist(Trunc.getNode());
3534  return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3535  }
3536 
3537  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3538  if (N1.getOpcode() == ISD::SHL) {
3539  SDValue N10 = N1.getOperand(0);
3540  if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3541  DAG.isKnownToBeAPowerOfTwo(N10)) {
3542  SDValue LogBase2 = BuildLogBase2(N10, DL);
3543  AddToWorklist(LogBase2.getNode());
3544 
3545  EVT ADDVT = N1.getOperand(1).getValueType();
3546  SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3547  AddToWorklist(Trunc.getNode());
3548  SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3549  AddToWorklist(Add.getNode());
3550  return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3551  }
3552  }
3553 
3554  // fold (udiv x, c) -> alternate
3556  if (isConstantOrConstantVector(N1) &&
3557  !TLI.isIntDivCheap(N->getValueType(0), Attr))
3558  if (SDValue Op = BuildUDIV(N))
3559  return Op;
3560 
3561  return SDValue();
3562 }
3563 
3564 // handles ISD::SREM and ISD::UREM
3565 SDValue DAGCombiner::visitREM(SDNode *N) {
3566  unsigned Opcode = N->getOpcode();
3567  SDValue N0 = N->getOperand(0);
3568  SDValue N1 = N->getOperand(1);
3569  EVT VT = N->getValueType(0);
3570  EVT CCVT = getSetCCResultType(VT);
3571 
3572  bool isSigned = (Opcode == ISD::SREM);
3573  SDLoc DL(N);
3574 
3575  // fold (rem c1, c2) -> c1%c2
3578  if (N0C && N1C)
3579  if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3580  return Folded;
3581  // fold (urem X, -1) -> select(X == -1, 0, x)
3582  if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue())
3583  return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3584  DAG.getConstant(0, DL, VT), N0);
3585 
3586  if (SDValue V = simplifyDivRem(N, DAG))
3587  return V;
3588 
3589  if (SDValue NewSel = foldBinOpIntoSelect(N))
3590  return NewSel;
3591 
3592  if (isSigned) {
3593  // If we know the sign bits of both operands are zero, strength reduce to a
3594  // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3595  if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3596  return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3597  } else {
3598  SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3599  if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3600  // fold (urem x, pow2) -> (and x, pow2-1)
3601  SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3602  AddToWorklist(Add.getNode());
3603  return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3604  }
3605  if (N1.getOpcode() == ISD::SHL &&
3606  DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3607  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3608  SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3609  AddToWorklist(Add.getNode());
3610  return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3611  }
3612  }
3613 
3615 
3616  // If X/C can be simplified by the division-by-constant logic, lower
3617  // X%C to the equivalent of X-X/C*C.
3618  // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
3619  // speculative DIV must not cause a DIVREM conversion. We guard against this
3620  // by skipping the simplification if isIntDivCheap(). When div is not cheap,
3621  // combine will not return a DIVREM. Regardless, checking cheapness here
3622  // makes sense since the simplification results in fatter code.
3623  if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
3624  SDValue OptimizedDiv =
3625  isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
3626  if (OptimizedDiv.getNode()) {
3627  // If the equivalent Div node also exists, update its users.
3628  unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3629  if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
3630  { N0, N1 }))
3631  CombineTo(DivNode, OptimizedDiv);
3632  SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3633  SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3634  AddToWorklist(OptimizedDiv.getNode());
3635  AddToWorklist(Mul.getNode());
3636  return Sub;
3637  }
3638  }
3639 
3640  // sdiv, srem -> sdivrem
3641  if (SDValue DivRem = useDivRem(N))
3642  return DivRem.getValue(1);
3643 
3644  return SDValue();
3645 }
3646 
3647 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3648  SDValue N0 = N->getOperand(0);
3649  SDValue N1 = N->getOperand(1);
3650  EVT VT = N->getValueType(0);
3651  SDLoc DL(N);
3652 
3653  if (VT.isVector()) {
3654  // fold (mulhs x, 0) -> 0
3656  return N1;
3658  return N0;
3659  }
3660 
3661  // fold (mulhs x, 0) -> 0
3662  if (isNullConstant(N1))
3663  return N1;
3664  // fold (mulhs x, 1) -> (sra x, size(x)-1)
3665  if (isOneConstant(N1))
3666  return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3667  DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3668  getShiftAmountTy(N0.getValueType())));
3669 
3670  // fold (mulhs x, undef) -> 0
3671  if (N0.isUndef() || N1.isUndef())
3672  return DAG.getConstant(0, DL, VT);
3673 
3674  // If the type twice as wide is legal, transform the mulhs to a wider multiply
3675  // plus a shift.
3676  if (VT.isSimple() && !VT.isVector()) {
3677  MVT Simple = VT.getSimpleVT();
3678  unsigned SimpleSize = Simple.getSizeInBits();
3679  EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3680  if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3681  N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3682  N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3683  N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3684  N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3685  DAG.getConstant(SimpleSize, DL,
3686  getShiftAmountTy(N1.getValueType())));
3687  return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3688  }
3689  }
3690 
3691  return SDValue();
3692 }
3693 
3694 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3695  SDValue N0 = N->getOperand(0);
3696  SDValue N1 = N->getOperand(1);
3697  EVT VT = N->getValueType(0);
3698  SDLoc DL(N);
3699 
3700  if (VT.isVector()) {
3701  // fold (mulhu x, 0) -> 0
3703  return N1;
3705  return N0;
3706  }
3707 
3708  // fold (mulhu x, 0) -> 0
3709  if (isNullConstant(N1))
3710  return N1;
3711  // fold (mulhu x, 1) -> 0
3712  if (isOneConstant(N1))
3713  return DAG.getConstant(0, DL, N0.getValueType());
3714  // fold (mulhu x, undef) -> 0
3715  if (N0.isUndef() || N1.isUndef())
3716  return DAG.getConstant(0, DL, VT);
3717 
3718  // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
3719  if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3720  DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
3721  SDLoc DL(N);
3722  unsigned NumEltBits = VT.getScalarSizeInBits();
3723  SDValue LogBase2 = BuildLogBase2(N1, DL);
3724  SDValue SRLAmt = DAG.getNode(
3725  ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
3726  EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3727  SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
3728  return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3729  }
3730 
3731  // If the type twice as wide is legal, transform the mulhu to a wider multiply
3732  // plus a shift.
3733  if (VT.isSimple() && !VT.isVector()) {
3734  MVT Simple = VT.getSimpleVT();
3735  unsigned SimpleSize = Simple.getSizeInBits();
3736  EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3737  if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3738  N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3739  N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3740  N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3741  N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3742  DAG.getConstant(SimpleSize, DL,
3743  getShiftAmountTy(N1.getValueType())));
3744  return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3745  }
3746  }
3747 
3748  return SDValue();
3749 }
3750 
3751 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3752 /// give the opcodes for the two computations that are being performed. Return
3753 /// true if a simplification was made.
3754 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3755  unsigned HiOp) {
3756  // If the high half is not needed, just compute the low half.
3757  bool HiExists = N->hasAnyUseOfValue(1);
3758  if (!HiExists && (!LegalOperations ||
3759  TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3760  SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3761  return CombineTo(N, Res, Res);
3762  }
3763 
3764  // If the low half is not needed, just compute the high half.
3765  bool LoExists = N->hasAnyUseOfValue(0);
3766  if (!LoExists && (!LegalOperations ||
3767  TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
3768  SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3769  return CombineTo(N, Res, Res);
3770  }
3771 
3772  // If both halves are used, return as it is.
3773  if (LoExists && HiExists)
3774  return SDValue();
3775 
3776  // If the two computed results can be simplified separately, separate them.
3777  if (LoExists) {
3778  SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3779  AddToWorklist(Lo.getNode());
3780  SDValue LoOpt = combine(Lo.getNode());
3781  if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3782  (!LegalOperations ||
3783  TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
3784  return CombineTo(N, LoOpt, LoOpt);
3785  }
3786 
3787  if (HiExists) {
3788  SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3789  AddToWorklist(Hi.getNode());
3790  SDValue HiOpt = combine(Hi.getNode());
3791  if (HiOpt.getNode() && HiOpt != Hi &&
3792  (!LegalOperations ||
3793  TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
3794  return CombineTo(N, HiOpt, HiOpt);
3795  }
3796 
3797  return SDValue();
3798 }
3799 
3800 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3801  if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3802  return Res;
3803 
3804  EVT VT = N->getValueType(0);
3805  SDLoc DL(N);
3806 
3807  // If the type is twice as wide is legal, transform the mulhu to a wider
3808  // multiply plus a shift.
3809  if (VT.isSimple() && !VT.isVector()) {
3810  MVT Simple = VT.getSimpleVT();
3811  unsigned SimpleSize = Simple.getSizeInBits();
3812  EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3813  if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3814  SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3815  SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3816  Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3817  // Compute the high part as N1.
3818  Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3819  DAG.getConstant(SimpleSize, DL,
3820  getShiftAmountTy(Lo.getValueType())));
3821  Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3822  // Compute the low part as N0.
3823  Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3824  return CombineTo(N, Lo, Hi);
3825  }
3826  }
3827 
3828  return SDValue();
3829 }
3830 
3831 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3832  if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3833  return Res;
3834 
3835  EVT VT = N->getValueType(0);
3836  SDLoc DL(N);
3837 
3838  // If the type is twice as wide is legal, transform the mulhu to a wider
3839  // multiply plus a shift.
3840  if (VT.isSimple() && !VT.isVector()) {
3841  MVT Simple = VT.getSimpleVT();
3842  unsigned SimpleSize = Simple.getSizeInBits();
3843  EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3844  if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3845  SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3846  SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3847  Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3848  // Compute the high part as N1.
3849  Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3850  DAG.getConstant(SimpleSize, DL,
3851  getShiftAmountTy(Lo.getValueType())));
3852  Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3853  // Compute the low part as N0.
3854  Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3855  return CombineTo(N, Lo, Hi);
3856  }
3857  }
3858 
3859  return SDValue();
3860 }
3861 
3862 SDValue DAGCombiner::visitMULO(SDNode *N) {
3863  bool IsSigned = (ISD::SMULO == N->getOpcode());
3864 
3865  // (mulo x, 2) -> (addo x, x)
3867  if (C2->getAPIntValue() == 2)
3868  return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, SDLoc(N),
3869  N->getVTList(), N->getOperand(0), N->getOperand(0));
3870 
3871  return SDValue();
3872 }
3873 
3874 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3875  SDValue N0 = N->getOperand(0);
3876  SDValue N1 = N->getOperand(1);
3877  EVT VT = N0.getValueType();
3878 
3879  // fold vector ops
3880  if (VT.isVector())
3881  if (SDValue FoldedVOp = SimplifyVBinOp(N))
3882  return FoldedVOp;
3883 
3884  // fold operation with constant operands.
3887  if (N0C && N1C)
3888  return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3889 
3890  // canonicalize constant to RHS
3893  return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3894 
3895  // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
3896  // Only do this if the current op isn't legal and the flipped is.
3897  unsigned Opcode = N->getOpcode();
3898  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3899  if (!TLI.isOperationLegal(Opcode, VT) &&
3900  (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
3901  (N1.isUndef() || DAG.SignBitIsZero(N1))) {
3902  unsigned AltOpcode;
3903  switch (Opcode) {
3904  case ISD::SMIN: AltOpcode = ISD::UMIN; break;
3905  case ISD::SMAX: AltOpcode = ISD::UMAX; break;
3906  case ISD::UMIN: AltOpcode = ISD::SMIN; break;
3907  case ISD::UMAX: AltOpcode = ISD::SMAX; break;
3908  default: llvm_unreachable("Unknown MINMAX opcode");
3909  }
3910  if (TLI.isOperationLegal(AltOpcode, VT))
3911  return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
3912  }
3913 
3914  return SDValue();
3915 }
3916 
3917 /// If this is a bitwise logic instruction and both operands have the same
3918 /// opcode, try to sink the other opcode after the logic instruction.
3919 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
3920  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3921  EVT VT = N0.getValueType();
3922  unsigned LogicOpcode = N->getOpcode();
3923  unsigned HandOpcode = N0.getOpcode();
3924  assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
3925  LogicOpcode == ISD::XOR) && "Expected logic opcode");
3926  assert(HandOpcode == N1.getOpcode() && "Bad input!");
3927 
3928  // Bail early if none of these transforms apply.
3929  if (N0.getNumOperands() == 0)
3930  return SDValue();
3931 
3932  // FIXME: We should check number of uses of the operands to not increase
3933  // the instruction count for all transforms.
3934 
3935  // Handle size-changing casts.
3936  SDValue X = N0.getOperand(0);
3937  SDValue Y = N1.getOperand(0);
3938  EVT XVT = X.getValueType();
3939  SDLoc DL(N);
3940  if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
3941  HandOpcode == ISD::SIGN_EXTEND) {
3942  // If both operands have other uses, this transform would create extra
3943  // instructions without eliminating anything.
3944  if (!N0.hasOneUse() && !N1.hasOneUse())
3945  return SDValue();
3946  // We need matching integer source types.
3947  if (XVT != Y.getValueType())
3948  return SDValue();
3949  // Don't create an illegal op during or after legalization. Don't ever
3950  // create an unsupported vector op.
3951  if ((VT.isVector() || LegalOperations) &&
3952  !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
3953  return SDValue();
3954  // Avoid infinite looping with PromoteIntBinOp.
3955  // TODO: Should we apply desirable/legal constraints to all opcodes?
3956  if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
3957  !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
3958  return SDValue();
3959  // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
3960  SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
3961  return DAG.getNode(HandOpcode, DL, VT, Logic);
3962  }
3963 
3964  // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
3965  if (HandOpcode == ISD::TRUNCATE) {
3966  // If both operands have other uses, this transform would create extra
3967  // instructions without eliminating anything.
3968  if (!N0.hasOneUse() && !N1.hasOneUse())
3969  return SDValue();
3970  // We need matching source types.
3971  if (XVT != Y.getValueType())
3972  return SDValue();
3973  // Don't create an illegal op during or after legalization.
3974  if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
3975  return SDValue();
3976  // Be extra careful sinking truncate. If it's free, there's no benefit in
3977  // widening a binop. Also, don't create a logic op on an illegal type.
3978  if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
3979  return SDValue();
3980  if (!TLI.isTypeLegal(XVT))
3981  return SDValue();
3982  SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
3983  return DAG.getNode(HandOpcode, DL, VT, Logic);
3984  }
3985 
3986  // For binops SHL/SRL/SRA/AND:
3987  // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
3988  if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
3989  HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
3990  N0.getOperand(1) == N1.getOperand(1)) {
3991  // If either operand has other uses, this transform is not an improvement.
3992  if (!N0.hasOneUse() || !N1.hasOneUse())
3993  return SDValue();
3994  SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
3995  return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
3996  }
3997 
3998  // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
3999  if (HandOpcode == ISD::BSWAP) {
4000  // If either operand has other uses, this transform is not an improvement.
4001  if (!N0.hasOneUse() || !N1.hasOneUse())
4002  return SDValue();
4003  SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4004  return DAG.getNode(HandOpcode, DL, VT, Logic);
4005  }
4006 
4007  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4008  // Only perform this optimization up until type legalization, before
4009  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4010  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4011  // we don't want to undo this promotion.
4012  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4013  // on scalars.
4014  if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
4015  Level <= AfterLegalizeTypes) {
4016  // Input types must be integer and the same.
4017  if (XVT.isInteger() && XVT == Y.getValueType()) {
4018  SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4019  return DAG.getNode(HandOpcode, DL, VT, Logic);
4020  }
4021  }
4022 
4023  // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4024  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4025  // If both shuffles use the same mask, and both shuffle within a single
4026  // vector, then it is worthwhile to move the swizzle after the operation.
4027  // The type-legalizer generates this pattern when loading illegal
4028  // vector types from memory. In many cases this allows additional shuffle
4029  // optimizations.
4030  // There are other cases where moving the shuffle after the xor/and/or
4031  // is profitable even if shuffles don't perform a swizzle.
4032  // If both shuffles use the same mask, and both shuffles have the same first
4033  // or second operand, then it might still be profitable to move the shuffle
4034  // after the xor/and/or operation.
4035  if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
4036  auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
4037  auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
4038  assert(X.getValueType() == Y.getValueType() &&
4039  "Inputs to shuffles are not the same type");
4040 
4041  // Check that both shuffles use the same mask. The masks are known to be of
4042  // the same length because the result vector type is the same.
4043  // Check also that shuffles have only one use to avoid introducing extra
4044  // instructions.
4045  if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
4046  !SVN0->getMask().equals(SVN1->getMask()))
4047  return SDValue();
4048 
4049  // Don't try to fold this node if it requires introducing a
4050  // build vector of all zeros that might be illegal at this stage.
4051  SDValue ShOp = N0.getOperand(1);
4052  if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4053  ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4054 
4055  // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4056  if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
4057  SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
4058  N0.getOperand(0), N1.getOperand(0));
4059  return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
4060  }
4061 
4062  // Don't try to fold this node if it requires introducing a
4063  // build vector of all zeros that might be illegal at this stage.
4064  ShOp = N0.getOperand(0);
4065  if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4066  ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4067 
4068  // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4069  if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
4070  SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
4071  N1.getOperand(1));
4072  return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
4073  }
4074  }
4075 
4076  return SDValue();
4077 }
4078 
4079 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4080 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
4081  const SDLoc &DL) {
4082  SDValue LL, LR, RL, RR, N0CC, N1CC;
4083  if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
4084  !isSetCCEquivalent(N1, RL, RR, N1CC))
4085  return SDValue();
4086 
4087  assert(N0.getValueType() == N1.getValueType() &&
4088  "Unexpected operand types for bitwise logic op");
4089  assert(LL.getValueType() == LR.getValueType() &&
4090  RL.getValueType() == RR.getValueType() &&
4091  "Unexpected operand types for setcc");
4092 
4093  // If we're here post-legalization or the logic op type is not i1, the logic
4094  // op type must match a setcc result type. Also, all folds require new
4095  // operations on the left and right operands, so those types must match.
4096  EVT VT = N0.getValueType();
4097  EVT OpVT = LL.getValueType();
4098  if (LegalOperations || VT.getScalarType() != MVT::i1)
4099  if (VT != getSetCCResultType(OpVT))
4100  return SDValue();
4101  if (OpVT != RL.getValueType())
4102  return SDValue();
4103 
4104  ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
4105  ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
4106  bool IsInteger = OpVT.isInteger();
4107  if (LR == RR && CC0 == CC1 && IsInteger) {
4108  bool IsZero = isNullOrNullSplat(LR);
4109  bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
4110 
4111  // All bits clear?
4112  bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
4113  // All sign bits clear?
4114  bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
4115  // Any bits set?
4116  bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
4117  // Any sign bits set?
4118  bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
4119 
4120  // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
4121  // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4122  // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
4123  // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
4124  if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
4125  SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
4126  AddToWorklist(Or.getNode());
4127  return DAG.getSetCC(DL, VT, Or, LR, CC1);
4128  }
4129 
4130  // All bits set?
4131  bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
4132  // All sign bits set?
4133  bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
4134  // Any bits clear?
4135  bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
4136  // Any sign bits clear?
4137  bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
4138 
4139  // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
4140  // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
4141  // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
4142  // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
4143  if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
4144  SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
4145  AddToWorklist(And.getNode());
4146  return DAG.getSetCC(DL, VT, And, LR, CC1);
4147  }
4148  }
4149 
4150  // TODO: What is the 'or' equivalent of this fold?
4151  // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
4152  if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
4153  IsInteger && CC0 == ISD::SETNE &&
4154  ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
4155  (isAllOnesConstant(LR) && isNullConstant(RR)))) {
4156  SDValue One = DAG.getConstant(1, DL, OpVT);
4157  SDValue Two = DAG.getConstant(2, DL, OpVT);
4158  SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
4159  AddToWorklist(Add.getNode());
4160  return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
4161  }
4162 
4163  // Try more general transforms if the predicates match and the only user of
4164  // the compares is the 'and' or 'or'.
4165  if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
4166  N0.hasOneUse() && N1.hasOneUse()) {
4167  // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
4168  // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
4169  if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
4170  SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
4171  SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
4172  SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
4173  SDValue Zero = DAG.getConstant(0, DL, OpVT);
4174  return DAG.getSetCC(DL, VT, Or, Zero, CC1);
4175  }
4176 
4177  // Turn compare of constants whose difference is 1 bit into add+and+setcc.
4178  if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
4179  // Match a shared variable operand and 2 non-opaque constant operands.
4182  if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
4183  // Canonicalize larger constant as C0.
4184  if (C1->getAPIntValue().ugt(C0->getAPIntValue()))
4185  std::swap(C0, C1);
4186 
4187  // The difference of the constants must be a single bit.
4188  const APInt &C0Val = C0->getAPIntValue();
4189  const APInt &C1Val = C1->getAPIntValue();
4190  if ((C0Val - C1Val).isPowerOf2()) {
4191  // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) -->
4192  // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq
4193  SDValue OffsetC = DAG.getConstant(-C1Val, DL, OpVT);
4194  SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LL, OffsetC);
4195  SDValue MaskC = DAG.getConstant(~(C0Val - C1Val), DL, OpVT);
4196  SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Add, MaskC);
4197  SDValue Zero = DAG.getConstant(0, DL, OpVT);
4198  return DAG.getSetCC(DL, VT, And, Zero, CC0);
4199  }
4200  }
4201  }
4202  }
4203 
4204  // Canonicalize equivalent operands to LL == RL.
4205  if (LL == RR && LR == RL) {
4206  CC1 = ISD::getSetCCSwappedOperands(CC1);
4207  std::swap(RL, RR);
4208  }
4209 
4210  // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4211  // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4212  if (LL == RL && LR == RR) {
4213  ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
4214  : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
4215  if (NewCC != ISD::SETCC_INVALID &&
4216  (!LegalOperations ||
4217  (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
4218  TLI.isOperationLegal(ISD::SETCC, OpVT))))
4219  return DAG.getSetCC(DL, VT, LL, LR, NewCC);
4220  }
4221 
4222  return SDValue();
4223 }
4224 
4225 /// This contains all DAGCombine rules which reduce two values combined by
4226 /// an And operation to a single value. This makes them reusable in the context
4227 /// of visitSELECT(). Rules involving constants are not included as
4228 /// visitSELECT() already handles those cases.
4229 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
4230  EVT VT = N1.getValueType();
4231  SDLoc DL(N);
4232 
4233  // fold (and x, undef) -> 0
4234  if (N0.isUndef() || N1.isUndef())
4235  return DAG.getConstant(0, DL, VT);
4236 
4237  if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
4238  return V;
4239 
4240  if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
4241  VT.getSizeInBits() <= 64) {
4242  if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4243  if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
4244  // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
4245  // immediate for an add, but it is legal if its top c2 bits are set,
4246  // transform the ADD so the immediate doesn't need to be materialized
4247  // in a register.
4248  APInt ADDC = ADDI->getAPIntValue();
4249  APInt SRLC = SRLI->getAPIntValue();
4250  if (ADDC.getMinSignedBits() <= 64 &&
4251  SRLC.ult(VT.getSizeInBits()) &&
4252  !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4254  SRLC.getZExtValue());
4255  if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
4256  ADDC |= Mask;
4257  if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4258  SDLoc DL0(N0);
4259  SDValue NewAdd =
4260  DAG.getNode(ISD::ADD, DL0, VT,
4261  N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
4262  CombineTo(N0.getNode(), NewAdd);
4263  // Return N so it doesn't get rechecked!
4264  return SDValue(N, 0);
4265  }
4266  }
4267  }
4268  }
4269  }
4270  }
4271 
4272  // Reduce bit extract of low half of an integer to the narrower type.
4273  // (and (srl i64:x, K), KMask) ->
4274  // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
4275  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4276  if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
4277  if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4278  unsigned Size = VT.getSizeInBits();
4279  const APInt &AndMask = CAnd->getAPIntValue();
4280  unsigned ShiftBits = CShift->getZExtValue();
4281 
4282  // Bail out, this node will probably disappear anyway.
4283  if (ShiftBits == 0)
4284  return SDValue();
4285 
4286  unsigned MaskBits = AndMask.countTrailingOnes();
4287  EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
4288 
4289  if (AndMask.isMask() &&
4290  // Required bits must not span the two halves of the integer and
4291  // must fit in the half size type.
4292  (ShiftBits + MaskBits <= Size / 2) &&
4293  TLI.isNarrowingProfitable(VT, HalfVT) &&
4294  TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
4295  TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
4296  TLI.isTruncateFree(VT, HalfVT) &&
4297  TLI.isZExtFree(HalfVT, VT)) {
4298  // The isNarrowingProfitable is to avoid regressions on PPC and
4299  // AArch64 which match a few 64-bit bit insert / bit extract patterns
4300  // on downstream users of this. Those patterns could probably be
4301  // extended to handle extensions mixed in.
4302 
4303  SDValue SL(N0);
4304  assert(MaskBits <= Size);
4305 
4306  // Extracting the highest bit of the low half.
4307  EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
4308  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
4309  N0.getOperand(0));
4310 
4311  SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
4312  SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
4313  SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
4314  SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
4315  return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
4316  }
4317  }
4318  }
4319  }
4320 
4321  return SDValue();
4322 }
4323 
4324 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
4325  EVT LoadResultTy, EVT &ExtVT) {
4326  if (!AndC->getAPIntValue().isMask())
4327  return false;
4328 
4329  unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
4330 
4331  ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4332  EVT LoadedVT = LoadN->getMemoryVT();
4333 
4334  if (ExtVT == LoadedVT &&
4335  (!LegalOperations ||
4336  TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
4337  // ZEXTLOAD will match without needing to change the size of the value being
4338  // loaded.
4339  return true;
4340  }
4341 
4342  // Do not change the width of a volatile load.
4343  if (LoadN->isVolatile())
4344  return false;
4345 
4346  // Do not generate loads of non-round integer types since these can
4347  // be expensive (and would be wrong if the type is not byte sized).
4348  if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
4349  return false;
4350 
4351  if (LegalOperations &&
4352  !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
4353  return false;
4354 
4355  if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
4356  return false;
4357 
4358  return true;
4359 }
4360 
4361 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
4362  ISD::LoadExtType ExtType, EVT &MemVT,
4363  unsigned ShAmt) {
4364  if (!LDST)
4365  return false;
4366  // Only allow byte offsets.
4367  if (ShAmt % 8)
4368  return false;
4369 
4370  // Do not generate loads of non-round integer types since these can
4371  // be expensive (and would be wrong if the type is not byte sized).
4372  if (!MemVT.isRound())
4373  return false;
4374 
4375  // Don't change the width of a volatile load.
4376  if (LDST->isVolatile())
4377  return false;
4378 
4379  // Verify that we are actually reducing a load width here.
4380  if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits())
4381  return false;
4382 
4383  // Ensure that this isn't going to produce an unsupported unaligned access.
4384  if (ShAmt &&
4385  !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4386  LDST->getAddressSpace(), ShAmt / 8))
4387  return false;
4388 
4389  // It's not possible to generate a constant of extended or untyped type.
4390  EVT PtrType = LDST->getBasePtr().getValueType();
4391  if (PtrType == MVT::Untyped || PtrType.isExtended())
4392  return false;
4393 
4394  if (isa<LoadSDNode>(LDST)) {
4395  LoadSDNode *Load = cast<LoadSDNode>(LDST);
4396  // Don't transform one with multiple uses, this would require adding a new
4397  // load.
4398  if (!SDValue(Load, 0).hasOneUse())
4399  return false;
4400 
4401  if (LegalOperations &&
4402  !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
4403  return false;
4404 
4405  // For the transform to be legal, the load must produce only two values
4406  // (the value loaded and the chain). Don't transform a pre-increment
4407  // load, for example, which produces an extra value. Otherwise the
4408  // transformation is not equivalent, and the downstream logic to replace
4409  // uses gets things wrong.
4410  if (Load->getNumValues() > 2)
4411  return false;
4412 
4413  // If the load that we're shrinking is an extload and we're not just
4414  // discarding the extension we can't simply shrink the load. Bail.
4415  // TODO: It would be possible to merge the extensions in some cases.
4416  if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
4417  Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4418  return false;
4419 
4420  if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
4421  return false;
4422  } else {
4423  assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
4424  StoreSDNode *Store = cast<StoreSDNode>(LDST);
4425  // Can't write outside the original store
4426  if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4427  return false;
4428 
4429  if (LegalOperations &&
4430  !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
4431  return false;
4432  }
4433  return true;
4434 }
4435 
4436 bool DAGCombiner::SearchForAndLoads(SDNode *N,
4438  SmallPtrSetImpl<SDNode*> &NodesWithConsts,
4440  SDNode *&NodeToMask) {
4441  // Recursively search for the operands, looking for loads which can be
4442  // narrowed.
4443  for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
4444  SDValue Op = N->getOperand(i);
4445 
4446  if (Op.getValueType().isVector())
4447  return false;
4448 
4449  // Some constants may need fixing up later if they are too large.
4450  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4451  if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
4452  (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
4453  NodesWithConsts.insert(N);
4454  continue;
4455  }
4456 
4457  if (!Op.hasOneUse())
4458  return false;
4459 
4460  switch(Op.getOpcode()) {
4461  case ISD::LOAD: {
4462  auto *Load = cast<LoadSDNode>(Op);
4463  EVT ExtVT;
4464  if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
4465  isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
4466 
4467  // ZEXTLOAD is already small enough.
4468  if (Load->getExtensionType() == ISD::ZEXTLOAD &&
4469  ExtVT.bitsGE(Load->getMemoryVT()))
4470  continue;
4471 
4472  // Use LE to convert equal sized loads to zext.
4473  if (ExtVT.bitsLE(Load->getMemoryVT()))
4474  Loads.push_back(Load);
4475 
4476  continue;
4477  }
4478  return false;
4479  }
4480  case ISD::ZERO_EXTEND:
4481  case ISD::AssertZext: {
4482  unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
4483  EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4484  EVT VT = Op.getOpcode() == ISD::AssertZext ?
4485  cast<VTSDNode>(Op.getOperand(1))->getVT() :
4486  Op.getOperand(0).getValueType();
4487 
4488  // We can accept extending nodes if the mask is wider or an equal
4489  // width to the original type.
4490  if (ExtVT.bitsGE(VT))
4491  continue;
4492  break;
4493  }
4494  case ISD::OR:
4495  case ISD::XOR:
4496  case ISD::AND:
4497  if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
4498  NodeToMask))
4499  return false;
4500  continue;
4501  }
4502 
4503  // Allow one node which will masked along with any loads found.
4504  if (NodeToMask)
4505  return false;
4506 
4507  // Also ensure that the node to be masked only produces one data result.
4508  NodeToMask = Op.getNode();
4509  if (NodeToMask->getNumValues() > 1) {
4510  bool HasValue = false;
4511  for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
4512  MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
4513  if (VT != MVT::Glue && VT != MVT::Other) {
4514  if (HasValue) {
4515  NodeToMask = nullptr;
4516  return false;
4517  }
4518  HasValue = true;
4519  }
4520  }
4521  assert(HasValue && "Node to be masked has no data result?");
4522  }
4523  }
4524  return true;
4525 }
4526 
4527 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
4528  auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
4529  if (!Mask)
4530  return false;
4531 
4532  if (!Mask->getAPIntValue().isMask())
4533  return false;
4534 
4535  // No need to do anything if the and directly uses a load.
4536  if (isa<LoadSDNode>(N->getOperand(0)))
4537  return false;
4538 
4540  SmallPtrSet<SDNode*, 2> NodesWithConsts;
4541  SDNode *FixupNode = nullptr;
4542  if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
4543  if (Loads.size() == 0)
4544  return false;
4545 
4546  LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
4547  SDValue MaskOp = N->getOperand(1);
4548 
4549  // If it exists, fixup the single node we allow in the tree that needs
4550  // masking.
4551  if (FixupNode) {
4552  LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
4553  SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
4554  FixupNode->getValueType(0),
4555  SDValue(FixupNode, 0), MaskOp);
4556  DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
4557  if (And.getOpcode() == ISD ::AND)
4558  DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
4559  }
4560 
4561  // Narrow any constants that need it.
4562  for (auto *LogicN : NodesWithConsts) {
4563  SDValue Op0 = LogicN->getOperand(0);
4564  SDValue Op1 = LogicN->getOperand(1);
4565 
4566  if (isa<ConstantSDNode>(Op0))
4567  std::swap(Op0, Op1);
4568 
4569  SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
4570  Op1, MaskOp);
4571 
4572  DAG.UpdateNodeOperands(LogicN, Op0, And);
4573  }
4574 
4575  // Create narrow loads.
4576  for (auto *Load : Loads) {
4577  LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
4578  SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
4579  SDValue(Load, 0), MaskOp);
4580  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
4581  if (And.getOpcode() == ISD ::AND)
4582  And = SDValue(
4583  DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
4584  SDValue NewLoad = ReduceLoadWidth(And.getNode());
4585  assert(NewLoad &&
4586  "Shouldn't be masking the load if it can't be narrowed");
4587  CombineTo(Load, NewLoad, NewLoad.getValue(1));
4588  }
4589  DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
4590  return true;
4591  }
4592  return false;
4593 }
4594 
4595 // Unfold
4596 // x & (-1 'logical shift' y)
4597 // To
4598 // (x 'opposite logical shift' y) 'logical shift' y
4599 // if it is better for performance.
4600 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
4601  assert(N->getOpcode() == ISD::AND);
4602 
4603  SDValue N0 = N->getOperand(0);
4604  SDValue N1 = N->getOperand(1);
4605 
4606  // Do we actually prefer shifts over mask?
4607  if (!TLI.preferShiftsToClearExtremeBits(N0))
4608  return SDValue();
4609 
4610  // Try to match (-1 '[outer] logical shift' y)
4611  unsigned OuterShift;
4612  unsigned InnerShift; // The opposite direction to the OuterShift.
4613  SDValue Y; // Shift amount.
4614  auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
4615  if (!M.hasOneUse())
4616  return false;
4617  OuterShift = M->getOpcode();
4618  if (OuterShift == ISD::SHL)
4619  InnerShift = ISD::SRL;
4620  else if (OuterShift == ISD::SRL)
4621  InnerShift = ISD::SHL;
4622  else
4623  return false;
4624  if (!isAllOnesConstant(M->getOperand(0)))
4625  return false;
4626  Y = M->getOperand(1);
4627  return true;
4628  };
4629 
4630  SDValue X;
4631  if (matchMask(N1))
4632  X = N0;
4633  else if (matchMask(N0))
4634  X = N1;
4635  else
4636  return SDValue();
4637 
4638  SDLoc DL(N);
4639  EVT VT = N->getValueType(0);
4640 
4641  // tmp = x 'opposite logical shift' y
4642  SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
4643  // ret = tmp 'logical shift' y
4644  SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
4645 
4646  return T1;
4647 }
4648 
4649 SDValue DAGCombiner::visitAND(SDNode *N) {
4650  SDValue N0 = N->getOperand(0);
4651  SDValue N1 = N->getOperand(1);
4652  EVT VT = N1.getValueType();
4653 
4654  // x & x --> x
4655  if (N0 == N1)
4656  return N0;
4657 
4658  // fold vector ops
4659  if (VT.isVector()) {
4660  if (SDValue FoldedVOp = SimplifyVBinOp(N))
4661  return FoldedVOp;
4662 
4663  // fold (and x, 0) -> 0, vector edition
4665  // do not return N0, because undef node may exist in N0
4667  SDLoc(N), N0.getValueType());
4669  // do not return N1, because undef node may exist in N1
4671  SDLoc(N), N1.getValueType());
4672 
4673  // fold (and x, -1) -> x, vector edition
4675  return N1;
4677  return N0;
4678  }
4679 
4680  // fold (and c1, c2) -> c1&c2
4683  if (N0C && N1C && !N1C->isOpaque())
4684  return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
4685  // canonicalize constant to RHS
4688  return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
4689  // fold (and x, -1) -> x
4690  if (isAllOnesConstant(N1))
4691  return N0;
4692  // if (and x, c) is known to be zero, return 0
4693  unsigned BitWidth = VT.getScalarSizeInBits();
4694  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4695  APInt::getAllOnesValue(BitWidth)))
4696  return DAG.getConstant(0, SDLoc(N), VT);
4697 
4698  if (SDValue NewSel = foldBinOpIntoSelect(N))
4699  return NewSel;
4700 
4701  // reassociate and
4702  if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
4703  return RAND;
4704 
4705  // Try to convert a constant mask AND into a shuffle clear mask.
4706  if (VT.isVector())
4707  if (SDValue Shuffle = XformToShuffleWithZero(N))
4708  return Shuffle;
4709 
4710  // fold (and (or x, C), D) -> D if (C & D) == D
4711  auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4712  return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4713  };
4714  if (N0.getOpcode() == ISD::OR &&
4715  ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4716  return N1;
4717  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4718  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4719  SDValue N0Op0 = N0.getOperand(0);
4720  APInt Mask = ~N1C->getAPIntValue();
4721  Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4722  if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4723  SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4724  N0.getValueType(), N0Op0);
4725 
4726  // Replace uses of the AND with uses of the Zero extend node.
4727  CombineTo(N, Zext);
4728 
4729  // We actually want to replace all uses of the any_extend with the
4730  // zero_extend, to avoid duplicating things. This will later cause this
4731  // AND to be folded.
4732  CombineTo(N0.getNode(), Zext);
4733  return SDValue(N, 0); // Return N so it doesn't get rechecked!
4734  }
4735  }
4736  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4737  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4738  // already be zero by virtue of the width of the base type of the load.
4739  //
4740  // the 'X' node here can either be nothing or an extract_vector_elt to catch
4741  // more cases.
4742  if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4744  N0.getOperand(0).getOpcode() == ISD::LOAD &&
4745  N0.getOperand(0).getResNo() == 0) ||
4746  (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4747  LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4748  N0 : N0.getOperand(0) );
4749 
4750  // Get the constant (if applicable) the zero'th operand is being ANDed with.
4751  // This can be a pure constant or a vector splat, in which case we treat the
4752  // vector as a scalar and use the splat value.
4754  if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4755  Constant = C->getAPIntValue();
4756  } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4757  APInt SplatValue, SplatUndef;
4758  unsigned SplatBitSize;
4759  bool HasAnyUndefs;
4760  bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4761  SplatBitSize, HasAnyUndefs);
4762  if (IsSplat) {
4763  // Undef bits can contribute to a possible optimisation if set, so
4764  // set them.
4765  SplatValue |= SplatUndef;
4766 
4767  // The splat value may be something like "0x00FFFFFF", which means 0 for
4768  // the first vector value and FF for the rest, repeating. We need a mask
4769  // that will apply equally to all members of the vector, so AND all the
4770  // lanes of the constant together.
4771  EVT VT = Vector->getValueType(0);
4772  unsigned BitWidth = VT.getScalarSizeInBits();
4773 
4774  // If the splat value has been compressed to a bitlength lower
4775  // than the size of the vector lane, we need to re-expand it to
4776  // the lane size.
4777  if (BitWidth > SplatBitSize)
4778  for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4779  SplatBitSize < BitWidth;
4780  SplatBitSize = SplatBitSize * 2)
4781  SplatValue |= SplatValue.shl(SplatBitSize);
4782 
4783  // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4784  // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4785  if (SplatBitSize % BitWidth == 0) {
4786  Constant = APInt::getAllOnesValue(BitWidth);
4787  for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4788  Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4789  }
4790  }
4791  }
4792 
4793  // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4794  // actually legal and isn't going to get expanded, else this is a false
4795  // optimisation.
4796  bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4797  Load->getValueType(0),
4798  Load->getMemoryVT());
4799 
4800  // Resize the constant to the same size as the original memory access before
4801  // extension. If it is still the AllOnesValue then this AND is completely
4802  // unneeded.
4803  Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4804 
4805  bool B;
4806  switch (Load->getExtensionType()) {
4807  default: B = false; break;
4808  case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4809  case ISD::ZEXTLOAD:
4810  case ISD::NON_EXTLOAD: B = true; break;
4811  }
4812 
4813  if (B && Constant.isAllOnesValue()) {
4814  // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4815  // preserve semantics once we get rid of the AND.
4816  SDValue NewLoad(Load, 0);
4817 
4818  // Fold the AND away. NewLoad may get replaced immediately.
4819  CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4820 
4821  if (Load->getExtensionType() == ISD::EXTLOAD) {
4822  NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4823  Load->getValueType(0), SDLoc(Load),
4824  Load->getChain(), Load->getBasePtr(),
4825  Load->getOffset(), Load->getMemoryVT(),
4826  Load->getMemOperand());
4827  // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4828  if (Load->getNumValues() == 3) {
4829  // PRE/POST_INC loads have 3 values.
4830  SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4831  NewLoad.getValue(2) };
4832  CombineTo(Load, To, 3, true);
4833  } else {
4834  CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4835  }
4836  }
4837 
4838  return SDValue(N, 0); // Return N so it doesn't get rechecked!
4839  }
4840  }
4841 
4842  // fold (and (load x), 255) -> (zextload x, i8)
4843  // fold (and (extload x, i16), 255) -> (zextload x, i8)
4844  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4845  if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4846  (N0.getOpcode() == ISD::ANY_EXTEND &&
4847  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4848  if (SDValue Res = ReduceLoadWidth(N)) {
4849  LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4850  ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4851  AddToWorklist(N);
4852  DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res);
4853  return SDValue(N, 0);
4854  }
4855  }
4856 
4857  if (Level >= AfterLegalizeTypes) {
4858  // Attempt to propagate the AND back up to the leaves which, if they're
4859  // loads, can be combined to narrow loads and the AND node can be removed.
4860  // Perform after legalization so that extend nodes will already be
4861  // combined into the loads.
4862  if (BackwardsPropagateMask(N, DAG)) {
4863  return SDValue(N, 0);
4864  }
4865  }
4866 
4867  if (SDValue Combined = visitANDLike(N0, N1, N))
4868  return Combined;
4869 
4870  // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
4871  if (N0.getOpcode() == N1.getOpcode())